deepcodex 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.codex-plugin/plugin.json +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +178 -0
  4. package/bin/opencodex.js +49 -0
  5. package/config/desktop.json +9 -0
  6. package/config/pilot.json +16 -0
  7. package/config/worker.json +78 -0
  8. package/node_modules/smol-toml/LICENSE +24 -0
  9. package/node_modules/smol-toml/README.md +418 -0
  10. package/node_modules/smol-toml/dist/date.d.ts +41 -0
  11. package/node_modules/smol-toml/dist/date.js +127 -0
  12. package/node_modules/smol-toml/dist/error.d.ts +38 -0
  13. package/node_modules/smol-toml/dist/error.js +63 -0
  14. package/node_modules/smol-toml/dist/extract.js +69 -0
  15. package/node_modules/smol-toml/dist/index.cjs +734 -0
  16. package/node_modules/smol-toml/dist/index.d.ts +43 -0
  17. package/node_modules/smol-toml/dist/index.js +33 -0
  18. package/node_modules/smol-toml/dist/parse.d.ts +36 -0
  19. package/node_modules/smol-toml/dist/parse.js +149 -0
  20. package/node_modules/smol-toml/dist/primitive.js +238 -0
  21. package/node_modules/smol-toml/dist/stringify.d.ts +31 -0
  22. package/node_modules/smol-toml/dist/stringify.js +181 -0
  23. package/node_modules/smol-toml/dist/struct.js +179 -0
  24. package/node_modules/smol-toml/dist/util.d.ts +38 -0
  25. package/node_modules/smol-toml/dist/util.js +89 -0
  26. package/node_modules/smol-toml/package.json +68 -0
  27. package/package.json +47 -0
  28. package/prompts/worker.md +20 -0
  29. package/scripts/credentials.js +102 -0
  30. package/scripts/desktop.js +199 -0
  31. package/scripts/pilot-router.js +241 -0
  32. package/scripts/pilot.js +242 -0
  33. package/scripts/toml.js +6 -0
  34. package/scripts/worker.js +637 -0
  35. package/skills/delegate-flash/SKILL.md +63 -0
  36. package/vendor/codex-router/LICENSE +21 -0
  37. package/vendor/codex-router/deepseek-responses.js +55 -0
  38. package/vendor/codex-router/json-number-rewrite.js +58 -0
  39. package/vendor/codex-router/namespace-relay.js +4294 -0
  40. package/vendor/codex-router/sse-prefix.js +115 -0
  41. package/vendor/codex-router/subagent-completion.js +261 -0
  42. package/vendor/codex-router/tool-arguments.js +111 -0
  43. package/vendor/codex-router/tool-schema-root.js +1008 -0
