Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(agent-driver): isolate Windows target environments (#1176)

Generc7c21a331bfa
diff --git a/src/daemon/agent-driver/src/internal/killTree.test.ts b/src/daemon/agent-driver/src/internal/killTree.test.ts
index 43ebde468..c5435c58c 100644
--- a/src/daemon/agent-driver/src/internal/killTree.test.ts
+++ b/src/daemon/agent-driver/src/internal/killTree.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, afterEach, vi } from "vitest";
import { execFileSync, spawn, type ChildProcess } from "child_process";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
@@ -14,10 +15,10 @@ import { spawnAgentProcess, killProcessTree, isAlive } from "./killTree.js";
*/
type ProcessReport = (event: string, detail?: Record<string, unknown>) => void;
-type OwnedProcess = { proc: ChildProcess; closed: Promise<void>; cwd?: string; report?: ProcessReport };
+type OwnedProcess = { proc: ChildProcess; closed: Promise<void>; cwd?: string; traceDirectory?: string; report?: ProcessReport };
const spawned: OwnedProcess[] = [];
-function ownProcess(proc: ChildProcess, diagnostics?: { cwd: string; report: ProcessReport }): ChildProcess {
+function ownProcess(proc: ChildProcess, diagnostics?: { cwd: string; traceDirectory?: string; report: ProcessReport }): ChildProcess {
const closed = new Promise<void>((resolve) => proc.once("close", () => resolve()));
spawned.push({ proc, closed, ...diagnostics });
return proc;
@@ -89,7 +90,10 @@ afterEach(async () => {
for (const dir of [...tempDirs]) {
rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
tempDirs.splice(tempDirs.indexOf(dir), 1);
- for (const owner of processes) if (owner.cwd === dir) owner.report?.("cwd-removed");
+ for (const owner of processes) {
+ if (owner.cwd === dir) owner.report?.("cwd-removed");
+ if (owner.traceDirectory === dir) owner.report?.("trace-directory-removed");
+ }
}
});
@@ -405,16 +409,57 @@ describe("spawnAgentProcess", () => {
process.kill(proc.pid!, "SIGKILL");
});
- it("pipes stdio and forwards cwd/env/shell", () => {
- const proc = spawnAgentProcess(process.execPath, ["-e", "process.exit(0)"], {
- cwd: process.cwd(),
- env: { ...process.env, FOO: "bar" },
- shell: false,
- });
- ownProcess(proc);
- expect(proc.stdin).not.toBeNull();
- expect(proc.stdout).not.toBeNull();
- expect(proc.stderr).not.toBeNull();
+ it("pipes stdio and forwards cwd/env/shell", async () => {
+ const keys = ["ALOOK_PROCESS_PARENT_FIXTURE", "ALOOK_PROCESS_CALLER_FIXTURE", "ALOOK_PROCESS_EMPTY_FIXTURE", "ALOOK_WINDOWS_JOB_PAYLOAD", "ALOOK_WINDOWS_JOB_ENV_CHUNK_777"];
+ const before = keys.map((key) => process.env[key]);
+ const digest = (value: string | undefined) => value === undefined ? null : createHash("sha256").update(value).digest("hex");
+ process.env.ALOOK_PROCESS_PARENT_FIXTURE = "parent-only";
+ delete process.env.ALOOK_PROCESS_CALLER_FIXTURE;
+ delete process.env.ALOOK_PROCESS_EMPTY_FIXTURE;
+ process.env.ALOOK_WINDOWS_JOB_PAYLOAD = "ignored-owner-value";
+ process.env.ALOOK_WINDOWS_JOB_ENV_CHUNK_777 = "ignored-owner-piece";
+ try {
+ const replacement: NodeJS.ProcessEnv = {
+ FOO: "bar",
+ ALOOK_PROCESS_CALLER_FIXTURE: "调用😀",
+ ALOOK_PROCESS_PARENT_FIXTURE: undefined,
+ ALOOK_PROCESS_EMPTY_FIXTURE: "",
+ alook_windows_job_runner: "ignored-caller-owner",
+ };
+ const environments: (NodeJS.ProcessEnv | undefined)[] = [undefined, {}, replacement];
+ for (const env of environments) {
+ const expected = env ?? process.env;
+ const stdout: Buffer[] = [];
+ const stderr: Buffer[] = [];
+ const proc = ownProcess(spawnAgentProcess(process.execPath, ["-e", `
+ const { createHash } = require("node:crypto");
+ const names = ["FOO", "ALOOK_PROCESS_PARENT_FIXTURE", "ALOOK_PROCESS_CALLER_FIXTURE", "ALOOK_PROCESS_EMPTY_FIXTURE"];
+ const hashes = Object.fromEntries(names.map(name => [name, process.env[name] === undefined ? null : createHash("sha256").update(process.env[name]).digest("hex")]));
+ const ownerKeys = Object.keys(process.env).filter(key => /^ALOOK_WINDOWS_JOB_/i.test(key)).sort();
+ process.stdout.write(JSON.stringify({ cwd: process.cwd(), hashes, ownerKeys }));
+ `], { cwd: process.cwd(), ...(env === undefined ? {} : { env }), shell: false }));
+ expect(proc.stdin).not.toBeNull();
+ expect(proc.stdout).not.toBeNull();
+ expect(proc.stderr).not.toBeNull();
+ proc.stdout!.on("data", (chunk: Buffer) => stdout.push(chunk));
+ proc.stderr!.on("data", (chunk: Buffer) => stderr.push(chunk));
+ await new Promise<void>((resolve, reject) => {
+ proc.once("error", reject);
+ proc.once("close", (code, signal) => code === 0 && signal === null ? resolve() : reject(new Error("Environment fixture did not exit successfully")));
+ });
+ expect(Buffer.concat(stderr).toString("utf8")).toBe("");
+ expect(JSON.parse(Buffer.concat(stdout).toString("utf8"))).toEqual({
+ cwd: process.cwd(),
+ hashes: Object.fromEntries(["FOO", "ALOOK_PROCESS_PARENT_FIXTURE", "ALOOK_PROCESS_CALLER_FIXTURE", "ALOOK_PROCESS_EMPTY_FIXTURE"].map((key) => [key, digest(expected[key])])),
+ ownerKeys: process.platform === "win32" ? [] : Object.keys(expected).filter((key) => /^ALOOK_WINDOWS_JOB_/i.test(key)).sort(),
+ });
+ }
+ } finally {
+ for (const [index, key] of keys.entries()) {
+ if (before[index] === undefined) delete process.env[key];
+ else process.env[key] = before[index];
+ }
+ }
});
it("supports a runtime that explicitly ignores stdin", async () => {
@@ -434,26 +479,154 @@ describe("spawnAgentProcess", () => {
it("starts an owned native process with an isolated PATH and preserves raw Unicode output", async () => {
const cwd = mkdtempSync(join(tmpdir(), "agent-driver-isolated-env-"));
tempDirs.push(cwd);
+ const traceDirectory = mkdtempSync(join(tmpdir(), "agent-driver-phase-trace-"));
+ tempDirs.push(traceDirectory);
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
const started = performance.now();
+ const requestedNs = process.hrtime.bigint();
+ let firstOutputNs: bigint | undefined;
let pid: number | null = null;
- const report: ProcessReport = (event, detail = {}) => console.info("AGENT_DRIVER_PROCESS", JSON.stringify({
- case: "isolated-path-unicode",
- event,
- elapsedMs: performance.now() - started,
- pid,
- cwd,
- stdoutBytes: stdout.reduce((bytes, chunk) => bytes + chunk.length, 0),
- stderrBytes: stderr.reduce((bytes, chunk) => bytes + chunk.length, 0),
- ...detail,
- }));
+ const collectPhases = (event: string) => {
+ const stages = ["ps-enter", "add-type-ready", "native-created", "native-resumed", "runner-enter", "target-spawn", "target-enter"] as const;
+ type Phase = { stage: string; pid: number; childPid?: number; clock: string; committed?: boolean; ticks?: string; frequency?: string; highResolution?: boolean; nanoseconds?: string; node?: string; platform?: string; arch?: string; traceEnvironmentPresent?: boolean };
+ const phases: Partial<Record<(typeof stages)[number], Phase>> = {};
+ const problems: { stage: string; problem: string }[] = [];
+ const observedNs = process.hrtime.bigint();
+ for (const stage of stages) {
+ const path = join(traceDirectory, `${stage}.json`);
+ try {
+ let committed = true;
+ let serialized: string;
+ try {
+ serialized = readFileSync(path, "utf8");
+ } catch (error) {
+ if (!existsSync(`${path}.tmp`)) throw error;
+ serialized = readFileSync(`${path}.tmp`, "utf8");
+ committed = false;
+ problems.push({ stage, problem: error instanceof Error && "code" in error ? String(error.code) : "final-marker-unavailable" });
+ }
+ const input: unknown = JSON.parse(serialized.replace(/^\uFEFF/, ""));
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("invalid-record");
+ const record = input as Record<string, unknown>;
+ if (record.stage !== stage || !Number.isSafeInteger(record.pid) || (record.pid as number) <= 0) throw new Error("invalid-identity");
+ const phase: Phase = { stage, pid: record.pid as number, clock: String(record.clock), committed };
+ if (stage === "native-created" || stage === "native-resumed" || stage === "target-spawn") {
+ if (!Number.isSafeInteger(record.childPid) || (record.childPid as number) <= 0) throw new Error("invalid-child-pid");
+ phase.childPid = record.childPid as number;
+ }
+ if (stage === "runner-enter" || stage === "target-spawn" || stage === "target-enter") {
+ if (record.clock !== "node-hrtime" || typeof record.nanoseconds !== "string" || !/^\d+$/.test(record.nanoseconds)
+ || typeof record.node !== "string" || typeof record.platform !== "string" || typeof record.arch !== "string") throw new Error("invalid-node-clock");
+ Object.assign(phase, { nanoseconds: record.nanoseconds, node: record.node, platform: record.platform, arch: record.arch });
+ if (stage === "target-enter") {
+ phase.traceEnvironmentPresent = record.traceEnvironmentPresent === true;
+ if (record.traceEnvironmentPresent !== false) problems.push({ stage, problem: "private-trace-env-not-proven-absent" });
+ }
+ } else {
+ if (record.clock !== "windows-qpc-stopwatch" || typeof record.ticks !== "string" || !/^\d+$/.test(record.ticks)
+ || typeof record.frequency !== "string" || !/^[1-9]\d*$/.test(record.frequency) || typeof record.highResolution !== "boolean") throw new Error("invalid-native-clock");
+ Object.assign(phase, { ticks: record.ticks, frequency: record.frequency, highResolution: record.highResolution });
+ }
+ phases[stage] = phase;
+ } catch (error) {
+ const problem = error instanceof Error && "code" in error ? String(error.code) : error instanceof Error ? error.message : "unknown";
+ problems.push({ stage, problem });
+ }
+ if (existsSync(`${path}.tmp`)) problems.push({ stage, problem: "unfinished-marker-write" });
+ }
+ const native = stages.slice(0, 4).map((stage) => phases[stage]);
+ const nodes = stages.slice(4).map((stage) => phases[stage]);
+ const complete = stages.every((stage) => phases[stage]) && problems.length === 0;
+ const associations = native.every((phase) => phase?.pid === pid)
+ && phases["native-created"]?.childPid === phases["runner-enter"]?.pid
+ && phases["native-resumed"]?.childPid === phases["runner-enter"]?.pid
+ && phases["runner-enter"]?.pid === phases["target-spawn"]?.pid
+ && phases["target-spawn"]?.childPid === phases["target-enter"]?.pid;
+ const providers = process.platform === "win32" && process.arch === "x64" && process.version === "v22.23.4"
+ && native.every((phase) => phase?.highResolution === true && phase.frequency === phases["ps-enter"]?.frequency)
+ && nodes.every((phase) => phase?.node === process.version && phase.platform === process.platform && phase.arch === process.arch);
+ const nanoseconds = (phase: Phase): bigint => phase.clock === "node-hrtime"
+ ? BigInt(phase.nanoseconds!) : BigInt(phase.ticks!) * 1_000_000_000n / BigInt(phase.frequency!);
+ const ordered = (names: (typeof stages)[number][]) => names.every((stage, index) => index === 0
+ || phases[names[index - 1]] && phases[stage] && nanoseconds(phases[names[index - 1]]!) <= nanoseconds(phases[stage]!));
+ const causalOrdering = ordered(["ps-enter", "add-type-ready", "native-created", "native-resumed"])
+ && ordered(["native-created", "runner-enter", "target-enter"])
+ && ordered(["runner-enter", "target-spawn"])
+ && (!firstOutputNs || !phases["target-enter"] || nanoseconds(phases["target-enter"]) <= firstOutputNs);
+ const inInvocation = Object.values(phases).every((phase) => {
+ const ns = nanoseconds(phase);
+ return ns >= requestedNs && ns <= observedNs;
+ });
+ const crossClockQualified = complete && associations && providers && causalOrdering && inInvocation;
+ const interval = (from: Phase | undefined, to: Phase | undefined): string => {
+ if (!from || !to || from.committed === false || to.committed === false) return "UNKNOWN";
+ const sameClock = from.pid === to.pid && from.clock === to.clock
+ && (from.clock === "node-hrtime" || from.highResolution === true && to.highResolution === true && from.frequency === to.frequency);
+ if (!sameClock && !crossClockQualified) return "UNKNOWN";
+ const gap = nanoseconds(to) - nanoseconds(from);
+ return gap >= 0n ? gap.toString() : "UNKNOWN";
+ };
+ const parentPhase = (ns: bigint): Phase => ({ stage: "parent", pid: process.pid, clock: "node-hrtime", nanoseconds: ns.toString() });
+ console.info("AGENT_DRIVER_PHASES", JSON.stringify({
+ case: "isolated-path-unicode", event, pid, cwd, traceDirectory, observedNs: observedNs.toString(),
+ observationStatus: complete ? "complete" : "incomplete", problems, phases,
+ crossClockQualification: crossClockQualified ? "qualified-node22.23.4-qpc" : "UNKNOWN",
+ qualification: { associations, providers, causalOrdering, inInvocation, parentNode: process.version, platform: process.platform, arch: process.arch },
+ intervalNs: {
+ requestToPs: interval(parentPhase(requestedNs), phases["ps-enter"]),
+ addType: interval(phases["ps-enter"], phases["add-type-ready"]),
+ nativePreparationAndCreate: interval(phases["add-type-ready"], phases["native-created"]),
+ assignAndResume: interval(phases["native-created"], phases["native-resumed"]),
+ resumeToRunner: interval(phases["native-resumed"], phases["runner-enter"]),
+ runnerToTargetSpawn: interval(phases["runner-enter"], phases["target-spawn"]),
+ spawnToTargetEntry: interval(phases["target-spawn"], phases["target-enter"]),
+ targetEntryToObservedOutput: firstOutputNs ? interval(phases["target-enter"], parentPhase(firstOutputNs)) : "UNKNOWN",
+ },
+ }));
+ };
+ const report: ProcessReport = (event, detail = {}) => {
+ const ns = process.hrtime.bigint();
+ if (event.endsWith("-data") && firstOutputNs === undefined) firstOutputNs = ns;
+ console.info("AGENT_DRIVER_PROCESS", JSON.stringify({
+ case: "isolated-path-unicode",
+ event,
+ elapsedMs: performance.now() - started,
+ hrtimeNs: ns.toString(),
+ pid,
+ cwd,
+ stdoutBytes: stdout.reduce((bytes, chunk) => bytes + chunk.length, 0),
+ stderrBytes: stderr.reduce((bytes, chunk) => bytes + chunk.length, 0),
+ ...detail,
+ }));
+ if (event === "cleanup-start" || event === "cleanup-close-observed") collectPhases(event);
+ };
report("spawn-requested", { node: process.version, platform: process.platform, arch: process.arch });
- const proc = ownProcess(spawnAgentProcess(process.execPath, ["-e", `
+ const proc = (() => {
+ const before = process.env.ALOOK_PROCESS_PARENT_FIXTURE;
+ process.env.ALOOK_PROCESS_PARENT_FIXTURE = "parent-only";
+ try {
+ return ownProcess(spawnAgentProcess(process.execPath, ["-e", `
+ try {
+ const nanoseconds = process.hrtime.bigint().toString();
+ const { writeFileSync, renameSync } = require("node:fs");
+ const path = ${JSON.stringify(join(traceDirectory, "target-enter.json"))};
+ writeFileSync(path + ".tmp", JSON.stringify({ stage: "target-enter", pid: process.pid, clock: "node-hrtime", nanoseconds, node: process.version, platform: process.platform, arch: process.arch, traceEnvironmentPresent: Object.hasOwn(process.env, "ALOOK_WINDOWS_JOB_TRACE") }));
+ renameSync(path + ".tmp", path);
+ } catch {}
+ const { createHash } = require("node:crypto");
+ if (createHash("sha256").update(process.env.PATH ?? "").digest("hex") !== ${JSON.stringify(createHash("sha256").update(cwd).digest("hex"))} || process.env.ALOOK_PROCESS_PARENT_FIXTURE !== undefined || Object.keys(process.env).some(key => /^ALOOK_WINDOWS_JOB_/i.test(key))) {
+ throw new Error("Isolated target environment contract failed");
+ }
const { writeSync } = require("node:fs");
writeSync(1, Buffer.from("你好😀"));
writeSync(2, Buffer.from("日志😀"));
- `], { cwd, env: { PATH: cwd }, stdin: "ignore" }), { cwd, report });
+ `], { cwd, env: { PATH: cwd }, stdin: "ignore", traceDirectory }), { cwd, traceDirectory, report });
+ } finally {
+ if (before === undefined) delete process.env.ALOOK_PROCESS_PARENT_FIXTURE;
+ else process.env.ALOOK_PROCESS_PARENT_FIXTURE = before;
+ }
+ })();
pid = proc.pid ?? null;
report("spawn-returned");
proc.once("spawn", () => report("spawn"));
@@ -487,22 +660,37 @@ describe("spawnAgentProcess", () => {
mkdirSync(cwd, { recursive: true });
const runtimeModule = join(base, "runtime.mjs");
const command = join(base, "runtime.cmd");
+ const largeEnvironment = {
+ ALOOK_JOB_LARGE_A: "甲😀".repeat(4096),
+ ALOOK_JOB_LARGE_B: "乙😃".repeat(4096),
+ ALOOK_JOB_LARGE_C: "丙😄".repeat(4096),
+ };
+ const largeEnvironmentDigest = createHash("sha256").update(JSON.stringify(Object.values(largeEnvironment))).digest("hex");
+ const shellValue = "caller-env-is-not-the-dispatcher";
+ const shellDigest = createHash("sha256").update(shellValue).digest("hex");
writeFileSync(runtimeModule, `
import { createInterface } from "node:readline";
+ import { createHash } from "node:crypto";
const lines = createInterface({ input: process.stdin });
let request = 0;
lines.on("line", (line) => {
request += 1;
- const result = { line, request, cwd: process.cwd(), env: process.env.ALOOK_JOB_FIXTURE };
+ const largeEnvironment = [process.env.ALOOK_JOB_LARGE_A, process.env.ALOOK_JOB_LARGE_B, process.env.ALOOK_JOB_LARGE_C];
+ const result = { line, request, cwd: process.cwd(), env: process.env.ALOOK_JOB_FIXTURE,
+ largeEnvironmentDigest: createHash("sha256").update(JSON.stringify(largeEnvironment)).digest("hex"),
+ shellDigest: createHash("sha256").update(process.env.ComSpec).digest("hex") };
process.stdout.write(JSON.stringify(result) + "\\n", () => {
if (request === 2) process.exit(37);
});
});
`);
writeFileSync(command, `@node "%~dp0\\runtime.mjs"\r\n`);
+ const env: NodeJS.ProcessEnv = { ...process.env, ALOOK_JOB_FIXTURE: "job-env-ok", ...largeEnvironment };
+ for (const key of Object.keys(env)) if (key.toUpperCase() === "COMSPEC") delete env[key];
+ env.ComSpec = shellValue;
const proc = spawnAgentProcess(command, ["app-server", "--listen", "stdio://"], {
cwd,
- env: { ...process.env, ALOOK_JOB_FIXTURE: "job-env-ok" },
+ env,
shell: true,
});
ownProcess(proc);
@@ -541,12 +729,16 @@ describe("spawnAgentProcess", () => {
request: 1,
cwd,
env: "job-env-ok",
+ largeEnvironmentDigest,
+ shellDigest,
},
{
line: "stdio-roundtrip-2",
request: 2,
cwd,
env: "job-env-ok",
+ largeEnvironmentDigest,
+ shellDigest,
},
]);
lines.close();
diff --git a/src/daemon/agent-driver/src/internal/killTree.ts b/src/daemon/agent-driver/src/internal/killTree.ts
index f9b3edaee..fc4551b84 100644
--- a/src/daemon/agent-driver/src/internal/killTree.ts
+++ b/src/daemon/agent-driver/src/internal/killTree.ts
@@ -52,6 +52,26 @@ const WINDOWS_JOB_NODE_ENV = "ALOOK_WINDOWS_JOB_NODE";
const WINDOWS_JOB_PAYLOAD_ENV = "ALOOK_WINDOWS_JOB_PAYLOAD";
const WINDOWS_JOB_RUNNER_ENV = "ALOOK_WINDOWS_JOB_RUNNER";
const WINDOWS_JOB_STDIN_PIPE_ENV = "ALOOK_WINDOWS_JOB_STDIN_PIPE";
+const WINDOWS_JOB_TRACE_ENV = "ALOOK_WINDOWS_JOB_TRACE";
+const WINDOWS_JOB_ENV_COUNT_ENV = "ALOOK_WINDOWS_JOB_ENV_COUNT";
+const WINDOWS_JOB_ENV_CHUNK_PREFIX = "ALOOK_WINDOWS_JOB_ENV_CHUNK_";
+const WINDOWS_JOB_ENV_CHUNK_SIZE = 16_384;
+const WINDOWS_JOB_PRIVATE_ENV = /^ALOOK_WINDOWS_JOB_(?:NODE|PAYLOAD|RUNNER|STDIN_PIPE|TRACE|ENV_COUNT|ENV_CHUNK_[0-9]+)$/i;
+
+function copyWindowsEnvironment(input: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
+ const result: NodeJS.ProcessEnv = Object.create(null);
+ for (const key in input) {
+ if (WINDOWS_JOB_PRIVATE_ENV.test(key)) continue;
+ const value = input[key];
+ if (value === undefined) continue;
+ const text = `${value}`;
+ if (key.includes("\0") || text.includes("\0")) {
+ throw Object.assign(new TypeError("Environment keys and values must not contain null bytes"), { code: "ERR_INVALID_ARG_VALUE" });
+ }
+ result[key] = text;
+ }
+ return result;
+}
// The tracked Windows child is a PowerShell supervisor that owns a kill-on-close
// Job Object. It creates the inner Node process suspended, gives it the
@@ -60,10 +80,88 @@ const WINDOWS_JOB_STDIN_PIPE_ENV = "ALOOK_WINDOWS_JOB_STDIN_PIPE";
// authority after a `.cmd` shell or runtime root exits. Persistent protocol
// stdin uses a dedicated named pipe: PowerShell must not own that pipe because
// its host can block while probing stdin before it runs the bootstrap.
-const WINDOWS_JOB_RUNNER = "const{spawn}=require('node:child_process');const{connect}=require('node:net');const p=JSON.parse(Buffer.from(process.env.ALOOK_WINDOWS_JOB_PAYLOAD,'base64').toString('utf8'));const pipe=process.env.ALOOK_WINDOWS_JOB_STDIN_PIPE;delete process.env.ALOOK_WINDOWS_JOB_NODE;delete process.env.ALOOK_WINDOWS_JOB_PAYLOAD;delete process.env.ALOOK_WINDOWS_JOB_RUNNER;delete process.env.ALOOK_WINDOWS_JOB_STDIN_PIPE;const run=stdin=>{const c=spawn(p.command,p.args,{cwd:p.cwd,env:process.env,shell:p.shell,stdio:[stdin,'inherit','inherit'],windowsHide:true});c.once('spawn',()=>{if(stdin!=='ignore')stdin.unref()});c.once('error',e=>{console.error(e);process.exitCode=1});c.once('exit',(code,signal)=>{process.exitCode=signal?1:(code??1)})};if(pipe){const input=connect(pipe);input.once('connect',()=>run(input));input.once('error',e=>{console.error(e);process.exitCode=1})}else run('ignore')";
+const WINDOWS_JOB_RUNNER = String.raw`
+const traceDirectory = process.env.ALOOK_WINDOWS_JOB_TRACE;
+const mark = (stage, childPid) => {
+ if (!traceDirectory) return;
+ try {
+ const nanoseconds = process.hrtime.bigint().toString();
+ const { writeFileSync, renameSync } = require('node:fs');
+ const { join } = require('node:path');
+ const path = join(traceDirectory, stage + '.json');
+ writeFileSync(path + '.tmp', JSON.stringify({ stage, pid: process.pid, childPid, clock: 'node-hrtime', nanoseconds, node: process.version, platform: process.platform, arch: process.arch }));
+ renameSync(path + '.tmp', path);
+ } catch {}
+};
+mark('runner-enter');
+const { spawn } = require('node:child_process');
+const { connect } = require('node:net');
+const p = JSON.parse(Buffer.from(process.env.ALOOK_WINDOWS_JOB_PAYLOAD, 'base64').toString('utf8'));
+const pipe = process.env.ALOOK_WINDOWS_JOB_STDIN_PIPE;
+const privateEnvironment = ${WINDOWS_JOB_PRIVATE_ENV};
+const targetEnv = (() => {
+ try {
+ const countText = process.env.${WINDOWS_JOB_ENV_COUNT_ENV};
+ if (!/^[1-9][0-9]*$/.test(countText ?? '')) throw new Error();
+ const count = Number(countText);
+ if (!Number.isSafeInteger(count) || count < 1) throw new Error();
+ const chunks = [];
+ for (let index = 0; index < count; index++) {
+ const value = process.env['${WINDOWS_JOB_ENV_CHUNK_PREFIX}' + index];
+ if (typeof value !== 'string' || value.length < 1 || value.length > ${WINDOWS_JOB_ENV_CHUNK_SIZE} || (index < count - 1 && value.length !== ${WINDOWS_JOB_ENV_CHUNK_SIZE})) throw new Error();
+ chunks.push(value);
+ }
+ const encoded = chunks.join('');
+ const bytes = Buffer.from(encoded, 'base64');
+ if (bytes.toString('base64') !== encoded) throw new Error();
+ const { TextDecoder } = require('node:util');
+ const input = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error();
+ const result = Object.create(null);
+ for (const [key, value] of Object.entries(input)) {
+ if (typeof value !== 'string' || key.includes('\0') || value.includes('\0') || privateEnvironment.test(key)) throw new Error();
+ result[key] = value;
+ }
+ return result;
+ } catch {
+ throw new Error('Invalid Windows target environment');
+ }
+})();
+for (const key of Object.keys(process.env)) if (privateEnvironment.test(key)) delete process.env[key];
+const run = stdin => {
+ const c = spawn(p.command, p.args, { cwd: p.cwd, env: targetEnv, shell: p.shell, stdio: [stdin, 'inherit', 'inherit'], windowsHide: true });
+ c.once('spawn', () => { mark('target-spawn', c.pid); if (stdin !== 'ignore') stdin.unref() });
+ c.once('error', e => { console.error(e); process.exitCode = 1 });
+ c.once('exit', (code, signal) => { process.exitCode = signal ? 1 : (code ?? 1) });
+};
+if (pipe) {
+ const input = connect(pipe);
+ input.once('connect', () => run(input));
+ input.once('error', e => { console.error(e); process.exitCode = 1 });
+} else run('ignore');
+`;
const WINDOWS_JOB_BOOTSTRAP = String.raw`
$ErrorActionPreference = "Stop"
+$traceDirectory = $env:ALOOK_WINDOWS_JOB_TRACE
+if ($traceDirectory) {
+ try {
+ $ticks = [Diagnostics.Stopwatch]::GetTimestamp().ToString([Globalization.CultureInfo]::InvariantCulture)
+ $frequency = [Diagnostics.Stopwatch]::Frequency.ToString([Globalization.CultureInfo]::InvariantCulture)
+ $highResolution = [Diagnostics.Stopwatch]::IsHighResolution.ToString().ToLowerInvariant()
+ $path = [IO.Path]::Combine($traceDirectory, 'ps-enter.json')
+ $record = '{"stage":"ps-enter","pid":' + $PID + ',"clock":"windows-qpc-stopwatch","ticks":"' + $ticks + '","frequency":"' + $frequency + '","highResolution":' + $highResolution + '}'
+ [IO.File]::WriteAllText($path + '.tmp', $record)
+ [IO.File]::Move($path + '.tmp', $path)
+ } catch {}
+}
+$jobEnvironment = @{}
+foreach ($entry in [Environment]::GetEnvironmentVariables().GetEnumerator()) {
+ if ([regex]::IsMatch([string]$entry.Key, '${WINDOWS_JOB_PRIVATE_ENV.source}', [Text.RegularExpressions.RegexOptions]::IgnoreCase)) {
+ $jobEnvironment[[string]$entry.Key] = [string]$entry.Value
+ [Environment]::SetEnvironmentVariable([string]$entry.Key, $null)
+ }
+}
Add-Type -TypeDefinition @"
using System;
using System.ComponentModel;
@@ -72,6 +170,24 @@ using System.Text;
using System.Threading;
public static class AlookAgentJob {
+ [DllImport("kernel32.dll")]
+ private static extern uint GetCurrentProcessId();
+
+ public static void Mark(string directory, string stage, uint childPid, long capturedTicks) {
+ if (String.IsNullOrEmpty(directory)) return;
+ try {
+ long ticks = capturedTicks == 0 ? System.Diagnostics.Stopwatch.GetTimestamp() : capturedTicks;
+ var culture = System.Globalization.CultureInfo.InvariantCulture;
+ string path = System.IO.Path.Combine(directory, stage + ".json");
+ string record = "{\"stage\":\"" + stage + "\",\"pid\":" + GetCurrentProcessId().ToString(culture)
+ + ",\"childPid\":" + childPid.ToString(culture) + ",\"clock\":\"windows-qpc-stopwatch\",\"ticks\":\"" + ticks.ToString(culture)
+ + "\",\"frequency\":\"" + System.Diagnostics.Stopwatch.Frequency.ToString(culture)
+ + "\",\"highResolution\":" + System.Diagnostics.Stopwatch.IsHighResolution.ToString().ToLowerInvariant() + "}";
+ System.IO.File.WriteAllText(path + ".tmp", record);
+ System.IO.File.Move(path + ".tmp", path);
+ } catch {}
+ }
+
[StructLayout(LayoutKind.Sequential)]
private struct BasicLimits {
public long PerProcessUserTimeLimit;
@@ -297,7 +413,7 @@ public static class AlookAgentJob {
}
}
- public static int RunNode(string nodePath, string runner) {
+ public static int RunNode(string nodePath, string runner, string traceDirectory) {
const uint CreateSuspended = 0x00000004;
const uint StartfUseStdHandles = 0x00000100;
const uint Infinite = 0xffffffff;
@@ -334,11 +450,14 @@ public static class AlookAgentJob {
)) throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateProcessW failed");
bool assigned = false;
try {
+ long createdTicks = String.IsNullOrEmpty(traceDirectory) ? 0 : System.Diagnostics.Stopwatch.GetTimestamp();
if (!AssignProcessToJobObject(job, child.Process))
throw new Win32Exception(Marshal.GetLastWin32Error(), "AssignProcessToJobObject failed");
assigned = true;
+ Mark(traceDirectory, "native-created", child.ProcessId, createdTicks);
if (ResumeThread(child.Thread) == uint.MaxValue)
throw new Win32Exception(Marshal.GetLastWin32Error(), "ResumeThread failed");
+ Mark(traceDirectory, "native-resumed", child.ProcessId, 0);
if (WaitForSingleObject(child.Process, Infinite) == WaitFailed)
throw new Win32Exception(Marshal.GetLastWin32Error(), "WaitForSingleObject failed");
uint exitCode;
@@ -368,13 +487,17 @@ public static class AlookAgentJob {
}
}
"@
-$exitCode = [AlookAgentJob]::RunNode($env:ALOOK_WINDOWS_JOB_NODE, $env:ALOOK_WINDOWS_JOB_RUNNER)
+[AlookAgentJob]::Mark($traceDirectory, 'add-type-ready', 0, 0)
+foreach ($entry in $jobEnvironment.GetEnumerator()) {
+ [Environment]::SetEnvironmentVariable([string]$entry.Key, [string]$entry.Value)
+}
+$exitCode = [AlookAgentJob]::RunNode($env:ALOOK_WINDOWS_JOB_NODE, $env:ALOOK_WINDOWS_JOB_RUNNER, $traceDirectory)
exit $exitCode
`;
interface AgentSpawnOptions {
cwd: string;
- env: NodeJS.ProcessEnv;
+ env?: NodeJS.ProcessEnv;
/** Run through a shell — needed on Windows for `.cmd`/`.bat` shims. */
shell?: boolean;
/**
@@ -383,6 +506,7 @@ interface AgentSpawnOptions {
* stdout/stderr stay piped regardless for protocol output and diagnostics.
*/
stdin?: "pipe" | "ignore";
+ traceDirectory?: string;
}
/**
@@ -395,6 +519,13 @@ interface AgentSpawnOptions {
*/
export function spawnAgentProcess(command: string, args: string[], opts: AgentSpawnOptions): ChildProcess {
if (!isPosix) {
+ const encodedTargetEnv = Buffer.from(JSON.stringify(copyWindowsEnvironment(opts.env ?? process.env))).toString("base64");
+ const environment = copyWindowsEnvironment(process.env);
+ let chunks = 0;
+ for (let offset = 0; offset < encodedTargetEnv.length; offset += WINDOWS_JOB_ENV_CHUNK_SIZE) {
+ environment[`${WINDOWS_JOB_ENV_CHUNK_PREFIX}${chunks++}`] = encodedTargetEnv.slice(offset, offset + WINDOWS_JOB_ENV_CHUNK_SIZE);
+ }
+ const payload = Buffer.from(JSON.stringify({ command: opts.shell ? quoteWindowsShimCommand(command) : command, args, cwd: opts.cwd, shell: opts.shell ? (process.env.comspec || "cmd.exe") : false })).toString("base64");
const stdin = opts.stdin ?? "pipe";
const stdinProxy = stdin === "pipe" ? new PassThrough() : undefined;
const stdinPipe = stdinProxy
@@ -418,11 +549,13 @@ export function spawnAgentProcess(command: string, args: string[], opts: AgentSp
stdinServer?.once("error", () => stdinProxy?.destroy());
if (stdinPipe) stdinServer?.listen(stdinPipe);
const env: NodeJS.ProcessEnv = {
- ...opts.env,
+ ...environment,
[WINDOWS_JOB_NODE_ENV]: process.execPath,
- [WINDOWS_JOB_PAYLOAD_ENV]: Buffer.from(JSON.stringify({ command: opts.shell ? quoteWindowsShimCommand(command) : command, args, cwd: opts.cwd, shell: opts.shell ?? false })).toString("base64"),
+ [WINDOWS_JOB_PAYLOAD_ENV]: payload,
[WINDOWS_JOB_RUNNER_ENV]: WINDOWS_JOB_RUNNER,
- ...(stdinPipe ? { [WINDOWS_JOB_STDIN_PIPE_ENV]: stdinPipe } : {}),
+ [WINDOWS_JOB_TRACE_ENV]: opts.traceDirectory,
+ [WINDOWS_JOB_STDIN_PIPE_ENV]: stdinPipe,
+ [WINDOWS_JOB_ENV_COUNT_ENV]: String(chunks),
};
let proc: ChildProcess;
try {