maka-agent 0.2.0-dev.52.20260926 → 0.2.0-dev.53.20260927

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 (71) hide show
  1. package/dist/activation-command.js +11 -3
  2. package/dist/pi-tui-mcp-status.js +73 -5
  3. package/dist/pi-tui-runner.js +1 -1
  4. package/dist/runtime-host-run-command.js +39 -6
  5. package/dist/runtime-host-run-mcp.js +161 -0
  6. package/dist/runtime-host-session-driver.js +22 -2
  7. package/dist/tui-copy-catalog.js +6 -0
  8. package/dist/tui-mcp-control.js +11 -2
  9. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  10. package/node_modules/@maka/core/dist/attachments.js +7 -0
  11. package/node_modules/@maka/core/dist/events.js +11 -0
  12. package/node_modules/@maka/core/dist/provider-registry.js +11 -2
  13. package/node_modules/@maka/core/dist/turn-origin.js +6 -0
  14. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +1 -5
  15. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +80 -24
  16. package/node_modules/@maka/runtime/dist/bots/proxied-fetch.js +5 -4
  17. package/node_modules/@maka/runtime/dist/computer-use-tools.js +136 -100
  18. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +4 -0
  19. package/node_modules/@maka/runtime/dist/conversation-copy.js +51 -205
  20. package/node_modules/@maka/runtime/dist/edit-replace.js +7 -7
  21. package/node_modules/@maka/runtime/dist/filesystem-executor.js +4 -20
  22. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +17 -28
  23. package/node_modules/@maka/runtime/dist/format-json.js +39 -0
  24. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +1 -6
  25. package/node_modules/@maka/runtime/dist/image-file.js +22 -14
  26. package/node_modules/@maka/runtime/dist/model-adapter.js +18 -2
  27. package/node_modules/@maka/runtime/dist/model-history.js +201 -3
  28. package/node_modules/@maka/runtime/dist/network/abortable-connector.js +55 -0
  29. package/node_modules/@maka/runtime/dist/network/proxy-dispatcher.js +72 -37
  30. package/node_modules/@maka/runtime/dist/network/proxy-test.js +1 -1
  31. package/node_modules/@maka/runtime/dist/network/scoped-fetch-transport.js +7 -2
  32. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +1 -3
  33. package/node_modules/@maka/runtime/dist/provider-error-classification.js +36 -8
  34. package/node_modules/@maka/runtime/dist/recovery-resolver.js +1 -91
  35. package/node_modules/@maka/runtime/dist/runtime-kernel.js +44 -0
  36. package/node_modules/@maka/runtime/dist/session-manager.js +54 -58
  37. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +84 -2
  38. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +63 -51
  39. package/node_modules/@maka/runtime/dist/workspace-executor.js +5 -6
  40. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +27 -6
  41. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +4 -1
  42. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +9 -9
  43. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +9 -1
  44. package/node_modules/@maka/runtime-host/dist/protocol/index.js +12 -1
  45. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +28 -6
  46. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +12 -2
  47. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +10 -7
  48. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +10 -2
  49. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +2 -0
  50. package/node_modules/@maka/runtime-host/dist/server/interactive-turn-coordinator.js +4 -1
  51. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +4 -2
  52. package/node_modules/@maka/runtime-host/dist/server/operation-dispatcher.js +4 -0
  53. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -5
  54. package/node_modules/@maka/runtime-host/dist/server/safe-boundary-resume-policy.js +27 -0
  55. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +5 -3
  56. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +7 -2
  57. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +11 -141
  58. package/node_modules/@maka/runtime-host/dist/server/session-revision-graph-references.js +46 -75
  59. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +18 -2
  60. package/node_modules/@maka/runtime-host/dist/server/workhub-result-coordinator.js +33 -3
  61. package/node_modules/@maka/runtime-host/dist/transport/framed-byte-stream-transport.js +39 -5
  62. package/node_modules/@maka/storage/dist/agent-run-store-contract.js +7 -1
  63. package/node_modules/@maka/storage/dist/artifact-store.js +1 -5
  64. package/node_modules/@maka/storage/dist/artifact-stores.js +0 -3
  65. package/node_modules/@maka/storage/dist/atomic-file-write.js +1 -0
  66. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +107 -57
  67. package/node_modules/@maka/storage/dist/codex-session-adapter.js +227 -19
  68. package/node_modules/@maka/storage/dist/external-session-importer.js +1 -1
  69. package/node_modules/@maka/storage/dist/mcp-config-store.js +22 -3
  70. package/node_modules/@maka/storage/dist/settings-store.js +281 -13
  71. package/package.json +1 -1
