Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/windows-engine.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: Windows engine launch
on:
workflow_dispatch:
push:
paths:
- 'packages/core/src/runtime/**'
- 'packages/core/src/account/**'
- 'packages/core/package.json'
- 'pnpm-lock.yaml'
- '.github/workflows/windows-engine.yml'
pull_request:
paths:
- 'packages/core/src/runtime/**'
- 'packages/core/src/account/**'
- 'packages/core/package.json'
- 'pnpm-lock.yaml'
- '.github/workflows/windows-engine.yml'
jobs:
launch:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with: { version: 9 }
- uses: actions/setup-node@v4
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @iqlabs-official/agent-sdk exec vitest run src/runtime/engineProcess.spec.ts
3 changes: 3 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@solana/web3.js": "^1.99.0"
},
"devDependencies": {
"@types/cross-spawn": "^6.0.6",
"@iqlabs-official/solana-sdk": "^0.2.0",
"@solana/web3.js": "^1.99.0",
"@types/jsdom": "^30.0.0",
Expand All @@ -36,6 +37,8 @@
"vitest": "^4.1.8"
},
"dependencies": {
"read-cmd-shim": "^5.0.0",
"cross-spawn": "^7.0.6",
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
"@modelcontextprotocol/sdk": "^1.29.0",
"@openai/codex-sdk": "^0.139.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/account/claudeAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
// the user's OAuth token off-device.) The only thing we persist is a tiny marker so the
// onboarding can skip the login screen on next launch; the real auth lives in the CLI.

import { spawn } from "node:child_process";
import { spawnEngine as spawn } from "../runtime/engineProcess.js";
import { readFile, rm, writeFile } from "node:fs/promises";
import { tokenFile, tokensDir, ensureDir } from "../core/paths.js";
import { resolveEngineBin } from "../runtime/engineBin.js";
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/account/codexAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// Exit 0 = success. We never see or store the session token — codex CLI owns it
// in ~/.codex/auth.json, device-local.

import { spawn } from "node:child_process";
import { spawnEngine as spawn } from "../runtime/engineProcess.js";
import { readFile, writeFile, rm } from "node:fs/promises";
import { tokenFile, tokensDir, ensureDir } from "../core/paths.js";
import { resolveEngineBin } from "../runtime/engineBin.js";
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/runtime/claudeModels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { query } from "@anthropic-ai/claude-agent-sdk";
import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
import type { ChatModelOption } from "../chat/modelOptions.js";
import { resolveEngineBin } from "./engineBin.js";
import { spawnClaudeProcess } from "./engineProcess.js";

// Live model catalog for the "claude" engine, pulled from the Claude Code CLI the user
// already runs. The agent SDK's query() exposes supportedModels() over its control
Expand Down Expand Up @@ -75,6 +76,7 @@ export async function listClaudeModelOptions(cwd?: string): Promise<ChatModelOpt
// and the picker silently drops to the static baseline (no Fable/Sonnet-1M). This
// is why codex synced but claude didn't: codexModels resolves its path, we didn't.
pathToClaudeCodeExecutable: resolveEngineBin("claude"),
spawnClaudeCodeProcess: spawnClaudeProcess,
},
});

Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/runtime/codex-approvals.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { EventEmitter } from "node:events";
import { PassThrough, Writable } from "node:stream";
import { afterEach, describe, expect, it, vi } from "vitest";
import { spawn } from "node:child_process";
import { spawnEngine as spawn } from "./engineProcess.js";
import { spawnCli } from "./spawn.js";

