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
@@ -72,6 +72,21 @@ const SUBSCRIPTION_CLOSE_ERRORS = [
72
72
  'internal_failure',
73
73
  ];
74
74
  export const SESSION_CONTINUITY_OPERATION_SPECS = {
75
+ 'subscription.pty_interest.set': defineOperation({
76
+ mode: 'control',
77
+ availability: 'ready',
78
+ errors: SUBSCRIPTION_CLOSE_ERRORS,
79
+ decodeInput: (value) => {
80
+ const record = requireExactRecord(value, 'PTY interest input', ['subscriptionId', 'refs']);
81
+ if (!Array.isArray(record.refs) || record.refs.length > 16)
82
+ throw invalidProtocolFrame('PTY interest must contain at most 16 refs');
83
+ const refs = record.refs.map(decodeRuntimeResourceRef);
84
+ if (new Set(refs).size !== refs.length)
85
+ throw invalidProtocolFrame('Duplicate PTY interest');
86
+ return { subscriptionId: requireId(record.subscriptionId, 'subscriptionId'), refs };
87
+ },
88
+ decodeOutput: decodeSubscriptionCloseResult,
89
+ }),
75
90
  'subscription.open': defineOperation({
76
91
  mode: 'control',
77
92
  availability: 'ready',
@@ -104,6 +119,31 @@ export const SESSION_CONTINUITY_OPERATION_SPECS = {
104
119
  export function decodeSubscriptionFrame(value) {
105
120
  requireEncodedByteLimit(value, 'subscription frame', SESSION_SUBSCRIPTION_FRAME_MAX_BYTES);
106
121
  const record = requireRecord(value, 'subscription frame');
122
+ if (record.kind === 'subscription.runtime_resource_pty_data') {
123
+ assertExactKeys(record, 'Runtime Resource PTY data frame', [
124
+ 'kind',
125
+ 'hostEpoch',
126
+ 'subscriptionId',
127
+ 'sessionId',
128
+ 'ref',
129
+ 'ptySequence',
130
+ 'data',
131
+ ...(Object.hasOwn(record, 'reset') ? ['reset'] : []),
132
+ ]);
133
+ if (record.reset !== undefined && record.reset !== true) {
134
+ throw invalidProtocolFrame('PTY reset must be true when present');
135
+ }
136
+ return {
137
+ kind: record.kind,
138
+ hostEpoch: requireId(record.hostEpoch, 'hostEpoch'),
139
+ subscriptionId: requireId(record.subscriptionId, 'subscriptionId'),
140
+ sessionId: requireEntityId(record.sessionId, 'sessionId'),
141
+ ref: decodeRuntimeResourceRef(record.ref),
142
+ ptySequence: requirePositiveCount(record.ptySequence, 'PTY sequence'),
143
+ data: requireUtf8BoundedString(record.data, 'Runtime Resource PTY data', SESSION_RUNTIME_RESOURCE_PTY_DATA_MAX_BYTES),
144
+ ...(record.reset === true ? { reset: true } : {}),
145
+ };
146
+ }
107
147
  const envelope = decodeEnvelope(record);
108
148
  let frame;
109
149
  if (record.kind === 'subscription.session_projection') {
@@ -209,26 +249,6 @@ export function decodeSubscriptionFrame(value) {
209
249
  }
210
250
  : { kind: record.kind, ...envelope, sessionId, domain };
211
251
  }
212
- else if (record.kind === 'subscription.runtime_resource_pty_data') {
213
- assertExactKeys(record, 'Runtime Resource PTY data frame', [
214
- 'kind',
215
- 'hostEpoch',
216
- 'subscriptionId',
217
- 'sequence',
218
- 'sessionId',
219
- 'ref',
220
- 'ptySequence',
221
- 'data',
222
- ]);
223
- frame = {
224
- kind: record.kind,
225
- ...envelope,
226
- sessionId: requireEntityId(record.sessionId, 'sessionId'),
227
- ref: decodeRuntimeResourceRef(record.ref),
228
- ptySequence: requirePositiveCount(record.ptySequence, 'PTY sequence'),
229
- data: requireUtf8BoundedString(record.data, 'Runtime Resource PTY data', SESSION_RUNTIME_RESOURCE_PTY_DATA_MAX_BYTES),
230
- };
231
- }
232
252
  else if (record.kind === 'subscription.closed') {
233
253
  assertExactKeys(record, 'subscription closed frame', [
234
254
  'kind',
@@ -105,7 +105,6 @@ export function decodeSessionTranscriptPageInput(value) {
105
105
  export function decodeSessionTranscriptBootstrap(value) {
106
106
  const bootstrap = requireExactRecord(value, 'Session transcript bootstrap', [
107
107
  'throughSequence',
108
- 'durableCoverage',
109
108
  'overlayMessageCount',
110
109
  'durable',
111
110
  'overlay',
@@ -113,9 +112,6 @@ export function decodeSessionTranscriptBootstrap(value) {
113
112
  const throughSequence = bootstrap.throughSequence === null
114
113
  ? null
115
114
  : requireCount(bootstrap.throughSequence, 'Session transcript watermark');
116
- if (bootstrap.durableCoverage !== 'complete' && bootstrap.durableCoverage !== 'projected') {
117
- throw invalidProtocolFrame('Invalid Session transcript durable coverage');
118
- }
119
115
  const overlayMessageCount = requireCount(bootstrap.overlayMessageCount, 'Session transcript overlay message count');
120
116
  if (overlayMessageCount > SESSION_TRANSCRIPT_OVERLAY_MAX_MESSAGES) {
121
117
  throw invalidProtocolFrame('Session transcript overlay exceeds its message limit');
@@ -135,7 +131,6 @@ export function decodeSessionTranscriptBootstrap(value) {
135
131
  }
136
132
  return {
137
133
  throughSequence,
138
- durableCoverage: bootstrap.durableCoverage,
139
134
  overlayMessageCount,
140
135
  durable,
141
136
  overlay,
@@ -16,6 +16,7 @@
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';
19
20
  import { decodeCanonicalMessage } from '@maka/core/session';
20
21
  import { truncateUtf8 } from '@maka/core/diagnostic-log';
21
22
  import { requireCount, requireEncodedByteLimit, requireEntityId, requireExactRecord, requireUtf8String, } from './codec.js';
@@ -47,11 +48,6 @@ export function mergeSessionTurnContributions(current, next) {
47
48
  ? next.latestState
48
49
  : current.latestState,
49
50
  userPromptPreview: current.userPromptPreview ?? next.userPromptPreview,
50
- hasAssistantMessage: current.hasAssistantMessage || next.hasAssistantMessage,
51
- hasAssistantOutput: current.hasAssistantOutput || next.hasAssistantOutput,
52
- hasToolResult: current.hasToolResult || next.hasToolResult,
53
- hasFailedToolResult: current.hasFailedToolResult || next.hasFailedToolResult,
54
- hasAbortNote: current.hasAbortNote || next.hasAbortNote,
55
51
  };
56
52
  }
57
53
  export function projectSessionTurnContributionForWire(contribution) {
@@ -69,11 +65,6 @@ export function projectSessionTurnContributionForWire(contribution) {
69
65
  userPromptPreview: contribution.userPromptPreview === null
70
66
  ? null
71
67
  : truncateUtf8(contribution.userPromptPreview, SESSION_TURN_PROMPT_PREVIEW_MAX_BYTES),
72
- hasAssistantMessage: contribution.hasAssistantMessage,
73
- hasAssistantOutput: contribution.hasAssistantOutput,
74
- hasToolResult: contribution.hasToolResult,
75
- hasFailedToolResult: contribution.hasFailedToolResult,
76
- hasAbortNote: contribution.hasAbortNote,
77
68
  };
78
69
  }
79
70
  function projectTurnStateMessageForWire(message) {
@@ -109,49 +100,44 @@ function projectTurnStateMessageForWire(message) {
109
100
  ...(message.errorClass
110
101
  ? { errorClass: truncateUtf8(message.errorClass, SESSION_TURN_DIAGNOSTIC_MAX_BYTES) }
111
102
  : {}),
112
- partialOutputRetained: message.partialOutputRetained,
103
+ ...(message.failureMessage
104
+ ? {
105
+ failureMessage: truncateUtf8(message.failureMessage, MODEL_FAILURE_MESSAGE_MAX_BYTES, '…'),
106
+ }
107
+ : {}),
108
+ ...(message.retry ? { retry: message.retry } : {}),
113
109
  };
114
110
  }
111
+ /**
112
+ * The Turn a contribution describes, or nothing when its ending is not on the
113
+ * page yet.
114
+ *
115
+ * A Turn's status is read off the `turn_state` its terminal projects; a
116
+ * contribution without one has not been folded up to its ending, and a status
117
+ * guessed from the rows that did arrive is one no reader trusts anyway.
118
+ */
115
119
  export function projectSessionTurnContribution(contribution) {
116
120
  const state = contribution.latestState?.message;
117
- const partialOutputRetained = contribution.hasAssistantOutput || contribution.hasToolResult;
118
- if (state) {
119
- return {
120
- turnId: contribution.turnId,
121
- firstSequence: contribution.firstSequence,
122
- ...(contribution.userPromptPreview
123
- ? { userPromptPreview: contribution.userPromptPreview }
124
- : {}),
125
- status: state.status,
126
- statusSource: 'recorded',
127
- ...(state.parentTurnId ? { parentTurnId: state.parentTurnId } : {}),
128
- ...(state.retriedFromTurnId ? { retriedFromTurnId: state.retriedFromTurnId } : {}),
129
- ...(state.regeneratedFromTurnId
130
- ? { regeneratedFromTurnId: state.regeneratedFromTurnId }
131
- : {}),
132
- ...(state.branchOfTurnId ? { branchOfTurnId: state.branchOfTurnId } : {}),
133
- ...(state.parentSessionId ? { parentSessionId: state.parentSessionId } : {}),
134
- ...(state.abortedAt !== undefined ? { abortedAt: state.abortedAt } : {}),
135
- ...(state.abortSource ? { abortSource: state.abortSource } : {}),
136
- ...(state.errorClass ? { errorClass: state.errorClass } : {}),
137
- partialOutputRetained: state.partialOutputRetained || partialOutputRetained,
138
- };
139
- }
121
+ if (!state)
122
+ return undefined;
140
123
  return {
141
124
  turnId: contribution.turnId,
142
125
  firstSequence: contribution.firstSequence,
143
126
  ...(contribution.userPromptPreview
144
127
  ? { userPromptPreview: contribution.userPromptPreview }
145
128
  : {}),
146
- status: contribution.hasAbortNote
147
- ? 'aborted'
148
- : contribution.hasAssistantMessage
149
- ? 'completed'
150
- : contribution.hasFailedToolResult
151
- ? 'failed'
152
- : 'completed',
153
- statusSource: 'inferred',
154
- partialOutputRetained,
129
+ status: state.status,
130
+ statusSource: 'recorded',
131
+ ...(state.parentTurnId ? { parentTurnId: state.parentTurnId } : {}),
132
+ ...(state.retriedFromTurnId ? { retriedFromTurnId: state.retriedFromTurnId } : {}),
133
+ ...(state.regeneratedFromTurnId ? { regeneratedFromTurnId: state.regeneratedFromTurnId } : {}),
134
+ ...(state.branchOfTurnId ? { branchOfTurnId: state.branchOfTurnId } : {}),
135
+ ...(state.parentSessionId ? { parentSessionId: state.parentSessionId } : {}),
136
+ ...(state.abortedAt !== undefined ? { abortedAt: state.abortedAt } : {}),
137
+ ...(state.abortSource ? { abortSource: state.abortSource } : {}),
138
+ ...(state.errorClass ? { errorClass: state.errorClass } : {}),
139
+ ...(state.failureMessage ? { failureMessage: state.failureMessage } : {}),
140
+ ...(state.retry ? { retry: state.retry } : {}),
155
141
  };
156
142
  }
157
143
  const QUERY_ERRORS = [
@@ -283,11 +269,6 @@ function decodeSessionTurnContribution(value) {
283
269
  'firstSequence',
284
270
  'latestState',
285
271
  'userPromptPreview',
286
- 'hasAssistantMessage',
287
- 'hasAssistantOutput',
288
- 'hasToolResult',
289
- 'hasFailedToolResult',
290
- 'hasAbortNote',
291
272
  ]);
292
273
  let latestState = null;
293
274
  if (contribution.latestState !== null) {
@@ -317,15 +298,5 @@ function decodeSessionTurnContribution(value) {
317
298
  userPromptPreview: contribution.userPromptPreview === null
318
299
  ? null
319
300
  : requireUtf8String(contribution.userPromptPreview, 'Session turn prompt preview', SESSION_TURN_PROMPT_PREVIEW_MAX_BYTES),
320
- hasAssistantMessage: requireBoolean(contribution.hasAssistantMessage),
321
- hasAssistantOutput: requireBoolean(contribution.hasAssistantOutput),
322
- hasToolResult: requireBoolean(contribution.hasToolResult),
323
- hasFailedToolResult: requireBoolean(contribution.hasFailedToolResult),
324
- hasAbortNote: requireBoolean(contribution.hasAbortNote),
325
301
  };
326
302
  }
327
- function requireBoolean(value) {
328
- if (typeof value !== 'boolean')
329
- throw invalidProtocolFrame('Invalid Session turn contribution');
330
- return value;
331
- }
@@ -427,6 +427,12 @@ function requirePositiveCount(value, label) {
427
427
  throw invalidProtocolFrame(`Invalid ${label}`);
428
428
  return count;
429
429
  }
430
+ function requireContextCompactRootExecutionKind(value) {
431
+ if (value !== 'context_compact') {
432
+ throw invalidProtocolFrame('Invalid Turn rootExecutionKind');
433
+ }
434
+ return value;
435
+ }
430
436
  export function decodeTurnSnapshot(value) {
431
437
  const record = requireRecord(value, 'Turn snapshot');
432
438
  const base = {
@@ -478,13 +484,16 @@ export function decodeTurnSnapshot(value) {
478
484
  abortSource: requireString(record.abortSource, 'abortSource', 128),
479
485
  };
480
486
  }
481
- requireShapedRecord(record, 'non-terminal Turn snapshot', ['sessionId', 'turnId', 'runId', 'status'], ['providerRetry']);
487
+ requireShapedRecord(record, 'non-terminal Turn snapshot', ['sessionId', 'turnId', 'runId', 'status'], ['providerRetry', 'rootExecutionKind']);
482
488
  return {
483
489
  ...base,
484
490
  status,
485
491
  ...(record.providerRetry !== undefined
486
492
  ? { providerRetry: decodeTurnProviderRetry(record.providerRetry) }
487
493
  : {}),
494
+ ...(record.rootExecutionKind !== undefined
495
+ ? { rootExecutionKind: requireContextCompactRootExecutionKind(record.rootExecutionKind) }
496
+ : {}),
488
497
  };
489
498
  }
490
499
  export function decodeContextCompactionOutcome(value) {
@@ -535,6 +544,7 @@ function requireProviderRetryReason(value) {
535
544
  if (value === 'network' ||
536
545
  value === 'provider_capacity' ||
537
546
  value === 'provider_unavailable' ||
547
+ value === 'stream_truncated' ||
538
548
  value === 'rate_limit' ||
539
549
  value === 'timeout' ||
540
550
  value === 'unknown') {
@@ -66,6 +66,7 @@ export const SESSION_GUEST_OPERATION_GRANTS = Object.freeze([
66
66
  'session.shared.query',
67
67
  'subscription.open',
68
68
  'subscription.close',
69
+ 'subscription.pty_interest.set',
69
70
  'session.transcript.page',
70
71
  'session.transcript.overlay.release',
71
72
  ]);
@@ -19,6 +19,7 @@
19
19
  import { truncateUtf8 } from '@maka/core/diagnostic-log';
20
20
  import { redactSecrets } from '@maka/core/redaction';
21
21
  import { readRunInvocation } from '@maka/core/runtime-event-store';
22
+ import { readLogicalRuntimeExecution } from '@maka/core/runtime-logical-execution';
22
23
  import { classifyTerminalRuntimeLedger } from '@maka/runtime/terminal-run-commit';
23
24
  import { TURN_FAILURE_MESSAGE_MAX_BYTES } from '../protocol/index.js';
24
25
  export async function readCanonicalTurnSnapshot(stores, identity, knownRun) {
@@ -29,8 +30,16 @@ export async function readCanonicalTurnSnapshot(stores, identity, knownRun) {
29
30
  if (run.turnId !== turnId) {
30
31
  throw new Error('Admitted Turn identity does not match its invocation');
31
32
  }
32
- const runtimeEvents = await stores.runtimeEventStore.readImmutableRuntimeEvents(sessionId, runId);
33
- const terminal = classifyTerminalRuntimeLedger(run, runtimeEvents);
33
+ const logical = await readLogicalRuntimeExecution(stores.runtimeEventStore, identity, run);
34
+ if (!logical)
35
+ throw new Error('Admitted logical execution disappeared');
36
+ const rootExecutionKind = logical.root.opening.root.kind === 'context_compact'
37
+ ? { rootExecutionKind: 'context_compact' }
38
+ : {};
39
+ if (logical.pendingHandoff) {
40
+ return { sessionId, turnId, runId, status: 'running', ...rootExecutionKind };
41
+ }
42
+ const terminal = classifyTerminalRuntimeLedger(logical.tip, logical.events);
34
43
  if (terminal.kind === 'fact') {
35
44
  const fact = terminal.fact;
36
45
  if (fact.runStatus === 'completed') {
@@ -76,8 +85,14 @@ export async function readCanonicalTurnSnapshot(stores, identity, knownRun) {
76
85
  }
77
86
  // No terminal event means the run is still open. Whether it is parked is the
78
87
  // pending-interaction store's answer, not something the run restates.
79
- const parked = await hasPendingInteraction(stores, sessionId, runId);
80
- return { sessionId, turnId, runId, status: parked ? 'waiting_for_user' : 'running' };
88
+ const parked = await hasPendingInteraction(stores, sessionId, logical.tip.runId);
89
+ return {
90
+ sessionId,
91
+ turnId,
92
+ runId,
93
+ status: parked ? 'waiting_for_user' : 'running',
94
+ ...rootExecutionKind,
95
+ };
81
96
  }
82
97
  /** Is this run waiting on a request the user has not answered? */
83
98
  async function hasPendingInteraction(stores, sessionId, runId) {
@@ -33,7 +33,7 @@ export class RuntimeHostConnectionSession {
33
33
  #clientCapabilities;
34
34
  #clientCapabilityCloseTask;
35
35
  #hostChanges;
36
- #inputClosed = false;
36
+ #inputClosedAbort = new AbortController();
37
37
  #closed = false;
38
38
  constructor(options) {
39
39
  this.#options = options;
@@ -65,7 +65,7 @@ export class RuntimeHostConnectionSession {
65
65
  }
66
66
  }
67
67
  async #closeAfterDispatchedReplies() {
68
- this.#inputClosed = true;
68
+ this.#inputClosedAbort.abort();
69
69
  this.#detachContinuity();
70
70
  this.#detachClientCapabilities();
71
71
  this.#detachHostChanges();
@@ -159,6 +159,7 @@ export class RuntimeHostConnectionSession {
159
159
  : undefined;
160
160
  const response = await dispatchOperation(frame, this.#options.resolveHandlers(), {
161
161
  ...this.#options.connection,
162
+ inputClosedSignal: this.#inputClosedAbort.signal,
162
163
  principal: this.#options.connection.authority.principalId,
163
164
  principalKind: this.#options.connection.authority.principalKind,
164
165
  ...(this.#options.connection.authority.credentialId
@@ -193,7 +194,7 @@ export class RuntimeHostConnectionSession {
193
194
  }
194
195
  }
195
196
  #ensureContinuity() {
196
- if (this.#closed || this.#inputClosed)
197
+ if (this.#closed || this.#inputClosedAbort.signal.aborted)
197
198
  return;
198
199
  const service = this.#options.resolveContinuity();
199
200
  if (!service)
@@ -222,7 +223,7 @@ export class RuntimeHostConnectionSession {
222
223
  this.#continuityService = undefined;
223
224
  }
224
225
  #ensureClientCapabilities() {
225
- if (this.#closed || this.#inputClosed)
226
+ if (this.#closed || this.#inputClosedAbort.signal.aborted)
226
227
  return;
227
228
  // Guests observe and submit approval requests; they cannot provide Client
228
229
  // Capabilities or directly admit a Turn. In particular, their pending and
@@ -274,7 +275,7 @@ export class RuntimeHostConnectionSession {
274
275
  void this.#clientCapabilityCloseTask.catch(() => undefined);
275
276
  }
276
277
  attachGlobalChanges() {
277
- if (this.#closed || this.#inputClosed)
278
+ if (this.#closed || this.#inputClosedAbort.signal.aborted)
278
279
  return;
279
280
  const service = this.#options.resolveHostChanges?.();
280
281
  if (!service || this.#hostChanges)
@@ -316,7 +317,7 @@ export class RuntimeHostConnectionSession {
316
317
  if (this.#closed)
317
318
  return;
318
319
  this.#closed = true;
319
- this.#inputClosed = true;
320
+ this.#inputClosedAbort.abort();
320
321
  this.#detachContinuity();
321
322
  this.#detachClientCapabilities();
322
323
  this.#detachHostChanges();
@@ -22,6 +22,7 @@ import { messageContentDigest, normalizeMessageContent } from '@maka/core/events
22
22
  import { NO_REAL_CONNECTION_CODE } from '@maka/core/connection-error-copy';
23
23
  import { generalizedErrorMessage } from '@maka/core/redaction';
24
24
  import { emptyPlanSessionState } from '@maka/core/plan';
25
+ import { readLogicalRuntimeExecutionForRun } from '@maka/core/runtime-logical-execution';
25
26
  import { runtimeInvocationOutcome, } from '@maka/core/runtime-invocation';
26
27
  import { isDeepResearchSession, WORKHUB_COORDINATION_SESSION_ID, WORKHUB_COORDINATION_REPLACEMENT_SCHEMA_VERSION, } from '@maka/core/session';
27
28
  import { AgentGraphCoordinator } from '@maka/runtime/stream-graph-coordinator';
@@ -77,7 +78,7 @@ import { HostGoalCoordinator } from './goal-coordinator.js';
77
78
  import { HostGoalExecutionCoordinator } from './goal-execution-coordinator.js';
78
79
  import { HostHostedExecutionCoordinator } from './hosted-execution-coordinator.js';
79
80
  import { HostHostedExecutionRunner } from './hosted-execution-runner.js';
80
- import { executeHostedExecutionToSettlement } from './hosted-execution-wait.js';
81
+ import { executeHostedExecutionToSettlement, waitForHostedExecutionIdleOrAbort, } from './hosted-execution-wait.js';
81
82
  import { beginRuntimeHostDomainModuleDrain, closeRuntimeHostDomainModules, composeRuntimeHostDomainHandlers, createRuntimeHostDomainModule, recoverRuntimeHostDomainModules, } from './host-composition.js';
82
83
  import { HostInteractionCoordinator } from './interaction-coordinator.js';
83
84
  import { HostInteractiveTurnCoordinator } from './interactive-turn-coordinator.js';
@@ -108,10 +109,11 @@ import { SessionAdmissionGate } from './session-admission-gate.js';
108
109
  import { HostSessionCatalogCoordinator } from './session-catalog-coordinator.js';
109
110
  import { HostWorkspaceResolver } from './workspace-resolver.js';
110
111
  import { HostSessionRetirementCoordinator } from './session-retirement-coordinator.js';
112
+ import { HostStorageMaintenance } from './storage-maintenance.js';
111
113
  import { HostSessionRevisionCoordinator } from './session-revision-coordinator.js';
112
114
  import { HostSessionEffectCoordinator } from './session-effect-coordinator.js';
113
115
  import { SessionContinuityCoordinator } from './session-continuity-coordinator.js';
114
- import { createSessionTranscriptReader } from './session-transcript-reader.js';
116
+ import { createSessionTranscriptReader, } from './session-transcript-reader.js';
115
117
  import { HostSkillCatalogCoordinator } from './skill-catalog-coordinator.js';
116
118
  import { SkillCatalogRepository } from './skill-catalog-repository.js';
117
119
  import { HostSessionTodoCoordinator } from './session-todo-coordinator.js';
@@ -160,6 +162,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
160
162
  let sessionEffects;
161
163
  let memoryExtraction;
162
164
  let unsubscribeTranscriptChanges;
165
+ let transcriptReader;
163
166
  let unsubscribeUsageChanges;
164
167
  let workspaceExecution;
165
168
  let goalExecutions;
@@ -198,9 +201,6 @@ export async function createExecutionRuntimeHostComposition(context, options = {
198
201
  cause: storage.contextOffloadUnavailable?.cause,
199
202
  });
200
203
  },
201
- collectGarbage: async () => {
202
- throw new Error('Context-offload Store is unavailable during context garbage collection', { cause: storage.contextOffloadUnavailable?.cause });
203
- },
204
204
  }
205
205
  : undefined;
206
206
  const openedUsageStores = storage.usage;
@@ -404,6 +404,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
404
404
  hostEpoch: context.hostEpoch,
405
405
  root: rootPort,
406
406
  durableProof: {
407
+ readLogicalExecution: (identity) => readLogicalRuntimeExecutionForRun(stores.runtimeEventStore, identity),
407
408
  readRootTurnSourceMessageReceipt: (sessionId, messageId) => stores.agentRunStore.readRootTurnSourceMessageReceipt(sessionId, messageId),
408
409
  readImmutableSteeringMessageProof: (sessionId, messageId) => stores.runtimeEventStore.readImmutableSteeringMessageProof(sessionId, messageId),
409
410
  },
@@ -425,7 +426,12 @@ export async function createExecutionRuntimeHostComposition(context, options = {
425
426
  const canonicalPermissionOutcomes = new HostCanonicalPermissionOutcomeReader({
426
427
  store: stores.interactionStore,
427
428
  });
428
- continuity = new SessionContinuityCoordinator(context.hostEpoch, (sessionId) => canonicalProjectionReader.read(sessionId), sessionAdmission, context.requestDrain, createSessionTranscriptReader({ stores, canonicalPermissionOutcomes }), (sessionId) => hostChanges.publishSessionCatalog(sessionId), context.sessionAccessAuthority);
429
+ transcriptReader = createSessionTranscriptReader({
430
+ stores,
431
+ canonicalPermissionOutcomes,
432
+ ensureTranscriptLedger: (sessionId) => requireSessionManager(manager).ensureTranscriptLedgerForRead(sessionId),
433
+ });
434
+ continuity = new SessionContinuityCoordinator(context.hostEpoch, (sessionId) => canonicalProjectionReader.read(sessionId), sessionAdmission, context.requestDrain, transcriptReader, (sessionId) => hostChanges.publishSessionCatalog(sessionId), context.sessionAccessAuthority);
429
435
  const continuityCoordinator = continuity;
430
436
  unsubscribeTranscriptChanges = stores.sessionStore.subscribeTranscriptChanges((sessionId) => continuityCoordinator.enqueueCanonicalRefresh(sessionId));
431
437
  unsubscribeUsageChanges = openedUsageStores.subscribeSessionUsageChanges((sessionId) => continuityCoordinator.enqueueSessionDomainChanged(sessionId, 'usage'));
@@ -713,6 +719,10 @@ export async function createExecutionRuntimeHostComposition(context, options = {
713
719
  throw new Error(preview.message);
714
720
  return preview.value;
715
721
  };
722
+ const recapReadModel = new RuntimeReadModel({
723
+ runtimeEventStore: stores.runtimeEventStore,
724
+ canonicalPermissionOutcomes,
725
+ });
716
726
  const sessionEffectCoordinator = new HostSessionEffectCoordinator({
717
727
  model: createHostSessionEffectModel({
718
728
  runtimePolicy: runtimePolicyStores,
@@ -720,11 +730,14 @@ export async function createExecutionRuntimeHostComposition(context, options = {
720
730
  usage: openedUsageStores,
721
731
  requestDrain: context.requestDrain,
722
732
  }),
723
- readModel: new RuntimeReadModel({
724
- runtimeEventStore: stores.runtimeEventStore,
725
- projectionCache: stores.sessionStore,
726
- canonicalPermissionOutcomes,
727
- }),
733
+ readModel: {
734
+ getSessionView: async (sessionId) => {
735
+ // A Session whose transcript predates the ledger projects an empty
736
+ // view, and a recap of nothing reads as a successful recap.
737
+ await requireSessionManager(manager).ensureTranscriptLedgerForRead(sessionId);
738
+ return recapReadModel.getSessionView(sessionId);
739
+ },
740
+ },
728
741
  artifacts: openedArtifactStore,
729
742
  sessions: stores.sessionStore,
730
743
  readSessionHeader: (sessionId) => stores.sessionStore.readHeaderSnapshot(sessionId),
@@ -990,6 +1003,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
990
1003
  goal = new HostGoalCoordinator({
991
1004
  store: openedGoalStore,
992
1005
  stores,
1006
+ readSessionMessages: (sessionId) => requireSessionManager(manager).getMessages(sessionId),
993
1007
  executions: coordinator,
994
1008
  sessionAdmission,
995
1009
  evaluator: createHostGoalEvaluator({
@@ -1022,6 +1036,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1022
1036
  });
1023
1037
  const sessionCatalog = new HostSessionCatalogCoordinator({
1024
1038
  stores: stores.sessionStore,
1039
+ turnIndex: requireTranscriptReader(transcriptReader),
1025
1040
  runtimePolicy: runtimePolicyStores,
1026
1041
  manager,
1027
1042
  admission: sessionAdmission,
@@ -1099,8 +1114,9 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1099
1114
  ? 'Safe-boundary resume is disabled for this Runtime Host'
1100
1115
  : 'WorkHub delegated execution is not resumable');
1101
1116
  }
1102
- if (plan.result.sourceRunId !== source.runId ||
1103
- plan.result.sourceTurnId !== source.turnId) {
1117
+ // Root planning authenticates handoff membership. Its source may be
1118
+ // a physical successor of this same logical Turn, never another Turn.
1119
+ if (plan.result.sourceTurnId !== source.turnId) {
1104
1120
  throw new WorkHubActionEffectFailure('operation_conflict', 'WorkHub resume source lineage changed during planning');
1105
1121
  }
1106
1122
  const targetTurnId = workHubResumedTurnId(actionId);
@@ -1396,7 +1412,17 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1396
1412
  });
1397
1413
  const hostedExecutions = new HostHostedExecutionCoordinator((input, signal) => hostedExecutionRunner.run(input, signal), context.requestDrain);
1398
1414
  let recoverySessions = [];
1415
+ const storageMaintenance = new HostStorageMaintenance({
1416
+ artifacts: openedArtifactStore,
1417
+ contextOffload: openedContextOffloadStore,
1418
+ onError: (name, error) => console.error(`[runtime-host] ${name} will retry: ${generalizedErrorMessage(error)}`),
1419
+ });
1399
1420
  domainModules = [
1421
+ createRuntimeHostDomainModule({
1422
+ id: 'storage-maintenance',
1423
+ drain: [() => storageMaintenance.beginDrain()],
1424
+ close: [() => storageMaintenance.close()],
1425
+ }),
1400
1426
  createRuntimeHostDomainModule({
1401
1427
  id: 'plugin-platform',
1402
1428
  handlers: [pluginPlatformCoordinator.handlers],
@@ -1458,17 +1484,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1458
1484
  configuration.handlers,
1459
1485
  ],
1460
1486
  recovery: {
1461
- state: async () => {
1462
- await skills.recover();
1463
- try {
1464
- await openedArtifactStore.reclaimUpgradeResidue();
1465
- }
1466
- catch (error) {
1467
- // Leftover bytes are not worth refusing to start over; the next
1468
- // start tries again.
1469
- console.error(`[runtime-host] upgrade residue could not be reclaimed: ${generalizedErrorMessage(error)}`);
1470
- }
1471
- },
1487
+ state: () => skills.recover(),
1472
1488
  },
1473
1489
  drain: [
1474
1490
  () => connectionEffects.beginDrain(),
@@ -1664,12 +1680,67 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1664
1680
  continuity: continuityCoordinator,
1665
1681
  clientCapabilities,
1666
1682
  hostChanges,
1683
+ prepareHandoff: async (hostEpoch, signal) => {
1684
+ if (draining || signal.aborted)
1685
+ return undefined;
1686
+ const goalHold = goal?.holdForHandoff();
1687
+ const scheduleHold = scheduledTasks?.holdForHandoff();
1688
+ let root;
1689
+ let detached = false;
1690
+ const cancel = () => {
1691
+ if (detached)
1692
+ return;
1693
+ root?.cancel();
1694
+ goalHold?.release();
1695
+ scheduleHold?.release();
1696
+ signal.removeEventListener('abort', cancel);
1697
+ };
1698
+ signal.addEventListener('abort', cancel, { once: true });
1699
+ try {
1700
+ if (!goalHold || !scheduleHold) {
1701
+ cancel();
1702
+ return undefined;
1703
+ }
1704
+ await waitForHostedExecutionIdleOrAbort(Promise.all([goalHold.settled(), scheduleHold.settled()]).then(() => undefined), signal);
1705
+ root = await requireRootCoordinator(coordinator).prepareHandoff(hostEpoch, signal);
1706
+ if (!root) {
1707
+ cancel();
1708
+ return undefined;
1709
+ }
1710
+ const prepared = root;
1711
+ return {
1712
+ seal: () => prepared.seal(),
1713
+ residencies: async () => {
1714
+ await waitForHostedExecutionIdleOrAbort(scheduleHold.settled(), signal);
1715
+ const goals = await goalHold.residencies(prepared.executions);
1716
+ const roots = await prepared.residencies();
1717
+ if (!goals || !roots || signal.aborted || draining)
1718
+ return undefined;
1719
+ return [...roots, ...goals, ...scheduleHold.residencies()];
1720
+ },
1721
+ detach: async () => {
1722
+ detached = true;
1723
+ signal.removeEventListener('abort', cancel);
1724
+ await prepared.detach();
1725
+ // Domain holds stay closed until the lifecycle owner drains us.
1726
+ },
1727
+ cancel,
1728
+ };
1729
+ }
1730
+ catch (error) {
1731
+ cancel();
1732
+ if (signal.aborted)
1733
+ return undefined;
1734
+ throw error;
1735
+ }
1736
+ },
1667
1737
  releaseConnection: (connectionId) => {
1668
1738
  for (const module of domainModules)
1669
1739
  module.releaseConnection?.(connectionId);
1670
1740
  },
1671
1741
  beginDrain,
1672
1742
  recover,
1743
+ startMaintenance: () => storageMaintenance.start(),
1673
1744
  close,
1674
1745
  };
1675
1746
  }
@@ -1871,6 +1942,11 @@ function requireSessionManager(manager) {
1871
1942
  throw new Error('Runtime Host SessionManager is not composed');
1872
1943
  return manager;
1873
1944
  }
1945
+ function requireTranscriptReader(reader) {
1946
+ if (!reader)
1947
+ throw new Error('Runtime Host transcript reader is not composed');
1948
+ return reader;
1949
+ }
1874
1950
  function requireGraphCoordinator(coordinator) {
1875
1951
  if (!coordinator)
1876
1952
  throw new Error('Runtime Host Agent Graph coordinator is not composed');