@@ -46,6 +46,17 @@ const TRANSPORT_FAILURE_CODES = new Set([
46
46
  'EHOSTUNREACH',
47
47
  'ENETUNREACH',
48
48
  ]);
49
+ // A successful status acknowledges the headers, not a complete response body.
50
+ // Unlike pre-response failures, require an explicit interruption code here:
51
+ // neither SDK retryability nor arbitrary TLS/undici errors prove a transient cut.
52
+ const RESPONSE_TRANSPORT_FAILURE_CODES = new Set([
53
+ 'ECONNRESET',
54
+ 'EPIPE',
55
+ 'ETIMEDOUT',
56
+ 'ECONNABORTED',
57
+ 'UND_ERR_SOCKET',
58
+ 'UND_ERR_BODY_TIMEOUT',
59
+ ]);
49
60
  /**
50
61
  * xAI emits this code for transient model capacity failures, including when
51
62
  * the same payload is relayed through an OpenAI-compatible gateway. Do not
@@ -114,12 +125,14 @@ function providerErrorTarget(error) {
114
125
  : error;
115
126
  }
116
127
  function isTransportFailure(target, statusCode) {
117
- if (statusCode)
128
+ const successfulResponse = /^2\d\d$/.test(statusCode);
129
+ if (statusCode && !successfulResponse)
118
130
  return false;
119
131
  const record = objectRecord(target);
120
132
  if (!record)
121
133
  return false;
122
- if (target instanceof Error &&
134
+ if (!successfulResponse &&
135
+ target instanceof Error &&
123
136
  target.name === 'AI_APICallError' &&
124
137
  safeField(record, 'isRetryable') === true) {
125
138
  return true;
@@ -131,12 +144,25 @@ function isTransportFailure(target, statusCode) {
131
144
  const currentRecord = objectRecord(current);
132
145
  if (!currentRecord)
133
146
  return false;
147
+ if (successfulResponse) {
148
+ const nestedStatus = safeField(currentRecord, 'statusCode') ?? safeField(currentRecord, 'status');
149
+ // Do not reinterpret a cancellation or a nested HTTP rejection as a
150
+ // recoverable body interruption merely because it has a socket cause.
151
+ if (safeField(currentRecord, 'name') === 'AbortError' ||
152
+ ((typeof nestedStatus === 'number' || typeof nestedStatus === 'string') &&
153
+ nestedStatus !== '' &&
154
+ !/^2\d\d$/.test(String(nestedStatus)))) {
155
+ return false;
156
+ }
157
+ }
134
158
  const code = safeField(currentRecord, 'code');
135
159
  if (typeof code === 'string' &&
136
- (TRANSPORT_FAILURE_CODES.has(code) ||
137
- code.startsWith('ERR_SSL_') ||
138
- code.startsWith('ERR_TLS_') ||
139
- code.startsWith('UND_ERR_'))) {
160
+ (successfulResponse
161
+ ? RESPONSE_TRANSPORT_FAILURE_CODES.has(code)
162
+ : TRANSPORT_FAILURE_CODES.has(code) ||
163
+ code.startsWith('ERR_SSL_') ||
164
+ code.startsWith('ERR_TLS_') ||
165
+ code.startsWith('UND_ERR_'))) {
140
166
  return true;
141
167
  }
142
168
  current = safeField(currentRecord, 'cause');
@@ -690,11 +716,13 @@ function isTrustedCodexEdgeRejection(facts) {
690
716
  const seen = new Set();
691
717
  for (let depth = 0; depth < 5 && current !== undefined && !seen.has(current); depth += 1) {
692
718
  seen.add(current);
693
- if (current instanceof Error && current.name === 'OpenAiCodexEdgeRejectionError')
719
+ if (current instanceof Error &&
720
+ safeField(current, 'name') ===
721
+ 'OpenAiCodexEdgeRejectionError')
694
722
  return true;
695
723
  current =
696
724
  typeof current === 'object' && current !== null
697
- ? current.cause
725
+ ? safeField(current, 'cause')
698
726
  : undefined;
699
727
  }
700
728
  return false;
@@ -16,10 +16,9 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- import { TOOL_BOUNDARY_PROTOCOL_V1, isTerminalRuntimeEvent, } from '@maka/core/runtime-event';
19
+ import { TOOL_BOUNDARY_PROTOCOL_V1, } from '@maka/core/runtime-event';
20
20
  import { scanToolLedger, } from '@maka/core/tool-ledger-scanner';
21
21
  import { interpretScannedToolRecovery } from '@maka/core/tool-recovery-bundle';
22
- import { compatibilityToolResultProjection } from './durable-tool-result-projection.js';
23
22
  export function resolveRuntimeRecovery(events) {
24
23
  const firstProtocol = events[0]?.actions?.runtimeProtocol;
25
24
  const toolBoundaryProtocol = firstProtocol?.toolBoundary === TOOL_BOUNDARY_PROTOCOL_V1
@@ -46,95 +45,6 @@ export function resolveRuntimeRecovery(events) {
46
45
  requiresReconciliation: !hasCorruption && decisions.some((decision) => decision.status === 'indeterminate'),
47
46
  };
48
47
  }
49
- export function buildInterruptedToolOutcomeCommits(events, now, toolMode) {
50
- const eventsById = new Map(events.map((event) => [event.id, event]));
51
- const terminalInvocations = new Set(events.filter(isTerminalRuntimeEvent).map((event) => event.invocationId));
52
- const recovery = resolveRuntimeRecovery(events);
53
- if (recovery.hasCorruption)
54
- return [];
55
- return recovery.decisions.flatMap((decision) => {
56
- if (decision.status !== 'indeterminate' ||
57
- decision.reason !== 'dispatch_without_response' ||
58
- !decision.operationId ||
59
- !decision.callRuntimeEventId) {
60
- return [];
61
- }
62
- const callEvent = eventsById.get(decision.callRuntimeEventId);
63
- const call = callEvent?.content;
64
- if (!callEvent || call?.kind !== 'function_call') {
65
- return [];
66
- }
67
- // A sealed invocation cannot accept new RuntimeEvents. Legacy sessions can
68
- // still contain this gap; their projection is repaired from the terminal
69
- // fact instead of appending a result after the immutable tail.
70
- if (terminalInvocations.has(callEvent.invocationId))
71
- return [];
72
- const codeModeExec = toolMode === 'code_mode' &&
73
- call.name === 'exec' &&
74
- callEvent.origin !== 'code_mode' &&
75
- callEvent.modelVisibility !== 'hidden';
76
- const interaction = call.name === 'AskUserQuestion';
77
- const result = codeModeExec
78
- ? {
79
- kind: 'json',
80
- value: {
81
- kind: 'code_mode',
82
- status: 'interrupted',
83
- message: 'Code Mode execution was interrupted by runtime recovery. Its side effects may or may not have occurred; do not retry it immediately. Inspect the current state first.',
84
- uncertainOutcome: { code: 'outcome_unknown', retrySafe: false },
85
- },
86
- }
87
- : {
88
- kind: 'text',
89
- text: interaction
90
- ? 'This question was interrupted by runtime recovery before an answer was submitted.'
91
- : `Tool ${call.name} was interrupted before its result was committed. Its side effects may or may not have occurred. Do not retry it immediately; inspect the current state first.`,
92
- ...(!interaction
93
- ? { uncertainOutcome: { code: 'outcome_unknown', retrySafe: false } }
94
- : {}),
95
- };
96
- const responseContent = {
97
- kind: 'function_response',
98
- id: call.id,
99
- name: call.name,
100
- result,
101
- isError: true,
102
- };
103
- const modelProjection = compatibilityToolResultProjection(responseContent, callEvent.sessionId);
104
- const runtimeEvent = {
105
- id: `${decision.operationId}_response`,
106
- invocationId: callEvent.invocationId,
107
- runId: callEvent.runId,
108
- sessionId: callEvent.sessionId,
109
- turnId: callEvent.turnId,
110
- ts: now,
111
- partial: false,
112
- role: 'tool',
113
- author: 'tool',
114
- origin: callEvent.origin ?? 'provider',
115
- modelVisibility: callEvent.modelVisibility ?? 'visible',
116
- content: { ...responseContent, ...(modelProjection ? { modelProjection } : {}) },
117
- refs: {
118
- operationId: decision.operationId,
119
- toolCallId: call.id,
120
- ...(callEvent.refs?.parentToolCallId
121
- ? { parentToolCallId: callEvent.refs.parentToolCallId }
122
- : {}),
123
- ...(callEvent.refs?.parentOperationId
124
- ? { parentOperationId: callEvent.refs.parentOperationId }
125
- : {}),
126
- },
127
- };
128
- return [
129
- {
130
- operationId: decision.operationId,
131
- journalEventId: `${decision.operationId}_outcome`,
132
- runtimeEvent,
133
- committedAt: now,
134
- },
135
- ];
136
- });
137
- }
138
48
  function decisionFromOperation(operation, toolBoundaryProtocol, eventOrder) {
139
49
  const decision = {
140
50
  toolCallId: operation.toolCallId,
@@ -17,6 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { agentRunCompositionFromEvents } from '@maka/core/agent-run';
20
+ import { randomUUID } from 'node:crypto';
20
21
  import { decodeRuntimeBoundaryCursor, } from '@maka/core/runtime-boundary';
21
22
  import { isTerminalRuntimeEvent, } from '@maka/core/runtime-event';
22
23
  import { isDeepStrictEqual } from 'node:util';
@@ -85,6 +86,13 @@ export class RuntimeKernel {
85
86
  if (deps.runStore && !deps.runtimeEventStore) {
86
87
  throw new Error('RuntimeEventStore is required when AgentRunStore is configured');
87
88
  }
89
+ // One identity per kernel process: catalog rows survive a Host restart
90
+ // while the per-session epoch counters restart at zero, so clients pair
91
+ // the generation with the epoch instead of comparing epochs across
92
+ // processes (#5713 review). Drawn outside the `newId` sequence so a
93
+ // restart identity never shifts the ids callers observe, and defaulted
94
+ // for deps that omit `newId` entirely.
95
+ this.#hostGeneration = deps.hostGeneration?.() ?? randomUUID();
88
96
  this.historyCompactCoordinator = new HistoryCompactCheckpointCoordinator(deps);
89
97
  }
90
98
  async runBackendActivation(execution, operation) {
@@ -216,6 +224,12 @@ export class RuntimeKernel {
216
224
  }
217
225
  execution.run = run;
218
226
  execution.phase = 'attached';
227
+ // A host-operation claim's run is visible through the claim itself before
228
+ // any backend reservation: the epoch must follow that visibility change
229
+ // too, or two same-revision reads can disagree about runningTurnIds
230
+ // (#5713 review).
231
+ if (execution.hostOperation)
232
+ this.#bumpSessionRunEpoch(execution.sessionId);
219
233
  if (execution.stopIntent) {
220
234
  run.stop(execution.stopIntent.input.source, execution.stopIntent.input.workHubActionId);
221
235
  }
@@ -260,6 +274,11 @@ export class RuntimeKernel {
260
274
  this.settleExecutionClaim(execution, { ok: true });
261
275
  }
262
276
  settleExecutionClaim(execution, outcome) {
277
+ // The claim removal takes a host-operation run out of the visible set:
278
+ // order that transition like the attach and the unregister (#5713 review).
279
+ if (execution.hostOperation && execution.run) {
280
+ this.#bumpSessionRunEpoch(execution.sessionId);
281
+ }
263
282
  const claims = this.executionClaims.get(execution.sessionId);
264
283
  claims?.delete(execution);
265
284
  if (claims?.size === 0)
@@ -347,6 +366,7 @@ export class RuntimeKernel {
347
366
  this.attachExecutionClaim(execution, run);
348
367
  yield* this.runAgentTurn(sessionId, run, execution, {
349
368
  steering: true,
369
+ allowPriorUnknownToolOutcomes: isExplicitClientMessage(input),
350
370
  onRunStarted: options.onRunStarted,
351
371
  initialHeader: header,
352
372
  });
@@ -878,6 +898,7 @@ export class RuntimeKernel {
878
898
  invocationId: begin.initialRuntimeEvent.invocationId,
879
899
  runId: run.runId,
880
900
  ...begin.backendInput,
901
+ ...(options.allowPriorUnknownToolOutcomes ? { allowPriorUnknownToolOutcomes: true } : {}),
881
902
  headAnchorRuntimeEvent: begin.initialRuntimeEvent,
882
903
  handoffBoundary: (signal, remainingSteps) => run.reachHandoffBoundary(signal, remainingSteps),
883
904
  ...runtimeSteeringInput(owners.messageOwner),
@@ -1535,6 +1556,17 @@ export class RuntimeKernel {
1535
1556
  runningTurnIds(sessionId) {
1536
1557
  return [...new Set(this.activeRunsFor(sessionId).map((run) => run.turnId))];
1537
1558
  }
1559
+ #sessionRunEpochs = new Map();
1560
+ #hostGeneration;
1561
+ sessionRunEpoch(sessionId) {
1562
+ return this.#sessionRunEpochs.get(sessionId) ?? 0;
1563
+ }
1564
+ sessionHostGeneration() {
1565
+ return this.#hostGeneration;
1566
+ }
1567
+ #bumpSessionRunEpoch(sessionId) {
1568
+ this.#sessionRunEpochs.set(sessionId, (this.#sessionRunEpochs.get(sessionId) ?? 0) + 1);
1569
+ }
1538
1570
  hasActiveRun(sessionId, runId, turnId) {
1539
1571
  return this.activeRunsFor(sessionId).some((run) => run.runId === runId && (turnId === undefined || run.turnId === turnId));
1540
1572
  }
@@ -1958,6 +1990,7 @@ export class RuntimeKernel {
1958
1990
  }
1959
1991
  active.activeRuns.set(run.runId, run);
1960
1992
  active.turnToRunId.set(run.turnId, run.runId);
1993
+ this.#bumpSessionRunEpoch(active.sessionId);
1961
1994
  }
1962
1995
  assertRunCanDispatch(run, backend) {
1963
1996
  const active = [...this.backendGenerations.values()].find((candidate) => candidate.backend === backend);
@@ -1978,6 +2011,7 @@ export class RuntimeKernel {
1978
2011
  if (active.turnToRunId.get(run.turnId) === run.runId) {
1979
2012
  active.turnToRunId.delete(run.turnId);
1980
2013
  }
2014
+ this.#bumpSessionRunEpoch(active.sessionId);
1981
2015
  }
1982
2016
  async unregisterParentRun(active, run) {
1983
2017
  this.unregisterRun(active, run);
@@ -2579,6 +2613,16 @@ function assertNoRemovedChildAgentRunLineage(input) {
2579
2613
  throw new Error('Live Turn cannot use removed child AgentRun lineage');
2580
2614
  }
2581
2615
  }
2616
+ function isExplicitClientMessage(input) {
2617
+ return (input.origin === undefined &&
2618
+ input.agentId === undefined &&
2619
+ input.agentName === undefined &&
2620
+ input.parentSessionId === undefined &&
2621
+ input.parentTurnId === undefined &&
2622
+ input.retriedFromTurnId === undefined &&
2623
+ input.regeneratedFromTurnId === undefined &&
2624
+ input.branchOfTurnId === undefined);
2625
+ }
2582
2626
  async function interactionResumeAllowed(interactionRun, event) {
2583
2627
  if (!interactionRun || !isHostedInteractionSettlementAckEvent(event)) {
2584
2628
  return true;
@@ -17,7 +17,7 @@
17
17
  * under the License.
18
18
  */
