@zvada/agent-server 0.3.20 → 0.3.22

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 (77) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +2 -1
  3. package/dist/types/client/connection.d.ts +2 -0
  4. package/dist/types/client/connection.d.ts.map +1 -1
  5. package/dist/types/client/logins.d.ts +2 -2
  6. package/dist/types/client/logins.d.ts.map +1 -1
  7. package/dist/types/core/agents/claude-code/approvals.d.ts +16 -5
  8. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  9. package/dist/types/core/agents/claude-code/options.d.ts +5 -3
  10. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  11. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  12. package/dist/types/core/agents/codex-app-server/client.d.ts +9 -0
  13. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  14. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +3 -1
  15. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -1
  16. package/dist/types/core/agents/codex-app-server/homes.d.ts +7 -5
  17. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  18. package/dist/types/core/agents/codex-app-server/mcp.d.ts +48 -8
  19. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -1
  20. package/dist/types/core/agents/codex-app-server/options.d.ts +6 -2
  21. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -1
  22. package/dist/types/core/agents/codex-app-server/session.d.ts +10 -1
  23. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  24. package/dist/types/core/agents/codex-app-server/turn.d.ts +6 -0
  25. package/dist/types/core/agents/codex-app-server/turn.d.ts.map +1 -1
  26. package/dist/types/core/agents/plan.d.ts +2 -13
  27. package/dist/types/core/agents/plan.d.ts.map +1 -1
  28. package/dist/types/core/index.d.ts +1 -1
  29. package/dist/types/core/index.d.ts.map +1 -1
  30. package/dist/types/core/runtime/agent-runtime.d.ts +2 -1
  31. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  32. package/dist/types/core/runtime/turn.d.ts +2 -0
  33. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  34. package/dist/types/core/utils/errors.d.ts +8 -0
  35. package/dist/types/core/utils/errors.d.ts.map +1 -1
  36. package/dist/types/operator/index.d.ts +11 -0
  37. package/dist/types/operator/index.d.ts.map +1 -0
  38. package/dist/types/operator/mcp.d.ts +33 -0
  39. package/dist/types/operator/mcp.d.ts.map +1 -0
  40. package/dist/types/operator/operator.d.ts +206 -0
  41. package/dist/types/operator/operator.d.ts.map +1 -0
  42. package/dist/types/operator/render.d.ts +87 -0
  43. package/dist/types/operator/render.d.ts.map +1 -0
  44. package/dist/types/operator/view.d.ts +44 -0
  45. package/dist/types/operator/view.d.ts.map +1 -0
  46. package/dist/types/protocol/plan.d.ts +20 -0
  47. package/dist/types/protocol/plan.d.ts.map +1 -0
  48. package/dist/types/server/acp/binding.d.ts.map +1 -1
  49. package/dist/types/sync/worker.d.ts.map +1 -1
  50. package/docs/consuming.md +188 -14
  51. package/docs/harnesses.md +13 -8
  52. package/package.json +6 -1
  53. package/src/client/connection.ts +10 -0
  54. package/src/client/logins.ts +23 -14
  55. package/src/core/agents/claude-code/approvals.ts +33 -6
  56. package/src/core/agents/claude-code/options.ts +5 -3
  57. package/src/core/agents/claude-code/session.ts +4 -2
  58. package/src/core/agents/codex-app-server/client.ts +32 -2
  59. package/src/core/agents/codex-app-server/codex-agent.ts +26 -5
  60. package/src/core/agents/codex-app-server/homes.ts +16 -9
  61. package/src/core/agents/codex-app-server/mcp.ts +122 -21
  62. package/src/core/agents/codex-app-server/options.ts +10 -1
  63. package/src/core/agents/codex-app-server/session.ts +46 -9
  64. package/src/core/agents/codex-app-server/turn.ts +26 -12
  65. package/src/core/agents/plan.ts +3 -19
  66. package/src/core/index.ts +1 -0
  67. package/src/core/runtime/agent-runtime.ts +22 -16
  68. package/src/core/runtime/turn.ts +2 -0
  69. package/src/core/utils/errors.ts +13 -0
  70. package/src/operator/index.ts +40 -0
  71. package/src/operator/mcp.ts +171 -0
  72. package/src/operator/operator.ts +778 -0
  73. package/src/operator/render.ts +435 -0
  74. package/src/operator/view.ts +82 -0
  75. package/src/protocol/plan.ts +35 -0
  76. package/src/server/acp/binding.ts +3 -2
  77. package/src/sync/worker.ts +4 -0
