@cogitator-ai/bridge 0.2.0 → 0.4.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 (116) hide show
  1. package/README.md +242 -8
  2. package/dist/adapter.d.ts +130 -0
  3. package/dist/adapter.d.ts.map +1 -0
  4. package/dist/adapter.js +2 -0
  5. package/dist/adapter.js.map +1 -0
  6. package/dist/adapters/claude.d.ts +145 -0
  7. package/dist/adapters/claude.d.ts.map +1 -0
  8. package/dist/adapters/claude.js +537 -0
  9. package/dist/adapters/claude.js.map +1 -0
  10. package/dist/adapters/codex.d.ts +71 -0
  11. package/dist/adapters/codex.d.ts.map +1 -0
  12. package/dist/adapters/codex.js +379 -0
  13. package/dist/adapters/codex.js.map +1 -0
  14. package/dist/adapters/exec.d.ts +70 -0
  15. package/dist/adapters/exec.d.ts.map +1 -0
  16. package/dist/adapters/exec.js +161 -0
  17. package/dist/adapters/exec.js.map +1 -0
  18. package/dist/adapters/hosted.d.ts +168 -0
  19. package/dist/adapters/hosted.d.ts.map +1 -0
  20. package/dist/adapters/hosted.js +361 -0
  21. package/dist/adapters/hosted.js.map +1 -0
  22. package/dist/adapters/tools-server.d.ts +21 -0
  23. package/dist/adapters/tools-server.d.ts.map +1 -0
  24. package/dist/adapters/tools-server.js +19 -0
  25. package/dist/adapters/tools-server.js.map +1 -0
  26. package/dist/client.d.ts +9 -2
  27. package/dist/client.d.ts.map +1 -1
  28. package/dist/client.js +17 -3
  29. package/dist/client.js.map +1 -1
  30. package/dist/dispatcher.d.ts +69 -17
  31. package/dist/dispatcher.d.ts.map +1 -1
  32. package/dist/dispatcher.js +243 -17
  33. package/dist/dispatcher.js.map +1 -1
  34. package/dist/host.d.ts +1 -1
  35. package/dist/host.d.ts.map +1 -1
  36. package/dist/index.d.ts +18 -3
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +9 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/inputs.d.ts +40 -1
  41. package/dist/inputs.d.ts.map +1 -1
  42. package/dist/inputs.js +25 -2
  43. package/dist/inputs.js.map +1 -1
  44. package/dist/paths.d.ts +6 -0
  45. package/dist/paths.d.ts.map +1 -1
  46. package/dist/paths.js +19 -0
  47. package/dist/paths.js.map +1 -1
  48. package/dist/protocol.d.ts +5 -0
  49. package/dist/protocol.d.ts.map +1 -1
  50. package/dist/protocol.js +5 -0
  51. package/dist/protocol.js.map +1 -1
  52. package/dist/server.d.ts.map +1 -1
  53. package/dist/server.js +6 -1
  54. package/dist/server.js.map +1 -1
  55. package/dist/setup/claude.d.ts +53 -0
  56. package/dist/setup/claude.d.ts.map +1 -0
  57. package/dist/setup/claude.js +261 -0
  58. package/dist/setup/claude.js.map +1 -0
  59. package/dist/setup/codex.d.ts +22 -0
  60. package/dist/setup/codex.d.ts.map +1 -0
  61. package/dist/setup/codex.js +95 -0
  62. package/dist/setup/codex.js.map +1 -0
  63. package/dist/setup/files.d.ts +22 -0
  64. package/dist/setup/files.d.ts.map +1 -0
  65. package/dist/setup/files.js +86 -0
  66. package/dist/setup/files.js.map +1 -0
  67. package/dist/setup/index.d.ts +6 -0
  68. package/dist/setup/index.d.ts.map +1 -0
  69. package/dist/setup/index.js +3 -0
  70. package/dist/setup/index.js.map +1 -0
  71. package/dist/setup/setup.d.ts +52 -0
  72. package/dist/setup/setup.d.ts.map +1 -0
  73. package/dist/setup/setup.js +2 -0
  74. package/dist/setup/setup.js.map +1 -0
  75. package/dist/testing/conformance.d.ts +65 -0
  76. package/dist/testing/conformance.d.ts.map +1 -0
  77. package/dist/testing/conformance.js +217 -0
  78. package/dist/testing/conformance.js.map +1 -0
  79. package/dist/testing/fake-harnesses.d.ts +121 -0
  80. package/dist/testing/fake-harnesses.d.ts.map +1 -0
  81. package/dist/testing/fake-harnesses.js +303 -0
  82. package/dist/testing/fake-harnesses.js.map +1 -0
  83. package/dist/testing/index.d.ts +5 -0
  84. package/dist/testing/index.d.ts.map +1 -0
  85. package/dist/testing/index.js +3 -0
  86. package/dist/testing/index.js.map +1 -0
  87. package/dist/tools/caller.d.ts +39 -0
  88. package/dist/tools/caller.d.ts.map +1 -0
  89. package/dist/tools/caller.js +92 -0
  90. package/dist/tools/caller.js.map +1 -0
  91. package/dist/tools/guidance.d.ts +33 -0
  92. package/dist/tools/guidance.d.ts.map +1 -0
  93. package/dist/tools/guidance.js +92 -0
  94. package/dist/tools/guidance.js.map +1 -0
  95. package/dist/tools/index.d.ts +27 -0
  96. package/dist/tools/index.d.ts.map +1 -0
  97. package/dist/tools/index.js +24 -0
  98. package/dist/tools/index.js.map +1 -0
  99. package/dist/tools/tools.d.ts +38 -0
  100. package/dist/tools/tools.d.ts.map +1 -0
  101. package/dist/tools/tools.js +354 -0
  102. package/dist/tools/tools.js.map +1 -0
  103. package/dist/types.d.ts +3 -39
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -0
  106. package/dist/types.js.map +1 -1
  107. package/dist/waiter.d.ts +36 -0
  108. package/dist/waiter.d.ts.map +1 -0
  109. package/dist/waiter.js +92 -0
  110. package/dist/waiter.js.map +1 -0
  111. package/fakes/claude.mjs +715 -0
  112. package/fakes/codex.mjs +571 -0
  113. package/fakes/lib.mjs +585 -0
  114. package/fakes/mcp.mjs +151 -0
  115. package/fakes/sandbox.mjs +84 -0
  116. package/package.json +19 -1
