maka-agent 0.2.0-dev.23.20260906 → 0.2.0-dev.24.20260907

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 (148) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  28. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  29. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  30. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  31. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  32. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  33. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  34. package/node_modules/@maka/core/dist/record-schema.js +9 -2
  35. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  36. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  37. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  38. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  39. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  40. package/node_modules/@maka/core/dist/session.js +54 -52
  41. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  42. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  43. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  44. package/node_modules/@maka/core/package.json +4 -0
  45. package/node_modules/@maka/mcp/dist/index.js +131 -1
  46. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  49. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +127 -133
  50. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  51. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  52. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  53. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  54. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  55. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  56. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  57. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  58. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  59. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  60. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  61. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  62. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  63. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  64. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  65. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  66. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  67. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  68. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  69. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  70. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  71. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  72. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  73. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  74. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  75. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  76. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  77. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  78. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  79. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  80. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  81. package/node_modules/@maka/runtime/package.json +1 -0
  82. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  83. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  84. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  85. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  86. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  87. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  88. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -0
  89. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  90. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  91. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  92. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  93. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  94. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +21 -12
  95. package/node_modules/@maka/runtime-host/dist/protocol/index.js +25 -1
  96. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  97. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  98. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  99. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  100. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  101. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  102. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  103. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  104. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +100 -24
  105. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  106. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  107. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  108. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +96 -17
  109. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  110. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  111. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  112. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +76 -6
  113. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +325 -73
  114. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  115. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  116. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +50 -7
  117. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  118. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  119. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  120. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  121. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  122. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  123. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  124. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +0 -1
  125. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  126. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  127. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  128. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  129. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  130. package/node_modules/@maka/storage/dist/execution-stores.js +9 -7
  131. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  132. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  133. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  134. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  135. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  136. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  137. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  138. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  139. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  140. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  141. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  142. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +7 -1
  143. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  144. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  145. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  146. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  147. package/node_modules/@maka/storage/package.json +2 -0
  148. package/package.json +1 -1
@@ -16,6 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { isRuntimeSystemNoteKind } from '@maka/core/session';
19
20
  import { createRuntimeEventId } from '@maka/core/runtime-event';
20
21
  export const RUNTIME_EVENT_BACKFILL_STATE_KEY = 'makaRuntimeRecovery';