19
19
  import { countRecallSearchableMessages, listRecallCandidateSessions, } from './recall-candidates.js';
20
- import { createHash } from 'node:crypto';
20
+ import { createHash, randomUUID } from 'node:crypto';
21
21
  import { isDeepStrictEqual } from 'node:util';
22
22
  import { setTimeout as delay } from 'node:timers/promises';
23
23
  import { messageContentsEqual } from '@maka/core/events';
@@ -45,7 +45,7 @@ import { isTranscriptLedgerInvocation, RuntimeLedgerRepair } from './runtime-led
45
45
  import { buildRecoveredTerminalRuntimeEvent, classifyTerminalRuntimeLedger, commitTerminalRunWithRuntimeFact, terminalRunStatusFromRuntimeEvent, } from './terminal-run-commit.js';
46
46
  import { readLatestContextDiagnostics } from './context-diagnostics.js';
47
47
  import { attributeSandboxBoundaryRestartClosure, classifyAgentRunRecovery, } from './agent-run-recovery.js';
48
- import { buildInterruptedToolOutcomeCommits, resolveRuntimeRecovery } from './recovery-resolver.js';
48
+ import { resolveRuntimeRecovery } from './recovery-resolver.js';
49
49
  import { isRuntimeHostedRootAuthority, RuntimeMessageAuthorityInvariantError, } from './message-authority.js';
