@rynx-ai/runtime 0.1.11-beta.4 → 0.1.11-beta.41

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 (65) hide show
  1. package/dist/claude/executor.d.ts +19 -5
  2. package/dist/claude/executor.js +56 -12
  3. package/dist/claude/models.d.ts +0 -5
  4. package/dist/claude/models.js +1 -7
  5. package/dist/claude/native-bridge.d.ts +103 -1
  6. package/dist/claude/native-bridge.js +445 -30
  7. package/dist/claude/native-hook-main.js +81 -1
  8. package/dist/claude/native-hooks.js +7 -0
  9. package/dist/claude/native-integration.d.ts +178 -26
  10. package/dist/claude/native-integration.js +1528 -170
  11. package/dist/claude/session-status.d.ts +39 -0
  12. package/dist/claude/session-status.js +163 -0
  13. package/dist/claude/transcript-clone.d.ts +18 -0
  14. package/dist/claude/transcript-clone.js +497 -0
  15. package/dist/claude/transcript.d.ts +27 -4
  16. package/dist/claude/transcript.js +158 -47
  17. package/dist/codex-app-server/client.d.ts +10 -6
  18. package/dist/codex-app-server/client.js +67 -15
  19. package/dist/codex-app-server/forwarder.d.ts +92 -3
  20. package/dist/codex-app-server/forwarder.js +532 -57
  21. package/dist/codex-app-server/mapping.d.ts +3 -6
  22. package/dist/codex-app-server/mapping.js +206 -36
  23. package/dist/codex-app-server/mcp-startup.d.ts +13 -0
  24. package/dist/codex-app-server/mcp-startup.js +63 -0
  25. package/dist/codex-app-server/process-registry.d.ts +36 -0
  26. package/dist/codex-app-server/process-registry.js +320 -0
  27. package/dist/codex-app-server/protocol.d.ts +64 -7
  28. package/dist/codex-app-server/ws-channel.d.ts +7 -0
  29. package/dist/codex-app-server/ws-channel.js +104 -28
  30. package/dist/codex-home.d.ts +35 -3
  31. package/dist/codex-home.js +323 -18
  32. package/dist/codex-session-store.d.ts +23 -0
  33. package/dist/codex-session-store.js +21 -0
  34. package/dist/host.d.ts +103 -46
  35. package/dist/host.js +1988 -634
  36. package/dist/index.d.ts +3 -3
  37. package/dist/index.js +1 -1
  38. package/dist/input-resources.d.ts +4 -0
  39. package/dist/input-resources.js +21 -5
  40. package/dist/models-catalog.d.ts +2 -1
  41. package/dist/models-catalog.js +94 -6
  42. package/dist/runner/child.d.ts +97 -28
  43. package/dist/runner/child.js +1486 -100
  44. package/dist/runner/manager.d.ts +110 -29
  45. package/dist/runner/manager.js +1481 -246
  46. package/dist/runner/protocol.d.ts +212 -24
  47. package/dist/runner/protocol.js +5 -0
  48. package/dist/runner/startup-policy.d.ts +7 -0
  49. package/dist/runner/startup-policy.js +10 -0
  50. package/dist/runner/transport.d.ts +18 -2
  51. package/dist/runner/transport.js +82 -3
  52. package/dist/runner-main.js +8 -3
  53. package/dist/terminal/claude-tui.d.ts +3 -1
  54. package/dist/terminal/claude-tui.js +3 -1
  55. package/dist/terminal/codex-tui.d.ts +4 -0
  56. package/dist/terminal/codex-tui.js +5 -0
  57. package/dist/terminal/control-parser.d.ts +39 -0
  58. package/dist/terminal/control-parser.js +172 -0
  59. package/dist/terminal/registry.d.ts +18 -15
  60. package/dist/terminal/registry.js +44 -23
  61. package/dist/terminal/spool.d.ts +47 -0
  62. package/dist/terminal/spool.js +231 -0
  63. package/dist/terminal/tmux.d.ts +126 -74
  64. package/dist/terminal/tmux.js +807 -211
  65. package/package.json +4 -4
@@ -1,9 +1,23 @@
1
- import { codexUserContent } from "../input-resources.js";
2
- import { mapCodexItem, mapCodexNotification } from "./mapping.js";
1
+ import { codexUserEchoContent } from "../input-resources.js";
2
+ import { codexResumeTerminalStatus, mapCodexItem, mapCodexNotification, } from "./mapping.js";
3
+ const MCP_STARTUP_STATUS_METHOD = "mcpServer/startupStatus/updated";
4
+ const MCP_TERMINAL_STATES = new Set(["ready", "failed", "cancelled"]);
3
5
  function threadIdFrom(params) {
4
6
  const p = params;
5
7
  return p?.threadId ?? p?.thread?.id;
6
8
  }