21
22
  export function backfillRuntimeEventsFromStoredMessages(input) {
@@ -115,13 +116,16 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
115
116
  case 'tool_call': {
116
117
  if (conversationTextOnly)
117
118
  break;
118
- if (message.providerExecuted === true && !replayableProviderToolUseIds.has(message.id)) {
119
+ // A provider-native call whose opaque output was not retained can never
120
+ // be replayed to a provider again, so it is converted hidden: the
121
+ // transcript keeps the card, and no model request is built from it.
122
+ const unreplayable = message.providerExecuted === true && !replayableProviderToolUseIds.has(message.id);
123
+ if (unreplayable) {
119
124
  diagnostics.push({
120
125
  code: 'skipped_provider_native_replay_gap',
121
126
  message: 'provider-native tool history requires the opaque provider output for lossless recovery',
122
127
  detail: { messageId: message.id, toolUseId: message.id },
123
128
  });
124
- break;
125
129
  }
126
130
  const stateDelta = toolCallStateDelta(message);
127
131
  events.push({
@@ -130,6 +134,7 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
130
134
  role: 'model',
131
135
  author: 'agent',
132
136
  ...storedToolActivityIdentity(message),
137
+ ...(unreplayable ? { modelVisibility: 'hidden' } : {}),
133
138
  content: {
134
139
  kind: 'function_call',
135
140
  id: message.id,
@@ -163,14 +168,16 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
163
168
  case 'tool_result': {
164
169
  if (conversationTextOnly)
165
170
  break;
166
- if (message.providerExecuted === true && message.providerOutput === undefined) {
167
- break;
168
- }
171
+ // Same rule as the call it answers: a result the provider cannot be
172
+ // shown again is kept as a transcript row and hidden from replay. A
173
+ // result whose call is not in this turn is hidden for the same reason —
174
+ // a lone result is not a request a provider would accept.
169
175
  const call = safePriorToolCall(toolCalls, message);
176
+ const unreplayable = !call || (message.providerExecuted === true && message.providerOutput === undefined);
170
177
  if (!call) {
171
178
  diagnostics.push({
172
179
  code: 'skipped_unmatched_tool_result',
173
- message: 'tool_result requires an earlier same-turn tool_call to recover RuntimeEvent function_response',
180
+ message: 'tool_result has no earlier same-turn tool_call, so its RuntimeEvent stays out of model replay',
174
181
  detail: {
175
182
  messageId: message.id,
176
183
  toolUseId: message.toolUseId,
@@ -178,18 +185,18 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
178
185
  turnId: input.run.turnId,
179
186
  },
180
187
  });
181
- break;
182
188
  }
183
189
  events.push({
184
190
  ...base,
185
191
  id: newId(),
186
192
  role: 'tool',
187
193
  author: 'tool',
188
- ...storedToolActivityIdentity(call),
194
+ ...storedToolActivityIdentity(call ?? message),
195
+ ...(unreplayable ? { modelVisibility: 'hidden' } : {}),
189
196
  content: {
190
197
  kind: 'function_response',
191
198
  id: message.toolUseId,
192
- name: call.toolName,
199
+ name: call?.toolName ?? '',
193
200
  result: message.content,
194
201
  isError: message.isError,
195
202
  ...(message.providerExecuted !== undefined
@@ -205,33 +212,22 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
205
212
  refs: {
206
213
  storedMessageId: message.id,
207
214
  toolCallId: message.toolUseId,
208
- ...(call.parentToolCallId !== undefined
215
+ ...(call?.parentToolCallId !== undefined
209
216
  ? { parentToolCallId: call.parentToolCallId }
210
217
  : {}),
211
- ...(call.parentOperationId !== undefined
218
+ ...(call?.parentOperationId !== undefined
212
219
  ? { parentOperationId: call.parentOperationId }
213
220
  : {}),
214
221
  },
215
222
  });
216
223
  break;
217
224
  }
218
- case 'permission_decision': {
225
+ // The decision names the tool it answered for, so it converts on its own
226
+ // evidence; a matching call in the same turn is confirmation, not a
227
+ // requirement.
228
+ case 'permission_decision':
219
229
  if (conversationTextOnly)
220
230
  break;
221
- const call = safePriorToolCall(toolCalls, message);
222
- if (!call) {
223
- diagnostics.push({
224
- code: 'skipped_unmatched_permission_decision',
225
- message: 'permission_decision requires an earlier same-turn tool_call to recover RuntimeEvent permissionDecision',
226
- detail: {
227
- messageId: message.id,
228
- toolUseId: message.toolUseId,
229
- runId: input.run.runId,
230
- turnId: input.run.turnId,
231
- },
232
- });
233
- break;
234
- }
235
231
  events.push({
236
232
  ...base,
237
233
  id: newId(),
@@ -242,15 +238,19 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
242
238
  permissionDecision: {
243
239
  requestId: message.id,
244
240
  decision: message.decision,
241
+ toolName: message.toolName,
245
242
  ...(message.rememberForTurn !== undefined
246
243
  ? { rememberForTurn: message.rememberForTurn }
247
244
  : {}),
245
+ ...(message.reviewer !== undefined ? { reviewer: message.reviewer } : {}),
246
+ ...(message.rationale !== undefined ? { rationale: message.rationale } : {}),
247
+ ...(message.riskLevel !== undefined ? { riskLevel: message.riskLevel } : {}),
248
+ ...(message.hint !== undefined ? { hint: message.hint } : {}),
248
249
  },
249
250
  },
250
- refs: { storedMessageId: message.id, toolCallId: call.id },
251
+ refs: { storedMessageId: message.id, toolCallId: message.toolUseId },
251
252
  });
252
253
  break;
253
- }
254
254
  case 'token_usage':
255
255
  if (conversationTextOnly)
256
256
  break;
@@ -271,20 +271,44 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
271
271
  },
272
272
  });
273
273
  break;
274
+ // Both are already accounted for elsewhere: the turn's ending becomes the
275
+ // terminal RuntimeEvent below, and a coordination record is the WorkHub's
276
+ // own durable proof, which no run ledger owns a copy of.
274
277
  case 'turn_state':
278
+ case 'workhub_coordination':
275
279
  break;
280
+ // A note that names a turn is that invocation's own fact, so it converts.
281
+ // A session-level kind that somehow carries a turnId is not: it says
282
+ // something about the Session, and the Session transcript keeps it.
276
283
  case 'system_note':
277
284
  if (conversationTextOnly)
278
285
  break;
279
- diagnostics.push({
280
- code: 'skipped_high_risk_message',
281
- message: 'system_note is not recovered into a run ledger because session-level notes may not belong to this run',
282
- detail: {
283
- messageId: message.id,
284
- kind: message.kind,
285
- runId: input.run.runId,
286
- turnId: input.run.turnId,
286
+ if (!isRuntimeSystemNoteKind(message.kind)) {
287
+ diagnostics.push({
288
+ code: 'skipped_high_risk_message',
289
+ message: 'session-level system_note is not recovered into a run ledger because it does not belong to this run',
290
+ detail: {
291
+ messageId: message.id,
292
+ kind: message.kind,
293
+ runId: input.run.runId,
294
+ turnId: input.run.turnId,
295
+ },
296
+ });
297
+ break;
298
+ }
299
+ events.push({
300
+ ...base,
301
+ id: newId(),
302
+ role: 'system',
303
+ author: 'system',
304
+ modelVisibility: 'hidden',
305
+ content: {
306
+ kind: 'system_note',
307
+ note: message.kind,
308
+ ...(message.data !== undefined ? { data: structuredClone(message.data) } : {}),
287
309
  },
310
+ actions: { stateDelta: recoveryState(now, message) },
311
+ refs: { storedMessageId: message.id },
288
312
  });
289
313
  break;
290
314
  }
@@ -297,12 +321,10 @@ export function backfillRuntimeEventsFromStoredMessages(input) {
297
321
  newId,
298
322
  now,
299
323
  });
300
- if (terminal.event) {
324
+ if (terminal.event)
301
325
  events.push(terminal.event);
302
- }
303
- else if (terminal.diagnostic) {
326
+ if (terminal.diagnostic)
304
327
  diagnostics.push(terminal.diagnostic);
305
- }
306
328
  return { events, diagnostics };
307
329
  }
308
330
  function storedToolActivityIdentity(message) {
@@ -346,23 +368,28 @@ function terminalRecoveryState(now, message) {
346
368
  }
347
369
  function terminalRuntimeEvent(input) {
348
370
  const turnState = latestTurnState(input.turnMessages);
349
- const status = terminalStatus(input.outcome, turnState);
350
- if (!status) {
351
- return {
352
- diagnostic: {
353
- code: 'skipped_unsafe_terminal_state',
354
- message: 'terminal RuntimeEvent was not recovered because legacy terminal evidence is incomplete',
355
- detail: {
356
- runId: input.run.runId,
357
- turnId: input.run.turnId,
358
- declaredStatus: input.outcome?.status,
359
- turnStatus: turnState?.status,
360
- },
371
+ const readStatus = terminalStatus(input.outcome, turnState);
372
+ // An invocation with no ending is not a legal ledger state, and leaving one
373
+ // open would strand the turn in recovery forever. Incomplete legacy evidence
374
+ // does not get to claim the turn completed, so it ends as the failure it
375
+ // actually was, marked so a reader can tell it apart from a recorded one.
376
+ const status = readStatus ?? 'failed';
377
+ const diagnostic = readStatus
378
+ ? undefined
379
+ : {
380
+ code: 'synthesized_terminal_event',
381
+ message: 'terminal RuntimeEvent was synthesized because legacy terminal evidence is incomplete',
382
+ detail: {
383
+ runId: input.run.runId,
384
+ turnId: input.run.turnId,
385
+ declaredStatus: input.outcome?.status,
386
+ turnStatus: turnState?.status,
361
387
  },
362
388
  };
363
- }
364
389
  const ts = turnState?.ts ?? input.outcome?.ts ?? input.now();
365
- const failureClass = status === 'failed' ? (turnState?.errorClass ?? input.outcome?.failureClass) : undefined;
390
+ const failureClass = status === 'failed'
391
+ ? (turnState?.errorClass ?? input.outcome?.failureClass ?? 'missing_terminal_event')
392
+ : undefined;
366
393
  const abortSource = status === 'aborted'
367
394
  ? (turnState?.abortSource ??
368
395
  input.outcome?.abortSource ??
@@ -390,6 +417,7 @@ function terminalRuntimeEvent(input) {
390
417
  },
391
418
  ...(turnState ? { refs: { storedMessageId: turnState.id } } : {}),
392
419
  },
420
+ ...(diagnostic ? { diagnostic } : {}),
393
421
  };
394
422
  }
395
423
  function terminalStatus(outcome, turnState) {
@@ -16,6 +16,8 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { MODEL_FAILURE_MESSAGE_MAX_BYTES } from '@maka/core/model-failure';
20
+ import { truncateUtf8 } from '@maka/core/diagnostic-log';
19
21
  import { markPersisted } from '@maka/core/persisted-value';
20
22
  import { SANDBOX_BOUNDARY_REQUEST_STATUSES, validateSandboxBoundaryExpansion, } from '@maka/core/sandbox-boundary';
21
23
  import { TOOL_ACTIVITY_KINDS, normalizeMessageContent } from '@maka/core/events';
@@ -42,7 +44,6 @@ const RUNTIME_EVENT_READ_MODEL_DIAGNOSTIC_SEVERITY = {
42
44
  archived_tool_result_placeholder: 'soft',
43
45
  generated_id: 'soft',
44
46
  tool_use_id_mismatch: 'hard',
45
- missing_legacy_message: 'soft',
46
47
  unexpected_projected_message: 'soft',
47
48
  };
48
49
  export function isHardRuntimeEventReadModelDiagnostic(diagnostic) {
@@ -89,7 +90,23 @@ export function projectRuntimeEventsToStoredMessages(events, options) {
89
90
  contentOrderByMessageId: new Map(),
90
91
  };
91
92
  const messages = [];
93
+ /**
94
+ * Which event each message came out of, by position.
95
+ *
96
+ * A message belongs to the event being read when it was appended: nothing
97
+ * rewrites an earlier message, so the rows that appear while one event is
98
+ * handled are exactly that event's rows. A durable reader numbers its pages
99
+ * from this, which is why it is recorded here rather than rediscovered.
100
+ */
101
+ const sourceEventIds = [];
102
+ let reading;
103
+ const attributeEmitted = () => {
104
+ while (sourceEventIds.length < messages.length)
105
+ sourceEventIds.push(reading.id);
106
+ };
92
107
  for (const event of events) {
108
+ attributeEmitted();
109
+ reading = event;
93
110
  recordStepContentOrder(event, state);
94
111
  if (isPartialRuntimeEvent(event)) {
95
112
  diagnostic(state, event, 'partial_skipped', 'partial RuntimeEvent skipped');
@@ -111,6 +128,9 @@ export function projectRuntimeEventsToStoredMessages(events, options) {
111
128
  case 'thinking':
112
129
  projected = projectThinking(event, state, messages) || projected;
113
130
  break;
131
+ case 'system_note':
132
+ projected = projectSystemNote(event, state, messages) || projected;
133
+ break;
114
134
  case 'invocation_opened':
115
135
  // The opening fact records route, configuration and lineage once per
116
136
  // invocation. Every reader joins it by invocationId; it has no chat row.
@@ -197,6 +217,10 @@ export function projectRuntimeEventsToStoredMessages(events, options) {
197
217
  // every provider-visible row the transfer leads to.
198
218
  projected = true;
199
219
  }
220
+ if (event.actions?.handoffPause) {
221
+ // Physical pause is not a logical Turn outcome or a chat message.
222
+ projected = true;
223
+ }
200
224
  if (event.actions?.runtimeProtocol) {
201
225
  // The protocol marker records which runtime contracts were live from a
202
226
  // run's first event. RecoveryResolver reads it; it has no chat row.
@@ -224,7 +248,7 @@ export function projectRuntimeEventsToStoredMessages(events, options) {
224
248
  if (event.actions?.tokenUsage) {
225
249
  projected = projectTokenUsage(event, state, messages) || projected;
226
250
  }
227
- if (isTerminalRuntimeEvent(event)) {
251
+ if (isTerminalRuntimeEvent(event) && !event.actions?.handoffPause) {
228
252
  projected = projectTerminalTurnState(event, state, messages) || projected;
229
253
  }
230
254
  if (!projected) {
@@ -247,7 +271,66 @@ export function projectRuntimeEventsToStoredMessages(events, options) {
247
271
  diagnostic(state, pending.event, 'unsupported_event', 'thinking content has no assistant text row with a matching message id');
248
272
  }
249
273
  }
250
- return { messages, diagnostics: state.diagnostics };
274
+ attributeEmitted();
275
+ return { messages, diagnostics: state.diagnostics, sourceEventIds };
276
+ }
277
+ /**
278
+ * A running invocation's events as the transcript should show them right now.
279
+ *
280
+ * Two things separate a live run from a finished one. Its last text or thinking
281
+ * event is still arriving, so it is presented as settled rather than withheld;
282
+ * and a step that has only thought so far has no assistant row to hang that
283
+ * thinking on, so an empty one is opened for it. Neither changes the ledger:
284
+ * both are how the same events read before the run ends.
285
+ */
286
+ export function activePresentationRuntimeEvents(events) {
287
+ const textMessages = new Set();
288
+ const lastThinkingByMessage = new Map();
289
+ for (const event of events) {
290
+ const content = event.content;
291
+ if (event.role !== 'model' || (content?.kind !== 'text' && content?.kind !== 'thinking')) {
292
+ continue;
293
+ }
294
+ const messageKey = activeMessageKey(event);
295
+ if (content.kind === 'text')
296
+ textMessages.add(messageKey);
297
+ else
298
+ lastThinkingByMessage.set(messageKey, event);
299
+ }
300
+ const syntheticAfter = new Map();
301
+ for (const [messageKey, thinking] of lastThinkingByMessage) {
302
+ if (textMessages.has(messageKey))
303
+ continue;
304
+ const existing = syntheticAfter.get(thinking) ?? [];
305
+ existing.push(emptyAssistantText(thinking));
306
+ syntheticAfter.set(thinking, existing);
307
+ }
308
+ const presented = [];
309
+ for (const event of events) {
310
+ presented.push(settledPresentationEvent(event));
311
+ presented.push(...(syntheticAfter.get(event) ?? []));
312
+ }
313
+ return presented;
314
+ }
315
+ function activeMessageKey(event) {
316
+ const messageId = event.refs?.providerEventId ?? event.refs?.storedMessageId ?? event.id;
317
+ return `${event.runId}\0${messageId}`;
318
+ }
319
+ function settledPresentationEvent(event) {
320
+ const content = event.content;
321
+ return event.partial &&
322
+ event.role === 'model' &&
323
+ (content?.kind === 'text' || content?.kind === 'thinking')
324
+ ? { ...event, partial: false }
325
+ : event;
326
+ }
327
+ function emptyAssistantText(thinking) {
328
+ return {
329
+ ...thinking,
330
+ id: `${thinking.id}:active-transcript-empty-text`,
331
+ partial: false,
332
+ content: { kind: 'text', text: '' },
333
+ };
251
334
  }
252
335
  export function projectRuntimeEventsToStoredMessagesWithArchiveStatuses(events, options) {
253
336
  return projectRuntimeEventsToStoredMessages(applyArchivedToolResultReadModelStatuses(events, options.archiveStatuses), options);
@@ -284,32 +367,6 @@ export function applyArchivedToolResultReadModelStatuses(events, archiveStatuses
284
367
  };
285
368
  });
286
369
  }
287
- export function compareRuntimeReadModelMessages(projected, legacy) {
288
- const diagnostics = [];
289
- const projectedCounts = countSemanticMessages(projected);
290
- const legacyCounts = countSemanticMessages(legacy);
291
- for (const [key, count] of legacyCounts) {
292
- const projectedCount = projectedCounts.get(key) ?? 0;
293
- if (projectedCount < count) {
294
- diagnostics.push({
295
- code: 'missing_legacy_message',
296
- message: 'projected RuntimeEvent read model is missing a legacy semantic message',
297
- detail: JSON.parse(key),
298
- });
299
- }
300
- }
301
- for (const [key, count] of projectedCounts) {
302
- const legacyCount = legacyCounts.get(key) ?? 0;
303
- if (legacyCount < count) {
304
- diagnostics.push({
305
- code: 'unexpected_projected_message',
306
- message: 'projected RuntimeEvent read model has no matching legacy semantic message',
307
- detail: JSON.parse(key),
308
- });
309
- }
310
- }
311
- return { compatible: diagnostics.length === 0, diagnostics };
312
- }
313
370
  export function classifyRuntimeEventTerminalFact(invocation, events) {
314
371
  const diagnostics = [];
315
372
  if (events.length === 0) {
@@ -665,6 +722,9 @@ function projectPermissionDecision(event, state, messages) {
665
722
  diagnostic(state, event, 'incomplete_event', 'permission decision toolName does not match its paired request or tool call');
666
723
  return false;
667
724
  }
725
+ // The prompt's own wording when the request survived, and the decision's copy
726
+ // of it when the decision is all that is left.
727
+ const hint = request?.hint ?? decision.hint;
668
728
  messages.push({
669
729
  type: 'permission_decision',
670
730
  id: decision.requestId,
@@ -679,7 +739,7 @@ function projectPermissionDecision(event, state, messages) {
679
739
  ...(decision.reviewer !== undefined ? { reviewer: decision.reviewer } : {}),
680
740
  ...(decision.rationale !== undefined ? { rationale: decision.rationale } : {}),
681
741
  ...(decision.riskLevel !== undefined ? { riskLevel: decision.riskLevel } : {}),
682
- ...(request?.hint !== undefined ? { hint: request.hint } : {}),
742
+ ...(hint !== undefined ? { hint } : {}),
683
743
  });
684
744
  return true;
685
745
  }
@@ -783,9 +843,6 @@ function projectTerminalTurnState(event, state, messages) {
783
843
  }
784
844
  const abortSource = status === 'aborted' ? abortSourceFromRuntime(event) : undefined;
785
845
  const failureClass = status === 'failed' ? failureClassFromRuntimeEvent(event) : undefined;
786
- const partialOutputRetained = messages.some((message) => message.turnId === event.turnId &&
787
- ((message.type === 'assistant' && message.text.trim().length > 0) ||
788
- message.type === 'tool_result'));
789
846
  messages.push({
790
847
  type: 'turn_state',
791
848
  id: stableMessageId(event, state, 'turn_state'),
@@ -802,7 +859,14 @@ function projectTerminalTurnState(event, state, messages) {
802
859
  ...(status === 'aborted' ? { abortedAt: event.ts } : {}),
803
860
  ...(abortSource ? { abortSource } : {}),
804
861
  ...(status === 'failed' ? { errorClass: failureClass ?? 'unknown' } : {}),
805
- partialOutputRetained,
862
+ ...(status === 'failed' && event.content?.kind === 'error' && event.content.message
863
+ ? {
864
+ failureMessage: truncateUtf8(event.content.message, MODEL_FAILURE_MESSAGE_MAX_BYTES, '…'),
865
+ }
866
+ : {}),
867
+ ...(status === 'failed' && event.content?.kind === 'error' && event.content.retry
868
+ ? { retry: event.content.retry }
869
+ : {}),
806
870
  });
807
871
  if (failureClass === 'tool_step_cap_reached') {
808
872
  messages.push({
@@ -818,6 +882,25 @@ function projectTerminalTurnState(event, state, messages) {
818
882
  // already reads `unknown` into an unreadable Session.
819
883
  return true;
820
884
  }
885
+ /**
886
+ * The note row of an invocation that wrote one.
887
+ *
888
+ * There is nothing to reconcile: the event carries the kind and the payload the
889
+ * row is made of, so the row is the event said back in the transcript's shape.
890
+ */
891
+ function projectSystemNote(event, state, messages) {
892
+ if (event.content?.kind !== 'system_note')
893
+ return false;
894
+ messages.push({
895
+ type: 'system_note',
896
+ id: stableMessageId(event, state, 'system_note'),
897
+ turnId: event.turnId,
898
+ ts: event.ts,
899
+ kind: event.content.note,
900
+ ...(event.content.data !== undefined ? { data: structuredClone(event.content.data) } : {}),
901
+ });
902
+ return true;
903
+ }
821
904
  function attachPendingThinking(event, state, messages, assistantMessageId) {
822
905
  const pendingItems = state.thinkingByMessageId.get(assistantMessageId);
823
906
  if (!pendingItems)
@@ -1039,128 +1122,3 @@ function isRuntimeEventDiagnosticDetail(detail) {
1039
1122
  typeof detail.runId === 'string' &&
1040
1123
  typeof detail.turnId === 'string');
1041
1124
  }
1042
- function countSemanticMessages(messages) {
1043
- const counts = new Map();
1044
- for (const message of messages) {
1045
- const key = stableSemanticKey(semanticMessage(message));
1046
- counts.set(key, (counts.get(key) ?? 0) + 1);
1047
- }
1048
- return counts;
1049
- }
1050
- function stableSemanticKey(value) {
1051
- return JSON.stringify(sortSemanticValue(value));
1052
- }
1053
- function sortSemanticValue(value) {
1054
- if (Array.isArray(value)) {
1055
- return value.map(sortSemanticValue);
1056
- }
1057
- if (!value || typeof value !== 'object') {
1058
- return value;
1059
- }
1060
- return Object.fromEntries(Object.keys(value)
1061
- .sort()
1062
- .map((key) => [key, sortSemanticValue(value[key])]));
1063
- }
1064
- function semanticMessage(message) {
1065
- switch (message.type) {
1066
- case 'user':
1067
- return {
1068
- type: message.type,
1069
- turnId: message.turnId,
1070
- text: message.text,
1071
- displayText: message.displayText,
1072
- origin: message.origin,
1073
- attachments: message.attachments ?? [],
1074
- directoryReferences: message.directoryReferences,
1075
- quotes: message.quotes ?? [],
1076
- };
1077
- case 'assistant':
1078
- return {
1079
- type: message.type,
1080
- turnId: message.turnId,
1081
- text: message.text,
1082
- modelId: message.modelId,
1083
- thinking: message.thinking,
1084
- };
1085
- case 'tool_call':
1086
- return {
1087
- type: message.type,
1088
- turnId: message.turnId,
1089
- toolUseId: message.id,
1090
- toolName: message.toolName,
1091
- activityKind: message.activityKind,
1092
- displayName: message.displayName,
1093
- intent: message.intent,
1094
- args: message.args,
1095
- };
1096
- case 'tool_result':
1097
- return {
1098
- type: message.type,
1099
- turnId: message.turnId,
1100
- toolUseId: message.toolUseId,
1101
- isError: message.isError,
1102
- content: message.content,
1103
- durationMs: message.durationMs,
1104
- };
1105
- case 'permission_decision':
1106
- return {
1107
- type: message.type,
1108
- turnId: message.turnId,
1109
- toolUseId: message.toolUseId,
1110
- toolName: message.toolName,
1111
- decision: message.decision,
1112
- rememberForTurn: message.rememberForTurn,
1113
- hint: message.hint,
1114
- };
1115
- case 'token_usage':
1116
- return {
1117
- type: message.type,
1118
- turnId: message.turnId,
1119
- input: message.input,
1120
- output: message.output,
1121
- cacheHitInput: message.cacheHitInput,
1122
- cacheMissInput: message.cacheMissInput,
1123
- cacheMissInputSource: message.cacheMissInputSource,
1124
- cacheWriteInput: message.cacheWriteInput,
1125
- reasoning: message.reasoning,
1126
- total: message.total,
1127
- rawFinishReason: message.rawFinishReason,
1128
- runtimeSteps: message.runtimeSteps,
1129
- cacheRead: message.cacheRead,
1130
- cacheCreation: message.cacheCreation,
1131
- costUsd: message.costUsd,
1132
- systemPromptHash: message.systemPromptHash,
1133
- contextRemaining: message.contextRemaining,
1134
- prefixHash: message.prefixHash,
1135
- prefixChangeReason: message.prefixChangeReason,
1136
- requestShapeHash: message.requestShapeHash,
1137
- requestShapeChangeReason: message.requestShapeChangeReason,
1138
- promptSegments: message.promptSegments,
1139
- contextBudget: message.contextBudget,
1140
- providerRequestTraceId: message.providerRequestTraceId,
1141
- lastRequestAnchor: message.lastRequestAnchor,
1142
- };
1143
- case 'turn_state':
1144
- return {
1145
- type: message.type,
1146
- turnId: message.turnId,
1147
- status: message.status,
1148
- parentTurnId: message.parentTurnId,
1149
- retriedFromTurnId: message.retriedFromTurnId,
1150
- regeneratedFromTurnId: message.regeneratedFromTurnId,
1151
- branchOfTurnId: message.branchOfTurnId,
1152
- parentSessionId: message.parentSessionId,
1153
- abortedAt: message.abortedAt,
1154
- abortSource: message.abortSource,
1155
- errorClass: message.errorClass,
1156
- partialOutputRetained: message.partialOutputRetained,
1157
- };
1158
- case 'system_note':
1159
- return {
1160
- type: message.type,
1161
- turnId: message.turnId,
1162
- kind: message.kind,
1163
- data: message.data,
1164
- };
1165
- }
1166
- }