50
50
  import { RuntimeInteractionInvariantError, } from './interaction-authority.js';
51
51
  import { RuntimeKernel, SessionQuiescentMutationBusyError, } from './runtime-kernel.js';
@@ -69,13 +69,6 @@ function runtimeContinuationAuthority(store) {
69
69
  ? candidate
70
70
  : undefined;
71
71
  }
72
- function runtimeCommitSinkFromEventStore(store) {
73
- const candidate = store;
74
- return typeof candidate?.commitToolPrepared === 'function' &&
75
- typeof candidate.commitToolOutcome === 'function'
76
- ? candidate
77
- : undefined;
78
- }
79
72
  export { normalizeStopSessionSource, workHubDirectStopAbortSource, } from './session-projection-helpers.js';
80
73
  const CHILD_AGENT_SUMMARY_MAX_CHARS = 4_000;
81
74
  export class SessionConfigurationTransitionError extends Error {
@@ -119,7 +112,6 @@ export class SessionManager {
119
112
  runtimeKernel;
120
113
  runtimeLedgerRepair;
121
114
  preparedTranscriptLedgers = new Set();
122
- runtimeCommitSink;
123
115
  activeHostedLinkedChildSessions = new Set();
124
116
  childSessionSpawns = new Map();
125
117
  claimedAgentGraphIntentRuns = new Map();
@@ -132,8 +124,6 @@ export class SessionManager {
132
124
  if (deps.publishChildWorkspacePatch && !deps.listArtifactsForTurn) {
133
125
  throw new Error('Child workspace patch publication requires Artifact turn listing');
134
126
  }
135
- this.runtimeCommitSink =
136
- deps.runtimeCommitSink ?? runtimeCommitSinkFromEventStore(deps.runtimeEventStore);
137
127
  if (deps.runStore && deps.runtimeEventStore) {
138
128
  this.runtimeLedgerRepair = new RuntimeLedgerRepair({
139
129
  runtimeEventStore: deps.runtimeEventStore,
@@ -165,13 +155,38 @@ export class SessionManager {
165
155
  runningTurnIds(sessionId) {
166
156
  return this.runtimeKernel.runningTurnIds?.(sessionId) ?? [];
167
157
  }
158
+ /**
159
+ * The live run state's own order, bumped on every turn start and end. Two
160
+ * same-revision catalog reads can disagree about `runningTurnIds`; the epoch
161
+ * says which one is older (#5713). The counter is per-process — pair it with
162
+ * `sessionHostGeneration` to tell which process an observation came from.
163
+ */
164
+ sessionRunEpoch(sessionId) {
165
+ return this.runtimeKernel.sessionRunEpoch?.(sessionId) ?? 0;
166
+ }
167
+ /**
168
+ * Identifies this process's run-epoch generation. Catalog rows survive a
169
+ * Host restart while the per-process epoch counters restart at zero, so
170
+ * clients order same-revision reads by generation first, never by epoch
171
+ * across restarts (#5713). Falls back to a random identity — fixed once,
172
+ * and drawn outside the `newId` sequence — when the kernel does not expose
173
+ * one.
174
+ */
175
+ #hostGenerationFallback = randomUUID();
176
+ sessionHostGeneration() {
177
+ return this.runtimeKernel.sessionHostGeneration?.() ?? this.#hostGenerationFallback;
178
+ }
168
179
  #projectLiveRunState(sessions) {
169
180
  const runningTurnIds = this.runtimeKernel.runningTurnIds?.bind(this.runtimeKernel);
170
181
  if (!runningTurnIds)
171
182
  return sessions;
183
+ const sessionRunEpoch = this.runtimeKernel.sessionRunEpoch?.bind(this.runtimeKernel);
184
+ const sessionHostGeneration = this.runtimeKernel.sessionHostGeneration?.bind(this.runtimeKernel);
172
185
  return sessions.map((session) => ({
173
186
  ...session,
174
187
  runningTurnIds: runningTurnIds(session.id),
188
+ ...(sessionRunEpoch ? { runEpoch: sessionRunEpoch(session.id) } : {}),
189
+ ...(sessionHostGeneration ? { runHostGeneration: sessionHostGeneration() } : {}),
175
190
  }));
176
191
  }
177
192
  async listSessions(filter) {
@@ -3204,40 +3219,20 @@ export class SessionManager {
3204
3219
  // T1 states; generic app-restart repair must never write into them.
3205
3220
  continue;
3206
3221
  }
3207
- if (this.runtimeCommitSink) {
3208
- const interruptedOutcomes = buildInterruptedToolOutcomeCommits(inspected.runtimeEvents, this.deps.now(), run.opening.configuration.toolMode);
3209
- let outcomeCommitFailed = false;
3210
- for (const outcome of interruptedOutcomes) {
3211
- const committed = await commitInterruptedOutcomeWithRetry(policy, () => this.runtimeCommitSink.commitToolOutcome(outcome));
3212
- if (!committed) {
3213
- // Keep the run non-terminal so a later recovery pass can retry the
3214
- // missing outcome before any terminal repair seals the ledger.
3215
- outcomeCommitFailed = true;
3216
- }
3217
- else {
3218
- recovered ||= committed.created;
3219
- }
3220
- }
3221
- if (outcomeCommitFailed) {
3222
- continue;
3223
- }
3224
- if (interruptedOutcomes.length > 0) {
3225
- inspected = await inspectAgentRunReadModel(recoveryRunStore, this.deps.runtimeEventStore, {
3226
- sessionId,
3227
- runId: run.runId,
3228
- invocation: run,
3229
- includeModelReplay: false,
3230
- includeProjection: false,
3231
- });
3232
- }
3233
- }
3222
+ let unknownDispatchedTools = [];
3234
3223
  if (!inspected.runtimeEvents.some(isTerminalRuntimeEvent)) {
3235
3224
  const toolRecovery = resolveRuntimeRecovery(inspected.runtimeEvents);
3225
+ const indeterminate = toolRecovery.decisions.filter((decision) => decision.status === 'indeterminate');
3226
+ unknownDispatchedTools = indeterminate
3227
+ .filter((decision) => decision.reason === 'dispatch_without_response')
3228
+ .map(({ toolCallId, toolName }) => ({
3229
+ toolCallId,
3230
+ ...(toolName ? { toolName } : {}),
3231
+ }));
3236
3232
  if (toolRecovery.hasCorruption ||
3237
- toolRecovery.decisions.some((decision) => decision.status === 'indeterminate')) {
3238
- // Never seal an invocation while a dispatched operation still lacks
3239
- // a result or an explicit recovery decision. A later recovery pass
3240
- // may retry the durable settlement; corruption stays fail-closed.
3233
+ (indeterminate.length > 0 && unknownDispatchedTools.length !== indeterminate.length)) {
3234
+ // Only a structurally valid T1-without-T2 boundary can be sealed as
3235
+ // unknown. Legacy gaps and corrupt recovery facts still fail closed.
3241
3236
  continue;
3242
3237
  }
3243
3238
  }
@@ -3252,9 +3247,24 @@ export class SessionManager {
3252
3247
  const classified = runtimeDecision ?? classifyAgentRunRecovery(run, inspected.events);
3253
3248
  if (!classified)
3254
3249
  continue;
3255
- const decision = classified.status === 'failed'
3250
+ let decision = classified.status === 'failed'
3256
3251
  ? attributeSandboxBoundaryRestartClosure(classified, await readBoundaryClosures())
3257
3252
  : classified;
3253
+ if (unknownDispatchedTools.length > 0) {
3254
+ decision = {
3255
+ ...decision,
3256
+ status: 'failed',
3257
+ failureClass: 'outcome_unknown',
3258
+ diagnostic: {
3259
+ ...decision.diagnostic,
3260
+ recoveryReason: 'outcome_unknown',
3261
+ unresolvedToolCalls: unknownDispatchedTools.map(({ toolCallId, toolName }) => ({
3262
+ toolCallId,
3263
+ ...(toolName ? { toolName } : {}),
3264
+ })),
3265
+ },
3266
+ };
3267
+ }
3258
3268
  if (await this.applyAgentRunRecovery(sessionId, decision, inspected, policy)) {
3259
3269
  recovered = true;
3260
3270
  }
@@ -3345,7 +3355,6 @@ function groupContinuationClaimsBySession(states) {
3345
3355
  }
3346
3356
  return grouped;
3347
3357
  }
3348
- const MAX_BEST_EFFORT_OUTCOME_COMMIT_ATTEMPTS = 2;
3349
3358
  function listSessionsForRecovery(store, policy) {
3350
3359
  return policy.kind === 'strict' ? policy.stores.sessionStore.listForRecovery() : store.list();
3351
3360
  }
@@ -3359,19 +3368,6 @@ async function recoverOr(policy, operation, fallback) {
3359
3368
  return fallback;
3360
3369
  }
3361
3370
  }
3362
- async function commitInterruptedOutcomeWithRetry(policy, operation) {
3363
- const attempts = policy.kind === 'strict' ? 1 : MAX_BEST_EFFORT_OUTCOME_COMMIT_ATTEMPTS;
3364
- for (let attempt = 0; attempt < attempts; attempt += 1) {
3365
- try {
3366
- return await operation();
3367
- }
3368
- catch (error) {
3369
- if (policy.kind === 'strict')
3370
- throw error;
3371
- }
3372
- }
3373
- return undefined;
3374
- }
3375
3371
  function continuationRepairEventId(kind, claimId) {
3376
3372
  return `continuation-repair-${kind}-${createHash('sha256')
3377
3373
  .update(`maka.continuation-repair.${kind}.v1\0${claimId}`)
@@ -121,11 +121,22 @@ function buildOpenAiCodexFetch(sessionId, fetchFn, refreshOAuthAccessToken) {
121
121
  catch {
122
122
  return checkedOpenAiCodexFetch(fetchFn, url, { ...init, headers }, refreshOAuthAccessToken);
123
123
  }
124
- return checkedOpenAiCodexFetch(fetchFn, url, {
124
+ // The Codex backend accepts only streamed requests and rejects
125
+ // `max_output_tokens`. Tool-free auxiliary calls (titles, goal evaluation,
126
+ // recap, Daily Review, prompt suggestions) go through `generateText`, so
127
+ // their request is streamed here and folded back into the one Responses
128
+ // body a non-streaming caller parses. Their output cap is an internal
129
+ // constant, so it is dropped. A streaming caller (a main turn) is sent as
130
+ // is: a cap it carries is the user's model setting and is not discarded
131
+ // here.
132
+ const foldStream = parsedBody.stream !== true;
133
+ const { max_output_tokens: _auxiliaryOutputCap, ...uncappedBody } = parsedBody;
134
+ const forwardedBody = foldStream ? { ...uncappedBody, stream: true } : parsedBody;
135
+ const response = await checkedOpenAiCodexFetch(fetchFn, url, {
125
136
  ...init,
126
137
  headers,
127
138
  body: JSON.stringify({
128
- ...parsedBody,
139
+ ...forwardedBody,
129
140
  instructions: codexInstructionsFromBody(parsedBody),
130
141
  store: false,
131
142
  text: {
@@ -140,8 +151,79 @@ function buildOpenAiCodexFetch(sessionId, fetchFn, refreshOAuthAccessToken) {
140
151
  },
141
152
  }),
142
153
  }, refreshOAuthAccessToken);
154
+ return foldStream ? foldOpenAiCodexStream(response) : response;
143
155
  };
144
156
  }
157
+ const OPENAI_CODEX_TERMINAL_EVENTS = new Set([
158
+ 'response.completed',
159
+ 'response.incomplete',
160
+ 'response.failed',
161
+ ]);
162
+ /**
163
+ * Folds a Codex Responses event stream into the single response body a
164
+ * non-streaming Responses caller expects. The backend's terminal event can
165
+ * carry an empty `output`; the items then arrive only as
166
+ * `response.output_item.done` events, so they are collected and restored.
167
+ */
168
+ async function foldOpenAiCodexStream(response) {
169
+ // Decide by the body, not `content-type`: against the live backend the
170
+ // stream did not arrive here with an event-stream content type. A JSON body
171
+ // passes through unchanged.
172
+ const text = await response.text();
173
+ if (text.trimStart().startsWith('{')) {
174
+ return new Response(text, { status: response.status, headers: response.headers });
175
+ }
176
+ const doneItems = [];
177
+ let terminal;
178
+ let terminalType;
179
+ for (const block of text.split(/\r?\n\r?\n/)) {
180
+ const data = block
181
+ .split(/\r?\n/)
182
+ .filter((line) => line.startsWith('data:'))
183
+ .map((line) => line.slice(5).trimStart())
184
+ .join('\n');
185
+ if (!data || data === '[DONE]')
186
+ continue;
187
+ let event;
188
+ try {
189
+ event = JSON.parse(data);
190
+ }
191
+ catch {
192
+ continue;
193
+ }
194
+ if (event === null || typeof event !== 'object')
195
+ continue;
196
+ const { type, item, response: eventResponse } = event;
197
+ if (type === 'response.output_item.done' && item !== undefined)
198
+ doneItems.push(item);
199
+ if (typeof type === 'string' &&
200
+ OPENAI_CODEX_TERMINAL_EVENTS.has(type) &&
201
+ eventResponse !== null &&
202
+ typeof eventResponse === 'object') {
203
+ terminal = eventResponse;
204
+ terminalType = type;
205
+ }
206
+ }
207
+ if (!terminal) {
208
+ throw new Error('Codex OAuth request failed: the stream ended without a terminal response');
209
+ }
210
+ if (terminalType === 'response.failed') {
211
+ const error = terminal.error;
212
+ throw new Error(`Codex OAuth request failed: ${typeof error?.message === 'string' ? error.message : 'response.failed'}`);
213
+ }
214
+ // An incomplete response carries partial output (e.g. a content filter cut
215
+ // it off). Folded into a normal body, a caller would take the fragment as
216
+ // its result, so it is rejected like a failed one.
217
+ if (terminalType === 'response.incomplete') {
218
+ const details = terminal.incomplete_details;
219
+ throw new Error(`Codex OAuth request incomplete: ${typeof details?.reason === 'string' ? details.reason : 'response.incomplete'}`);
220
+ }
221
+ const output = Array.isArray(terminal.output) && terminal.output.length > 0 ? terminal.output : doneItems;
222
+ return new Response(JSON.stringify({ ...terminal, output }), {
223
+ status: response.status,
224
+ headers: { 'content-type': 'application/json' },
225
+ });
226
+ }
145
227
  async function checkedOpenAiCodexFetch(fetchFn, url, init, refreshOAuthAccessToken) {
146
228
  const edgeRetryDelaysMs = [2_000, 10_000, 30_000];
147
229
  let authorizationReplayUsed = false;