Repository navigation
Expand file tree
/
Copy pathcodex-cli.js
More file actions
292 lines (260 loc) · 12.1 KB
/
Copy pathcodex-cli.js
File metadata and controls
292 lines (260 loc) · 12.1 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import { spawn } from 'child_process';
import { existsSync, mkdtempSync, writeFileSync, rmSync } from 'fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { ASIDE_TOOL_NAMES } from './aside-mcp.js';
import { APPLE_TOOL_NAMES } from './apple-mcp.js';
const DEFAULT_WORKING_DIRECTORY = '/Users/quinnodonnell/oneiro/runtime/workspace';
const DEFAULT_TIMEOUT_MS = 180_000;
const MAX_DIAGNOSTIC_CHARS = 8_000;
function clampTimeout(value) {
const parsed = Number.parseInt(String(value || ''), 10);
if (!Number.isFinite(parsed)) return DEFAULT_TIMEOUT_MS;
return Math.max(10_000, Math.min(parsed, 30 * 60_000));
}
function resolveCodexCLI(env = process.env) {
const configured = String(env.ONEIRO_CODEX_CLI || env.OCA_CODEX_CLI || '').trim();
const candidates = [
configured,
'/opt/homebrew/bin/codex',
'/usr/local/bin/codex',
].filter(Boolean);
return candidates.find(candidate => existsSync(candidate)) || configured || 'codex';
}
export function buildCodexEnvironment(env = process.env) {
const childEnv = { ...env };
// Codex must use its cached ChatGPT login. Never let a provider key inherited
// from Oneiro silently switch this path to metered API billing.
delete childEnv.OPENAI_API_KEY;
delete childEnv.ANTHROPIC_API_KEY;
delete childEnv.OPENAI_BASE_URL;
childEnv.HOME = env.HOME || env.USERPROFILE || '/Users/quinnodonnell';
childEnv.PATH = [
`${childEnv.HOME}/.local/bin`,
'/opt/homebrew/bin',
'/usr/local/bin',
'/usr/bin',
'/bin',
].join(':');
childEnv.TERM = 'dumb';
return childEnv;
}
export const REASONING_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh'];
export const SANDBOX_MODES = ['read-only', 'workspace-write', 'danger-full-access'];
// Self-build's Codex coder is an agent, not the thinker: its model and sandbox come from the environment
// (OCA_SELF_BUILD_MODEL, OCA_SELF_BUILD_EFFORT, OCA_SELF_BUILD_SANDBOX), never from the inference policy the
// thinker uses. Unset or invalid values leave the caller's options as they are.
export function selfBuildCodexOptions(options = {}, env = process.env) {
const model = String(env.OCA_SELF_BUILD_MODEL || '').trim(), sandbox = String(env.OCA_SELF_BUILD_SANDBOX || '').trim();
const effort = String(env.OCA_SELF_BUILD_EFFORT || '').trim().toLowerCase();
return { ...options, ...(/^[A-Za-z0-9._:-]{1,64}$/.test(model) ? { model } : {}), ...(REASONING_EFFORTS.includes(effort) ? { reasoningEffort: effort } : {}),
...(SANDBOX_MODES.includes(sandbox) ? { sandbox } : {}) };
}
// The engine's one browser, offered to every Codex run as a read-only MCP tool server. Codex spawns MCP
// servers outside its command sandbox, so this is how a sandboxed slice reaches Aside. Read tools only —
// open, read, snapshot, search, tabs — auto-approved because none of them can act on the world.
export const ASIDE_MCP_SERVER = new URL('./aside-mcp.js', import.meta.url).pathname;
export const ASIDE_MCP_TOOLS = ASIDE_TOOL_NAMES; // every tool the server offers is pre-approved: the server itself is the boundary
export function asideMcpArgs({ server = ASIDE_MCP_SERVER, node = process.execPath } = {}) {
return [
'-c', `mcp_servers.aside.command=${JSON.stringify(node)}`,
'-c', `mcp_servers.aside.args=${JSON.stringify([server])}`,
'-c', 'mcp_servers.aside.startup_timeout_sec=30',
'-c', 'mcp_servers.aside.tool_timeout_sec=960', // a delegated sign-in or post runs minutes, not seconds
...ASIDE_MCP_TOOLS.flatMap(t => ['-c', `mcp_servers.aside.tools.${t}.approval_mode="approve"`]),
];
}
// Apple's APIs, through the Apple broker, offered beside Aside. Every tool is pre-approved for the same reason:
// the broker, running as its own account, is the boundary, and it decides every write.
export const APPLE_MCP_SERVER = new URL('./apple-mcp.js', import.meta.url).pathname;
export function appleMcpArgs({ server = APPLE_MCP_SERVER, node = process.execPath } = {}) {
return [
'-c', `mcp_servers.apple.command=${JSON.stringify(node)}`,
'-c', `mcp_servers.apple.args=${JSON.stringify([server])}`,
'-c', 'mcp_servers.apple.startup_timeout_sec=30',
'-c', 'mcp_servers.apple.tool_timeout_sec=600', // a report download can take minutes
...APPLE_TOOL_NAMES.flatMap(t => ['-c', `mcp_servers.apple.tools.${t}.approval_mode="approve"`]),
];
}
// A plain answer, not a working session. The engine's own model calls (think, plan, classify, review) read what
// they're given and reply. With a shell, code mode, a browser and tool servers, a thorough model opens the files and
// pages named in its prompt, and a ten-second answer turns into a three-minute investigation that times out.
export const ANSWER_ONLY_DISABLED = ['shell_tool', 'code_mode_host', 'browser_use', 'browser_use_external', 'computer_use', 'multi_agent',
'apps', 'plugins', 'image_generation', 'memories', 'skill_search', 'goals', 'sleep_tool'];
export function buildCodexArgs({
workingDirectory = DEFAULT_WORKING_DIRECTORY,
model = '',
sandbox = 'read-only',
persistent = false, threadId = null, outputSchemaPath = null,
reasoningEffort = '', aside = true, answerOnly = false,
} = {}) {
const args = [
'exec',
'--json',
...(!persistent ? ['--ephemeral'] : []),
'--ignore-user-config',
'--skip-git-repo-check',
'--sandbox',
sandbox,
'--config',
'approval_policy="never"',
'--cd',
workingDirectory,
];
const selectedModel = String(model || '').trim();
if (selectedModel && /^[A-Za-z0-9._:-]+$/.test(selectedModel)) {
args.push('--model', selectedModel);
}
// --ignore-user-config drops ~/.codex/config.toml, so the effort the engine wants is stated explicitly.
const effort = String(reasoningEffort || '').trim().toLowerCase();
if (REASONING_EFFORTS.includes(effort)) args.push('--config', `model_reasoning_effort="${effort}"`);
if (answerOnly) args.push(...ANSWER_ONLY_DISABLED.flatMap(feature => ['--disable', feature]));
else if (aside) args.push(...asideMcpArgs(), ...appleMcpArgs());
if (outputSchemaPath) args.push('--output-schema', outputSchemaPath);
if (threadId) {
if (!/^[a-f0-9-]{36}$/i.test(threadId)) throw new Error('Invalid Codex session ID');
args.splice(1, 0, 'resume');
const sandboxIndex = args.indexOf('--sandbox'); args.splice(sandboxIndex, 2);
const cwdIndex = args.indexOf('--cd'); args.splice(cwdIndex, 2);
args.push('--config', `sandbox_mode="${sandbox}"`, threadId);
}
args.push('-');
return args;
}
export function parseCodexEvent(line) {
let event;
try {
event = JSON.parse(line);
} catch {
return null;
}
if (event?.type === 'item.completed' && event?.item?.type === 'agent_message') {
return { type: 'text', text: String(event.item.text || '') };
}
if (event?.type === 'turn.completed') {
return { type: 'usage', usage: event.usage || null };
}
return { type: 'event', event };
}
export function codexAvailable(env = process.env) {
const binary = resolveCodexCLI(env);
return binary !== 'codex' ? existsSync(binary) : true;
}
export function runCodex(prompt, {
workingDirectory = DEFAULT_WORKING_DIRECTORY,
model = process.env.OCA_CODEX_MODEL || process.env.ONEIRO_CODEX_MODEL || '',
sandbox = 'read-only',
timeoutMs = process.env.OCA_CODEX_TIMEOUT_MS || process.env.LLM_CLI_TIMEOUT_MS,
signal = null,
onText = null, onEvent = null,
persistent = false, threadId = null, outputSchema = null,
reasoningEffort = process.env.OCA_CODEX_REASONING_EFFORT || process.env.ONEIRO_CODEX_REASONING_EFFORT || '',
aside = !/^(0|false|no|off)$/i.test(String(process.env.OCA_CODEX_ASIDE || '')),
answerOnly = false,
env = process.env,
} = {}) {
const codexCLI = resolveCodexCLI(env);
const schemaDir = outputSchema ? mkdtempSync(join(tmpdir(), 'oneiro-codex-schema-')) : null;
const outputSchemaPath = schemaDir ? join(schemaDir, 'response.json') : null;
if (outputSchemaPath) writeFileSync(outputSchemaPath, JSON.stringify(outputSchema), { mode: 0o600 });
let args;
try { args = buildCodexArgs({ workingDirectory, model, sandbox, persistent, threadId, outputSchemaPath, reasoningEffort, aside, answerOnly }); }
catch (error) { if (schemaDir) rmSync(schemaDir, { recursive: true, force: true }); throw error; }
const childEnv = buildCodexEnvironment(env);
const timeout = clampTimeout(timeoutMs);
return new Promise((resolve, reject) => {
const child = spawn(codexCLI, args, {
cwd: workingDirectory,
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
detached: true,
});
let stdoutBuffer = '';
let stderr = '';
let responseText = '';
let usage = null;
let finished = false;
let actualThreadId = threadId;
let eventWrites = Promise.resolve();
let eventError = null;
const stopChild = () => {
try { process.kill(-child.pid, 'SIGTERM'); } catch {}
const escalation = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) { try { process.kill(-child.pid, 'SIGKILL'); } catch {} } }, 2000);
escalation.unref();
};
const finish = (error, result) => {
if (finished) return;
finished = true;
clearTimeout(timer);
if (schemaDir) rmSync(schemaDir, { recursive: true, force: true });
if (signal) signal.removeEventListener('abort', abort);
if (error) reject(error);
else resolve(result);
};
const consumeLine = line => {
if (!line.trim()) return;
const parsed = parseCodexEvent(line);
let raw; try { raw = JSON.parse(line); } catch {}
if (raw?.type === 'thread.started') actualThreadId = raw.thread_id;
if (raw && typeof onEvent === 'function') {
eventWrites = eventWrites.then(() => onEvent(raw)).catch(error => { eventError = error; stopChild(); });
}
if (parsed?.type === 'text' && parsed.text) {
// Completed assistant items include commentary. Only the final item is the answer.
responseText = parsed.text;
if (typeof onText === 'function') onText(parsed.text);
} else if (parsed?.type === 'usage') {
usage = parsed.usage;
}
};
const abort = () => {
stopChild();
finish(new Error('Codex request cancelled'));
};
const timer = setTimeout(() => {
stopChild();
finish(new Error(`Codex CLI timed out after ${Math.round(timeout / 1000)} seconds`));
}, timeout);
if (signal) {
if (signal.aborted) return abort();
signal.addEventListener('abort', abort, { once: true });
}
child.stdout.on('data', chunk => {
stdoutBuffer += chunk.toString();
const lines = stdoutBuffer.split('\n');
stdoutBuffer = lines.pop() || '';
for (const line of lines) consumeLine(line);
});
child.stderr.on('data', chunk => {
stderr = (stderr + chunk.toString()).slice(-MAX_DIAGNOSTIC_CHARS);
});
child.on('error', error => {
finish(new Error(`Could not start Codex CLI: ${error.message}`));
});
child.on('close', async code => {
if (stdoutBuffer.trim()) consumeLine(stdoutBuffer);
await eventWrites;
if (finished) return;
if (eventError) return finish(eventError);
if (code === 0 && responseText.trim()) {
finish(null, {
text: responseText.trim(),
usage,
model: model || 'codex-default',
via: 'codex_chatgpt_subscription', threadId: actualThreadId,
});
return;
}
// Prefer the lines that explain the failure over skill-loader warnings that precede them.
const lines = stderr.trim().split('\n').filter(l => l.trim());
const explanatory = lines.filter(l => /^ERROR:|usage limit|unauthori|not logged|rate limit|quota|timed out|ECONN|network/i.test(l) && !/failed to load skill/i.test(l));
const detail = (explanatory.length ? explanatory.slice(-2) : lines.filter(l => !/failed to load skill/i.test(l)).slice(-4)).join(' | ');
finish(new Error(`Codex CLI exited ${code}${detail ? `: ${detail}` : ''}`));
});
child.stdin.on('error', error => {
if (error.code !== 'EPIPE') finish(new Error(`Could not send prompt to Codex CLI: ${error.message}`));
});
child.stdin.end(String(prompt || ''));
});
}
export default { runCodex, codexAvailable };