@@ -0,0 +1,242 @@
1
+ // Run the opt-in live native-subagent pilot; consumes Codex and DeepSeek usage.
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { chmodSync, closeSync, copyFileSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync,
5
+ rmSync, statSync, writeFileSync } from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+ import { ROOT, configArgs, doctor, killGroup, loadConfig, loadCredentials, workerEnvironment } from './worker.js';
10
+
11
+ export function assess(receipts, markers, returncode, events) {
12
+ const children = receipts.filter((entry) => entry.route === 'deepseek');
13
+ const recipients = new Set(children.flatMap((entry) => entry.recipients ?? []));
14
+ return {
15
+ parent_completed: returncode === 0 && events.some((event) => event.type === 'turn.completed'),
16
+ native_spawn: receipts.some((entry) => entry.route === 'native'
17
+ && (entry.calls ?? []).some((call) => call.name === 'spawn_agent')),
18
+ deepseek_completed: children.length > 0 && children.every((entry) => Boolean(entry.completed)),
19
+ tool_used: children.some((entry) => (entry.calls ?? []).some((call) => call.name === 'exec_command')),
20
+ file_values_returned: markers.every((_, index) => children.some((entry) =>
21
+ Boolean((entry.tool_results ?? [])[index]) && Boolean((entry.answers ?? [])[index]))),
22
+ same_agent_followup: recipients.size === 1 && children.some((entry) => (entry.task_count ?? 0) >= 2),
23
+ no_transport_errors: receipts.every((entry) => entry.route === 'cancelled'
24
+ || (entry.route !== 'error' && entry.http_status === 200)),
25
+ };
26
+ }
27
+
28
+ export function authFile(env) {
29
+ return path.join(env.CODEX_HOME ?? path.join(os.homedir(), '.codex'), 'auth.json');
30
+ }
31
+
32
+ export function execArgs(workspace, runDir) {
33
+ return ['exec', '--ephemeral', '--json', '--strict-config', '--skip-git-repo-check',
34
+ '--sandbox', 'read-only', '--cd', workspace, '--output-last-message', path.join(runDir, 'final.txt'), '-'];
35
+ }
36
+
37
+ function emit(value) {
38
+ process.stdout.write(`${JSON.stringify(value)}\n`);
39
+ }
40
+
41
+ function jsonLines(file) {
42
+ const lines = readFileSync(file, 'utf8').split('\n');
43
+ if (lines.at(-1) === '') lines.pop();
44
+ return lines.map((line) => JSON.parse(line));
45
+ }
46
+
47
+ function capture(command, args) {
48
+ const result = spawnSync(command, args, { encoding: 'utf8' });
49
+ if (result.error) throw result.error;
50
+ if (result.status !== 0) {
51
+ throw new Error(`${command} ${args.join(' ')} exited with ${result.status}: ${result.stderr}`);
52
+ }
53
+ return result.stdout;
54
+ }
55
+
56
+ // SIGINT or SIGTERM aborts the active wait so the cleanup still removes the copied credentials and
57
+ // kills both process groups.
58
+ function captureSignals() {
59
+ const controller = new AbortController();
60
+ const handlers = new Map(['SIGINT', 'SIGTERM'].map((name) => [name,
61
+ () => controller.abort(new Error(`Pilot interrupted by ${name}`))]));
62
+ for (const [name, handler] of handlers) process.once(name, handler);
63
+ return { signal: controller.signal, dispose: () => {
64
+ for (const [name, handler] of handlers) process.off(name, handler);
65
+ } };
66
+ }
67
+
68
+ function readRouterReadiness(router, timeout_ms, signal) {
69
+ return new Promise((resolve, reject) => {
70
+ let text = '';
71
+ const onData = (chunk) => {
72
+ text += chunk;
73
+ const newline = text.indexOf('\n');
74
+ if (newline === -1) return;
75
+ try { finish(null, JSON.parse(text.slice(0, newline))); } catch (error) { finish(error); }
76
+ };
77
+ const onEnd = () => finish(new Error('Pilot router did not start'));
78
+ const onAbort = () => finish(signal.reason);
79
+ const onError = () => finish(new Error('Pilot router did not start'));
80
+ const timer = setTimeout(() => finish(new Error('Pilot router did not start')), timeout_ms);
81
+ const finish = (error, value) => {
82
+ clearTimeout(timer);
83
+ signal.removeEventListener('abort', onAbort);
84
+ router.stdout.off('data', onData);
85
+ router.stdout.off('end', onEnd);
86
+ router.stdout.off('error', onEnd);
87
+ router.off('error', onError);
88
+ if (error) reject(error); else resolve(value);
89
+ };
90
+ router.stdout.on('data', onData);
91
+ router.stdout.on('end', onEnd);
92
+ router.stdout.on('error', onEnd);
93
+ router.on('error', onError);
94
+ signal.addEventListener('abort', onAbort, { once: true });
95
+ });
96
+ }
97
+
98
+ function waitForExit(child, timeout_ms, signal) {
99
+ return new Promise((resolve, reject) => {
100
+ const onClose = (code) => finish(null, code);
101
+ const onError = (error) => finish(error);
102
+ const onAbort = () => finish(signal.reason);
103
+ const timer = setTimeout(() => finish(new Error('Codex exec did not finish within timeout_seconds')), timeout_ms);
104
+ const finish = (error, value) => {
105
+ clearTimeout(timer);
106
+ signal.removeEventListener('abort', onAbort);
107
+ child.off('close', onClose);
108
+ child.off('error', onError);
109
+ if (error) reject(error); else resolve(value);
110
+ };
111
+ child.once('close', onClose);
112
+ child.once('error', onError);
113
+ signal.addEventListener('abort', onAbort, { once: true });
114
+ });
115
+ }
116
+
117
+ export async function run() {
118
+ const config = JSON.parse(readFileSync(path.join(ROOT, 'config/pilot.json'), 'utf8'));
119
+ const workerConfig = loadConfig();
120
+ const sourceEnv = workerEnvironment(process.env);
121
+ loadCredentials(sourceEnv, workerConfig);
122
+ const diagnosis = doctor(workerConfig, sourceEnv);
123
+ if (diagnosis.status !== 'ready') throw new Error('OpenCodex doctor is not ready');
124
+ const authSource = authFile(sourceEnv);
125
+ if (!statSync(authSource, { throwIfNoEntry: false })?.isFile()) {
126
+ throw new Error('Pilot requires the existing Codex auth.json login');
127
+ }
128
+ const runDir = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'opencodex-pilot-')));
129
+ const home = path.join(runDir, 'codex-home');
130
+ const workspace = path.join(runDir, 'workspace');
131
+ mkdirSync(home, { mode: 0o700, recursive: true });
132
+ mkdirSync(workspace);
133
+ const markers = [randomBytes(16).toString('hex'), randomBytes(16).toString('hex')];
134
+ ['first.txt', 'second.txt'].forEach((filename, index) => {
135
+ writeFileSync(path.join(workspace, filename), `${markers[index]}\n`);
136
+ });
137
+ const capability = randomBytes(32).toString('base64url');
138
+ const provider = workerConfig.codex.model_provider;
139
+ Object.assign(config, {
140
+ child_model: workerConfig.codex.model,
141
+ native_models: [config.parent_model],
142
+ deepseek_url: `${workerConfig.codex.model_providers[provider].base_url}/responses`,
143
+ receipts: path.join(runDir, 'receipts.jsonl'),
144
+ markers,
145
+ });
146
+ let router = null;
147
+ let child = null;
148
+ const started = performance.now() / 1000;
149
+ const signals = captureSignals();
150
+ try {
151
+ copyFileSync(authSource, path.join(home, 'auth.json'));
152
+ chmodSync(path.join(home, 'auth.json'), 0o600);
153
+ const native = JSON.parse(capture(diagnosis.codex, ['debug', 'models', '--bundled']));
154
+ const parent = (native.models ?? []).find((model) => model.slug === config.parent_model);
155
+ if (!parent) throw new Error(`Native model catalog has no ${config.parent_model}`);
156
+ const metadata = { ...workerConfig.model_metadata, slug: config.child_model, multi_agent_version: 'v2',
157
+ base_instructions: readFileSync(path.join(ROOT, 'prompts/worker.md'), 'utf8') };
158
+ const catalog = path.join(home, 'models.json');
159
+ writeFileSync(catalog, JSON.stringify({ models: [parent, metadata] }));
160
+ const env = workerEnvironment(sourceEnv);
161
+ env.CODEX_HOME = home;
162
+ const routerErrors = openSync(path.join(runDir, 'router-errors.txt'), 'w');
163
+ try {
164
+ router = spawn(process.execPath, [path.join(ROOT, 'scripts/pilot-router.js')],
165
+ { env, cwd: workspace, stdio: ['pipe', 'pipe', routerErrors], detached: true });
166
+ router.stdin.end(JSON.stringify({ config, capability }));
167
+ const ready = await readRouterReadiness(router, config.startup_timeout_seconds * 1000, signals.signal);
168
+ emit({ event: 'pilot.router_started', ...ready, cwd: workspace, owner: 'OpenCodex isolated pilot',
169
+ artifacts: runDir });
170
+ const values = { ...workerConfig.codex };
171
+ Object.assign(values, { model: config.parent_model, model_provider: 'opencodex-pilot',
172
+ model_reasoning_effort: config.parent_effort, model_catalog_json: catalog,
173
+ cli_auth_credentials_store: 'file',
174
+ agents: { enabled: true, max_concurrent_threads_per_session: 1 } });
175
+ values.features = { ...values.features, multi_agent: true, multi_agent_v2: true,
176
+ enable_request_compression: false };
177
+ values.model_providers = { 'opencodex-pilot': {
178
+ name: 'OpenCodex isolated pilot',
179
+ base_url: `http://127.0.0.1:${ready.port}`,
180
+ wire_api: 'responses',
181
+ requires_openai_auth: true,
182
+ supports_websockets: false,
183
+ http_headers: { 'x-opencodex-pilot': capability },
184
+ request_max_retries: 0,
185
+ stream_max_retries: 0,
186
+ stream_idle_timeout_ms: config.request_timeout_ms,
187
+ } };
188
+ const flat = configArgs(values);
189
+ const configPath = path.join(home, 'config.toml');
190
+ writeFileSync(configPath, `${flat.filter((_, index) => index % 2 === 1).join('\n')}\n`);
191
+ chmodSync(configPath, 0o600);
192
+ delete env.DEEPSEEK_API_KEY;
193
+ const prompt = `Run this authorized native subagent integration test. Spawn exactly one agent named flash, `
194
+ + `model=${config.child_model}, fork_turns=none, reasoning_effort=high. Its first task is: `
195
+ + `Use exec_command to read first.txt in the current workspace and return exactly its content. `
196
+ + `Do not read either file yourself. Wait for the child's result. Then use followup_task on the SAME `
197
+ + `agent to read second.txt with exec_command and return exactly its content. Wait again. `
198
+ + `Never substitute another model or create another agent. Do not use shell to launch Codex. `
199
+ + `If any step fails, report the exact failure. At the end report both returned values and `
200
+ + `the agent's canonical name in Spanish. Do not modify any files.`;
201
+ const eventsFd = openSync(path.join(runDir, 'events.jsonl'), 'w');
202
+ const errorsFd = openSync(path.join(runDir, 'codex-errors.txt'), 'w');
203
+ let returncode;
204
+ try {
205
+ child = spawn(diagnosis.codex, execArgs(workspace, runDir),
206
+ { env, cwd: workspace, stdio: ['pipe', eventsFd, errorsFd], detached: true });
207
+ child.stdin.on('error', () => {});
208
+ child.stdin.end(prompt);
209
+ returncode = await waitForExit(child, config.timeout_seconds * 1000, signals.signal);
210
+ } finally {
211
+ closeSync(eventsFd);
212
+ closeSync(errorsFd);
213
+ }
214
+ const receipts = jsonLines(config.receipts);
215
+ const events = jsonLines(path.join(runDir, 'events.jsonl'));
216
+ const checks = assess(receipts, markers, returncode, events);
217
+ const result = { status: Object.values(checks).every(Boolean) ? 'passed' : 'failed', checks,
218
+ artifacts: runDir, duration_seconds: Math.round((performance.now() / 1000 - started) * 100) / 100,
219
+ routes: receipts.map((entry) => Object.fromEntries(
220
+ Object.entries(entry).filter(([key]) => key !== 'recipients'))) };
221
+ writeFileSync(path.join(runDir, 'result.json'), JSON.stringify(result, null, 2));
222
+ emit(result);
223
+ return result.status === 'passed' ? 0 : 1;
224
+ } finally {
225
+ closeSync(routerErrors);
226
+ }
227
+ } finally {
228
+ signals.dispose();
229
+ try {
230
+ const stopped = await Promise.allSettled([child, router].filter(Boolean).map(killGroup));
231
+ const failed = stopped.find(result => result.status === 'rejected');
232
+ if (failed) throw failed.reason;
233
+ } finally {
234
+ rmSync(home, { recursive: true, force: true });
235
+ emit({ event: 'pilot.stopped', artifacts: runDir, temporary_credentials_removed: true });
236
+ }
237
+ }
238
+ }
239
+
240
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
241
+ process.exitCode = await run();
242
+ }
@@ -0,0 +1,6 @@
1
+ import { parse } from 'smol-toml';
2
+
3
+ export function parseToml(text) {
4
+ try { return parse(text); }
5
+ catch { throw new Error('Invalid TOML configuration'); }
6
+ }