@@ -0,0 +1,571 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * A stand-in for the Codex command line as far as the bridge adapters use it: `exec` with JSON
4
+ * events, `queue`, the app-server daemon, `mcp` and `delete`. The commands `__open` and `__app`
5
+ * exist only here and play the desktop app with its threads. The behaviour was measured on
6
+ * codex-cli 0.167.0-alpha.4.1.
7
+ *
8
+ * MCP servers: a thread has the servers of `mcp add` and of `-c mcp_servers.<name>.*`. A server
9
+ * is started outside the sandbox of the thread, with next to nothing of the environment and no
10
+ * thread id in it: Codex names the thread in `_meta` of every tool call. A thread of `exec`
11
+ * cannot ask anybody for an approval, so it calls only tools that say they destroy nothing and
12
+ * stay in a closed world. The commands of a sandboxed thread reach no socket and write nowhere
13
+ * outside their folder.
14
+ */
15
+ import { randomUUID } from 'node:crypto';
16
+ import { rmSync, statSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { text } from 'node:stream/consumers';
19
+ import { fileURLToPath } from 'node:url';
20
+ import {
21
+ CliError,
22
+ POLL_MS,
23
+ Unsupported,
24
+ abandonWork,
25
+ awaitJson,
26
+ boundLife,
27
+ canonical,
28
+ enqueue,
29
+ flag,
30
+ isAlive,
31
+ isStateName,
32
+ listRecords,
33
+ listedIn,
34
+ lock,
35
+ onStopSignal,
36
+ option,
37
+ parseArgs,
38
+ pending,
39
+ performTurn,
40
+ print,
41
+ readJson,
42
+ recordTurn,
43
+ renderHelp,
44
+ repeated,
45
+ runCli,
46
+ sandboxedEnv,
47
+ sleep,
48
+ spawnDetached,
49
+ stateRoot,
50
+ takeNext,
51
+ terminate,
52
+ tryLock,
53
+ unlock,
54
+ writeJson,
55
+ } from './lib.mjs';
56
+ import { envPairs, toolServers } from './mcp.mjs';
57
+
58
+ const SELF = fileURLToPath(import.meta.url);
59
+ const VERSION = '0.167.0-alpha.4.1';
60
+ const OWNER_KINDS = ['daemon', 'app'];
61
+ const THREAD_OWNERS = ['app', 'none'];
62
+ const TURN_STARTED = { type: 'turn.started' };
63
+ const TURN_COMPLETED = {
64
+ type: 'turn.completed',
65
+ usage: { input_tokens: 1, cached_input_tokens: 0, output_tokens: 1 },
66
+ };
67
+ const EXIT_ON_STOP_SIGNAL = 143;
68
+
69
+ const HELP_FLAGS = { '--help': flag('help'), '-h': flag('help') };
70
+ const FOLDER_FLAGS = { '-C': option('cd'), '--cd': option('cd') };
71
+ const EXEC_FLAGS = {
72
+ ...HELP_FLAGS,
73
+ ...FOLDER_FLAGS,
74
+ '--json': flag('json'),
75
+ '-s': option('sandbox'),
76
+ '--sandbox': option('sandbox'),
77
+ '--skip-git-repo-check': flag('skipGitRepoCheck'),
78
+ '-m': option('model'),
79
+ '--model': option('model'),
80
+ '-c': repeated('config'),
81
+ '--config': repeated('config'),
82
+ };
83
+ const MCP_ADD_FLAGS = { '--env': repeated('env') };
84
+ const MCP_JSON_FLAGS = { '--json': flag('json') };
85
+ /** What a server of tools gets of the environment of Codex: Codex gives it next to nothing */
86
+ const SERVER_ENV = ['PATH', 'HOME', 'TMPDIR', 'USER', 'LOGNAME', 'SHELL', 'LANG'];
87
+ const NEEDS_APPROVAL = 'MCP tool call requires approval, but approval policy is never';
88
+ const QUEUE_FLAGS = {
89
+ ...HELP_FLAGS,
90
+ ...FOLDER_FLAGS,
91
+ '--thread': option('thread'),
92
+ '--message': option('message'),
93
+ '--resume': flag('resume'),
94
+ };
95
+ const OPEN_FLAGS = {
96
+ ...FOLDER_FLAGS,
97
+ '--owner': option('owner'),
98
+ '--sandbox': option('sandbox'),
99
+ };
100
+ const DELETE_FLAGS = { '--force': flag('force') };
101
+
102
+ const HELP = [
103
+ 'Codex CLI',
104
+ '',
105
+ 'Usage: codex [OPTIONS] [PROMPT]',
106
+ ' codex [OPTIONS] <COMMAND> [ARGS]',
107
+ '',
108
+ 'Commands:',
109
+ ' exec Run Codex non-interactively',
110
+ ['queue', ' queue Queue a message for a thread'],
111
+ ' app-server Run the app server or its daemon',
112
+ ' mcp Manage external MCP servers for Codex',
113
+ ' delete Delete a thread',
114
+ '',
115
+ 'Options:',
116
+ ' -h, --help Print help',
117
+ ' -V, --version Print version',
118
+ ];
119
+
120
+ const EXEC_HELP = [
121
+ 'Run Codex non-interactively',
122
+ '',
123
+ 'Usage: codex exec [OPTIONS] [PROMPT]',
124
+ ' codex exec resume <THREAD> [PROMPT]',
125
+ '',
126
+ 'Options:',
127
+ ['exec-json', ' --json Print events to stdout as JSONL'],
128
+ ' -C, --cd <DIR> The folder the agent works in',
129
+ ' -s, --sandbox <SANDBOX_MODE> The sandbox policy for the commands the model runs',
130
+ ' --skip-git-repo-check Allow running outside a Git repository',
131
+ ' -m, --model <MODEL> The model the agent uses',
132
+ ' -c, --config <key=value> Override a configuration value',
133
+ ' -h, --help Print help',
134
+ ];
135
+
136
+ const QUEUE_HELP = [
137
+ 'Queue a message for a thread',
138
+ '',
139
+ 'Usage: codex queue [OPTIONS] --thread <THREAD> --message <TEXT>',
140
+ '',
141
+ 'Options:',
142
+ ' --thread <THREAD> The thread that gets the message',
143
+ ' --message <TEXT> The text of the message',
144
+ ' --resume After queueing, try to resume the thread on the local daemon',
145
+ ' -C, --cd <DIR> The folder to look the thread up from',
146
+ ' -h, --help Print help',
147
+ ];
148
+
149
+ const missing = () => listedIn('FAKE_CODEX_MISSING');
150
+ const version = () => process.env.FAKE_CODEX_VERSION || VERSION;
151
+ const threadsDir = () => join(stateRoot('codex'), 'threads');
152
+ const ownerFile = (kind) => join(stateRoot('codex'), `${kind}.json`);
153
+ const configFile = () => join(stateRoot('codex'), 'config.json');
154
+
155
+ function threadFiles(threadId) {
156
+ const base = join(threadsDir(), threadId);
157
+ return {
158
+ record: `${base}.json`,
159
+ transcript: `${base}.jsonl`,
160
+ queue: `${base}.queue`,
161
+ lock: `${base}.lock`,
162
+ running: `${base}.pid`,
163
+ };
164
+ }
165
+
166
+ async function main(argv) {
167
+ const [command, ...rest] = argv;
168
+ switch (command) {
169
+ case '--version':
170
+ case '-V':
171
+ return print(`codex-cli ${version()}`);
172
+ case '--help':
173
+ case '-h':
174
+ return print(renderHelp(HELP, missing()));
175
+ case 'exec':
176
+ return exec(rest);
177
+ case 'queue':
178
+ return queue(rest);
179
+ case 'app-server':
180
+ return appServer(rest);
181
+ case 'mcp':
182
+ return mcp(rest);
183
+ case 'delete':
184
+ return remove(rest);
185
+ case '__open':
186
+ return open(rest);
187
+ case '__app':
188
+ return ownerCommand('app', rest);
189
+ case '__owner':
190
+ return serve(rest);
191
+ default:
192
+ throw new Unsupported();
193
+ }
194
+ }
195
+
196
+ async function exec(argv) {
197
+ const { values, positionals } = parseArgs(argv, EXEC_FLAGS);
198
+ if (values.help) return print(renderHelp(EXEC_HELP, missing()));
199
+ if (values.json && missing().has('exec-json')) {
200
+ throw new CliError("error: unexpected argument '--json' found", 2);
201
+ }
202
+ if (process.env.FAKE_CODEX_EXEC_FAIL) throw new CliError(process.env.FAKE_CODEX_EXEC_FAIL);
203
+ const { resumed, promptArgument } = execTarget(positionals);
204
+ const cwd = resumed ? undefined : workFolder(values.cd);
205
+ const prompt = await promptText(promptArgument);
206
+ const thread =
207
+ resumed ??
208
+ createThread({
209
+ cwd,
210
+ sandbox: values.sandbox ?? 'read-only',
211
+ owner: 'none',
212
+ servers: { ...configuredServers(), ...overriddenServers(values.config ?? []) },
213
+ });
214
+ await foregroundTurn(thread, prompt, values.json === true);
215
+ }
216
+
217
+ /** The MCP servers of the configuration, as `mcp add` left them */
218
+ function configuredServers() {
219
+ return readJson(configFile(), {}).mcp_servers ?? {};
220
+ }
221
+
222
+ /**
223
+ * The MCP servers `-c mcp_servers.<name>.<field>=<value>` describes. The values are TOML: a
224
+ * string, an array of strings, or for `env` an inline table of strings.
225
+ * @param {string[]} overrides
226
+ */
227
+ function overriddenServers(overrides) {
228
+ const servers = {};
229
+ for (const override of overrides) {
230
+ const match = /^mcp_servers\.([\w-]+)\.(command|args|env)=(.*)$/s.exec(override);
231
+ if (!match) continue;
232
+ const [, name, field, value] = match;
233
+ servers[name] = { ...servers[name], [field]: tomlValue(field, value) };
234
+ }
235
+ return Object.fromEntries(
236
+ Object.entries(servers).filter(([, server]) => typeof server.command === 'string')
237
+ );
238
+ }
239
+
240
+ function tomlValue(field, value) {
241
+ try {
242
+ if (field !== 'env') return JSON.parse(value);
243
+ const pairs = [...value.matchAll(/([\w-]+)\s*=\s*("(?:[^"\\]|\\.)*")/g)];
244
+ return Object.fromEntries(pairs.map(([, key, text]) => [key, JSON.parse(text)]));
245
+ } catch {
246
+ throw new CliError(`Error: invalid override value: ${value}`);
247
+ }
248
+ }
249
+
250
+ /** Tells `exec <prompt>` from `exec resume <threadId> <prompt>` */
251
+ function execTarget(positionals) {
252
+ const [first, ...rest] = positionals;
253
+ if (first !== 'resume') {
254
+ if (rest.length > 0) throw new Unsupported();
255
+ return { promptArgument: first };
256
+ }
257
+ if (rest.length < 1 || rest.length > 2) throw new Unsupported();
258
+ return { resumed: findThread(rest[0]), promptArgument: rest[1] };
259
+ }
260
+
261
+ function workFolder(dir) {
262
+ const folder = canonical(dir ?? process.cwd());
263
+ if (!statSync(folder, { throwIfNoEntry: false })?.isDirectory()) {
264
+ throw new CliError(`Error: ${folder} is not a directory`);
265
+ }
266
+ return folder;
267
+ }
268
+
269
+ /** The prompt of `exec`: its argument, or stdin when the argument is `-` or absent */
270
+ async function promptText(argument) {
271
+ const piped = argument === undefined || argument === '-';
272
+ const prompt = piped ? (await text(process.stdin)).trimEnd() : argument;
273
+ if (prompt.trim() === '') throw new CliError('No prompt provided');
274
+ return prompt;
275
+ }
276
+
277
+ function createThread({ cwd, sandbox, owner, servers }) {
278
+ const thread = { threadId: randomUUID(), cwd, sandbox, owner, servers, createdAt: Date.now() };
279
+ writeJson(threadFiles(thread.threadId).record, thread);
280
+ return thread;
281
+ }
282
+
283
+ function findThread(threadId) {
284
+ const thread = isStateName(threadId) ? readJson(threadFiles(threadId).record) : undefined;
285
+ if (thread === undefined) throw new CliError(`Error: no session found for '${threadId}'`);
286
+ return thread;
287
+ }
288
+
289
+ /** Runs one turn of `exec` to its end. The first event leaves before the turn starts */
290
+ async function foregroundTurn(thread, prompt, asJson) {
291
+ const { lock: lockFile, running } = threadFiles(thread.threadId);
292
+ onStopSignal(() => {
293
+ rmSync(running, { force: true });
294
+ abandonWork();
295
+ process.exit(EXIT_ON_STOP_SIGNAL);
296
+ });
297
+ await lock(lockFile);
298
+ writeJson(running, { pid: process.pid });
299
+ try {
300
+ if (asJson) {
301
+ await printEvents({ type: 'thread.started', thread_id: thread.threadId }, TURN_STARTED);
302
+ }
303
+ if (process.env.FAKE_CODEX_TURN_FAIL) throw new CliError(process.env.FAKE_CODEX_TURN_FAIL);
304
+ const answer = await threadTurn(thread, prompt, 'exec');
305
+ if (!asJson) return await print(answer);
306
+ const item = { id: 'item_0', type: 'agent_message', text: answer };
307
+ await printEvents({ type: 'item.completed', item }, TURN_COMPLETED);
308
+ } finally {
309
+ rmSync(running, { force: true });
310
+ unlock(lockFile);
311
+ }
312
+ }
313
+
314
+ async function printEvents(...events) {
315
+ for (const event of events) await print(JSON.stringify(event));
316
+ }
317
+
318
+ /** One turn of a thread. The caller holds the lock of the thread */
319
+ async function threadTurn(thread, input, wokenBy) {
320
+ const env = sandboxedEnv(
321
+ {
322
+ ...process.env,
323
+ CODEX_THREAD_ID: thread.threadId,
324
+ ...(thread.sandbox !== undefined && { FAKE_CODEX_SANDBOX: thread.sandbox }),
325
+ },
326
+ thread.sandbox,
327
+ thread.cwd
328
+ );
329
+ const servers = toolServers(thread.servers ?? {}, {
330
+ cwd: thread.cwd,
331
+ envOf: (config) => ({
332
+ ...Object.fromEntries(
333
+ SERVER_ENV.flatMap((name) =>
334
+ process.env[name] === undefined ? [] : [[name, process.env[name]]]
335
+ )
336
+ ),
337
+ ...config.env,
338
+ }),
339
+ clientInfo: { name: 'codex-mcp-client', title: 'Codex', version: version() },
340
+ });
341
+ const turnId = randomUUID();
342
+ try {
343
+ const outcome = await performTurn({
344
+ input,
345
+ cwd: thread.cwd,
346
+ env,
347
+ callTool: (server, tool, args) => callTool(thread, servers, turnId, server, tool, args),
348
+ });
349
+ recordTurn(threadFiles(thread.threadId).transcript, outcome, wokenBy);
350
+ return outcome.answer;
351
+ } finally {
352
+ servers.close();
353
+ }
354
+ }
355
+
356
+ /** Whether a tool says it changes nothing, or destroys nothing and stays in a closed world */
357
+ function isHarmless(annotations) {
358
+ return (
359
+ annotations?.readOnlyHint === true ||
360
+ (annotations?.destructiveHint === false && annotations?.openWorldHint === false)
361
+ );
362
+ }
363
+
364
+ /**
365
+ * One tool call of a thread. A thread nobody sits at (`exec`) is refused a tool it would have
366
+ * to ask about. The thread is named in `_meta`, the only place a server learns it from.
367
+ */
368
+ async function callTool(thread, servers, turnId, serverName, toolName, args) {
369
+ const found = await servers.get(serverName);
370
+ if (!found) return { text: `unknown MCP server '${serverName}'`, isError: true };
371
+ const tool = found.tools.find(({ name }) => name === toolName);
372
+ if (!tool) return { text: `unknown tool '${toolName}' of '${serverName}'`, isError: true };
373
+ if (thread.owner === 'none' && !isHarmless(tool.annotations)) {
374
+ return { text: NEEDS_APPROVAL, isError: true };
375
+ }
376
+ const { threadId } = thread;
377
+ return found.server.call(toolName, args, {
378
+ callId: `exec-${randomUUID()}`,
379
+ 'x-codex-turn-metadata': {
380
+ session_id: threadId,
381
+ thread_id: threadId,
382
+ turn_id: turnId,
383
+ sandbox_mode: thread.sandbox ?? 'danger-full-access',
384
+ codex_version: version(),
385
+ },
386
+ threadId,
387
+ sessionId: threadId,
388
+ progressToken: 1,
389
+ });
390
+ }
391
+
392
+ async function open(argv) {
393
+ const { values, positionals } = parseArgs(argv, OPEN_FLAGS);
394
+ const owner = values.owner ?? 'app';
395
+ if (positionals.length > 0 || !THREAD_OWNERS.includes(owner)) throw new Unsupported();
396
+ const thread = createThread({
397
+ cwd: workFolder(values.cd),
398
+ sandbox: values.sandbox,
399
+ owner,
400
+ servers: configuredServers(),
401
+ });
402
+ await print(thread.threadId);
403
+ }
404
+
405
+ /** `mcp add`, `get`, `list` and `remove`: the servers every new thread gets */
406
+ async function mcp(argv) {
407
+ const [action, ...rest] = argv;
408
+ const servers = configuredServers();
409
+ const save = () => writeJson(configFile(), { mcp_servers: servers });
410
+ const shown = (name) => ({
411
+ name,
412
+ enabled: true,
413
+ disabled_reason: null,
414
+ transport: {
415
+ type: 'stdio',
416
+ command: servers[name].command,
417
+ args: servers[name].args ?? [],
418
+ env: servers[name].env ?? null,
419
+ env_vars: [],
420
+ cwd: null,
421
+ },
422
+ });
423
+ if (action === 'add') {
424
+ const { values, positionals } = parseArgs(rest, MCP_ADD_FLAGS);
425
+ const [name, command, ...args] = positionals;
426
+ const env = envPairs(values.env ?? []);
427
+ if (name === undefined || command === undefined || env === undefined) throw new Unsupported();
428
+ servers[name] = { command, args, ...(Object.keys(env).length > 0 && { env }) };
429
+ save();
430
+ return print(`Added global MCP server '${name}'.`);
431
+ }
432
+ const { values, positionals } = parseArgs(rest, MCP_JSON_FLAGS);
433
+ const [name] = positionals;
434
+ if (action === 'list' && positionals.length === 0) {
435
+ const all = Object.keys(servers).map(shown);
436
+ return print(values.json ? JSON.stringify(all, null, 2) : all.map((s) => s.name).join('\n'));
437
+ }
438
+ if (positionals.length !== 1) throw new Unsupported();
439
+ const known = Object.hasOwn(servers, name);
440
+ if (action === 'get') {
441
+ if (!known) throw new CliError(`Error: No MCP server named '${name}' found.`);
442
+ const { transport } = shown(name);
443
+ return print(
444
+ values.json
445
+ ? JSON.stringify(shown(name), null, 2)
446
+ : `${name}\n enabled: true\n transport: stdio\n command: ${transport.command}\n args: ${transport.args.join(' ')}`
447
+ );
448
+ }
449
+ if (action !== 'remove') throw new Unsupported();
450
+ if (!known) return print(`No MCP server named '${name}' found.`);
451
+ delete servers[name];
452
+ save();
453
+ return print(`Removed global MCP server '${name}'.`);
454
+ }
455
+
456
+ async function queue(argv) {
457
+ if (missing().has('queue')) throw new CliError("error: unrecognized subcommand 'queue'", 2);
458
+ const { values, positionals } = parseArgs(argv, QUEUE_FLAGS);
459
+ if (values.help) return print(renderHelp(QUEUE_HELP, missing()));
460
+ const { thread: threadId, message } = values;
461
+ if (threadId === undefined || message === undefined || positionals.length > 0) {
462
+ throw new Unsupported();
463
+ }
464
+ findThread(threadId);
465
+ const messageId = randomUUID();
466
+ enqueue(threadFiles(threadId).queue, { text: message });
467
+ await print(`Queued message ${messageId} for thread ${threadId}.`);
468
+ if (values.resume && !isOwnerAlive('daemon')) {
469
+ process.stderr.write(
470
+ `Warning: message was queued, but could not resume thread ${threadId}: ` +
471
+ 'start a local daemon or specify a server with --remote\n'
472
+ );
473
+ }
474
+ }
475
+
476
+ function isOwnerAlive(kind) {
477
+ const pid = readJson(ownerFile(kind))?.pid;
478
+ return pid !== undefined && isAlive(pid);
479
+ }
480
+
481
+ async function appServer(argv) {
482
+ const [group, ...rest] = argv;
483
+ if (group !== 'daemon') throw new Unsupported();
484
+ if (rest.length === 1 && rest[0] === 'version') return daemonVersion();
485
+ return ownerCommand('daemon', rest);
486
+ }
487
+
488
+ async function daemonVersion() {
489
+ if (!isOwnerAlive('daemon')) {
490
+ const socket = join(stateRoot('codex'), 'app-server-control', 'app-server-control.sock');
491
+ throw new CliError(`Error: failed to connect to ${socket}`);
492
+ }
493
+ await print(JSON.stringify({ cliVersion: version(), appServerVersion: version() }));
494
+ }
495
+
496
+ /** `start` or `stop` of the daemon, or of the stand-in of the desktop app */
497
+ async function ownerCommand(kind, argv) {
498
+ const [action] = argv;
499
+ if (argv.length !== 1 || !['start', 'stop'].includes(action)) throw new Unsupported();
500
+ await print(action === 'start' ? startOwner(kind) : await stopOwner(kind));
501
+ }
502
+
503
+ function startOwner(kind) {
504
+ if (isOwnerAlive(kind)) return 'already running';
505
+ writeJson(ownerFile(kind), { pid: spawnDetached(SELF, ['__owner', kind]) });
506
+ return 'started';
507
+ }
508
+
509
+ async function stopOwner(kind) {
510
+ const running = isOwnerAlive(kind);
511
+ if (running) await terminate(readJson(ownerFile(kind)).pid);
512
+ rmSync(ownerFile(kind), { force: true });
513
+ return running ? 'stopped' : 'not running';
514
+ }
515
+
516
+ /**
517
+ * An owner process: runs the queued messages of the threads it serves, each message as one
518
+ * turn. The daemon serves every thread, the app only the threads it owns.
519
+ */
520
+ async function serve(argv) {
521
+ const [kind] = argv;
522
+ if (argv.length !== 1 || !OWNER_KINDS.includes(kind)) throw new Unsupported();
523
+ if ((await awaitJson(ownerFile(kind))) === undefined) return;
524
+ boundLife(ownerFile(kind), () => {
525
+ abandonWork();
526
+ process.exit(0);
527
+ });
528
+ const draining = new Set();
529
+ for (;;) {
530
+ for (const thread of listRecords(threadsDir())) {
531
+ const { threadId, owner } = thread;
532
+ if ((kind === 'app' && owner !== 'app') || draining.has(threadId)) continue;
533
+ draining.add(threadId);
534
+ void drain(thread).finally(() => draining.delete(threadId));
535
+ }
536
+ await sleep(POLL_MS);
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Runs what waits in the queue of a thread, in order. The lock keeps it to one turn at a time
542
+ * per thread when the daemon, the app and `exec resume` meet on it.
543
+ */
544
+ async function drain(thread) {
545
+ const files = threadFiles(thread.threadId);
546
+ if (pending(files.queue).length === 0 || !tryLock(files.lock)) return;
547
+ try {
548
+ for (let message = takeNext(files.queue); message; message = takeNext(files.queue)) {
549
+ await threadTurn(thread, message.text, 'queue');
550
+ }
551
+ } finally {
552
+ unlock(files.lock);
553
+ }
554
+ }
555
+
556
+ async function remove(argv) {
557
+ const { values, positionals } = parseArgs(argv, DELETE_FLAGS);
558
+ const [threadId] = positionals;
559
+ if (positionals.length !== 1) throw new Unsupported();
560
+ if (!values.force) throw new CliError(`error: deleting thread ${threadId} needs --force`, 2);
561
+ findThread(threadId);
562
+ const files = threadFiles(threadId);
563
+ await lock(files.lock);
564
+ rmSync(files.record, { force: true });
565
+ rmSync(files.transcript, { force: true });
566
+ rmSync(files.queue, { recursive: true, force: true });
567
+ rmSync(files.running, { force: true });
568
+ unlock(files.lock);
569
+ }
570
+
571
+ await runCli('codex', main);