9
+ /** Agent-control children announce their own thread on the shared app-server.
10
+ * They do not replace the parent TUI thread: only a top-level thread switch is
11
+ * a Session rotation boundary. */
12
+ function isSubagentThreadStarted(params) {
13
+ const source = params?.thread?.source?.subAgent?.thread_spawn;
14
+ return source !== null && typeof source === "object" && !Array.isArray(source);
15
+ }
16
+ /** Internal system threads are non-persistable and never replace the parent
17
+ * TUI thread, even though the app-server broadcasts `thread/started`. */
18
+ function isEphemeralThreadStarted(params) {
19
+ return params?.thread?.ephemeral === true;
20
+ }
7
21
  function turnIdFrom(params) {
8
22
  const p = params;
9
23
  return p?.turnId ?? p?.turn?.id;
@@ -11,14 +25,7 @@ function turnIdFrom(params) {
11
25
  function userMessageContent(item) {
12
26
  if (item.type !== "userMessage")
13
27
  return undefined;
14
- const parts = codexUserContent(item.content);
15
- if (parts.length === 0)
16
- return undefined;
17
- if (parts.every((part) => part.type === "input_text")) {
18
- const text = parts.map((part) => part.text).join("").trim();
19
- return text || undefined;
20
- }
21
- return parts;
28
+ return codexUserEchoContent(item.content);
22
29
  }
23
30
  /** Whether a notification implies the thread is now active (its first turn has
24
31
  * begun, so the rollout exists). Mirrors reference implementation's `_event_indicates_thread_active`. */
@@ -31,6 +38,46 @@ function indicatesActive(method, params) {
31
38
  }
32
39
  return false;
33
40
  }
41
+ function isThreadIdle(method, params) {
42
+ if (method !== "thread/status/changed")
43
+ return false;
44
+ const status = params?.status;
45
+ return status === "idle" || (typeof status === "object" && status?.type === "idle");
46
+ }
47
+ function isModelOutput(method, params) {
48
+ if (method !== "item/started" && method !== "item/completed")
49
+ return false;
50
+ const item = params?.item;
51
+ return Boolean(item?.type && item.type !== "userMessage");
52
+ }
53
+ function isTerminalTurnMethod(method) {
54
+ return method === "turn/completed" || method === "turn/failed";
55
+ }
56
+ /** Turn-scoped notifications must never be reassigned to whichever newer turn
57
+ * happens to be current when an app-server frame arrives late. */
58
+ function isTurnScopedMethod(method) {
59
+ return method.startsWith("turn/") || method.startsWith("item/") ||
60
+ method === "queue/status" || method === "error";
61
+ }
62
+ /** Recover a missed turn/started only from visible, fully-scoped assistant/plan
63
+ * deltas. Other deltas require an already matching active turn. */
64
+ function canRecoverMissedTurnFrom(method) {
65
+ return method === "item/agentMessage/delta" || method === "item/plan/delta";
66
+ }
67
+ /** Live deltas require the bridge's exact active Codex turn. Assistant/plan
68
+ * deltas may recover a missed `turn/started` when
69
+ * fully scoped; command output never opens or recovers a Turn. */
70
+ function requiresMatchingActiveTurn(method) {
71
+ return canRecoverMissedTurnFrom(method) || method === "item/commandExecution/outputDelta";
72
+ }
73
+ /** Turn content that remains valid independently of lifecycle status. */
74
+ function isIndependentTurnContent(method) {
75
+ return method === "item/started" ||
76
+ method === "item/reasoning/textDelta" ||
77
+ method === "item/reasoning/summaryTextDelta" ||
78
+ method === "item/fileChange/patchUpdated" ||
79
+ method === "turn/plan/updated";
80
+ }
34
81
  export class CodexSessionForwarder {
35
82
  client;
36
83
  sink;
@@ -41,9 +88,16 @@ export class CodexSessionForwarder {
41
88
  currentThreadIdValue = null;
42
89
  activeSignaled = false;
43
90
  completionTimer = null;
91
+ /** Turn id retained only for late-item dedup while a terminal response waits
92
+ * for its bounded output-ordering grace. It is not an active provider turn. */
93
+ pendingCompletionTurnId = null;
44
94
  assistantMessageTimer = null;
45
95
  deferredAssistantMessage = null;
46
96
  pendingCompletion = null;
97
+ pendingMcpServers = new Set();
98
+ failedMcpServers = new Map();
99
+ mcpStartupTimer = null;
100
+ lastMcpStatusNote = null;
47
101
  /** Completed-item dedup keys already mirrored (live vs resume backfill). Key =
48
102
  * `threadId:turnId:item.id`; anonymous items use a per-(thread,turn) position
49
103
  * counter. Mirrors reference implementation `_completed_item_key` + `synced_item_keys`. */
@@ -51,6 +105,11 @@ export class CodexSessionForwarder {
51
105
  /** Per-(thread,turn) position counter for items lacking a stable codex id
52
106
  * (peek-then-advance; advanced only on a successful claim). reference implementation anon path. */
53
107
  anonCounters = new Map();
108
+ pendingPlanImplementation = null;
109
+ /** Latest aggregate diff per Turn. Codex republishes the complete diff after
110
+ * every edit; only the terminal snapshot belongs in transcript history. */
111
+ turnDiffByTurn = new Map();
112
+ replayingBackfill = false;
54
113
  constructor(client, sink, options = {}) {
55
114
  this.client = client;
56
115
  this.sink = sink;
@@ -61,31 +120,101 @@ export class CodexSessionForwarder {
61
120
  if (this.unsubscribe)
62
121
  return;
63
122
  this.unsubscribe = this.client.onNotification((method, params) => {
64
- this.handle(method, params);
123
+ try {
124
+ this.handle(method, params);
125
+ }
126
+ catch (error) {
127
+ // One malformed or unsupported notification must not detach the
128
+ // long-lived observer from every later event in this session.
129
+ console.error(`[codex-forwarder] notification handler failed for ${method}; continuing:`, error);
130
+ }
65
131
  });
132
+ const startup = this.options.mcpStartup;
133
+ if (startup?.servers.length) {
134
+ for (const server of startup.servers)
135
+ this.pendingMcpServers.add(server);
136
+ this.mcpStartupTimer = setTimeout(() => this.settleMcpStartup(), startup.settleTimeoutMs);
137
+ this.mcpStartupTimer.unref?.();
138
+ }
66
139
  }
67
140
  stop() {
68
141
  this.unsubscribe?.();
69
142
  this.unsubscribe = null;
143
+ this.clearMcpStartupTimer();
70
144
  this.flushPendingCompletion();
71
145
  this.flushDeferredAssistantMessage();
72
146
  if (this.turnOpen) {
73
147
  this.turnOpen = false;
148
+ this.currentTurnIdValue = null;
74
149
  this.sink.onTurnEnd();
75
150
  }
151
+ else {
152
+ this.currentTurnIdValue = null;
153
+ }
154
+ this.turnDiffByTurn.clear();
76
155
  }
77
- /** True while a turn is open injection uses `turn/steer` then, else `turn/start`. */
156
+ /** True while the provider owns an active turn, including the short interval
157
+ * between injection acceptance and observer confirmation. */
78
158
  isTurnOpen() {
79
- return this.turnOpen;
159
+ return this.turnOpen || this.currentTurnIdValue !== null;
80
160
  }
81
161
  /** The current turn's codex id (only meaningful while {@link isTurnOpen}). */
82
162
  currentTurnId() {
83
163
  return this.currentTurnIdValue;
84
164
  }
165
+ /**
166
+ * Record a turn accepted by the injection connection before the independent
167
+ * observer receives `turn/started`. This closes the read-decide-RPC-write race:
168
+ * another web message arriving in that window must steer this turn, not start
169
+ * a second one.
170
+ */
171
+ noteTurnAccepted(turnId) {
172
+ if (!turnId)
173
+ return;
174
+ if (this.pendingCompletion)
175
+ this.flushPendingCompletion();
176
+ this.currentTurnIdValue = turnId;
177
+ this.emitMcpStartupStatus();
178
+ }
179
+ hasPendingMcpStartup() {
180
+ return this.pendingMcpServers.size > 0;
181
+ }
182
+ /** Mark and return the startup servers cancelled by a web Stop. */
183
+ cancelMcpStartup() {
184
+ const pending = [...this.pendingMcpServers].sort();
185
+ if (pending.length === 0)
186
+ return pending;
187
+ this.pendingMcpServers.clear();
188
+ this.clearMcpStartupTimer();
189
+ if (this.isTurnOpen()) {
190
+ this.emitMcpStatus(`MCP startup cancelled: ${pending.join(", ")}`);
191
+ }
192
+ return pending;
193
+ }
194
+ /** Diagnostic suffix for an injection failure during Provider startup. */
195
+ mcpStartupDetail() {
196
+ const pending = [...this.pendingMcpServers].sort();
197
+ if (pending.length)
198
+ return `MCP startup still waiting on ${pending.join(", ")}`;
199
+ const failed = [...this.failedMcpServers.entries()]
200
+ .sort(([left], [right]) => left.localeCompare(right))
201
+ .map(([name, error]) => error ? `${name}: ${error}` : name);
202
+ return failed.length ? `MCP startup failed for ${failed.join(", ")}` : null;
203
+ }
85
204
  /** The bound codex thread id captured from `thread/started` (null until then). */
86
205
  threadId() {
87
206
  return this.currentThreadIdValue;
88
207
  }
208
+ /** Seed an already-persisted/resumed thread binding. The bridge retains this
209
+ * state even when app-server does not rebroadcast `thread/started`, so
210
+ * terminal-boundary recovery must know it too. */
211
+ noteThreadBound(threadId) {
212
+ if (!threadId || this.currentThreadIdValue === threadId)
213
+ return;
214
+ if (this.currentThreadIdValue !== null || this.turnOpen)
215
+ return;
216
+ this.currentThreadIdValue = threadId;
217
+ }
89
218
  /**
90
219
  * Replay the backlog turns from a `thread/resume` response as if they were live
91
220
  * `item/completed` notifications — the fresh-thread first-turn backfill. Each
@@ -94,25 +223,52 @@ export class CodexSessionForwarder {
94
223
  * not doubled.
95
224
  */
96
225
  replayBackfill(turns) {
97
- for (const turn of turns) {
98
- const turnId = turn.id ?? turn.turnId;
99
- if (turnId)
100
- this.currentTurnIdValue = turnId;
101
- this.ensureTurn();
102
- for (const item of turn.items ?? [])
103
- this.processCompletedItem(item);
104
- if (turn.status === "inProgress")
105
- continue;
106
- const mapped = mapCodexNotification("turn/completed", { turn });
107
- this.turnOpen = false;
108
- if (mapped.fatalError)
109
- this.sink.onTurnError(mapped.fatalError);
110
- else
111
- this.sink.onTurnEnd(mapped.usage);
226
+ this.replayingBackfill = true;
227
+ try {
228
+ for (const turn of turns) {
229
+ const turnId = turn.id ?? turn.turnId;
230
+ if (turnId)
231
+ this.currentTurnIdValue = turnId;
232
+ this.ensureTurn();
233
+ for (const item of turn.items ?? [])
234
+ this.processCompletedItem(item);
235
+ if (codexResumeTerminalStatus(turn) === undefined)
236
+ continue;
237
+ const mapped = mapCodexNotification("turn/completed", { turn });
238
+ this.turnOpen = false;
239
+ this.currentTurnIdValue = null;
240
+ if (mapped.fatalError)
241
+ this.sink.onTurnError(mapped.fatalError);
242
+ else
243
+ this.sink.onTurnEnd(mapped.usage);
244
+ }
245
+ }
246
+ finally {
247
+ this.replayingBackfill = false;
112
248
  }
113
249
  }
250
+ /** Suppress our synthesized picker when a future app-server emits the native
251
+ * `plan_implementation` request itself. */
252
+ noteNativePlanImplementationPrompt(turnId) {
253
+ if (!this.pendingPlanImplementation)
254
+ return;
255
+ if (!turnId || this.pendingPlanImplementation.turnId === turnId) {
256
+ this.pendingPlanImplementation = null;
257
+ }
258
+ }
259
+ /** Fail an open response exactly once when its observer or terminal exits. */
260
+ failOpenTurn(error) {
261
+ if (!this.isTurnOpen())
262
+ return false;
263
+ this.ensureTurn();
264
+ this.settle({ kind: "error", error });
265
+ return true;
266
+ }
114
267
  handle(method, params) {
115
268
  if (method === "thread/started" || method === "thread.started") {
269
+ if (method === "thread/started" &&
270
+ (isSubagentThreadStarted(params) || isEphemeralThreadStarted(params)))
271
+ return;
116
272
  const tid = threadIdFrom(params);
117
273
  if (tid && tid !== this.currentThreadIdValue) {
118
274
  const forkedFromId = params?.thread?.forkedFromId;
@@ -128,6 +284,7 @@ export class CodexSessionForwarder {
128
284
  }
129
285
  this.currentTurnIdValue = null;
130
286
  this.activeSignaled = false;
287
+ this.turnDiffByTurn.clear();
131
288
  this.currentThreadIdValue = tid;
132
289
  this.sink.onThreadStarted?.(tid, normalizedForkedFromId);
133
290
  }
@@ -138,6 +295,33 @@ export class CodexSessionForwarder {
138
295
  notificationThreadId &&
139
296
  notificationThreadId !== this.currentThreadIdValue)
140
297
  return;
298
+ if (method === MCP_STARTUP_STATUS_METHOD) {
299
+ this.handleMcpStartupStatus(params);
300
+ return;
301
+ }
302
+ if (method === "thread/settings/updated") {
303
+ const threadSettings = params?.threadSettings;
304
+ const model = typeof threadSettings?.model === "string" && threadSettings.model.trim()
305
+ ? threadSettings.model.trim()
306
+ : undefined;
307
+ const effort = threadSettings?.effort;
308
+ if (model !== undefined || effort === null || typeof effort === "string") {
309
+ this.sink.onThreadSettingsChanged?.({
310
+ ...(model === undefined ? {} : { model }),
311
+ ...(effort === null || typeof effort === "string"
312
+ ? { reasoningEffort: effort }
313
+ : {}),
314
+ });
315
+ }
316
+ const mode = (threadSettings?.collaborationMode ?? threadSettings?.collaboration_mode)?.mode;
317
+ if (mode === "plan" || mode === "default") {
318
+ this.sink.onCollaborationModeChanged?.(mode);
319
+ }
320
+ return;
321
+ }
322
+ if (isThreadIdle(method, params) || isModelOutput(method, params)) {
323
+ this.settleMcpStartup();
324
+ }
141
325
  // Release a parked resume as soon as the thread shows activity (rollout now
142
326
  // exists). Fire once.
143
327
  if (!this.activeSignaled && indicatesActive(method, params)) {
@@ -148,33 +332,147 @@ export class CodexSessionForwarder {
148
332
  // behavior unchanged unless the Traex host explicitly opts in.
149
333
  if (method === "queue/status" && !this.options.surfaceQueueStatus)
150
334
  return;
335
+ if (method === "queue/status" && this.currentTurnIdValue === null)
336
+ return;
151
337
  const carriedTurnId = turnIdFrom(params);
338
+ if (method === "turn/diff/updated") {
339
+ if (!carriedTurnId)
340
+ return;
341
+ const update = params;
342
+ const diff = typeof update?.diff === "string"
343
+ ? update.diff
344
+ : typeof update?.unifiedDiff === "string"
345
+ ? update.unifiedDiff
346
+ : "";
347
+ if (diff)
348
+ this.turnDiffByTurn.set(carriedTurnId, diff);
349
+ else
350
+ this.turnDiffByTurn.delete(carriedTurnId);
351
+ return;
352
+ }
152
353
  if (method === "turn/started") {
153
- this.flushPendingCompletion();
154
- this.flushDeferredAssistantMessage();
155
- if (carriedTurnId)
354
+ this.beginTurn(carriedTurnId);
355
+ this.sink.onTurnObserved?.(carriedTurnId);
356
+ return;
357
+ }
358
+ if (isTerminalTurnMethod(method)) {
359
+ if (!this.terminalBoundaryMatchesActiveTurn(carriedTurnId, notificationThreadId)) {
360
+ const staleDiff = this.consumeTurnDiff(carriedTurnId);
361
+ if (staleDiff && carriedTurnId) {
362
+ this.sink.onTurnContentEvent?.(carriedTurnId, staleDiff);
363
+ }
364
+ return;
365
+ }
366
+ const hadActiveTurn = this.currentTurnIdValue !== null;
367
+ const hadOpenResponse = this.turnOpen;
368
+ const mapped = mapCodexNotification(method, params);
369
+ const terminalTurnId = carriedTurnId ?? this.currentTurnIdValue;
370
+ const turnDiff = this.consumeTurnDiff(terminalTurnId);
371
+ if (!hadActiveTurn && !hadOpenResponse) {
372
+ if (turnDiff && terminalTurnId) {
373
+ this.sink.onTurnContentEvent?.(terminalTurnId, turnDiff);
374
+ }
375
+ const turn = params?.turn;
376
+ const recoveredStatus = mapped.fatalError ||
377
+ method === "turn/failed" ||
378
+ codexResumeTerminalStatus(turn) === "failed"
379
+ ? "failed"
380
+ : "idle";
381
+ this.sink.onRecoveredTurnStatus?.(recoveredStatus, carriedTurnId, mapped.fatalError);
382
+ return;
383
+ }
384
+ if (carriedTurnId && this.currentTurnIdValue === null) {
156
385
  this.currentTurnIdValue = carriedTurnId;
386
+ }
157
387
  this.ensureTurn();
388
+ this.pendingCompletionTurnId = carriedTurnId ?? this.currentTurnIdValue;
389
+ // The provider lifecycle closes immediately. A configured grace keeps
390
+ // only the canonical response open long enough to absorb late items.
391
+ this.currentTurnIdValue = null;
392
+ for (const event of mapped.events.filter((event) => event.type !== "runtime_debug")) {
393
+ this.sink.onEvent(event);
394
+ }
395
+ this.scheduleCompletion(mapped.fatalError
396
+ ? { kind: "error", error: mapped.fatalError, ...(turnDiff ? { turnDiff } : {}) }
397
+ : mapped.turnInterrupted
398
+ ? {
399
+ kind: "interrupted",
400
+ ...(mapped.usage ? { usage: mapped.usage } : {}),
401
+ ...(turnDiff ? { turnDiff } : {}),
402
+ }
403
+ : {
404
+ kind: "end",
405
+ ...(mapped.usage ? { usage: mapped.usage } : {}),
406
+ ...(turnDiff ? { turnDiff } : {}),
407
+ });
158
408
  return;
159
409
  }
160
- if (carriedTurnId)
161
- this.currentTurnIdValue = carriedTurnId;
410
+ // A late event from an older turn must not replace the app-server's active
411
+ // turn id. That was the source of stale completions closing a newer turn.
412
+ if (carriedTurnId &&
413
+ this.currentTurnIdValue &&
414
+ carriedTurnId !== this.currentTurnIdValue &&
415
+ isTurnScopedMethod(method)) {
416
+ // Durable completed items and passive content belong to their carried
417
+ // response even if a newer Turn is active. Only active-turn deltas and
418
+ // lifecycle edges are stale with respect to the newer Turn.
419
+ if (method === "item/completed") {
420
+ // Continue into the completed-item dedup/order path below.
421
+ }
422
+ else if (isIndependentTurnContent(method) && this.sink.onTurnContentEvent) {
423
+ const mapped = mapCodexNotification(method, params);
424
+ for (const event of mapped.events) {
425
+ if (event.type !== "runtime_debug") {
426
+ this.sink.onTurnContentEvent(carriedTurnId, event);
427
+ }
428
+ }
429
+ return;
430
+ }
431
+ else {
432
+ return;
433
+ }
434
+ }
435
+ if (requiresMatchingActiveTurn(method)) {
436
+ if (this.currentTurnIdValue !== null) {
437
+ // An id-less delta is not attributable to the active Turn. Require
438
+ // the exact active Turn id before forwarding it.
439
+ if (carriedTurnId !== this.currentTurnIdValue)
440
+ return;
441
+ }
442
+ else if (carriedTurnId &&
443
+ canRecoverMissedTurnFrom(method) &&
444
+ this.notificationMatchesCurrentThread(notificationThreadId)) {
445
+ this.currentTurnIdValue = carriedTurnId;
446
+ this.ensureTurn();
447
+ }
448
+ else {
449
+ return;
450
+ }
451
+ }
162
452
  // Completed items (user echo, assistant, tool, reasoning) go through the
163
453
  // deduped path so a resume backfill and the live stream never double them.
164
454
  if (method === "item/completed") {
165
455
  const item = params?.item;
166
456
  if (item) {
457
+ if (carriedTurnId &&
458
+ this.currentTurnIdValue &&
459
+ carriedTurnId !== this.currentTurnIdValue) {
460
+ // This is durable content for an older response, not an ordering
461
+ // signal for the newer Turn's deferred assistant message.
462
+ this.processCompletedItem(item, carriedTurnId);
463
+ return;
464
+ }
167
465
  if (this.shouldDeferAssistantMessage(item)) {
168
- this.deferAssistantMessage(item);
466
+ this.deferAssistantMessage(item, carriedTurnId);
169
467
  this.refreshCompletionGrace();
170
468
  return;
171
469
  }
172
- // A late reasoning item belongs before the held final answer. Any other
173
- // completed item establishes that the held message was not final and
174
- // must retain its original position.
470
+ // Within one Turn, a late reasoning item belongs before the held final
471
+ // answer. Any other completed item establishes that the held message
472
+ // was not final and must retain its original position.
175
473
  if (item.type !== "reasoning")
176
474
  this.flushDeferredAssistantMessage();
177
- this.processCompletedItem(item);
475
+ this.processCompletedItem(item, carriedTurnId);
178
476
  this.refreshCompletionGrace();
179
477
  return;
180
478
  }
@@ -189,6 +487,19 @@ export class CodexSessionForwarder {
189
487
  if (canonicalEvents.some((event) => event.type !== "reasoning_delta" && event.type !== "reasoning_completed")) {
190
488
  this.flushDeferredAssistantMessage();
191
489
  }
490
+ // Item/content delivery is independent from turn lifecycle status. A
491
+ // scoped item or reasoning delta that arrives after the terminal
492
+ // edge remains visible, but must not synthesize another running response.
493
+ if (!this.turnOpen &&
494
+ this.currentTurnIdValue === null &&
495
+ !mapped.fatalError &&
496
+ canonicalEvents.length > 0 &&
497
+ this.sink.onTurnContentEvent) {
498
+ for (const event of canonicalEvents) {
499
+ this.sink.onTurnContentEvent(carriedTurnId, event);
500
+ }
501
+ return;
502
+ }
192
503
  if (canonicalEvents.length || mapped.turnCompleted || mapped.fatalError) {
193
504
  this.ensureTurn();
194
505
  }
@@ -200,7 +511,9 @@ export class CodexSessionForwarder {
200
511
  return;
201
512
  }
202
513
  if (mapped.turnCompleted) {
203
- this.scheduleCompletion({ kind: "end", ...(mapped.usage ? { usage: mapped.usage } : {}) });
514
+ this.scheduleCompletion(mapped.turnInterrupted
515
+ ? { kind: "interrupted", ...(mapped.usage ? { usage: mapped.usage } : {}) }
516
+ : { kind: "end", ...(mapped.usage ? { usage: mapped.usage } : {}) });
204
517
  }
205
518
  else {
206
519
  this.refreshCompletionGrace();
@@ -237,39 +550,150 @@ export class CodexSessionForwarder {
237
550
  }
238
551
  settle(completion) {
239
552
  this.flushDeferredAssistantMessage();
553
+ const completedTurnId = this.pendingCompletionTurnId ?? this.currentTurnIdValue;
554
+ const planPrompt = completion.kind === "end" &&
555
+ this.pendingPlanImplementation?.turnId === completedTurnId
556
+ ? this.pendingPlanImplementation
557
+ : null;
558
+ if (this.pendingPlanImplementation?.turnId === completedTurnId) {
559
+ this.pendingPlanImplementation = null;
560
+ }
561
+ if (completion.turnDiff)
562
+ this.sink.onEvent(completion.turnDiff);
563
+ if (completedTurnId)
564
+ this.turnDiffByTurn.delete(completedTurnId);
240
565
  this.turnOpen = false;
566
+ this.currentTurnIdValue = null;
567
+ this.pendingCompletionTurnId = null;
241
568
  if (completion.kind === "error")
242
569
  this.sink.onTurnError(completion.error);
243
- else
570
+ else if (completion.kind === "interrupted") {
571
+ if (this.sink.onTurnInterrupted)
572
+ this.sink.onTurnInterrupted(completion.usage);
573
+ else
574
+ this.sink.onTurnEnd(completion.usage);
575
+ }
576
+ else {
244
577
  this.sink.onTurnEnd(completion.usage);
578
+ if (planPrompt)
579
+ this.sink.onPlanImplementationPrompt?.(planPrompt);
580
+ }
581
+ }
582
+ handleMcpStartupStatus(params) {
583
+ const update = params;
584
+ const name = typeof update?.name === "string" ? update.name : "";
585
+ const status = typeof update?.status === "string" ? update.status : "";
586
+ if (!name || (status !== "starting" && !MCP_TERMINAL_STATES.has(status)))
587
+ return;
588
+ if (status === "starting") {
589
+ this.pendingMcpServers.add(name);
590
+ this.failedMcpServers.delete(name);
591
+ }
592
+ else {
593
+ this.pendingMcpServers.delete(name);
594
+ if (status === "failed") {
595
+ this.failedMcpServers.set(name, typeof update?.error === "string" && update.error ? update.error : undefined);
596
+ }
597
+ else {
598
+ this.failedMcpServers.delete(name);
599
+ }
600
+ if (this.pendingMcpServers.size === 0)
601
+ this.clearMcpStartupTimer();
602
+ }
603
+ this.emitMcpStartupStatus();
604
+ }
605
+ settleMcpStartup() {
606
+ if (this.pendingMcpServers.size === 0) {
607
+ this.clearMcpStartupTimer();
608
+ return;
609
+ }
610
+ this.pendingMcpServers.clear();
611
+ this.clearMcpStartupTimer();
612
+ this.emitMcpStartupStatus();
613
+ }
614
+ clearMcpStartupTimer() {
615
+ if (this.mcpStartupTimer)
616
+ clearTimeout(this.mcpStartupTimer);
617
+ this.mcpStartupTimer = null;
618
+ }
619
+ emitMcpStartupStatus() {
620
+ if (!this.isTurnOpen())
621
+ return;
622
+ const pending = [...this.pendingMcpServers].sort();
623
+ if (pending.length) {
624
+ this.emitMcpStatus(`Starting MCP servers: ${pending.join(", ")}`);
625
+ return;
626
+ }
627
+ const failed = [...this.failedMcpServers.keys()].sort();
628
+ if (failed.length) {
629
+ this.emitMcpStatus(`MCP startup failed: ${failed.join(", ")}`);
630
+ return;
631
+ }
632
+ if (this.lastMcpStatusNote !== null) {
633
+ this.lastMcpStatusNote = null;
634
+ if (this.sink.onStatus)
635
+ this.sink.onStatus(undefined);
636
+ else
637
+ this.sink.onEvent({ type: "status" });
638
+ }
639
+ }
640
+ emitMcpStatus(note) {
641
+ if (this.lastMcpStatusNote === note)
642
+ return;
643
+ this.lastMcpStatusNote = note;
644
+ if (this.sink.onStatus)
645
+ this.sink.onStatus(note, "startup");
646
+ else
647
+ this.sink.onEvent({ type: "status", statusKind: "startup", note });
245
648
  }
246
649
  /** Map + emit one completed codex item, deduped by a TOTAL key and routing the
247
650
  * user echo to {@link CodexForwarderSink.onUserMessage}. Shared by live + backfill. */
248
- processCompletedItem(item) {
249
- if (!this.claimCompletedItem(item))
651
+ processCompletedItem(item, completedTurnId) {
652
+ if (!this.claimCompletedItem(item, completedTurnId))
250
653
  return;
251
- this.emitCompletedItem(item);
654
+ this.emitCompletedItem(item, completedTurnId);
252
655
  }
253
- claimCompletedItem(item) {
254
- const { key, isAnon } = this.completedItemKey(item);
656
+ claimCompletedItem(item, completedTurnId) {
657
+ const { key, isAnon } = this.completedItemKey(item, completedTurnId);
255
658
  if (this.seenCompletedItems.has(key))
256
659
  return false;
257
660
  this.seenCompletedItems.add(key);
258
661
  if (isAnon)
259
- this.advanceAnonCounter();
662
+ this.advanceAnonCounter(completedTurnId);
260
663
  return true;
261
664
  }
262
- emitCompletedItem(item) {
665
+ emitCompletedItem(item, completedTurnId) {
666
+ const outsideTurnLifecycle = !this.turnOpen || Boolean(completedTurnId &&
667
+ this.currentTurnIdValue &&
668
+ completedTurnId !== this.currentTurnIdValue);
263
669
  const userContent = userMessageContent(item);
264
670
  if (userContent !== undefined) {
671
+ if (outsideTurnLifecycle && this.sink.onTurnContentUserMessage) {
672
+ this.sink.onTurnContentUserMessage(completedTurnId, userContent);
673
+ return;
674
+ }
265
675
  this.ensureTurn();
266
676
  this.sink.onUserMessage?.(userContent);
267
677
  return;
268
678
  }
679
+ if (item.type === "plan" && !this.replayingBackfill) {
680
+ const text = item.text?.trim();
681
+ const turnId = this.currentTurnIdValue ?? this.pendingCompletionTurnId;
682
+ const threadId = this.currentThreadIdValue;
683
+ if (text && turnId && threadId) {
684
+ this.pendingPlanImplementation = { threadId, turnId, text };
685
+ }
686
+ }
269
687
  const mapped = mapCodexItem("item/completed", item);
270
688
  const canonicalEvents = mapped.events.filter((event) => event.type !== "runtime_debug");
271
689
  if (canonicalEvents.length === 0)
272
690
  return;
691
+ if (outsideTurnLifecycle && this.sink.onTurnContentEvent) {
692
+ for (const event of canonicalEvents) {
693
+ this.sink.onTurnContentEvent(completedTurnId, event);
694
+ }
695
+ return;
696
+ }
273
697
  this.ensureTurn();
274
698
  for (const event of canonicalEvents)
275
699
  this.sink.onEvent(event);
@@ -280,11 +704,11 @@ export class CodexSessionForwarder {
280
704
  }
281
705
  return Boolean(item.text?.trim());
282
706
  }
283
- deferAssistantMessage(item) {
284
- if (!this.claimCompletedItem(item))
707
+ deferAssistantMessage(item, turnId) {
708
+ if (!this.claimCompletedItem(item, turnId))
285
709
  return;
286
710
  this.flushDeferredAssistantMessage();
287
- this.deferredAssistantMessage = item;
711
+ this.deferredAssistantMessage = { item, ...(turnId ? { turnId } : {}) };
288
712
  const graceMs = this.options.assistantMessageGraceMs ?? 0;
289
713
  this.assistantMessageTimer = setTimeout(() => this.flushDeferredAssistantMessage(), graceMs);
290
714
  this.assistantMessageTimer.unref?.();
@@ -293,26 +717,27 @@ export class CodexSessionForwarder {
293
717
  if (this.assistantMessageTimer)
294
718
  clearTimeout(this.assistantMessageTimer);
295
719
  this.assistantMessageTimer = null;
296
- const item = this.deferredAssistantMessage;
720
+ const deferred = this.deferredAssistantMessage;
297
721
  this.deferredAssistantMessage = null;
298
- if (item)
299
- this.emitCompletedItem(item);
722
+ if (deferred)
723
+ this.emitCompletedItem(deferred.item, deferred.turnId);
300
724
  }
301
725
  /** Build a total dedup key for one completed item. Stable-id items use
302
726
  * `threadId:turnId:item.id` — identical across replay + live, so the second
303
727
  * delivery is dropped. Items without a codex id fall back to a per-(thread,turn)
304
728
  * position counter (peeked here; advanced only on a successful claim, via
305
729
  * {@link advanceAnonCounter}). Mirrors reference implementation `_completed_item_key`. */
306
- completedItemKey(item) {
730
+ completedItemKey(item, completedTurnId) {
307
731
  const threadId = this.currentThreadIdValue ?? "thread";
308
- const turnId = this.currentTurnIdValue ?? "turn";
732
+ const turnId = completedTurnId ?? this.currentTurnIdValue ?? this.pendingCompletionTurnId ?? "turn";
309
733
  if (item.id)
310
734
  return { key: `${threadId}:${turnId}:${item.id}`, isAnon: false };
311
735
  const n = this.anonCounters.get(`${threadId}:${turnId}`) ?? 0;
312
736
  return { key: `${threadId}:${turnId}:anon:${n}`, isAnon: true };
313
737
  }
314
- advanceAnonCounter() {
315
- const k = `${this.currentThreadIdValue ?? "thread"}:${this.currentTurnIdValue ?? "turn"}`;
738
+ advanceAnonCounter(completedTurnId) {
739
+ const turnId = completedTurnId ?? this.currentTurnIdValue ?? this.pendingCompletionTurnId ?? "turn";
740
+ const k = `${this.currentThreadIdValue ?? "thread"}:${turnId}`;
316
741
  this.anonCounters.set(k, (this.anonCounters.get(k) ?? 0) + 1);
317
742
  }
318
743
  ensureTurn() {
@@ -321,4 +746,54 @@ export class CodexSessionForwarder {
321
746
  this.sink.onTurnStart(this.currentTurnIdValue ?? undefined);
322
747
  }
323
748
  }
749
+ consumeTurnDiff(turnId) {
750
+ if (!turnId)
751
+ return undefined;
752
+ const diff = this.turnDiffByTurn.get(turnId);
753
+ this.turnDiffByTurn.delete(turnId);
754
+ return diff
755
+ ? { type: "turn_diff", callId: `codex_turn_diff_${turnId}`, diff }
756
+ : undefined;
757
+ }
758
+ /** Start (or confirm) the app-server's authoritative active turn. A newer
759
+ * start supersedes an older response whose terminal edge arrived late; a
760
+ * pending Traex completion is flushed first so its final item grace remains
761
+ * intact. */
762
+ beginTurn(turnId) {
763
+ if (this.pendingCompletion)
764
+ this.flushPendingCompletion();
765
+ const nextTurnId = turnId ?? null;
766
+ const changesIdentifiedTurn = this.turnOpen &&
767
+ this.currentTurnIdValue !== null &&
768
+ nextTurnId !== null &&
769
+ this.currentTurnIdValue !== nextTurnId;
770
+ if (changesIdentifiedTurn) {
771
+ this.flushPendingCompletion();
772
+ this.flushDeferredAssistantMessage();
773
+ if (this.turnOpen) {
774
+ this.turnOpen = false;
775
+ this.sink.onTurnEnd(undefined, "superseded");
776
+ }
777
+ }
778
+ this.currentTurnIdValue = nextTurnId;
779
+ this.ensureTurn();
780
+ }
781
+ /** Active-turn clearing contract:
782
+ *
783
+ * - an identified active turn is closed only by the same id;
784
+ * - an id-less boundary cannot close an identified active turn;
785
+ * - with no observed active turn, an identified boundary may recover a
786
+ * missed start only when it carries the currently-bound thread id. */
787
+ terminalBoundaryMatchesActiveTurn(terminalTurnId, notificationThreadId) {
788
+ if (this.currentTurnIdValue !== null) {
789
+ return terminalTurnId === this.currentTurnIdValue;
790
+ }
791
+ if (terminalTurnId === undefined)
792
+ return true;
793
+ return this.notificationMatchesCurrentThread(notificationThreadId);
794
+ }
795
+ notificationMatchesCurrentThread(notificationThreadId) {
796
+ return this.currentThreadIdValue !== null &&
797
+ notificationThreadId === this.currentThreadIdValue;
798
+ }
324
799
  }