@@ -90,7 +90,9 @@ export interface CodexAppServerAgentOptions {
90
90
  processes?: NativeProcesses;
91
91
  /**
92
92
  * What a thread loads by itself (LLP 0001, D17). At `all` (the default) a
93
- * turn runs in the `CODEX_HOME` it names, else the process's. At `project`
93
+ * turn runs in the `CODEX_HOME` it names, else the process's, which the
94
+ * engine never writes: there a turn's MCP servers go in its thread's own
95
+ * config (D21). At `project`
94
96
  * every turn must name a home of its session's own (absolute, not the
95
97
  * shared one, one session to a home): the user's configuration stays out,
96
98
  * the repository's `AGENTS.md` and skills load. `none` also keeps the
@@ -166,6 +168,18 @@ export class CodexAppServerAgent extends SessionAgent {
166
168
  let session: CodexSession | undefined;
167
169
  let stop: TurnStop | undefined;
168
170
  let turn: CodexTurn | undefined;
171
+ // @ref LLP 0001#d21--a-codex-turn-that-names-no-home-carries-its-mcp-servers-in-its-thread — a thread is the session's once Codex takes a turn on it
172
+ // The thread the turn asked for is the session's already. One this turn
173
+ // started is not yet: Codex writes a thread at its first turn, so until
174
+ // then nothing of it can be resumed, and a turn that fails before
175
+ // leaves the session without a conversation, not with one no later
176
+ // process could resume.
177
+ let named = false;
178
+ const nameStarted = () => {
179
+ if (named || !session || !turn?.taken) return;
180
+ named = true;
181
+ options.onNativeSession?.(session.threadId, { resumed: false });
182
+ };
169
183
  try {
170
184
  signal.throwIfAborted();
171
185
  // @ref LLP 0001#d5--messages-map-to-model-messages-no-silent-surface — no silent surface
@@ -187,9 +201,8 @@ export class CodexAppServerAgent extends SessionAgent {
187
201
  });
188
202
  signal.throwIfAborted();
189
203
  session = await this.sessions.acquire(options, scope, mcp);
190
- options.onNativeSession?.(session.threadId, {
191
- resumed: session.threadId === options.resumeSessionId,
192
- });
204
+ named = session.threadId === options.resumeSessionId;
205
+ if (named) options.onNativeSession?.(session.threadId, { resumed: true });
193
206
  const commands = new TurnCommands(session.client, session.threadId, this.timing.graceMs);
194
207
  stop = this.stopFor(session, scope, commands, options.sessionId);
195
208
  signal.throwIfAborted();
@@ -206,8 +219,16 @@ export class CodexAppServerAgent extends SessionAgent {
206
219
  };
207
220
  turn = new CodexTurn(session, scope, options, commands, stop, steering, this.timing);
208
221
  this.turns.set(controller, turn);
209
- yield* turn.run(userInput);
222
+ for await (const event of turn.run(userInput)) {
223
+ nameStarted();
224
+ yield event;
225
+ }
210
226
  } catch (error) {
227
+ // A turn Codex took is on the thread, whatever came of it. A session
228
+ // released meanwhile refuses the name; the turn ends as it was ending.
229
+ try {
230
+ nameStarted();
231
+ } catch {}
211
232
  if (!signal.aborted) throw error;
212
233
  if (turn) yield* turn.endCancelled();
213
234
  throw new Error("turn aborted");
@@ -8,10 +8,12 @@ import type { InheritConfig } from "../inherit-config.ts";
8
8
  /**
9
9
  * Which logical session owns each `CODEX_HOME` its turns name. A turn that
10
10
  * names one claims it for its session, which keeps it until it is released,
11
- * through process eviction and failed preparation: one session to a home. A
12
- * turn with MCP servers must name one, since the engine writes them there,
13
- * and below `inheritConfig: "all"` every turn must: the user's own home holds
14
- * the user's configuration. That home is never claimed, nor written to.
11
+ * through process eviction and failed preparation: one session to a home,
12
+ * since the engine writes the turn's MCP servers there. Below
13
+ * `inheritConfig: "all"` every turn must name one: the user's own home holds
14
+ * the user's configuration. At `all` a turn that names none runs in the
15
+ * process's, the user's own, which is never claimed, nor written to: its
16
+ * MCP servers go in its thread's config instead (`mcp.ts`).
15
17
  */
16
18
  export class CodexHomes {
17
19
  private readonly owners = new Map<string, string>();
@@ -19,7 +21,7 @@ export class CodexHomes {
19
21
  constructor(private readonly level: InheritConfig = "all") {}
20
22
 
21
23
  /** Whether the turn runs in a home of its session's own, which it claims. */
22
- claim(options: AgentExecuteOptions, hasServers: boolean): boolean {
24
+ claim(options: AgentExecuteOptions): boolean {
23
25
  const home = options.env?.CODEX_HOME;
24
26
  // @ref LLP 0001#d17--a-turn-inherits-what-the-operator-chooses-all-the-projects-or-none — every turn's home, below `all`
25
27
  const needs =
@@ -28,22 +30,27 @@ export class CodexHomes {
28
30
  const refused = (message: string) =>
29
31
  new InvalidRequestError([{ path: "env.CODEX_HOME", message }]);
30
32
  if (!home) {
31
- if (this.level === "all" && !hasServers) return false;
33
+ if (this.level === "all") return false;
32
34
  throw refused(
33
35
  `${needs} requires a session-specific one (an existing absolute folder no other session uses)`,
34
36
  );
35
37
  }
36
38
  if (!isAbsolute(home)) throw refused("must be an absolute path");
37
39
  const shared = resolve(process.env.CODEX_HOME ?? `${homedir()}/.codex`);
38
- if (resolve(home) === shared) throw refused(`${needs} cannot use the user's shared one`);
40
+ // A home a turn names is written to. At `all` a turn runs in the user's
41
+ // by naming none.
42
+ const isShared = () =>
43
+ refused(
44
+ `${needs} cannot use the user's shared one${this.level === "all" ? " as a session's home; leave it out to run there" : ""}`,
45
+ );
46
+ if (resolve(home) === shared) throw isShared();
39
47
  let path: string;
40
48
  try {
41
49
  path = realpathSync(home);
42
50
  } catch {
43
51
  throw refused(`${home} must be an existing folder`);
44
52
  }
45
- if (existsSync(shared) && path === realpathSync(shared))
46
- throw refused(`${needs} cannot use the user's shared one`);
53
+ if (existsSync(shared) && path === realpathSync(shared)) throw isShared();
47
54
  const owner = this.owners.get(path);
48
55
  if (owner && owner !== options.sessionId) {
49
56
  throw refused(
@@ -1,4 +1,6 @@
1
1
  import { AsyncQueue, type ErrorInfo, type McpServerConfig } from "../../../protocol/index.ts";
2
+ import { InvalidRequestError } from "../../utils/errors.ts";
3
+ import { isRecord } from "../../utils/is-record.ts";
2
4
  import type { AgentExecuteOptions } from "../base.ts";
3
5
  import { configFingerprint } from "../config-fingerprint.ts";
4
6
  import {
@@ -86,6 +88,51 @@ export async function assertCodexMcpConfig(
86
88
  }
87
89
  }
88
90
 
91
+ /** A higher layer of Codex's configuration over a lower: tables key by key, anything else replaced. */
92
+ function mergedOver(base: unknown, over: unknown): unknown {
93
+ if (!isRecord(base) || !isRecord(over)) return over;
94
+ const merged: Record<string, unknown> = { ...base };
95
+ for (const [key, value] of Object.entries(over)) merged[key] = mergedOver(base[key], value);
96
+ return merged;
97
+ }
98
+
99
+ // @ref LLP 0001#d21--a-codex-turn-that-names-no-home-carries-its-mcp-servers-in-its-thread — a name Codex's own configuration has
100
+ /**
101
+ * Refuse a turn's server that Codex's own configuration would change. A
102
+ * server in a thread's config is the top layer of Codex's, merged table by
103
+ * table over one of the same name in the user's or the repository's: the
104
+ * turn's values win, and whatever else the other sets stays (its headers
105
+ * and environment sent to the turn's server, its tool filter, `enabled =
106
+ * false`). One that sets nothing more is the turn's server whole, and
107
+ * goes on. Asked before the thread opens, so no connection is made first.
108
+ */
109
+ export async function assertCodexThreadMcp(
110
+ client: Pick<CodexConnection, "request">,
111
+ cwd: string,
112
+ servers: Record<string, unknown>,
113
+ ): Promise<void> {
114
+ if (!Object.keys(servers).length) return;
115
+ const result = (await client.request("config/read", { cwd })) as {
116
+ config?: { mcp_servers?: Record<string, unknown> };
117
+ };
118
+ const native = result.config?.mcp_servers ?? {};
119
+ const changed = Object.entries(servers).flatMap(([name, server]) =>
120
+ native[name] !== undefined &&
121
+ configFingerprint(normalizedConfig(mergedOver(native[name], server))) !==
122
+ configFingerprint(normalizedConfig(server))
123
+ ? [name]
124
+ : [],
125
+ );
126
+ if (changed.length)
127
+ throw new InvalidRequestError(
128
+ changed.map((name) => ({
129
+ path: `mcpServers.${name}`,
130
+ message:
131
+ "Codex's own configuration (the user's or the repository's) has a server of this name, whose settings would apply to the turn's; rename one of them",
132
+ })),
133
+ );
134
+ }
135
+
89
136
  /**
90
137
  * Codex's startup error for a server, readable: its Rust type paths out, a
91
138
  * chain it repeats said once, and no prefix naming the server again.
@@ -193,28 +240,45 @@ export async function settleCodexMcp(
193
240
  }
194
241
  }
195
242
 
196
- /** A turn's MCP servers: as the wire gave them, and as Codex takes them, when its home is the engine's. */
243
+ /**
244
+ * A turn's MCP servers: as the wire gave them, and as Codex takes them, by
245
+ * where they go. A turn that names a home has them written there
246
+ * (`servers`); one that names none has them in its thread's own config
247
+ * (`thread`), which is fixed when the thread is opened.
248
+ */
197
249
  export interface CodexTurnMcp {
198
250
  wire: Record<string, McpServerConfig>;
199
- /** Absent when the turn runs in a home the engine does not write. */
251
+ /** For the home the turn names, `{}` when it has none: that home's servers are the turn's. */
200
252
  servers?: Record<string, unknown>;
253
+ /** For the thread's own config: a turn with servers that names no home, which the engine never writes. */
254
+ thread?: Record<string, unknown>;
201
255
  }
202
256
 
203
257
  /** The turn's servers, snapshotted before anything asynchronous can let the caller change them. */
204
258
  export function codexTurnMcp(options: AgentExecuteOptions, homes: CodexHomes): CodexTurnMcp {
205
259
  const wire = snapshotMcpServers(options.mcpServers);
206
260
  const servers = codexMcpServers(wire);
207
- return homes.claim(options, Object.keys(servers).length > 0) ? { wire, servers } : { wire };
261
+ if (homes.claim(options)) return { wire, servers };
262
+ return Object.keys(servers).length ? { wire, thread: servers } : { wire };
263
+ }
264
+
265
+ /** Which servers a thread's own config holds: a turn with another set runs on a thread opened again. */
266
+ export function threadMcpFingerprint(mcp: CodexTurnMcp): string {
267
+ return configFingerprint(mcp.thread ?? {});
208
268
  }
209
269
 
210
270
  /**
211
- * A session's MCP servers on Codex: the configuration last written to its
212
- * home, why each server last failed to start, and the ones its turns went
213
- * without.
271
+ * A session's MCP servers on Codex, for one process: the configuration last
272
+ * written to its home, why each server last failed to start, and the ones
273
+ * its turns went without.
214
274
  */
215
275
  export class CodexMcpState {
216
276
  /** Last native config write; readiness is checked separately before every prompt. */
217
277
  private fingerprint?: string;
278
+ /** A turn was prepared on this process: the servers its thread carries started when it opened. */
279
+ private prepared = false;
280
+ /** The last turn's servers did not settle: the next one starts them again. */
281
+ private unsettled = false;
218
282
  /**
219
283
  * Why each MCP server last failed to start, as Codex said, from the
220
284
  * client's first notification: a fast failure can come before a turn asks.
@@ -239,8 +303,14 @@ export class CodexMcpState {
239
303
  else if (params.status === "ready" || params.status === "starting") this.causes.delete(name);
240
304
  }
241
305
 
242
- /** Write the turn's servers to the session's home, check Codex took them, and reload them when they changed. */
243
- async configure(servers: Record<string, unknown> | undefined): Promise<void> {
306
+ /**
307
+ * Before the thread opens, and before each turn. Servers for the home the
308
+ * turn names are written there, checked as Codex took them, and reloaded
309
+ * when they changed; servers the thread carries are checked against
310
+ * Codex's own configuration.
311
+ */
312
+ async configure({ servers, thread }: CodexTurnMcp): Promise<void> {
313
+ if (thread) return assertCodexThreadMcp(this.client, this.cwd, thread);
244
314
  if (servers === undefined) return;
245
315
  const fingerprint = configFingerprint(servers);
246
316
  const changed = this.fingerprint !== fingerprint;
@@ -259,26 +329,57 @@ export class CodexMcpState {
259
329
  */
260
330
  async prepare(
261
331
  threadId: string,
262
- { wire, servers }: CodexTurnMcp,
332
+ mcp: CodexTurnMcp,
263
333
  onWarning: ((warning: ErrorInfo) => Promise<void>) | undefined,
264
334
  ): Promise<void> {
265
- // A server the last turn went without is reloaded once due (a reload
266
- // restarts the thread's servers, so not on every turn), or at once
267
- // when this turn requires it: its old failure must not decide.
268
- if (this.unavailable.retryNow(wire).length) this.fingerprint = undefined;
269
- const reloading = servers !== undefined && this.fingerprint !== configFingerprint(servers);
270
- await this.configure(servers);
335
+ // A server the last turn went without is started again once it is due
336
+ // (not on every turn: a reload is a round trip to every server that is
337
+ // down), or at once when this turn requires it: its old failure must
338
+ // not decide. So is every server after a turn whose servers did not settle.
339
+ const again = this.unavailable.retryNow(mcp.wire).length > 0 || this.unsettled;
340
+ const started = mcp.thread
341
+ ? await this.startThreadServers(mcp, again)
342
+ : await this.startHomeServers(mcp, again);
271
343
  let unavailable: Record<string, string>;
272
344
  try {
273
- unavailable = await settleCodexMcp(this.client, threadId, servers ? wire : {}, this.causes);
345
+ unavailable = await settleCodexMcp(this.client, threadId, mcp.wire, this.causes);
274
346
  } catch (error) {
275
- // A later explicit turn must reload failed clients even if config is unchanged.
276
- this.fingerprint = undefined;
347
+ this.unsettled = true;
277
348
  throw error;
278
349
  }
279
- // The turn goes on without a server it does not require, and says so;
280
- // a reload restarts every server of the thread, so it tried them all.
281
- this.unavailable.record(unavailable, () => reloading);
350
+ this.unsettled = false;
351
+ // The turn goes on without a server it does not require, and says so.
352
+ // `started`: this turn tried the ones that were down, so their clock starts now.
353
+ this.unavailable.record(unavailable, () => started);
282
354
  await this.unavailable.announce(onWarning);
283
355
  }
356
+
357
+ /**
358
+ * The servers of a home the turn names: written, checked and reloaded when
359
+ * they changed or are to be started `again`. Whether this turn started them.
360
+ */
361
+ private async startHomeServers(mcp: CodexTurnMcp, again: boolean): Promise<boolean> {
362
+ // Forgetting the last write makes `configure` write and reload it again.
363
+ if (again) this.fingerprint = undefined;
364
+ const starting =
365
+ mcp.servers !== undefined && this.fingerprint !== configFingerprint(mcp.servers);
366
+ await this.configure(mcp);
367
+ return starting;
368
+ }
369
+
370
+ // @ref LLP 0001#d21--a-codex-turn-that-names-no-home-carries-its-mcp-servers-in-its-thread — a reload starts a thread's own servers again
371
+ /**
372
+ * The servers a thread carries: they started when it opened, on the first
373
+ * turn this process prepares. After that a reload starts the ones that are
374
+ * not running `again` and leaves the others connected. Whether this turn
375
+ * started them.
376
+ */
377
+ private async startThreadServers(mcp: CodexTurnMcp, again: boolean): Promise<boolean> {
378
+ await this.configure(mcp);
379
+ const reloading = this.prepared && again;
380
+ if (reloading) await this.client.request("config/mcpServer/reload", undefined);
381
+ const started = reloading || !this.prepared;
382
+ this.prepared = true;
383
+ return started;
384
+ }
284
385
  }
@@ -111,10 +111,15 @@ export function clientOptionsFor(
111
111
  const MANAGED_SUBAGENTS =
112
112
  "Collect the results of every subagent before ending your turn. Stop any worker you no longer need. Delegated work cannot continue after this task completes.";
113
113
 
114
- /** The params `thread/start` and `thread/resume` take for a turn with these options. */
114
+ /**
115
+ * The params `thread/start` and `thread/resume` take for a turn with these
116
+ * options. `mcpServers`: the servers the thread carries in its own config,
117
+ * for a turn that names no home.
118
+ */
115
119
  export function threadParams(
116
120
  options: AgentExecuteOptions,
117
121
  inheritConfig: InheritConfig = "all",
122
+ mcpServers?: Record<string, unknown>,
118
123
  ): Record<string, unknown> {
119
124
  const identity = processIdentity(options);
120
125
  // @ref LLP 0001#d14--nothing-the-agent-does-is-off-the-stream — Codex continues a goal by itself
@@ -129,6 +134,10 @@ export function threadParams(
129
134
  // Codex reads every AGENTS.md from the repository's root to the working
130
135
  // folder by itself; at `none`, none of them. The home's own still loads.
131
136
  if (inheritConfig === "none") config.project_doc_max_bytes = 0;
137
+ // @ref LLP 0001#d21--a-codex-turn-that-names-no-home-carries-its-mcp-servers-in-its-thread — the thread's own config
138
+ // Beside the servers of Codex's own configuration, by name; no file is
139
+ // written, and a resume without them has none of them.
140
+ if (mcpServers) config.mcp_servers = mcpServers;
132
141
  const instructions =
133
142
  options.subagentMode === "turn"
134
143
  ? [options.systemPromptAppend, MANAGED_SUBAGENTS].filter(Boolean).join("\n\n")
@@ -6,7 +6,7 @@ import { SessionPool } from "../session-pool.ts";
6
6
  import type { CodexConnection } from "./client.ts";
7
7
  import { type CodexAuth, authFingerprint, logIn } from "./credentials.ts";
8
8
  import { CodexHomes } from "./homes.ts";
9
- import { CodexMcpState, type CodexTurnMcp, codexTurnMcp } from "./mcp.ts";
9
+ import { CodexMcpState, type CodexTurnMcp, codexTurnMcp, threadMcpFingerprint } from "./mcp.ts";
10
10
  import type { CodexModelThinking } from "./models.ts";
11
11
  import {
12
12
  type CodexProcessIdentity,
@@ -25,6 +25,11 @@ export interface CodexSession extends CodexProcessIdentity {
25
25
  /** Native model connections retain the identity used at their first handshake. */
26
26
  authFingerprint?: string;
27
27
  mcp: CodexMcpState;
28
+ /**
29
+ * The MCP servers its thread was opened with, in the thread's own config
30
+ * (`threadMcpFingerprint`): a turn with another set runs in another process.
31
+ */
32
+ threadMcp: string;
28
33
  /** The logical session's thread settings, which outlive this process. */
29
34
  thread: CodexThread;
30
35
  /** The turn that has the session: Codex's requests answer for it alone. */
@@ -50,15 +55,17 @@ export type CodexConnector = (
50
55
 
51
56
  /**
52
57
  * Start the session's thread, or resume the one it names: never a new one in
53
- * its place, so a resume that fails fails the turn.
58
+ * its place, so a resume that fails fails the turn. `mcpServers`: the
59
+ * servers the thread carries in its own config.
54
60
  */
55
61
  async function openThread(
56
62
  client: CodexConnection,
57
63
  options: AgentExecuteOptions,
58
64
  inheritConfig: InheritConfig,
65
+ mcpServers: Record<string, unknown> | undefined,
59
66
  ): Promise<CodexThreadOpened & { threadId: string }> {
60
67
  const resume = options.resumeSessionId;
61
- const params = threadParams(options, inheritConfig);
68
+ const params = threadParams(options, inheritConfig, mcpServers);
62
69
  const opened = (await client
63
70
  .request(
64
71
  resume ? "thread/resume" : "thread/start",
@@ -94,6 +101,8 @@ export class CodexSessions {
94
101
  private readonly unsettled = new Map<string, CodexConnection>();
95
102
  /** Counts the login changes: a process keeps the login it read at its start. */
96
103
  private login = 0;
104
+ /** Each session's process that was ended and has not exited yet: when it has. */
105
+ private readonly leaving = new Map<string, Promise<void>>();
97
106
 
98
107
  constructor(
99
108
  private readonly connect: CodexConnector,
@@ -119,7 +128,9 @@ export class CodexSessions {
119
128
  * thread. Codex caches an authenticated model WebSocket across turns, so
120
129
  * login alone cannot switch its identity: an account or key change
121
130
  * restarts the process and resumes the thread. Same-account token renewal
122
- * keeps it warm.
131
+ * keeps it warm. So does an unchanged set of the servers the thread
132
+ * carries; a thread's config is fixed once it is open, so another set
133
+ * resumes the thread in a new process.
123
134
  */
124
135
  async acquire(
125
136
  options: AgentExecuteOptions,
@@ -133,7 +144,8 @@ export class CodexSessions {
133
144
  codexSessionCompatible(existing, options) &&
134
145
  existing.authFingerprint === authFingerprint(turn.auth) &&
135
146
  !existing.stale &&
136
- existing.login === this.login
147
+ existing.login === this.login &&
148
+ existing.threadMcp === threadMcpFingerprint(mcp)
137
149
  )
138
150
  return this.reuse(existing, turn);
139
151
  this.pool.close(options.sessionId);
@@ -231,9 +243,32 @@ export class CodexSessions {
231
243
  mcp: CodexTurnMcp,
232
244
  ): Promise<CodexSession> {
233
245
  const { signal } = turn;
246
+ const { sessionId } = options;
247
+ // @ref LLP 0001#d21--a-codex-turn-that-names-no-home-carries-its-mcp-servers-in-its-thread — one writer to a thread
248
+ // Codex lets one process write a thread, and refuses a resume while the
249
+ // one before still exits: replaced just now, or ended a while ago. The
250
+ // wait is the stop's grace at most, and a cancelled turn does not sit it out.
251
+ const leaving = this.leaving.get(sessionId);
252
+ if (leaving) {
253
+ let offCancel = () => {};
254
+ const cancelled = new Promise<void>((resolve) => {
255
+ offCancel = onAbort(signal, resolve);
256
+ });
257
+ await Promise.race([leaving, cancelled]);
258
+ offCancel();
259
+ signal.throwIfAborted();
260
+ }
234
261
  const client = await this.connect(options, turn.auth, signal);
235
262
  // Self-heal: if the subprocess ever exits, drop it so the next turn respawns.
236
- client.onClose(() => this.pool.dropIfCurrent(options.sessionId, client));
263
+ client.onClose(() => {
264
+ this.pool.dropIfCurrent(sessionId, client);
265
+ const gone = client.gone?.();
266
+ if (!gone) return;
267
+ this.leaving.set(sessionId, gone);
268
+ void gone.then(() => {
269
+ if (this.leaving.get(sessionId) === gone) this.leaving.delete(sessionId);
270
+ });
271
+ });
237
272
  const untrack = this.pool.trackPending(options.sessionId, client);
238
273
  const offAbort = onAbort(signal, () => client.close());
239
274
  let thread = this.threads.get(options.sessionId);
@@ -248,6 +283,7 @@ export class CodexSessions {
248
283
  authFingerprint: authFingerprint(turn.auth),
249
284
  login: this.login,
250
285
  mcp: new CodexMcpState(client, options.cwd),
286
+ threadMcp: threadMcpFingerprint(mcp),
251
287
  thread,
252
288
  turn,
253
289
  };
@@ -257,9 +293,10 @@ export class CodexSessions {
257
293
  signal.throwIfAborted();
258
294
  await client.initialize();
259
295
  await authenticate(client, turn);
260
- // Clear stale per-turn credentials before thread startup can use them.
261
- await session.mcp.configure(mcp.servers);
262
- const opened = await openThread(client, options, this.inheritConfig);
296
+ // Before the thread opens: a home is cleared of the turn before's
297
+ // servers, and a set the thread carries is checked against Codex's own.
298
+ await session.mcp.configure(mcp);
299
+ const opened = await openThread(client, options, this.inheritConfig, mcp.thread);
263
300
  signal.throwIfAborted();
264
301
  session.threadId = opened.threadId;
265
302
  thread.adopt(opened, options);
@@ -249,6 +249,7 @@ export class CodexTurn {
249
249
  private stallTimer?: ReturnType<typeof setTimeout>;
250
250
  private acknowledged?: Promise<boolean>;
251
251
  private readonly unsubscribe: Array<() => void>;
252
+ private accepted = false;
252
253
 
253
254
  constructor(
254
255
  readonly session: CodexSession,
@@ -289,6 +290,14 @@ export class CodexTurn {
289
290
  return this.acknowledged;
290
291
  }
291
292
 
293
+ /**
294
+ * Codex took a turn of this one (it accepted `turn/start`): from then on
295
+ * it writes the thread, which before had nothing to resume.
296
+ */
297
+ get taken(): boolean {
298
+ return this.accepted;
299
+ }
300
+
292
301
  /** Whether the turn puts Codex's plan to the user: a plan turn with someone to ask. */
293
302
  get asksAboutPlans(): boolean {
294
303
  return this.stop.continues && this.scope.mode === "plan" && !!this.scope.onPermissionRequest;
@@ -366,18 +375,23 @@ export class CodexTurn {
366
375
  this.native = native;
367
376
  session.thread.settings = settings;
368
377
  session.sandbox = sandbox;
369
- session.client.request("turn/start", params).catch((error: unknown) => {
370
- // Codex refused it: the thread is as it was. Anything else leaves the
371
- // thread's settings unknown, so this process is done with.
372
- if (error instanceof CodexRpcError) {
373
- session.thread.settings = previous.settings;
374
- session.sandbox = previous.sandbox;
375
- } else session.client.close();
376
- // A cancelled turn ends by its cancel.
377
- if (this.signal.aborted) return;
378
- native.queue.push({ method: "error", params: { message: String(error) } });
379
- native.finish();
380
- });
378
+ session.client.request("turn/start", params).then(
379
+ () => {
380
+ this.accepted = true;
381
+ },
382
+ (error: unknown) => {
383
+ // Codex refused it: the thread is as it was. Anything else leaves the
384
+ // thread's settings unknown, so this process is done with.
385
+ if (error instanceof CodexRpcError) {
386
+ session.thread.settings = previous.settings;
387
+ session.sandbox = previous.sandbox;
388
+ } else session.client.close();
389
+ // A cancelled turn ends by its cancel.
390
+ if (this.signal.aborted) return;
391
+ native.queue.push({ method: "error", params: { message: String(error) } });
392
+ native.finish();
393
+ },
394
+ );
381
395
  return native;
382
396
  }
383
397
 
@@ -1,23 +1,7 @@
1
- import type { PermissionMode, PermissionOption } from "../../protocol/index.ts";
1
+ import type { PermissionMode } from "../../protocol/index.ts";
2
2
 
3
- // @ref LLP 0001#d4--permission-requests-are-first-class-protocol — a plan's approval picks the mode
4
- /**
5
- * How a user answers an agent's plan: go on in a mode, or keep planning. Each
6
- * option's id is the permission mode the session goes on in. These are Claude
7
- * Code's own choices; Codex's TUI asks the same ("implement this plan" / "stay
8
- * in Plan mode"). Auto-accepting edits is a standing choice for the edits to
9
- * come (`allow_always`, as claude-agent-acp marks it), so an approver that
10
- * takes the one-time approval implements asking for each edit. No standing
11
- * rule answers a later plan: the broker keeps none for a harness's options.
12
- */
13
- export const PLAN_OPTIONS: PermissionOption[] = [
14
- { optionId: "accept_edits", name: "Yes, and auto-accept edits", kind: "allow_always" },
15
- { optionId: "default", name: "Yes, and manually approve edits", kind: "allow_once" },
16
- { optionId: "plan", name: "No, keep planning", kind: "reject_once" },
17
- ];
18
-
19
- /** What a plan's approval asks. */
20
- export const PLAN_TITLE = "Implement this plan?";
3
+ // The plan's options live in the protocol, so a client that asks or answers a plan uses the same ones.
4
+ export { PLAN_OPTIONS, PLAN_TITLE } from "../../protocol/plan.ts";
21
5
 
22
6
  /** The mode an approved plan is implemented in. */
23
7
  export function approvedPlanMode(optionId: string | undefined): PermissionMode {
package/src/core/index.ts CHANGED
@@ -129,6 +129,7 @@ export {
129
129
  HarnessNotAvailableError,
130
130
  InvalidRequestError,
131
131
  TurnConflictError,
132
+ TurnForgottenError,
132
133
  UnknownLoginError,
133
134
  TurnActiveError,
134
135
  UnsupportedAttachmentError,
@@ -20,9 +20,8 @@ import type { AgentRegistry } from "../agents/registry.ts";
20
20
  import type { DiagnosticHandler } from "../diagnostics.ts";
21
21
  import type { NativeRecord } from "../processes/identity.ts";
22
22
  import type { NativeProcessEvent, OrphanOutcome } from "../processes/native-processes.ts";
23
- import { setBounded } from "../utils/bounded.ts";
24
23
  import { withTimeout } from "../utils/deadline.ts";
25
- import { InvalidRequestError, TurnConflictError } from "../utils/errors.ts";
24
+ import { InvalidRequestError, TurnConflictError, TurnForgottenError } from "../utils/errors.ts";
26
25
  import { type EventSink, EventSinkError } from "./event-sink.ts";
27
26
  import { harnessCliProgress, harnessClis } from "./harness-clis.ts";
28
27
  import { HarnessLogins } from "./harness-logins.ts";
@@ -45,7 +44,11 @@ const turnKeyOf = (sessionId: string, turnId: string) => JSON.stringify([session
45
44
  // @ref LLP 0003#commit-before-acknowledging — a turn sent again converges when it is the same turn
46
45
  const inputKeyOf = (request: RunRequest) => canonicalJson(turnIdentity(request));
47
46
 
48
- /** Per-session convergence window; old turns fall out and a stale retry would re-execute. */
47
+ /**
48
+ * Per-session convergence window. An older turn keeps only its id: a retry
49
+ * of it is refused (`TurnForgottenError`), since a turn id names one turn in
50
+ * the session's stream (LLP 0002) and a turn that ran never runs again.
51
+ */
49
52
  const SETTLED_TURNS = 16;
50
53
  /** Give up on stragglers after this long; the process is exiting anyway. */
51
54
  const DEFAULT_DRAIN_TIMEOUT_MS = 10_000;
@@ -221,7 +224,8 @@ export class AgentRuntime {
221
224
  * `new` (would run), `inflight`/`completed` (an identical request was
222
225
  * already admitted — a retry must converge, not re-execute). Throws
223
226
  * `TurnConflictError` when this turnId was admitted with DIFFERENT input,
224
- * and the turn's `EventSinkError` when its durable sink stopped it.
227
+ * or ran too long ago to converge on (`TurnForgottenError`), and the turn's
228
+ * `EventSinkError` when its durable sink stopped it.
225
229
  * Wire seats use this to quick-ack a duplicate instead of starting it.
226
230
  */
227
231
  admission(request: RunRequest): TurnAdmission {
@@ -235,10 +239,12 @@ export class AgentRuntime {
235
239
  /** The admitted turn a request names, in flight or settled; throws as `admission` says. */
236
240
  private known(request: RunRequest): Turn | { summary: RunSummary } | undefined {
237
241
  const { sessionId, turnId } = request;
238
- const known =
239
- this.turns.get(turnKeyOf(sessionId, turnId)) ??
240
- this.sessions.get(sessionId)?.settled.get(turnId);
241
- if (!known) return undefined;
242
+ const memory = this.sessions.get(sessionId);
243
+ const known = this.turns.get(turnKeyOf(sessionId, turnId)) ?? memory?.settled.get(turnId);
244
+ if (!known) {
245
+ if (memory?.forgotten.has(turnId)) throw new TurnForgottenError(sessionId, turnId);
246
+ return undefined;
247
+ }
242
248
  if (known.inputKey !== inputKeyOf(request)) throw new TurnConflictError(sessionId, turnId);
243
249
  if (known instanceof Turn) return known;
244
250
  // It may have run tools before its sink failed: never run it again.
@@ -305,13 +311,13 @@ export class AgentRuntime {
305
311
  ): void {
306
312
  if (this.turns.get(key) === turn) this.turns.delete(key);
307
313
  if (!settled) return;
308
- const { settled: window } = this.memoryOf(turn.sessionId);
309
- setBounded(
310
- window,
311
- turn.turnId,
312
- { inputKey: turn.inputKey, steers: turn.steers.answers(), ...settled },
313
- SETTLED_TURNS,
314
- );
314
+ const { settled: window, forgotten } = this.memoryOf(turn.sessionId);
315
+ window.set(turn.turnId, { inputKey: turn.inputKey, steers: turn.steers.answers(), ...settled });
316
+ for (const oldest of window.keys()) {
317
+ if (window.size <= SETTLED_TURNS) break;
318
+ window.delete(oldest);
319
+ forgotten.add(oldest);
320
+ }
315
321
  }
316
322
 
317
323
  /**
@@ -466,7 +472,7 @@ export class AgentRuntime {
466
472
  private memoryOf(sessionId: string): SessionMemory {
467
473
  let memory = this.sessions.get(sessionId);
468
474
  if (!memory) {
469
- memory = { standingRules: new StandingRules(), settled: new Map() };
475
+ memory = { standingRules: new StandingRules(), settled: new Map(), forgotten: new Set() };
470
476
  this.sessions.set(sessionId, memory);
471
477
  }
472
478
  return memory;
@@ -59,6 +59,8 @@ export interface SessionMemory {
59
59
  announcedNative?: string;
60
60
  /** Its recently settled turns, oldest first: a retry converges on one. */
61
61
  readonly settled: Map<string, SettledTurn>;
62
+ /** The turns that fell out of `settled`, by id: a retry of one is refused, never run again. */
63
+ readonly forgotten: Set<string>;
62
64
  }
63
65
 
64
66
  /** What the runtime lends its turns. */