vi.mock("node:child_process", async (importOriginal) => ({
...await importOriginal<typeof import("node:child_process")>(),
spawn: vi.fn(),
vi.mock("./engineProcess.js", async (importOriginal) => ({
...await importOriginal<typeof import("./engineProcess.js")>(),
spawnEngine: vi.fn(),
}));

afterEach(() => {
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/runtime/codex-resume-fallback.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { PassThrough, Writable } from "node:stream";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { spawn } from "node:child_process";
import { spawnEngine as spawn } from "./engineProcess.js";
import { spawnCli } from "./spawn.js";
import { createRuntime } from "./index.js";
import { getNativeId } from "./inject/idmap.js";
Expand All @@ -16,9 +16,9 @@ import { codexSessionsDir } from "../core/paths.js";
import type { ApprovalRequest } from "./approval/channel.js";
import type { ChatMessage } from "./contract.js";

vi.mock("node:child_process", async (importOriginal) => ({
...await importOriginal<typeof import("node:child_process")>(),
spawn: vi.fn(),
vi.mock("./engineProcess.js", async (importOriginal) => ({
...await importOriginal<typeof import("./engineProcess.js")>(),
spawnEngine: vi.fn(),
}));

afterEach(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/runtime/codexModels.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { spawn } from "node:child_process";
import { spawnEngine as spawn } from "./engineProcess.js";
import readline from "node:readline";
import type { ChatModelOption } from "../chat/modelOptions.js";
import type { Model } from "./codex_bindings/v2/Model.js";
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/runtime/detect.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// CLI availability check for onboarding. Standalone (no wallet/storage) —
// answers "is codex/claude installed, and logged in?" so the UI can guide setup.

import { spawn } from "node:child_process";
import { spawnEngine as spawn } from "./engineProcess.js";
import { isClaudeLoggedIn } from "../account/claudeAuth.js";
import { isCodexLoggedIn } from "../account/codexAuth.js";
import { resolveEngineBin } from "./engineBin.js";
Expand Down
11 changes: 7 additions & 4 deletions packages/core/src/runtime/engineBin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,15 @@ let nodeBin: string | undefined;
function fromPath(name: string): string | undefined {
try {
const cmd = process.platform === "win32" ? "where" : "which";
const hit = execFileSync(cmd, [name], {
const hits = execFileSync(cmd, [name], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
})
.split("\n")[0]
?.trim();
return hit && existsSync(hit) ? hit : undefined;
.split("\n").map((hit) => hit.trim()).filter((hit) => hit && existsSync(hit));
// `where` may list npm's extensionless POSIX shim before its Windows launcher.
return process.platform === "win32"
? hits.find((hit) => /\.(exe|com|cmd|bat)$/i.test(hit))
: hits[0];
} catch {
return undefined;
}
Expand Down Expand Up @@ -83,6 +85,7 @@ function candidates(name: EngineName | "node"): string[] {
return [
// the official native installer: ~/.local/bin/claude is a symlink to
// ~/.local/share/claude/versions/<ver>
...(win && name !== "node" ? [join(home, ".local", "bin", `${name}.exe`)] : []),
join(home, ".local", "bin", exe),
// node version managers: one global-bin dir per runtime version, newest first
...versionedBins(join(home, ".nvm", "versions", "node"), ["bin"], exe),
Expand Down
99 changes: 99 additions & 0 deletions packages/core/src/runtime/engineProcess.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, realpathSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, it, vi } from "vitest";
import { spawnEngine, spawnClaudeProcess } from "./engineProcess.js";

const home = mkdtempSync(join(tmpdir(), "agentnet-launch-"));
const binDir = join(home, "engine install (226)");
mkdirSync(binDir);
const entry = join(binDir, "probe.cjs");
writeFileSync(entry, `#!/usr/bin/env node
const args = process.argv.slice(2);
if (args[0] === '--version') console.log('codex 0.154.0');
else if (args[0] === 'login') console.log('Logged in using ChatGPT');
else if (args[0] === 'auth') console.log(JSON.stringify({ loggedIn: true }));
else if (args[0] === 'wait') process.stdin.resume();
else console.log(JSON.stringify(args));
`);
const cmd = join(binDir, "codex.cmd");
// Match npm/cmd-shim's dispatch instead of a hand-written batch wrapper.
writeFileSync(cmd, [
'@ECHO off', 'GOTO start', ':find_dp0', 'SET dp0=%~dp0', 'EXIT /b',
':start', 'SETLOCAL', 'CALL :find_dp0',
`SET "_prog=${process.execPath}"`,
'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\probe.cjs" %*',
'',
].join('\r\n'));
afterAll(() => { vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }); });

describe("engine process launch", () => {
it("preserves argument boundaries through the shared launcher", async () => {
const args = ['two words', 'a"b', '(paren)', 'x&y', '%PATH%', 'semi;colon'];
const child = spawnEngine(process.execPath, [entry, ...args], { stdio: ["ignore", "pipe", "pipe"] });
let output = "";
child.stdout.on("data", (data) => { output += data; });
const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); });
expect(code).toBe(0);
expect(JSON.parse(output)).toEqual(args);
});

it("forwards the Claude SDK abort signal to a piped child", async () => {
const ctl = new AbortController();
const child = spawnClaudeProcess({ command: process.execPath, args: [entry, 'wait'], env: process.env, signal: ctl.signal });
const error = new Promise<Error>((resolve) => child.once("error", resolve));
const closed = new Promise((resolve) => child.once("close", resolve));
await new Promise((resolve) => child.once("spawn", resolve));
ctl.abort();
expect((await error).name).toBe("AbortError");
await closed;
});
});

describe.skipIf(process.platform !== "win32")("Windows npm launcher", () => {
it("rejects unknown batch wrappers instead of forwarding arguments through a shell", () => {
for (const ext of ['cmd', 'bat']) {
const wrapper = join(binDir, `unknown.${ext}`);
writeFileSync(wrapper, '@echo off\r\necho %*\r\n');
expect(() => spawnEngine(wrapper, ['a"b&c'], { stdio: 'pipe' })).toThrow(/doesn't appear to be a cmd-shim/);
}
});

it("runs a cmd shim in a spaced path with quoted and shell-special arguments", async () => {
const args = ['two words', 'a"b', '(paren)', 'x&y', '%PATH%', 'semi;colon'];
const child = spawnEngine(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
let output = "";
let stderr = "";
child.stdout.on("data", (data) => { output += data; });
child.stderr.on("data", (data) => { stderr += data; });
const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); });
expect(code, stderr).toBe(0);
expect(JSON.parse(output)).toEqual(args);
});

it("detects and authenticates engines launched through cmd files", async () => {
vi.stubEnv("AGENTNET_CODEX_PATH", cmd);
vi.stubEnv("AGENTNET_CLAUDE_PATH", cmd);
const { detectCli } = await import("./detect.js");
expect(await detectCli()).toEqual({ claude: "ok", codex: "ok" });
});

it("launches the Claude SDK process through the same cmd adapter", async () => {
const child = spawnClaudeProcess({ command: cmd, args: ['SDK round trip'], env: process.env, signal: new AbortController().signal });
let output = "";
child.stdout.on("data", (data) => { output += data; });
const code = await new Promise((resolve, reject) => { child.on("error", reject); child.on("close", resolve); });
expect(code).toBe(0);
expect(JSON.parse(output)).toEqual(['SDK round trip']);
});

it("prefers the Windows shim when where also finds an extensionless launcher", async () => {
vi.unstubAllEnvs();
vi.stubEnv("PATH", `${binDir};${process.env.PATH}`);
vi.stubEnv("AGENTNET_CODEX_PATH", "");
writeFileSync(join(binDir, "codex"), "#!/bin/sh\nexit 1\n");
vi.resetModules();
const { resolveEngineBin } = await import("./engineBin.js");
expect(realpathSync.native(resolveEngineBin("codex"))).toBe(realpathSync.native(cmd));
});
});
24 changes: 24 additions & 0 deletions packages/core/src/runtime/engineProcess.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/// <reference path="./read-cmd-shim.d.ts" />
import crossSpawn from "cross-spawn";
import readCmdShim from "read-cmd-shim";
import { dirname, resolve } from "node:path";
import type { SpawnOptions } from "@anthropic-ai/claude-agent-sdk";

// cross-spawn preserves Node's stdio behavior but its typings omit the overloads
// that narrow piped streams. Keep that contract at the shared import boundary.
export const spawnEngine = ((command, args, options) => {
// Global npm shims require another cmd parsing pass, which can reinterpret
// quoted arguments. Resolve their target as npm does for a symlink instead.
// cross-spawn then follows the target's shebang without passing through cmd.
if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command)) {
command = resolve(dirname(command), readCmdShim.sync(command));
}
return crossSpawn(command, args, options);
}) as typeof import("node:child_process").spawn;

// Adapt the SDK process contract to the same Windows-aware launcher used by the
// login, version and Codex paths. Forward the SDK's delayed abort signal so its
// graceful stdin shutdown still gets a chance to finish.
export function spawnClaudeProcess({ command, args, cwd, env, signal }: SpawnOptions) {
return spawnEngine(command, args, { cwd, env, signal, stdio: "pipe", windowsHide: true });
}
2 changes: 1 addition & 1 deletion packages/core/src/runtime/engineVersions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// engine's own updater, or the official npm command when the engine is missing. All
// host-side, on an explicit user tap.

import { spawn } from "node:child_process";
import { spawnEngine as spawn } from "./engineProcess.js";
import { basename } from "node:path";
import { ENGINE_UPDATE_COMMAND } from "./engineInstall.js";
import { resolveEngineBin, type EngineName } from "./engineBin.js";
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/runtime/read-cmd-shim.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module "read-cmd-shim" {
const readCmdShim: { sync(path: string): string };
export default readCmdShim;
}
3 changes: 2 additions & 1 deletion packages/core/src/runtime/spawn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
// and never imports an SDK type. Output is delivered as already-mapped ChatMessages
// (convert/* map the SDK events); the runtime just appends + paints.

import { spawn } from "node:child_process";
import readline from "node:readline";
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { mkdir, writeFile, unlink } from "node:fs/promises";
Expand All @@ -34,6 +33,7 @@ import type {
} from "./approval/channel.js";
import { autoApprove } from "./approval/channel.js";
import { resolveEngineBin } from "./engineBin.js";
import { spawnEngine as spawn, spawnClaudeProcess } from "./engineProcess.js";

// Loosely-typed view of AskUserQuestion's raw input (the SDK hands us `unknown`-ish data).
type ApprovalQuestionInput = {
Expand Down Expand Up @@ -442,6 +442,7 @@ function claudeEngine(opts: SpawnOpts): Engine {
// use the user's installed claude (logged in) so the bundled extension doesn't
// need the SDK's own native binary on its (unresolvable) bundle-relative path.
pathToClaudeCodeExecutable: claudeBin,
spawnClaudeCodeProcess: spawnClaudeProcess,
stderr: (d: string) => { if (d.trim()) cb.emitErr(`[claude] ${d.trim()}`); },
// Passive skill-shopping wiring (issue #21): the MCP marketplace server + its
// allowed tools, when the toggle is ON. The "which skills you have" directive is
Expand Down
22 changes: 22 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading