-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathspawn.ts
More file actions
193 lines (163 loc) · 5.86 KB
/
Copy pathspawn.ts
File metadata and controls
193 lines (163 loc) · 5.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import { type ChildProcess, spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { delimiter, dirname } from "node:path";
import type { Readable, Writable } from "node:stream";
import type { ProcessSpawnedCallback } from "../../types";
import { Logger } from "../../utils/logger";
import type { CodexSettings } from "./settings";
export interface CodexProcessOptions {
cwd?: string;
apiBaseUrl?: string;
apiKey?: string;
model?: string;
reasoningEffort?: string;
/**
* Guidance appended on top of Codex's model-optimized base prompt via the
* `developer_instructions` config key. Unlike `instructions` /
* `model_instructions_file`, this does not replace the native base prompt.
*/
developerInstructions?: string;
binaryPath?: string;
codexHome?: string;
logger?: Logger;
processCallbacks?: ProcessSpawnedCallback;
settings?: CodexSettings;
/** Additional writable roots passed to Codex's workspace-write sandbox. */
additionalDirectories?: string[];
}
export interface CodexProcess {
process: ChildProcess;
stdin: Writable;
stdout: Readable;
kill: () => void;
}
function buildConfigArgs(options: CodexProcessOptions): string[] {
const args: string[] = [];
args.push("-c", `features.remote_models=false`);
// Disable the user's local MCPs one-by-one so Codex only uses the MCPs we
// provide via ACP. We can't use `-c mcp_servers={}` because that makes Codex
// ignore MCPs entirely, including the ones we inject later.
//
// Only bare-key names are emitted: codex's `-c` parser rejects quoted key
// segments, so a name with a dot or other special character cannot be
// expressed as `mcp_servers.<name>.enabled=false` without producing an
// override that fails to load and crashes the whole codex session. Skipping
// such a name leaves that server enabled (harmless) instead of killing codex.
for (const name of options.settings?.mcpServerNames ?? []) {
if (!/^[A-Za-z0-9_-]+$/.test(name)) continue;
args.push("-c", `mcp_servers.${name}.enabled=false`);
}
if (options.apiBaseUrl) {
args.push("-c", `model_provider="posthog"`);
args.push("-c", `model_providers.posthog.name="PostHog Gateway"`);
args.push("-c", `model_providers.posthog.base_url="${options.apiBaseUrl}"`);
args.push("-c", `model_providers.posthog.wire_api="responses"`);
args.push(
"-c",
`model_providers.posthog.env_key="POSTHOG_GATEWAY_API_KEY"`,
);
}
if (options.model) {
args.push("-c", `model="${options.model}"`);
}
if (options.reasoningEffort) {
args.push("-c", `model_reasoning_effort="${options.reasoningEffort}"`);
}
if (options.additionalDirectories?.length) {
const escaped = options.additionalDirectories
.map((p) => `"${p.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`)
.join(",");
args.push("-c", `sandbox_workspace_write.writable_roots=[${escaped}]`);
}
if (options.developerInstructions) {
const escaped = options.developerInstructions
.replace(/\\/g, "\\\\")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/"/g, '\\"');
args.push("-c", `developer_instructions="${escaped}"`);
}
return args;
}
function findCodexBinary(options: CodexProcessOptions): {
command: string;
args: string[];
} {
const configArgs = buildConfigArgs(options);
if (options.binaryPath && existsSync(options.binaryPath)) {
return { command: options.binaryPath, args: configArgs };
}
if (options.binaryPath) {
throw new Error(
`codex-acp binary not found at ${options.binaryPath}. Run "node apps/code/scripts/download-binaries.mjs" to download it.`,
);
}
return { command: "npx", args: ["@zed-industries/codex-acp", ...configArgs] };
}
export function spawnCodexProcess(options: CodexProcessOptions): CodexProcess {
const logger =
options.logger ?? new Logger({ debug: true, prefix: "[CodexSpawn]" });
const env: NodeJS.ProcessEnv = { ...process.env };
// The agent host puts a `node -> Electron app binary` shim on PATH; without
// this flag, every `node` this process tree spawns boots the full desktop app.
env.ELECTRON_RUN_AS_NODE = "1";
delete env.ELECTRON_NO_ASAR;
if (options.apiKey) {
env.POSTHOG_GATEWAY_API_KEY = options.apiKey;
}
if (options.codexHome) {
env.CODEX_HOME = options.codexHome;
}
const { command, args } = findCodexBinary(options);
if (options.binaryPath && existsSync(options.binaryPath)) {
const binDir = dirname(options.binaryPath);
env.PATH = `${binDir}${delimiter}${env.PATH ?? ""}`;
}
logger.info("Spawning codex-acp process", {
command,
args,
cwd: options.cwd,
hasApiBaseUrl: !!options.apiBaseUrl,
hasApiKey: !!options.apiKey,
binaryPath: options.binaryPath,
});
const child = spawn(command, args, {
cwd: options.cwd,
env,
stdio: ["pipe", "pipe", "pipe"],
detached: process.platform !== "win32",
});
child.stderr?.on("data", (data: Buffer) => {
logger.warn("codex-acp stderr:", data.toString());
});
child.on("error", (err) => {
logger.error("codex-acp process error:", err);
});
child.on("exit", (code, signal) => {
logger.info("codex-acp process exited", { code, signal });
if (child.pid && options.processCallbacks?.onProcessExited) {
options.processCallbacks.onProcessExited(child.pid);
}
});
if (!child.stdin || !child.stdout) {
throw new Error("Failed to get stdio streams from codex-acp process");
}
if (child.pid && options.processCallbacks?.onProcessSpawned) {
options.processCallbacks.onProcessSpawned({
pid: child.pid,
command,
});
}
return {
process: child,
stdin: child.stdin,
stdout: child.stdout,
kill: () => {
logger.info("Killing codex-acp process", { pid: child.pid });
child.stdin?.destroy();
child.stdout?.destroy();
child.stderr?.destroy();
child.kill("SIGTERM");
},
};
}