Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(daemon): support Windows npm runtimes and injected CLI callbacks (#895)

Gustavo Ye5d06ce2edf98
diff --git a/.github/workflows/windows-runtime.yml b/.github/workflows/windows-runtime.yml
new file mode 100644
index 000000000..bb412c5c6
--- /dev/null
+++ b/.github/workflows/windows-runtime.yml
@@ -0,0 +1,93 @@
+name: Windows npm runtimes
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - src/daemon/agent-driver/**
+ - .github/workflows/windows-runtime.yml
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: windows-npm-runtimes-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ native-node24:
+ name: Windows npm runtime QA (Node 24)
+ runs-on: windows-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020
+ with:
+ node-version: 24
+ cache: pnpm
+ - run: pnpm install --frozen-lockfile
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
+ with:
+ bun-version: 1.3.11
+ - name: Pack and install the exact candidate agent CLI
+ shell: pwsh
+ run: |
+ $packDir = Join-Path $env:RUNNER_TEMP 'Alook candidate pack'
+ $installDir = Join-Path $env:RUNNER_TEMP 'Alook candidate install'
+ New-Item -ItemType Directory -Force $packDir | Out-Null
+ pnpm --filter @alook/daemon pack --pack-destination "$packDir"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ $archive = (Get-ChildItem $packDir -Filter '*.tgz').FullName
+ npm install --ignore-scripts --no-audit --no-fund --prefix "$installDir" "$archive"
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ $cliPath = Join-Path $installDir 'node_modules/@alook/daemon/dist/cli/index.js'
+ if (-not (Test-Path $cliPath)) { throw 'Missing candidate CLI' }
+ "ALOOK_NATIVE_CLI_PATH=$cliPath" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ "ALOOK_NATIVE_BASH_PATH=C:/Program Files/Git/bin/bash.exe" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ Get-FileHash $archive, $cliPath -Algorithm SHA256 | Format-Table
+ - name: Exercise the native agent callback CLI
+ run: pnpm --filter @alook/agent-driver exec vitest run src/internal/cliLink.windows.test.ts --no-file-parallelism
+ - name: Install isolated native providers in a space-containing prefix
+ shell: pwsh
+ run: |
+ $qaPrefix = Join-Path $env:RUNNER_TEMP 'Alook npm QA'
+ npm install --global --prefix "$qaPrefix" @openai/[email protected] [email protected] @anthropic-ai/[email protected]
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ npm install --global --ignore-scripts --prefix "$qaPrefix" @earendil-works/[email protected]
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
+ "ALOOK_NATIVE_NPM_PREFIX=$qaPrefix" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ - name: Install official native Cursor and Grok binaries
+ shell: pwsh
+ run: |
+ $qaPrefix = $env:ALOOK_NATIVE_NPM_PREFIX
+ $cursorVersion = '2026.10.01-e373342'
+ $cursorVersions = Join-Path $qaPrefix 'versions'
+ New-Item -ItemType Directory -Force $cursorVersions | Out-Null
+ $cursorZip = Join-Path $env:RUNNER_TEMP 'cursor-cli.zip'
+ Invoke-WebRequest "https://downloads.cursor.com/lab/$cursorVersion/windows/x64/agent-cli-package.zip" -OutFile $cursorZip
+ Expand-Archive $cursorZip -DestinationPath $cursorVersions
+ Rename-Item (Join-Path $cursorVersions 'dist-package') $cursorVersion
+ Get-ChildItem (Join-Path $cursorVersions $cursorVersion) -Filter 'cursor-agent*' | Copy-Item -Destination $qaPrefix
+ Invoke-WebRequest 'https://x.ai/cli/grok-1.0.50-windows-x86_64.exe' -OutFile (Join-Path $qaPrefix 'grok.exe')
+ - name: Fetch the official Claude native distribution
+ shell: pwsh
+ run: |
+ $releaseBase = 'https://downloads.claude.ai/claude-code-releases/2.1.295'
+ $manifest = Invoke-RestMethod "$releaseBase/manifest.json"
+ $nativeClaude = Join-Path $env:RUNNER_TEMP 'claude-native.exe'
+ Invoke-WebRequest "$releaseBase/win32-x64/claude.exe" -OutFile $nativeClaude
+ $checksum = (Get-FileHash $nativeClaude -Algorithm SHA256).Hash.ToLower()
+ if ($checksum -ne $manifest.platforms.'win32-x64'.checksum) { throw 'Claude native checksum mismatch' }
+ Write-Output "Claude native SHA256: $checksum"
+ "ALOOK_NATIVE_CLAUDE_PATH=$nativeClaude" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ - name: Install the Google Antigravity native ACP server
+ shell: pwsh
+ run: |
+ $agyZip = Join-Path $env:RUNNER_TEMP 'agy-acp-server.zip'
+ Invoke-WebRequest 'https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.3.0-windows-x86_64.zip' -OutFile $agyZip
+ Expand-Archive $agyZip -DestinationPath $env:ALOOK_NATIVE_NPM_PREFIX -Force
+ if (-not (Test-Path (Join-Path $env:ALOOK_NATIVE_NPM_PREFIX 'agy_acp_server.exe'))) { throw 'Missing Antigravity ACP entry' }
+ - name: Exercise real detection, persistent startup and cleanup
+ run: pnpm --filter @alook/agent-driver exec vitest run src/internal/probe.test.ts src/internal/probe.windows.test.ts src/internal/killTree.windows-errors.test.ts src/adapters/antigravity/index.test.ts --no-file-parallelism
diff --git a/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts b/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts
index 09e4e0c24..81ec27de4 100644
--- a/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/antigravity/index.test.ts
@@ -383,3 +383,28 @@ it("delegates driver discovery to the noninteractive native probe", async () =>
try { expect(await new AntigravityDriver().probe("fixture-native")).toEqual({ status: "healthy", version: "fixture" }); expect(probe).toHaveBeenCalledWith("fixture-native"); }
finally { probe.mockRestore(); }
});
+
+
+describe("Antigravity Windows cold start budget", () => {
+ it.each(["win32", "darwin"] as const)("bounds a 16-second native initialize on %s", async (platform) => {
+ const h = setup();
+ const platformSpy = vi.spyOn(process, "platform", "get").mockReturnValue(platform);
+ vi.useFakeTimers();
+ h.proc.stdin.removeAllListeners("data");
+ h.proc.stdin.on("data", chunk => {
+ const message = JSON.parse(String(chunk));
+ if (message.method === "initialize") setTimeout(() => h.emit({ id: message.id, result: {
+ protocolVersion: 1, agentInfo: { name: "antigravity-acp", version: "1.3.0" }, agentCapabilities: { loadSession: true },
+ } }), 16_000);
+ if (message.method === "session/new") h.emit({ id: message.id, error: { code: -32000, message: "Authentication required" } });
+ });
+ try {
+ const probe = probeAntigravity("/custom/agy_acp_server.par", { cacheDirectory: h.directory, spawn: (() => h.proc) as never, cleanup: async () => { h.proc.kill(); } });
+ await vi.advanceTimersByTimeAsync(16_100);
+ expect(await probe).toMatchObject(platform === "win32" ? { status: "healthy", version: "1.3.0" } : { status: "unhealthy", lastError: "antigravity_acp_timeout" });
+ } finally {
+ platformSpy.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/antigravity/probe.ts b/src/daemon/agent-driver/src/adapters/antigravity/probe.ts
index 4c0f57b3a..4eb57c721 100644
--- a/src/daemon/agent-driver/src/adapters/antigravity/probe.ts
+++ b/src/daemon/agent-driver/src/adapters/antigravity/probe.ts
@@ -62,7 +62,7 @@ export async function probeAntigravity(command?: string, options: ProbeOptions =
void cleanup(proc).then(() => resolve(result), () => resolve({ status: "unhealthy", lastError: "antigravity_acp_cleanup_failed" }));
};
const fail = (lastError: string) => finish({ status: "unhealthy", lastError });
- const timer = setTimeout(() => fail("antigravity_acp_timeout"), options.timeoutMs ?? 10_000);
+ const timer = setTimeout(() => fail("antigravity_acp_timeout"), options.timeoutMs ?? (process.platform === "win32" ? 30_000 : 10_000));
const write = (value: unknown) => {
try {
if (!proc.stdin || proc.stdin.destroyed || proc.stdin.writableEnded || proc.stdin.writable === false) {
diff --git a/src/daemon/agent-driver/src/internal/cliLink.test.ts b/src/daemon/agent-driver/src/internal/cliLink.test.ts
index f18be7a91..c2f071388 100644
--- a/src/daemon/agent-driver/src/internal/cliLink.test.ts
+++ b/src/daemon/agent-driver/src/internal/cliLink.test.ts
@@ -2,7 +2,7 @@ import { describe, it, expect, afterEach } from "vitest";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
-import { writeCliLink } from "./cliLink.js";
+import { writeCliLink, writeWindowsBashEnv } from "./cliLink.js";
const tmpDirs: string[] = [];
function mkTmp(): string {
@@ -46,6 +46,14 @@ describe("writeCliLink (POSIX symlink)", () => {
});
describe("writeCliLink (Windows .cmd shim)", () => {
+ it.each(["index.js", "index.cjs", "index.MJS"])("runs %s with the daemon's Node executable", filename => {
+ const stateDir = mkTmp();
+ const host = `C:\\host with spaces\\${filename}`;
+ const binDir = writeCliLink(stateDir, "alook", host, "win32");
+ expect(fs.readFileSync(path.join(binDir, "alook.cmd"), "utf8"))
+ .toBe(`@echo off\r\n"${process.execPath}" "${host}" %*\r\n`);
+ });
+
it("writes a .cmd shim forwarding to hostCliPath", () => {
const stateDir = mkTmp();
const host = "C:\\host\\alook.exe";
@@ -54,8 +62,24 @@ describe("writeCliLink (Windows .cmd shim)", () => {
expect(fs.existsSync(cmd)).toBe(true);
const body = fs.readFileSync(cmd, "utf8");
expect(body).toContain(`"${host}" %*`);
- // No bare POSIX symlink on Windows.
- expect(fs.existsSync(path.join(binDir, "alook"))).toBe(false);
+ expect(fs.readFileSync(path.join(binDir, "alook"), "utf8"))
+ .toBe("#!/bin/sh\nMSYS2_ARG_CONV_EXCL='*' exec 'C:/host/alook.exe' \"$@\"\n");
+ expect(fs.lstatSync(path.join(binDir, "alook")).isSymbolicLink()).toBe(false);
+ });
+
+ it("quotes shell metacharacters in the Bash launcher without changing arguments", () => {
+ const binDir = writeCliLink(mkTmp(), "house", "C:\\host's $directory\\index.js", "win32");
+ const body = fs.readFileSync(path.join(binDir, "house"), "utf8");
+ expect(body).toContain("'C:/host'\\''s $directory/index.js' \"$@\"");
+ });
+
+ it("sources an existing Bash startup file before selecting the shell's launcher", () => {
+ const binDir = path.join(mkTmp(), "bin");
+ fs.mkdirSync(binDir);
+ const startup = writeWindowsBashEnv(binDir, "house", "HOUSE", "C:\\user's home\\startup.sh");
+ expect(fs.readFileSync(startup, "utf8")).toBe(`. 'C:/user'\\''s home/startup.sh'\nexport 'HOUSE_CLI=${binDir.replaceAll("\\", "/")}/house'\n`);
+ expect(() => writeWindowsBashEnv(binDir, "house", "HOUSE", startup)).not.toThrow();
+ expect(fs.readFileSync(startup, "utf8")).not.toContain(`. '${startup}'`);
});
it("creates no shim in mock mode on Windows", () => {
diff --git a/src/daemon/agent-driver/src/internal/cliLink.ts b/src/daemon/agent-driver/src/internal/cliLink.ts
index 76731bbdd..323a4610b 100644
--- a/src/daemon/agent-driver/src/internal/cliLink.ts
+++ b/src/daemon/agent-driver/src/internal/cliLink.ts
@@ -12,8 +12,8 @@
* ship its own self-exec wrapper as hostCliPath.
* - Windows: a symlink/hardlink named `.exe` pointing at a `.js` is NOT a valid
* executable (PE-format mismatch), so for interpreted CLIs we keep a `.cmd`
- * shim. This is the ONLY place a generated wrapper survives, purely due to
- * the platform.
+ * shim for cmd/PowerShell and a POSIX launcher for Git Bash. Only the Bash
+ * launcher disables MSYS argument conversion, preserving literal CLI refs.
*
* With no hostCliPath (the mock), neither is created — `cliName` stays
* unresolved and invoking it fails with command-not-found (the mock never calls
@@ -24,6 +24,19 @@
import * as fs from "fs";
import * as path from "path";
+function shellQuote(value: string): string {
+ return `'${value.replaceAll("'", "'\\''")}'`;
+}
+
+export function writeWindowsBashEnv(binDir: string, cliName: string, envPrefix: string, previous: string | undefined): string {
+ const startup = path.join(binDir, `${cliName}.bash-env`).replaceAll("\\", "/");
+ const envValue = startup.replace(/[$`]/g, "\\$&");
+ const source = previous && previous !== envValue && previous.replaceAll("\\", "/") !== startup
+ ? `. ${shellQuote(previous.replaceAll("\\", "/"))}\n` : "";
+ fs.writeFileSync(startup, source + `export ${shellQuote(`${envPrefix}_CLI=${path.join(binDir, cliName).replaceAll("\\", "/")}`)}\n`);
+ return envValue;
+}
+
/**
* Create the per-launch `bin` dir and the link/shim for `cliName`. Returns the
* bin dir to prepend to PATH. Idempotent: safe to call again on resume/restart.
@@ -41,11 +54,16 @@ export function writeCliLink(
if (!hostCliPath) return binDir;
if (platform === "win32") {
- // .cmd shim — the only surviving wrapper, and only because a Windows link
- // named .exe pointing at a .js wouldn't be a valid executable.
const cmdFile = path.join(binDir, `${cliName}.cmd`);
- const body = `@echo off\r\n"${hostCliPath}" %*\r\n`;
+ const executable = /\.(?:c|m)?js$/i.test(hostCliPath)
+ ? `"${process.execPath}" "${hostCliPath}"`
+ : `"${hostCliPath}"`;
+ const body = `@echo off\r\n${executable} %*\r\n`;
fs.writeFileSync(cmdFile, body); // overwrite is fine (idempotent)
+ const bashExecutable = /\.(?:c|m)?js$/i.test(hostCliPath)
+ ? `${shellQuote(process.execPath.replaceAll("\\", "/"))} ${shellQuote(hostCliPath.replaceAll("\\", "/"))}`
+ : shellQuote(hostCliPath.replaceAll("\\", "/"));
+ fs.writeFileSync(path.join(binDir, cliName), `#!/bin/sh\nMSYS2_ARG_CONV_EXCL='*' exec ${bashExecutable} "$@"\n`, { mode: 0o755 });
return binDir;
}
diff --git a/src/daemon/agent-driver/src/internal/cliLink.windows.test.ts b/src/daemon/agent-driver/src/internal/cliLink.windows.test.ts
new file mode 100644
index 000000000..4aaf02618
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/cliLink.windows.test.ts
@@ -0,0 +1,234 @@
+import { once } from "node:events";
+import { createServer } from "node:http";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { fakeLaunchContext, fakePrepared } from "../testing/adapter-fixture.js";
+import { prepareCliTransport } from "./cliTransport.js";
+import { writeCliLink } from "./cliLink.js";
+import { isAlive, killProcessTree, spawnAgentProcess } from "./killTree.js";
+
+async function invoke(command: string, args: string[], cwd: string, shell: boolean,
+ options: { env?: NodeJS.ProcessEnv; stdin?: string } = {}) {
+ const child = spawnAgentProcess(command, args, { cwd, env: options.env ?? process.env, shell });
+ let stdout = "";
+ let stderr = "";
+ child.stdout?.on("data", chunk => { stdout += String(chunk); });
+ child.stderr?.on("data", chunk => { stderr += String(chunk); });
+ const closed = once(child, "close");
+ if (options.stdin !== undefined) child.stdin?.end(options.stdin, "utf8");
+ const timeout = setTimeout(() => { void killProcessTree(child.pid!).catch(() => {}); }, 30_000);
+ try {
+ await closed;
+ return { stdout: stdout.trim(), stderr: stderr.trim(), code: child.exitCode };
+ } finally {
+ clearTimeout(timeout);
+ if (child.pid && isAlive(child.pid)) await killProcessTree(child.pid);
+ }
+}
+
+describe.skipIf(process.platform !== "win32")("native Windows injected Node CLI", () => {
+ it("executes a Node JS CLI through both its wrapper and actual transport env", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "alook Node CLI with spaces-"));
+ const host = join(directory, "index.js");
+ const marker = "alook-native-node-cli-ready";
+ writeFileSync(host, `#!/usr/bin/env node\nconsole.log(JSON.stringify({ marker: ${JSON.stringify(marker)}, args: process.argv.slice(2) }));\n`);
+ const expected = JSON.stringify({ marker, args: ["--help"] });
+ try {
+ const control = await invoke(process.execPath, [host, "--help"], directory, false);
+ console.log(JSON.stringify({ stage: "node-control", ...control }));
+ expect(control.stdout).toBe(expected);
+ expect(control.code).toBe(0);
+ const bin = writeCliLink(join(directory, "wrapper"), "alook", host);
+ const viaWrapper = await invoke(join(bin, "alook.cmd"), ["--help"], directory, true);
+ console.log(JSON.stringify({ stage: "generated-wrapper", ...viaWrapper }));
+ expect.soft(viaWrapper.stdout).toBe(expected);
+ expect.soft(viaWrapper.code).toBe(0);
+ const ctx = fakeLaunchContext("codex", directory, {
+ prepared: {
+ ...fakePrepared({ base: process.env, platformProtected: { ALOOK_CLI: host }, networkProtected: { PATH: process.env.PATH } }),
+ executablePath: host,
+ },
+ });
+ const { spawnEnv } = await prepareCliTransport(ctx);
+ expect.soft(spawnEnv.ALOOK_CLI).toMatch(/\.cmd$/i);
+ expect.soft(spawnEnv.ALOOK_CLI).not.toContain("\\");
+ const injected = await invoke(spawnEnv.ALOOK_CLI!, ["--help"], directory, true, { env: spawnEnv });
+ console.log(JSON.stringify({ stage: "injected-cli", ...injected }));
+ expect.soft(injected.stdout).toBe(expected);
+ expect.soft(injected.code).toBe(0);
+ } finally {
+ rmSync(directory, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
+ }
+ }, 120_000);
+
+ it("preserves UTF-8 stdin and exit codes through cmd and PowerShell", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "alook Windows stdin with spaces-"));
+ const host = join(directory, "index.cjs");
+ const message = "Windows 中文回复✓ nonce-cli-165";
+ writeFileSync(host, "if(process.argv.includes('--fail'))process.exit(23);console.log(require('node:fs').readFileSync(0,'utf8').trimEnd());\n");
+ try {
+ const ctx = fakeLaunchContext("codex", directory, {
+ prepared: {
+ ...fakePrepared({ base: process.env, platformProtected: { ALOOK_CLI: host } }),
+ executablePath: host,
+ },
+ });
+ const { spawnEnv } = await prepareCliTransport(ctx);
+ const cmd = await invoke(spawnEnv.ALOOK_CLI!, ["--stdin"], directory, true, { env: spawnEnv, stdin: message });
+ console.log(JSON.stringify({ stage: "cmd-utf8-stdin", ...cmd }));
+ expect(cmd.stdout).toBe(message);
+ expect(cmd.code).toBe(0);
+ const script = [
+ "$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)",
+ "@'", message, "'@ | & $env:ALOOK_CLI --stdin",
+ "exit $LASTEXITCODE",
+ ].join("\r\n");
+ const powershell = await invoke("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
+ Buffer.from(script, "utf16le").toString("base64")], directory, false, { env: spawnEnv });
+ console.log(JSON.stringify({ stage: "powershell-utf8-stdin", ...powershell }));
+ expect(powershell.stdout).toBe(message);
+ expect(powershell.code).toBe(0);
+ const failed = await invoke(spawnEnv.ALOOK_CLI!, ["--fail"], directory, true, { env: spawnEnv });
+ expect(failed.code).toBe(23);
+ if (process.env.ALOOK_NATIVE_BASH_PATH) {
+ const bashFailed = await invoke(process.env.ALOOK_NATIVE_BASH_PATH, ["--noprofile", "--norc", "-c", '"$ALOOK_CLI" --fail'], directory, false, { env: spawnEnv });
+ expect(bashFailed.code).toBe(23);
+ }
+ } finally {
+ rmSync(directory, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
+ }
+ }, 120_000);
+
+
+});
+
+describe.skipIf(process.platform === "win32")("Windows Bash launcher logic on POSIX", () => {
+ it("preserves startup, literal arguments and CLI-local environment through the public process authority", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "alook Bash's $path-"));
+ try {
+ const host = join(directory, "host.cjs");
+ const startup = join(directory, "user startup.sh");
+ writeFileSync(host, "console.log(JSON.stringify({ args: process.argv.slice(2), exclusion: process.env.MSYS2_ARG_CONV_EXCL, startup: process.env.USER_STARTUP_MARKER }));\n");
+ writeFileSync(startup, "export USER_STARTUP_MARKER=loaded\n");
+ const ctx = fakeLaunchContext("codex", directory, {
+ prepared: { ...fakePrepared({ base: { ...process.env, BASH_ENV: startup } }), executablePath: host },
+ });
+ const { spawnEnv } = await prepareCliTransport(ctx, {}, undefined, "win32");
+ const result = await invoke("/bin/bash", ["--noprofile", "--norc", "-c", '"$ALOOK_CLI" --target "/server#0042/general" "中文✓"; test "${MSYS2_ARG_CONV_EXCL-unset}" = unset'], directory, false, { env: { ...spawnEnv, MSYS2_ARG_CONV_EXCL: undefined } });
+ expect(JSON.parse(result.stdout)).toEqual({ args: ["--target", "/server#0042/general", "中文✓"], exclusion: "*", startup: "loaded" });
+ expect(result.code).toBe(0);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
+});
+
+describe.skipIf(!process.env.ALOOK_NATIVE_CLI_PATH)("installed host CLI callback", () => {
+ it("pulls, acknowledges and sends literal stdin through the injected product CLI", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "alook candidate callback with spaces-"));
+ const channel = "/windows-qa#0042/general";
+ const requests: Array<{ method: string | undefined; path: string | undefined; body: Record<string, unknown>; authorized: boolean }> = [];
+ const incoming = { seq: "#1", channel, sender: "@qa#0042", content: { text: "callback-inbox-nonce-165" }, time: "2026-10-09T00:00:00Z" };
+ let sentCount = 0;
+ const server = createServer(async (req, res) => {
+ try {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}") as Record<string, unknown>;
+ const authorized = req.headers.authorization === "Bearer vch_windows_cli_fixture";
+ requests.push({ method: req.method, path: req.url, body, authorized });
+ res.setHeader("content-type", "application/json");
+ if (!authorized) { res.writeHead(401).end(JSON.stringify({ error: "fixture authorization missing" })); return; }
+ if (req.url === "/api/community/users/me/inbox/pull") {
+ res.end(JSON.stringify({ messages: [incoming], hasMore: false, markedCount: 0 }));
+ } else if (req.url === "/api/community/users/me/inbox/ack") {
+ res.end(JSON.stringify({ applied: body.cursors, failed: [] }));
+ } else if (req.url === "/api/community/channels/resolve/messages") {
+ sentCount += 1;
+ res.end(JSON.stringify({ state: "sent", message: { ...incoming, seq: `#${sentCount + 1}`, content: body.content } }));
+ } else if (req.url === "/__alook/local/message-reminder") {
+ res.end(JSON.stringify({ armed: false, reason: "disabled" }));
+ } else {
+ res.writeHead(404).end(JSON.stringify({ error: "unexpected fixture route" }));
+ }
+ } catch {
+ res.writeHead(500).end(JSON.stringify({ error: "invalid fixture request" }));
+ }
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ try {
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("missing fixture TCP port");
+ const voucherFile = join(directory, "voucher.txt");
+ writeFileSync(voucherFile, "vch_windows_cli_fixture", { mode: 0o600 });
+ const host = process.env.ALOOK_NATIVE_CLI_PATH!;
+ const originalBashEnv = join(directory, "user startup.sh");
+ writeFileSync(originalBashEnv, "export USER_STARTUP_MARKER=original-bash-env-loaded\n");
+ const ctx = fakeLaunchContext("codex", directory, {
+ prepared: {
+ ...fakePrepared({
+ base: { ...process.env, BASH_ENV: originalBashEnv.replaceAll("\\", "/") },
+ platformProtected: { ALOOK_ID: "agent_cli_fixture", ALOOK_CLI: host },
+ networkProtected: { ALOOK_PROXY_URL: `http://127.0.0.1:${address.port}` },
+ credentialSensitive: { ALOOK_PROXY_TOKEN_FILE: voucherFile },
+ }),
+ executablePath: host,
+ },
+ });
+ const { spawnEnv } = await prepareCliTransport(ctx);
+ const windows = process.platform === "win32";
+ const pull = await invoke(spawnEnv.ALOOK_CLI!, ["inbox", "pull"], directory, windows, { env: spawnEnv });
+ console.log(JSON.stringify({ stage: "candidate-inbox-pull", ...pull }));
+ expect(JSON.parse(pull.stdout).success.messages[0].content.text).toBe(incoming.content.text);
+ expect(JSON.parse(pull.stdout).success.acked).toBe(1);
+ expect(pull.code).toBe(0);
+ const message = "Windows 中文回复✓ nonce-product-cli-165";
+ const sendArgs = ["message", "send", "--target", channel, "--reply", "1", "--stdin", "--remind-after", "0"];
+ const send = await invoke(spawnEnv.ALOOK_CLI!, sendArgs, directory, windows, { env: spawnEnv, stdin: message });
+ console.log(JSON.stringify({ stage: "candidate-stdin-send", ...send }));
+ expect(JSON.parse(send.stdout).success.sent).toBe(`${channel}#2`);
+ expect(send.code).toBe(0);
+ const expectedBodies = [message];
+ if (windows) {
+ const script = "$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\r\n@'\r\n" + message +
+ `\r\n'@ | & $env:ALOOK_CLI message send --target '${channel}' --reply 1 --stdin --remind-after 0\r\nexit $LASTEXITCODE`;
+ const powershell = await invoke("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand",
+ Buffer.from(script, "utf16le").toString("base64")], directory, false, { env: spawnEnv });
+ console.log(JSON.stringify({ stage: "candidate-powershell-send", ...powershell }));
+ expect(JSON.parse(powershell.stdout).success.sent).toBe(`${channel}#3`);
+ expect(powershell.code).toBe(0);
+ expectedBodies.push(message + "\r\n");
+ const bashPath = process.env.ALOOK_NATIVE_BASH_PATH;
+ expect(bashPath).toBeTruthy();
+ const bashScript = join(directory, "send.sh");
+ const nodeScript = join(directory, "native-path-control.cjs");
+ const controlFile = join(directory, "native-path-control.json");
+ writeFileSync(nodeScript, "require('node:fs').writeFileSync(process.argv[3], JSON.stringify({ arg: process.argv[2], startup: process.env.USER_STARTUP_MARKER, exclusion: process.env.MSYS2_ARG_CONV_EXCL ?? null }));\n");
+ writeFileSync(bashScript, `"$ALOOK_CLI" message send --target '${channel}' --reply 1 --stdin --remind-after 0 <<'ALOOK_CLI_TEST_165'\n${message}\nALOOK_CLI_TEST_165\nstatus=$?\n'${process.execPath.replaceAll("\\", "/")}' '${nodeScript.replaceAll("\\", "/")}' /ordinary/path '${controlFile.replaceAll("\\", "/")}'\nexit "$status"\n`);
+ const bash = await invoke(bashPath!, ["--noprofile", "--norc", bashScript.replaceAll("\\", "/")], directory, false, { env: spawnEnv });
+ console.log(JSON.stringify({ stage: "candidate-git-bash-send", ...bash }));
+ expect(JSON.parse(bash.stdout).success.sent).toBe(`${channel}#4`);
+ expect(bash.code).toBe(0);
+ const control = JSON.parse(readFileSync(controlFile, "utf8"));
+ expect(control.startup).toBe("original-bash-env-loaded");
+ expect(control.exclusion).toBe(process.env.MSYS2_ARG_CONV_EXCL ?? null);
+ expect(control.arg.replaceAll("\\", "/")).toMatch(/^[A-Za-z]:\/.*\/ordinary\/path$/);
+ expectedBodies.push(message + "\n");
+ }
+ const sends = requests.filter(req => req.path === "/api/community/channels/resolve/messages");
+ expect(sends.map(req => req.body.content)).toEqual(expectedBodies.map(text => ({ text })));
+ expect(sends.every(req => req.body.channel === channel && req.body.replyToSeq === 1 && typeof req.body.nonce === "string")).toBe(true);
+ expect(requests.every(req => req.authorized && !("agentId" in req.body))).toBe(true);
+ expect(requests.filter(req => req.path === "/api/community/users/me/inbox/ack").map(req => req.body.cursors))
+ .toEqual([[{ channel, seq: 1 }]]);
+ expect(requests).toHaveLength(2 + expectedBodies.length * 2);
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) => server.close(err => err ? reject(err) : resolve()));
+ rmSync(directory, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
+ }
+ }, 120_000);
+});
diff --git a/src/daemon/agent-driver/src/internal/cliTransport.test.ts b/src/daemon/agent-driver/src/internal/cliTransport.test.ts
index e3efab87b..cde389449 100644
--- a/src/daemon/agent-driver/src/internal/cliTransport.test.ts
+++ b/src/daemon/agent-driver/src/internal/cliTransport.test.ts
@@ -38,6 +38,48 @@ function baseCtx(workingDirectory: string, overrides: Partial<AdapterLaunchConte
}
describe("prepareCliTransport", () => {
+ it("protects the runnable Windows launcher using the configured CLI prefix", async () => {
+ const wd = mkTmp();
+ const host = path.join(wd, "host with spaces.js");
+ const ctx = baseCtx(wd, {
+ prepared: {
+ ...fakePrepared({ platformProtected: { HOUSE_CLI: host } }),
+ executablePath: host,
+ },
+ });
+ const cli: CliTransportConfig = { cliName: "house", envPrefix: "HOUSE", stateDirName: ".house" };
+ const { stateDir, spawnEnv } = await prepareCliTransport(ctx, { HOUSE_CLI: "driver-override" }, cli, "win32");
+ expect(spawnEnv.HOUSE_CLI).toBe(path.join(stateDir, "bin", "house.cmd").replaceAll("\\", "/"));
+ expect(fs.existsSync(spawnEnv.HOUSE_CLI!)).toBe(true);
+ expect(spawnEnv.BASH_ENV).toBe(path.join(stateDir, "bin", "house.bash-env").replaceAll("\\", "/"));
+ expect(spawnEnv.MSYS2_ARG_CONV_EXCL).toBeUndefined();
+ });
+
+ it("retains the selected user's Bash startup file without globally disabling conversion", async () => {
+ const wd = mkTmp();
+ const ctx = baseCtx(wd, {
+ config: { runtimeConfig: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default", environment: { BASH_ENV: "C:/user startup.sh" } } },
+ prepared: { ...fakePrepared({ base: { BASH_ENV: "C:/base.sh", MSYS2_ARG_CONV_EXCL: "--existing=" } }), executablePath: "C:/host.js" },
+ });
+ const { spawnEnv } = await prepareCliTransport(ctx, {}, undefined, "win32");
+ expect(fs.readFileSync(spawnEnv.BASH_ENV!, "utf8")).toContain(". 'C:/user startup.sh'\n");
+ expect(spawnEnv.MSYS2_ARG_CONV_EXCL).toBe("--existing=");
+ });
+
+ it("preserves the POSIX CLI contract when the prepared host is a JS entrypoint", async () => {
+ const wd = mkTmp();
+ const host = path.join(wd, "index.js");
+ const ctx = baseCtx(wd, {
+ prepared: {
+ ...fakePrepared({ platformProtected: { ALOOK_CLI: host } }),
+ executablePath: host,
+ },
+ });
+ const { spawnEnv } = await prepareCliTransport(ctx, {}, undefined, "linux");
+ expect(spawnEnv.ALOOK_CLI).toBe(host);
+ expect(spawnEnv.BASH_ENV).toBeUndefined();
+ });
+
it("prepends the per-launch bin dir to PATH", async () => {
const { spawnEnv, stateDir } = await prepareCliTransport(baseCtx(mkTmp()), {}, undefined, "linux");
expect((spawnEnv.PATH ?? "").split(path.delimiter)[0]).toBe(path.join(stateDir, "bin"));
diff --git a/src/daemon/agent-driver/src/internal/cliTransport.ts b/src/daemon/agent-driver/src/internal/cliTransport.ts
index 403e5b170..f3fe5e93e 100644
--- a/src/daemon/agent-driver/src/internal/cliTransport.ts
+++ b/src/daemon/agent-driver/src/internal/cliTransport.ts
@@ -30,7 +30,7 @@ import * as fs from "fs";
import * as path from "path";
import type { AdapterLaunchContext } from "./adapter.js";
import { resolveLaunchFieldsOrDefault } from "./config.js";
-import { writeCliLink } from "./cliLink.js";
+import { writeCliLink, writeWindowsBashEnv } from "./cliLink.js";
import { mergeEnvLayers, type EnvLayer } from "./spawnEnv.js";
interface PreparedCliTransport {
@@ -129,7 +129,14 @@ export async function prepareCliTransport(
{
name: "platformProtected",
precedence: 40,
- vars: { ...resource.platformProtected, FORCE_COLOR: "0", NO_COLOR: "1" },
+ vars: {
+ ...resource.platformProtected,
+ ...(platform === "win32" && hostCliPath
+ ? { [`${cli.envPrefix}_CLI`]: path.join(binDir, `${cli.cliName}.cmd`).replaceAll("\\", "/") }
+ : {}),
+ FORCE_COLOR: "0",
+ NO_COLOR: "1",
+ },
},
{ name: "runtimeProtected", precedence: 50, vars: resource.runtimeProtected },
{
@@ -146,6 +153,9 @@ export async function prepareCliTransport(
},
];
const { env: spawnEnv } = mergeEnvLayers(resource.base, layers);
+ if (platform === "win32" && hostCliPath) {
+ spawnEnv.BASH_ENV = writeWindowsBashEnv(binDir, cli.cliName, cli.envPrefix, spawnEnv.BASH_ENV);
+ }
const tokenFile = String(resource.credentialSensitive.ALOOK_PROXY_TOKEN_FILE ?? "");
return { stateDir, tokenFile, spawnEnv };
}
diff --git a/src/daemon/agent-driver/src/internal/killTree.ts b/src/daemon/agent-driver/src/internal/killTree.ts
index 128701c21..0bc842456 100644
--- a/src/daemon/agent-driver/src/internal/killTree.ts
+++ b/src/daemon/agent-driver/src/internal/killTree.ts
@@ -22,6 +22,7 @@ import { execFileSync, spawn, type ChildProcess } from "child_process";
import { randomUUID } from "node:crypto";
import { createServer, type Socket } from "node:net";
import { PassThrough } from "node:stream";
+import { quoteWindowsShimCommand } from "./probe.js";
const POLL_MS = 100;
const FORCE_EXIT_WAIT_MS = 2_000;
@@ -420,7 +421,7 @@ export function spawnAgentProcess(command: string, args: string[], opts: AgentSp
const env: NodeJS.ProcessEnv = {
...opts.env,
[WINDOWS_JOB_NODE_ENV]: process.execPath,
- [WINDOWS_JOB_PAYLOAD_ENV]: Buffer.from(JSON.stringify({ command, args, cwd: opts.cwd, shell: opts.shell ?? false })).toString("base64"),
+ [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_RUNNER_ENV]: WINDOWS_JOB_RUNNER,
...(stdinPipe ? { [WINDOWS_JOB_STDIN_PIPE_ENV]: stdinPipe } : {}),
};
@@ -564,6 +565,8 @@ function signalPosixTargets(targets: PosixTreeTargets, signal: NodeJS.Signals):
}
}
+class WindowsTreeExitError extends Error {}
+
/** Stop the live Windows job supervisor and await its forced tree walk. */
function taskkillTree(pid: number): Promise<void> {
return new Promise((resolve, reject) => {
@@ -594,7 +597,7 @@ function taskkillTree(pid: number): Promise<void> {
}
settle(
"reject",
- new Error(`Windows process-tree termination failed (exit=${String(code)}, signal=${String(signal)})`),
+ new WindowsTreeExitError(`Windows process-tree termination failed (exit=${String(code)}, signal=${String(signal)})`),
);
});
});
@@ -607,9 +610,15 @@ async function killWindowsProcessTree(pid: number): Promise<void> {
// actual runtime and make a later tree walk unable to discover it. Windows
// has no safe recursive graceful-signal primitive, so start this immediately;
// the controller separately owns the public force deadline.
- await taskkillTree(pid);
+ let terminationError: WindowsTreeExitError | undefined;
+ try {
+ await taskkillTree(pid);
+ } catch (error) {
+ if (!(error instanceof WindowsTreeExitError)) throw error;
+ terminationError = error;
+ }
await waitForProcessExit(pid, FORCE_EXIT_WAIT_MS);
- if (isAlive(pid)) throw new Error(`Windows process tree ${pid} remained alive after taskkill completed`);
+ if (isAlive(pid)) throw terminationError ?? new Error(`Windows process tree ${pid} remained alive after taskkill completed`);
}
async function waitForProcessExit(pid: number, timeoutMs: number): Promise<void> {
diff --git a/src/daemon/agent-driver/src/internal/killTree.windows-errors.test.ts b/src/daemon/agent-driver/src/internal/killTree.windows-errors.test.ts
index 77de4388f..c9236c492 100644
--- a/src/daemon/agent-driver/src/internal/killTree.windows-errors.test.ts
+++ b/src/daemon/agent-driver/src/internal/killTree.windows-errors.test.ts
@@ -53,6 +53,23 @@ describe.skipIf(process.platform !== "win32")("Windows process-tree error handli
await expect(exitStopping).rejects.toThrow("exit=5");
});
+ it("accepts a nonzero taskkill exit only after the job supervisor has exited", async () => {
+ vi.useFakeTimers();
+ let alive = true;
+ vi.spyOn(process, "kill").mockImplementation(() => {
+ if (alive) return true;
+ throw Object.assign(new Error("not found"), { code: "ESRCH" });
+ });
+ const killer = fakeChild();
+ const module = await importWithSpawn(vi.fn(() => killer));
+ const stopping = module.killProcessTree(4_242);
+ killer.emit("close", 128, null);
+ await vi.advanceTimersByTimeAsync(100);
+ alive = false;
+ await vi.advanceTimersByTimeAsync(100);
+ await expect(stopping).resolves.toBeUndefined();
+ });
+
it("times out taskkill and kills the stuck helper", async () => {
vi.useFakeTimers();
vi.spyOn(process, "kill").mockImplementation(() => true);
diff --git a/src/daemon/agent-driver/src/internal/probe.test.ts b/src/daemon/agent-driver/src/internal/probe.test.ts
index 1bf564272..b20a12b7a 100644
--- a/src/daemon/agent-driver/src/internal/probe.test.ts
+++ b/src/daemon/agent-driver/src/internal/probe.test.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { describe, it, expect, vi } from "vitest";
import { execFileSync } from "child_process";
import {
+ resolveCommandOnPath,
resolveClaudeCommand,
resolveSpawnSpec,
probeCliRuntime,
@@ -78,6 +79,35 @@ describe("resolveSpawnSpec", () => {
});
describe("resolveClaudeCommand", () => {
+ it("finds the Windows native installer entry even when the inherited PATH is stale", () => {
+ const homeDir = mkdtempSync(join(tmpdir(), "claude native home with spaces-"));
+ const platform = vi.spyOn(process, "platform", "get").mockReturnValue("win32");
+ const executable = join(homeDir, ".local", "bin", "claude.exe");
+ mkdirSync(join(executable, ".."), { recursive: true });
+ writeFileSync(executable, "");
+ vi.stubEnv("USERPROFILE", homeDir);
+ vi.stubEnv("HOME", join(homeDir, "different Bash home"));
+ try {
+ expect(resolveClaudeCommand({ which: () => null })).toBe(executable);
+ expect(resolveClaudeCommand({ homeDir, which: () => "C:/selected/claude.cmd" })).toBe("C:/selected/claude.cmd");
+ } finally {
+ platform.mockRestore();
+ vi.unstubAllEnvs();
+ rmSync(homeDir, { recursive: true, force: true });
+ }
+ });
+
+ it("keeps a missing Windows native installation unresolved", () => {
+ const homeDir = mkdtempSync(join(tmpdir(), "claude-missing-home-"));
+ const platform = vi.spyOn(process, "platform", "get").mockReturnValue("win32");
+ try {
+ expect(resolveClaudeCommand({ homeDir, which: () => null })).toBeNull();
+ } finally {
+ platform.mockRestore();
+ rmSync(homeDir, { recursive: true, force: true });
+ }
+ });
+
it("uses the macOS per-user app fallback when PATH has no Claude binary", () => {
const homeDir = mkdtempSync(join(tmpdir(), "claude-probe-home-"));
const platform = vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
@@ -263,3 +293,71 @@ describe("probeCommandOutput", () => {
);
});
});
+
+
+describe("Windows npm PATH resolution", () => {
+ it.each(["codex", "opencode", "claude", "cursor-agent", "grok", "pi"])("probes %s via its .cmd instead of the npm POSIX shim", (binary) => {
+ const platform = vi.spyOn(process, "platform", "get").mockReturnValue("win32");
+ const root = "C:\\Users\\me\\AppData\\Roaming\\npm";
+ const shim = `${root}\\${binary}.cmd`;
+ vi.mocked(execFileSync).mockImplementation((command) => {
+ if (command === "where") return `${root}\\${binary}\r\n${shim}\r\n`;
+ if (command === shim) return "1.2.3\r\n";
+ throw Object.assign(new Error("not a Windows executable"), { code: "EINVAL" });
+ });
+ try {
+ expect(probeCliRuntime(binary)).toEqual({ status: "healthy", version: "1.2.3" });
+ expect(resolveSpawnSpec(binary, ["serve"])).toEqual({ command: shim, args: ["serve"], shell: true });
+ } finally {
+ platform.mockRestore();
+ }
+ });
+
+ it.each(["CMD", "bat", "exe", "com"])("keeps the first runnable .%s entry in PATH order", (extension) => {
+ const platform = vi.spyOn(process, "platform", "get").mockReturnValue("win32");
+ const first = `C:\\first\\runtime.${extension}`;
+ vi.mocked(execFileSync).mockReturnValue(`\r\nC:\\first\\runtime\r\nC:\\first\\runtime.ps1\r\n${first}\r\nC:\\second\\runtime.cmd\r\n`);
+ try {
+ expect(resolveCommandOnPath("runtime")).toBe(first);
+ } finally {
+ platform.mockRestore();
+ }
+ });
+
+ it.each(["", "C:\\npm\\codex\r\nC:\\npm\\codex.ps1\r\n"])("rejects lookup output without a runnable Windows entry: %j", (output) => {
+ const platform = vi.spyOn(process, "platform", "get").mockReturnValue("win32");
+ vi.mocked(execFileSync).mockReturnValue(output);
+ try {
+ expect(probeCliRuntime("codex")).toEqual({ status: "unhealthy", lastError: "not_on_path" });
+ } finally {
+ platform.mockRestore();
+ }
+ });
+
+ it("preserves POSIX extensionless command lookup", () => {
+ const platform = vi.spyOn(process, "platform", "get").mockReturnValue("linux");
+ vi.mocked(execFileSync).mockReturnValue("/usr/local/bin/codex\n");
+ try {
+ expect(resolveCommandOnPath("codex")).toBe("/usr/local/bin/codex");
+ } finally {
+ platform.mockRestore();
+ }
+ });
+});
+
+
+describe("Windows shim paths with spaces", () => {
+ const command = "C:\\Users\\Alook User\\AppData\\Roaming\\npm\\codex.cmd";
+
+ it("quotes the executable for version probes", () => {
+ vi.mocked(execFileSync).mockReturnValue("1.2.3\n");
+ expect(probeCommandVersion(command, [], {}, "win32")).toEqual({ ok: true, version: "1.2.3" });
+ expect(vi.mocked(execFileSync).mock.calls.at(-1)?.[0]).toBe(`"${command}"`);
+ });
+
+ it("quotes the executable for model catalog probes", () => {
+ vi.mocked(execFileSync).mockReturnValue("provider/model\n");
+ expect(probeCommandOutput(command, ["models", "--pure"], "win32")).toEqual({ ok: true, output: "provider/model\n" });
+ expect(vi.mocked(execFileSync).mock.calls.at(-1)?.[0]).toBe(`"${command}"`);
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/probe.ts b/src/daemon/agent-driver/src/internal/probe.ts
index c2af1cb01..4dd42e3bb 100644
--- a/src/daemon/agent-driver/src/internal/probe.ts
+++ b/src/daemon/agent-driver/src/internal/probe.ts
@@ -5,6 +5,7 @@
import { execFileSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
+import { homedir } from "os";
import type { ProbeResult } from "./adapter.js";
/**
@@ -32,8 +33,9 @@ export function resolveCommandOnPath(command: string, deps: ProbeDeps = {}): str
// PER call — with ~9 runtimes probed sequentially at daemon startup /
// in `detectRuntimes()` tests, that added up to 30s+ wall time.
const out = execFileSync("where", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
- const first = out.split(/\r?\n/).find((line) => line.trim().length > 0);
- return first?.trim() || null;
+ const first = out.split(/\r?\n/).map((line) => line.trim())
+ .find((line) => /\.(exe|com|cmd|bat)$/i.test(line));
+ return first || null;
}
const out = execFileSync("which", [command], { encoding: "utf8", timeout: PROBE_TIMEOUT_MS });
return out.trim() || null;
@@ -80,6 +82,10 @@ function needsWindowsShimShell(command: string, platform: NodeJS.Platform): bool
return platform === "win32" && /\.(cmd|bat)$/i.test(command);
}
+export function quoteWindowsShimCommand(command: string, platform: NodeJS.Platform = process.platform): string {
+ return needsWindowsShimShell(command, platform) && /\s/.test(command) ? `"${command}"` : command;
+}
+
/**
* Actually spawn `<command> --version` and read stdout. Returns `ok: true`
* only when the child exits 0 AND emits a non-empty first line. A spawn
@@ -114,7 +120,7 @@ export function probeCommandVersion(
// (execFileSync returns it) — that's what we parse. A misbehaving shim that
// ignores all of this and prints a prompt anyway is caught by the
// `looksLikeVersion` validation below.
- const out = execFileSync(command, [...args, "--version"], {
+ const out = execFileSync(quoteWindowsShimCommand(command, platform), [...args, "--version"], {
encoding: "utf8",
timeout: PROBE_TIMEOUT_MS,
shell,
@@ -140,7 +146,7 @@ export function probeCommandOutput(
platform: NodeJS.Platform = process.platform,
): CommandOutputProbeResult {
try {
- const output = execFileSync(command, args, {
+ const output = execFileSync(quoteWindowsShimCommand(command, platform), args, {
encoding: "utf8",
timeout: PROBE_TIMEOUT_MS,
maxBuffer: PROBE_OUTPUT_MAX_BYTES,
@@ -196,10 +202,14 @@ export function resolveSpawnSpec(
return { command: resolved, args, shell: needsWindowsShimShell(resolved, platform) };
}
-/** Detect the Claude Code CLI, including macOS app-bundle fallbacks. */
+/** Detect Claude Code on PATH, then in its platform-native installation. */
export function resolveClaudeCommand(deps: ProbeDeps = {}): string | null {
const onPath = resolveCommandOnPath("claude", deps);
if (onPath) return onPath;
+ if (process.platform === "win32") {
+ const home = deps.homeDir || process.env.USERPROFILE || process.env.HOME || homedir();
+ return firstExistingPath([path.join(home, ".local", "bin", "claude.exe")]);
+ }
if (process.platform === "darwin") {
return firstExistingPath([
resolveHomePath("Applications/Claude Code URL Handler.app/Contents/MacOS/claude", deps),
diff --git a/src/daemon/agent-driver/src/internal/probe.windows.test.ts b/src/daemon/agent-driver/src/internal/probe.windows.test.ts
new file mode 100644
index 000000000..21793d1dd
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/probe.windows.test.ts
@@ -0,0 +1,331 @@
+import { once } from "node:events";
+import { copyFileSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { tmpdir, release } from "node:os";
+import { delimiter, dirname, join } from "node:path";
+import { createInterface } from "node:readline";
+import { createServer } from "node:net";
+import { execFileSync, type ChildProcess } from "node:child_process";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { loadPiSdkModule } from "../adapters/pi/sessionDeps.js";
+import { createAgentDriverSdk } from "../index.js";
+import { scrubDriverErrorMessage } from "./errors.js";
+import { isAlive, killProcessTree, spawnAgentProcess } from "./killTree.js";
+import { probeCliRuntime, probeCommandOutput, probeCommandVersion, resolveClaudeCommand, resolveCommandOnPath, resolveSpawnSpec } from "./probe.js";
+
+const roots: string[] = [];
+const children: ChildProcess[] = [];
+const diagnostics = new Map<ChildProcess, { binary: string; stdout: string; stderr: string }>();
+
+function setPrefix(prefix: string) {
+ const bin = process.platform === "win32" ? prefix : join(prefix, "bin");
+ vi.stubEnv("PATH", `${bin}${delimiter}${process.env.PATH}`);
+ mkdirSync(join(prefix, "codex-home"), { recursive: true });
+ vi.stubEnv("CODEX_HOME", join(prefix, "codex-home"));
+ vi.stubEnv("PI_CODING_AGENT_DIR", join(prefix, "pi-home"));
+ vi.stubEnv("GEMINI_HOME", join(prefix, "gemini-home"));
+ vi.stubEnv("CURSOR_CONFIG_DIR", join(prefix, "cursor-home"));
+ vi.stubEnv("GROK_DISABLE_AUTOUPDATER", "1");
+ vi.stubEnv("HOME", prefix);
+ vi.stubEnv("USERPROFILE", prefix);
+ vi.stubEnv("XDG_CONFIG_HOME", join(prefix, "config"));
+ vi.stubEnv("XDG_DATA_HOME", join(prefix, "data"));
+}
+
+function launch(binary: string, args: string[]) {
+ const spec = resolveSpawnSpec(binary, args);
+ const child = spawnAgentProcess(spec.command, spec.args, {
+ cwd: process.cwd(), env: process.env, shell: spec.shell,
+ });
+ children.push(child);
+ const trace = { binary, stdout: "", stderr: "" };
+ diagnostics.set(child, trace);
+ child.stdout?.on("data", chunk => { trace.stdout = (trace.stdout + String(chunk)).slice(-4096); });
+ child.stderr?.on("data", chunk => { trace.stderr = (trace.stderr + String(chunk)).slice(-4096); });
+ return child;
+}
+
+function waitForLine(child: ChildProcess, matches: (line: string) => boolean): Promise<string> {
+ const lines = createInterface({ input: child.stdout! });
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ const trace = diagnostics.get(child);
+ console.log(JSON.stringify({ stage: "readiness-timeout", binary: trace?.binary, pid: child.pid,
+ alive: child.pid ? isAlive(child.pid) : false, stdout: scrubDriverErrorMessage(trace?.stdout ?? ""), stderr: scrubDriverErrorMessage(trace?.stderr ?? "") }));
+ finish(new Error("runtime output timed out"));
+ }, 20_000);
+ const onExit = (code: number | null, signal: string | null) => {
+ const trace = diagnostics.get(child);
+ finish(new Error(`${trace?.binary} exited before readiness: code=${code}, signal=${signal}, stderr=${scrubDriverErrorMessage(trace?.stderr ?? "")}`));
+ };
+ function finish(error?: Error, line?: string) {
+ clearTimeout(timer);
+ lines.close();
+ child.off("exit", onExit);
+ child.off("error", finish);
+ if (error) reject(error);
+ else resolve(line!);
+ }
+ lines.on("line", (line) => { if (matches(line)) finish(undefined, line); });
+ child.once("exit", onExit);
+ child.once("error", finish);
+ });
+}
+
+type WindowsProcessIdentity = { pid: number; parent: number; name: string; created: string };
+
+function descendantsFromSnapshot(processes: WindowsProcessIdentity[], rootPid: number): WindowsProcessIdentity[] {
+ const root = processes.find(process => process.pid === rootPid);
+ if (!root) throw new Error(`live supervisor ${rootPid} missing from process snapshot`);
+ const visited = new Set([rootPid]);
+ const queue = [root];
+ for (let index = 0; index < queue.length; index++) {
+ const parent = queue[index]!;
+ for (const child of processes) {
+ if (child.parent !== parent.pid || child.created < parent.created || visited.has(child.pid)) continue;
+ visited.add(child.pid);
+ queue.push(child);
+ }
+ }
+ return queue.slice(1);
+}
+
+describe("native process snapshot ownership", () => {
+ const root: WindowsProcessIdentity = { pid: 10, parent: 0, name: "supervisor", created: "2026-10-09T01:00:00Z" };
+ it("excludes stale parent PID references while retaining nested owned processes", () => {
+ const child = { pid: 20, parent: 10, name: "runtime", created: "2026-10-09T01:00:01Z" };
+ const grandchild = { pid: 30, parent: 20, name: "tool", created: "2026-10-09T01:00:02Z" };
+ const stale = { pid: 40, parent: 10, name: "unrelated", created: "2026-10-09T00:00:00Z" };
+ expect(descendantsFromSnapshot([root, grandchild, stale, child], root.pid)).toEqual([child, grandchild]);
+ });
+ it("bounds a cycle and rejects a missing root instead of declaring no owned children", () => {
+ const child = { pid: 20, parent: root.pid, name: "runtime", created: root.created };
+ expect(descendantsFromSnapshot([{ ...root, parent: child.pid }, child], root.pid)).toEqual([child]);
+ expect(() => descendantsFromSnapshot([child], root.pid)).toThrow("missing from process snapshot");
+ });
+});
+
+function windowsDescendants(pid: number): WindowsProcessIdentity[] {
+ if (process.platform !== "win32") return [];
+ const script = `$found = @(Get-CimInstance Win32_Process | Where-Object { $_.CreationDate } | ForEach-Object { @{pid=[int]$_.ProcessId;parent=[int]$_.ParentProcessId;name=$_.Name;created=$_.CreationDate.ToUniversalTime().ToString("o")} }); ConvertTo-Json -InputObject $found -Compress`;
+ const snapshot = JSON.parse(execFileSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", timeout: 10_000 })) as WindowsProcessIdentity[];
+ return descendantsFromSnapshot(snapshot, pid);
+}
+
+async function stop(child: ChildProcess) {
+ const owned = windowsDescendants(child.pid!);
+ const closed = once(child, "close");
+ await killProcessTree(child.pid!, { graceMs: 300 });
+ await closed;
+ expect(isAlive(child.pid!)).toBe(false);
+ const alive = owned.filter(process => isAlive(process.pid));
+ if (alive.length) {
+ const script = `$found = @(); foreach ($id in @(${alive.map(process => process.pid).join(",")})) { foreach ($process in @(Get-CimInstance Win32_Process -Filter ("ProcessId=" + $id))) { $found += @{pid=$id;name=$process.Name;created=$process.CreationDate.ToString("o")} } }; ConvertTo-Json -InputObject @($found) -Compress`;
+ const current = JSON.parse(execFileSync("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", timeout: 10_000 }));
+ console.log(JSON.stringify({ stage: "owned-descendant-still-alive", binary: diagnostics.get(child)?.binary, captured: alive, current }));
+ }
+ expect(alive).toEqual([]);
+ children.splice(children.indexOf(child), 1);
+}
+
+afterEach(async () => {
+ for (const child of children.splice(0)) {
+ if (child.pid && isAlive(child.pid)) await killProcessTree(child.pid, { graceMs: 100 });
+ }
+ diagnostics.clear();
+ vi.unstubAllEnvs();
+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
+});
+
+describe.skipIf(process.platform !== "win32")("native Windows npm shim detection and launch", () => {
+ it.each(["npm-prefix-", "npm prefix with spaces-"])("detects and launches npm shim triplets in %s", async (name) => {
+ const prefix = mkdtempSync(join(tmpdir(), name));
+ roots.push(prefix);
+ setPrefix(prefix);
+ writeFileSync(join(prefix, "fixture.cjs"), `
+ if (process.argv.includes('--version')) console.log('1.2.3');
+ else if (process.argv.includes('models')) console.log('fixture/model');
+ else {
+ console.log('ready:' + process.pid);
+ require('node:readline').createInterface({ input: process.stdin }).on('line', line => console.log('echo:' + line));
+ setInterval(() => {}, 1000);
+ }
+ `);
+ for (const binary of ["codex", "opencode", "claude", "cursor-agent", "grok", "pi"]) {
+ writeFileSync(join(prefix, binary), "#!/bin/sh\nexit 1\n");
+ writeFileSync(join(prefix, `${binary}.ps1`), "exit 1\n");
+ writeFileSync(join(prefix, `${binary}.cmd`), `@echo off\r\n"${process.execPath}" "%~dp0fixture.cjs" %*\r\n`);
+ const oldFirst = execFileSync("where", [binary], { encoding: "utf8" }).split(/\r?\n/)[0]!.trim();
+ expect(probeCommandVersion(oldFirst).ok).toBe(false);
+ const found = statSync(resolveCommandOnPath(binary)!);
+ const expected = statSync(join(prefix, `${binary}.cmd`));
+ expect({ dev: found.dev, ino: found.ino }).toEqual({ dev: expected.dev, ino: expected.ino });
+ expect(probeCliRuntime(binary)).toEqual({ status: "healthy", version: "1.2.3" });
+ const catalog = probeCommandOutput(join(prefix, `${binary}.cmd`), ["models", "--pure"]);
+ expect(catalog.ok).toBe(true);
+ if (catalog.ok) expect(catalog.output.trim()).toBe("fixture/model");
+ const child = launch(binary, ["persistent"]);
+ const ready = await waitForLine(child, line => line.startsWith("ready:"));
+ const runtimePid = Number(ready.slice("ready:".length));
+ expect(isAlive(runtimePid)).toBe(true);
+ const echo = waitForLine(child, line => line === "echo:hello");
+ child.stdin!.write("hello\n");
+ expect(await echo).toBe("echo:hello");
+ await stop(child);
+ expect(isAlive(runtimePid)).toBe(false);
+ }
+ }, 60_000);
+
+ it("keeps missing and damaged npm entries unhealthy", () => {
+ const prefix = mkdtempSync(join(tmpdir(), "npm-broken-"));
+ roots.push(prefix);
+ setPrefix(prefix);
+ const binary = "alook-qa-missing-runtime";
+ expect(probeCliRuntime(binary)).toEqual({ status: "unhealthy", lastError: "not_on_path" });
+ writeFileSync(join(prefix, `${binary}.cmd`), "@exit /b 7\r\n");
+ expect(probeCliRuntime(binary).status).toBe("unhealthy");
+ });
+});
+
+
+const nativePrefix = process.env.ALOOK_NATIVE_NPM_PREFIX;
+describe.skipIf(process.platform !== "win32" || !process.env.ALOOK_NATIVE_CLAUDE_PATH)("official Windows Claude native layout", () => {
+ it("detects and initializes the standard native entry absent from the daemon PATH", async () => {
+ const home = mkdtempSync(join(tmpdir(), "Claude native profile with spaces-"));
+ roots.push(home);
+ const entry = join(home, ".local", "bin", "claude.exe");
+ mkdirSync(dirname(entry), { recursive: true });
+ setPrefix(home);
+ const system = process.env.SystemRoot!;
+ vi.stubEnv("PATH", [join(system, "System32"), join(system, "System32", "WindowsPowerShell", "v1.0"), dirname(process.execPath)].join(delimiter));
+ vi.stubEnv("DISABLE_AUTOUPDATER", "1");
+ expect(resolveCommandOnPath("claude")).toBeNull();
+ writeFileSync(entry, "broken native executable");
+ const sdk = createAgentDriverSdk();
+ expect((await sdk.probe({ backend: "claude" })).status).toBe("unhealthy");
+ copyFileSync(process.env.ALOOK_NATIVE_CLAUDE_PATH!, entry);
+ expect(resolveClaudeCommand()).toBe(entry);
+ expect((await sdk.probe({ backend: "claude", command: join(home, "explicit missing.exe") })).status).toBe("unhealthy");
+ const probe = await sdk.probe({ backend: "claude" });
+ expect(probe.status).toBe("healthy");
+ console.log(JSON.stringify({ backend: "claude-native", os: release(), node: process.version, status: probe.status,
+ version: probe.status === "healthy" ? probe.version : undefined, absentFromPath: true }));
+ const claude = launch(resolveClaudeCommand()!, ["--input-format", "stream-json", "--output-format", "stream-json", "--verbose"]);
+ const initialized = waitForLine(claude, line => {
+ try { return JSON.parse(line).type === "control_response"; } catch { return false; }
+ });
+ claude.stdin!.write(JSON.stringify({ type: "control_request", request_id: "alook-qa-native-init", request: { subtype: "initialize" } }) + "\n");
+ expect(JSON.parse(await initialized)).toMatchObject({ type: "control_response", response: { subtype: "success" } });
+ await stop(claude);
+ }, 60_000);
+});
+
+describe.skipIf(!nativePrefix)("real npm and native providers from an isolated prefix", () => {
+ it.each(["codex", "opencode", "claude", "cursor", "pi", "antigravity"] as const)("detects the real %s install via its public SDK probe", async (backend) => {
+ setPrefix(nativePrefix!);
+ console.log(JSON.stringify({ backend, os: release(), node: process.version, nodePath: process.execPath }));
+ const started = Date.now();
+ const result = await createAgentDriverSdk().probe({ backend });
+ console.log(JSON.stringify({ backend, elapsedMs: Date.now() - started, status: result.status, version: result.status === "healthy" ? result.version : undefined,
+ error: result.status === "unhealthy" ? result.error.code : undefined }));
+ expect(result.status).toBe("healthy");
+ }, 60_000);
+
+ it("starts real Codex app-server and completes initialize", async () => {
+ setPrefix(nativePrefix!);
+ const codex = launch("codex", ["app-server", "--listen", "stdio://"]);
+ const initialized = waitForLine(codex, line => {
+ try { return JSON.parse(line).id === 1; } catch { return false; }
+ });
+ codex.stdin!.write(JSON.stringify({ id: 1, method: "initialize", params: { clientInfo: { name: "alook-windows-qa", version: "1.0.0" } } }) + "\n");
+ expect(JSON.parse(await initialized)).toHaveProperty("result");
+ codex.stdin!.write(JSON.stringify({ method: "initialized" }) + "\n");
+ await stop(codex);
+ });
+
+ it("starts real OpenCode serve and returns localhost health", async () => {
+ setPrefix(nativePrefix!);
+ const portFinder = createServer();
+ portFinder.listen(0, "127.0.0.1");
+ await once(portFinder, "listening");
+ const port = (portFinder.address() as { port: number }).port;
+ await new Promise<void>((resolve) => portFinder.close(() => resolve()));
+ const opencode = launch("opencode", ["serve", "--hostname", "127.0.0.1", "--port", String(port)]);
+ await waitForLine(opencode, line => line.includes(`127.0.0.1:${port}`));
+ const health = await fetch(`http://127.0.0.1:${port}/global/health`, { signal: AbortSignal.timeout(5000) });
+ expect(health.ok).toBe(true);
+ expect(await health.json()).toMatchObject({ healthy: true });
+ await stop(opencode);
+ });
+
+ it("starts real Claude's stream-json control protocol", async () => {
+ setPrefix(nativePrefix!);
+ const claude = launch("claude", ["--input-format", "stream-json", "--output-format", "stream-json", "--verbose"]);
+ const initialized = waitForLine(claude, line => {
+ try { return JSON.parse(line).type === "control_response"; } catch { return false; }
+ });
+ claude.stdin!.write(JSON.stringify({ type: "control_request", request_id: "alook-qa-init", request: { subtype: "initialize" } }) + "\n");
+ expect(JSON.parse(await initialized)).toMatchObject({ type: "control_response", response: { subtype: "success" } });
+ await stop(claude);
+ });
+
+ it.each([
+ ["cursor-agent", ["acp"]],
+ ["grok", ["agent", "--no-leader", "stdio"]],
+ ["agy_acp_server.exe", []],
+ ] as const)("initializes the real %s ACP process without a model request", async (binary, args) => {
+ setPrefix(nativePrefix!);
+ const started = Date.now();
+ const child = launch(binary, [...args]);
+ const initialized = waitForLine(child, line => {
+ try { return JSON.parse(line).id === 1; } catch { return false; }
+ });
+ child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: {
+ protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "alook-windows-qa", version: "1.0.0" },
+ } }) + "\n");
+ let initializedLine: string;
+ try {
+ initializedLine = await initialized;
+ } catch (error) {
+ if (binary === "agy_acp_server.exe") {
+ try {
+ const late = await waitForLine(child, line => {
+ try { return JSON.parse(line).id === 1; } catch { return false; }
+ });
+ console.log(JSON.stringify({ binary, phase: "diagnostic-late-initialize", elapsedMs: Date.now() - started, responseKind: JSON.parse(late).result ? "result" : "error" }));
+ } catch {}
+ }
+ throw error;
+ }
+ expect(JSON.parse(initializedLine)).toMatchObject({ result: { protocolVersion: 1 } });
+ console.log(JSON.stringify({ binary, phase: "initialize", elapsedMs: Date.now() - started }));
+ if (binary === "agy_acp_server.exe") {
+ const session = waitForLine(child, line => {
+ try { return JSON.parse(line).id === 2; } catch { return false; }
+ });
+ child.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "session/new", params: { cwd: nativePrefix!, mcpServers: [] } }) + "\n");
+ const reply = JSON.parse(await session);
+ expect(reply.result !== undefined || reply.error !== undefined).toBe(true);
+ console.log(JSON.stringify({ binary, phase: "session/new", elapsedMs: Date.now() - started, errorCode: reply.error?.code }));
+ }
+ await stop(child);
+ }, 60_000);
+
+ it("classifies real Grok authentication separately from installation", async () => {
+ setPrefix(nativePrefix!);
+ expect(probeCliRuntime("grok").status).toBe("healthy");
+ const probe = await createAgentDriverSdk().probe({ backend: "grok" });
+ console.log(JSON.stringify({ backend: "grok", status: probe.status, error: probe.status === "unhealthy" ? probe.error.code : undefined }));
+ if (probe.status === "unhealthy") expect(probe.error.code).toBe("grok_acp_authentication_failed");
+ });
+
+ it("imports the real Pi SDK and creates/disposes a persistent session without a model request", async () => {
+ setPrefix(nativePrefix!);
+ const piSdk = await loadPiSdkModule();
+ const sessionManager = piSdk.SessionManager.create(nativePrefix!, join(nativePrefix!, "pi-sessions"));
+ const { session } = await piSdk.createAgentSession({ cwd: nativePrefix!, agentDir: join(nativePrefix!, "pi-home"), sessionManager, tools: [] });
+ const nativeSession = session as { sessionId: string; prompt: unknown; dispose(): void };
+ expect(typeof nativeSession.sessionId).toBe("string");
+ expect(typeof nativeSession.prompt).toBe("function");
+ nativeSession.dispose();
+ });
+});