maka-agent 0.2.0-dev.26.20260909 → 0.2.0-dev.28.20260911

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 (125) hide show
  1. package/LICENSE +106 -0
  2. package/dist/cli-core.js +28 -0
  3. package/dist/runtime-host-cli.js +43 -3
  4. package/dist/runtime-host-handoff-surface.js +10 -8
  5. package/dist/runtime-host-lifecycle-transaction.js +28 -3
  6. package/dist/runtime-host-local-source-retirement.js +1 -1
  7. package/dist/runtime-host-run-command.js +15 -7
  8. package/dist/runtime-host-setup-command.js +29 -6
  9. package/dist/runtime-host-update-command.js +49 -5
  10. package/dist/session-export-command.js +72 -0
  11. package/dist/session-import-command.js +69 -0
  12. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  13. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  14. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  15. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  16. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  17. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +9 -4
  18. package/node_modules/@maka/core/dist/diagnostic-log.js +18 -7
  19. package/node_modules/@maka/core/dist/text-sanitize.js +8 -2
  20. package/node_modules/@maka/core/dist/usage-stats/types.js +2 -0
  21. package/node_modules/@maka/core/dist/workhub-routing.js +126 -0
  22. package/node_modules/@maka/core/package.json +2 -1
  23. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +15 -11
  24. package/node_modules/@maka/runtime/dist/archive-read-tool.js +3 -1
  25. package/node_modules/@maka/runtime/dist/bots/bot-test.js +2 -1
  26. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +24 -20
  27. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +5 -3
  28. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +87 -29
  29. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +40 -36
  30. package/node_modules/@maka/runtime/dist/builtin-tools.js +21 -2
  31. package/node_modules/@maka/runtime/dist/computer-use-tools.js +4 -1
  32. package/node_modules/@maka/runtime/dist/deep-research-tools.js +11 -5
  33. package/node_modules/@maka/runtime/dist/edit-replace.js +2 -2
  34. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +5 -6
  35. package/node_modules/@maka/runtime/dist/memory-extraction-evidence.js +7 -1
  36. package/node_modules/@maka/runtime/dist/memory-extraction.js +12 -7
  37. package/node_modules/@maka/runtime/dist/openai-responses-websocket.js +2 -5
  38. package/node_modules/@maka/runtime/dist/plugin-agent-service.js +131 -0
  39. package/node_modules/@maka/runtime/dist/plugin-approval-service.js +33 -0
  40. package/node_modules/@maka/runtime/dist/plugin-attachment-service.js +53 -0
  41. package/node_modules/@maka/runtime/dist/plugin-command-service.js +100 -0
  42. package/node_modules/@maka/runtime/dist/plugin-composition-loader.js +11 -2
  43. package/node_modules/@maka/runtime/dist/plugin-data-services.js +332 -0
  44. package/node_modules/@maka/runtime/dist/plugin-fs-service.js +62 -0
  45. package/node_modules/@maka/runtime/dist/plugin-goal-service.js +61 -0
  46. package/node_modules/@maka/runtime/dist/plugin-invocation-signal.js +24 -0
  47. package/node_modules/@maka/runtime/dist/plugin-llm-service.js +85 -0
  48. package/node_modules/@maka/runtime/dist/plugin-lsp-service.js +94 -0
  49. package/node_modules/@maka/runtime/dist/plugin-scope-registry.js +91 -0
  50. package/node_modules/@maka/runtime/dist/plugin-session-query-service.js +71 -0
  51. package/node_modules/@maka/runtime/dist/plugin-shell-env-service.js +87 -0
  52. package/node_modules/@maka/runtime/dist/plugin-shell-service.js +74 -0
  53. package/node_modules/@maka/runtime/dist/plugin-skill-service.js +93 -0
  54. package/node_modules/@maka/runtime/dist/plugin-system-prompt-service.js +346 -0
  55. package/node_modules/@maka/runtime/dist/plugin-tool-service.js +18 -52
  56. package/node_modules/@maka/runtime/dist/plugin-user-question-service.js +43 -0
  57. package/node_modules/@maka/runtime/dist/plugin-web-service.js +69 -0
  58. package/node_modules/@maka/runtime/dist/request-customization-fetch.js +14 -7
  59. package/node_modules/@maka/runtime/dist/session-export.js +178 -0
  60. package/node_modules/@maka/runtime/dist/session-import.js +100 -0
  61. package/node_modules/@maka/runtime/dist/session-manager.js +6 -1
  62. package/node_modules/@maka/runtime/dist/shell-run-manager.js +9 -6
  63. package/node_modules/@maka/runtime/dist/shell-run-tool-result.js +13 -6
  64. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +43 -10
  65. package/node_modules/@maka/runtime/dist/stream-graph-handoff.js +6 -1
  66. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +1 -4
  67. package/node_modules/@maka/runtime/dist/system-prompt/workspace-instructions.js +11 -6
  68. package/node_modules/@maka/runtime/dist/tavily-search.js +8 -2
  69. package/node_modules/@maka/runtime/dist/text-line-window.js +49 -0
  70. package/node_modules/@maka/runtime/dist/tool-output.js +35 -12
  71. package/node_modules/@maka/runtime/dist/unified-diff.js +40 -10
  72. package/node_modules/@maka/runtime/dist/web-fetch-tool.js +4 -2
  73. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +82 -33
  74. package/node_modules/@maka/runtime/dist/workspace-executor.js +2 -6
  75. package/node_modules/@maka/runtime/package.json +20 -1
  76. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +73 -24
  77. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +46 -12
  78. package/node_modules/@maka/runtime-host/dist/operator/setup-frame.js +31 -21
  79. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +7 -4
  80. package/node_modules/@maka/runtime-host/dist/protocol/artifact.js +2 -2
  81. package/node_modules/@maka/runtime-host/dist/protocol/index.js +10 -1
  82. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +30 -5
  83. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +3 -2
  84. package/node_modules/@maka/runtime-host/dist/protocol/skill-catalog.js +2 -1
  85. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +25 -23
  86. package/node_modules/@maka/runtime-host/dist/server/artifact-coordinator.js +2 -0
  87. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +62 -4
  88. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +481 -11
  89. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +74 -0
  90. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +6 -1
  91. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +2 -2
  92. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +30 -0
  93. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +114 -20
  94. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +49 -12
  95. package/node_modules/@maka/runtime-host/dist/server/plugin-data-runtime.js +234 -0
  96. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  97. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +12 -0
  98. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +17 -8
  99. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +189 -92
  100. package/node_modules/@maka/runtime-host/dist/server/runtime-resource-projection.js +3 -9
  101. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +20 -21
  102. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +24 -2
  103. package/node_modules/@maka/runtime-host/dist/server/skill-catalog-coordinator.js +18 -2
  104. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -35
  105. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +92 -10
  106. package/node_modules/@maka/runtime-host/dist/transport/framed-byte-stream-transport.js +4 -1
  107. package/node_modules/@maka/runtime-host/dist/transport/local-ipc-framing.js +4 -2
  108. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +9 -8
  109. package/node_modules/@maka/runtime-host/dist/transport/resumable-peer-stream.js +14 -9
  110. package/node_modules/@maka/storage/dist/agent-run-store.js +54 -10
  111. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +32 -10
  112. package/node_modules/@maka/storage/dist/context-value-mutation-gate.js +59 -0
  113. package/node_modules/@maka/storage/dist/execution-stores.js +1 -1
  114. package/node_modules/@maka/storage/dist/session-bundle-policy.js +909 -34
  115. package/node_modules/@maka/storage/dist/session-message-projection.js +8 -4
  116. package/node_modules/@maka/storage/dist/session-store.js +2 -2
  117. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +18 -4
  118. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +12 -5
  119. package/node_modules/@maka/storage/dist/stable-storage.js +2 -1
  120. package/node_modules/@maka/storage/package.json +2 -0
  121. package/node_modules/@modelcontextprotocol/client/dist/src-D_zzAWoS.mjs +22 -5
  122. package/node_modules/@modelcontextprotocol/client/dist/src-NAgB4Mp8.cjs +22 -5
  123. package/node_modules/zod/v4/core/memoizer.cjs +12 -16
  124. package/node_modules/zod/v4/core/memoizer.js +12 -16
  125. package/package.json +1 -1
@@ -32,6 +32,7 @@ import { RuntimeOwnerCleanupError } from '@maka/runtime/runtime-kernel';
32
32
  import { parseSkillInvocationTokens, } from '@maka/runtime/skill-invocation';
33
33
  import { skillInvocationInlineReferences } from '@maka/runtime/skill-invocation-receipt';
34
34
  import { authenticateExecutionStoresWriter, isSessionNotFoundError, normalizeRootTurnAdmissionPayload, } from '@maka/storage/execution-stores';
35
+ import { hostedExecutionRunProfile } from './hosted-execution-tool-profile.js';
35
36
  import { runtimeHostExecutionUnavailableReason, runtimeHostExternalTurnUnavailableReason, runtimeHostSafeBoundaryContinuationUnavailableReason, WORKHUB_COORDINATION_EXECUTION_UNAVAILABLE_REASON, } from './host-session-availability.js';
36
37
  import { completedHostedExecutionAdmission } from './hosted-execution-authority.js';
37
38
  import { HostedExecutionProjectionReader } from './hosted-execution-projection.js';
@@ -54,6 +55,7 @@ export class RootTurnCoordinator {
54
55
  agentGraphEpochs;
55
56
  nameSessionFromRootMessage;
56
57
  directoryHostId;
58
+ prepareWorkHubRoutingDecision;
57
59
  handlers = {
58
60
  'turn.resume.query': (input, context) => this.queryTurnResume(input, context),
59
61
  'turn.resume.start': (input, context) => this.startTurnResume(input, context),
@@ -67,7 +69,7 @@ export class RootTurnCoordinator {
67
69
  executionProjection;
68
70
  attachmentValidator;
69
71
  prepareSkillInvocation;
70
- constructor(manager, stores, sessionAdmission, rootAdmissionOwner, interactions, messages, continuity, acquireRecoveryResidency, requestHostDrain, clientCapabilities, resolveExecutionObserver, assertScheduledTaskRecoveryAdmission, attachmentValidator, prepareSkillInvocation, agentGraphEpochs, nameSessionFromRootMessage, directoryHostId) {
72
+ constructor(manager, stores, sessionAdmission, rootAdmissionOwner, interactions, messages, continuity, acquireRecoveryResidency, requestHostDrain, clientCapabilities, resolveExecutionObserver, assertScheduledTaskRecoveryAdmission, attachmentValidator, prepareSkillInvocation, agentGraphEpochs, nameSessionFromRootMessage, directoryHostId, prepareWorkHubRoutingDecision) {
71
73
  this.manager = manager;
72
74
  this.sessionAdmission = sessionAdmission;
73
75
  this.rootAdmissionOwner = rootAdmissionOwner;
@@ -82,6 +84,7 @@ export class RootTurnCoordinator {
82
84
  this.agentGraphEpochs = agentGraphEpochs;
83
85
  this.nameSessionFromRootMessage = nameSessionFromRootMessage;
84
86
  this.directoryHostId = directoryHostId;
87
+ this.prepareWorkHubRoutingDecision = prepareWorkHubRoutingDecision;
85
88
  this.stores = authenticateExecutionStoresWriter(stores, 'interactive');
86
89
  this.executionProjection = new HostedExecutionProjectionReader(this.stores);
87
90
  this.#admissions = new HostedExecutionAdmissionRegistry((sessionId) => this.#executions.has(sessionId));
@@ -104,79 +107,98 @@ export class RootTurnCoordinator {
104
107
  }
105
108
  async recover() {
106
109
  for (const [sessionId, plan] of this.#recoveryPlansBySession) {
107
- for (const admission of plan.admissions) {
108
- const run = await this.readRunIfPresent(sessionId, admission.runId);
109
- if (!run)
110
- continue;
111
- await this.assertRunMatchesDurableExecution(run, admission.turnId, admission.execution);
112
- const snapshot = await this.readCanonicalSnapshot(sessionId, admission.turnId, admission.runId, run);
113
- if (isTerminalSnapshot(snapshot)) {
114
- if (admission.sourceMessages.length > 0) {
115
- await this.messages.materializeMessageHandoffsForRun({
116
- sessionId,
117
- turnId: admission.turnId,
118
- runId: admission.runId,
119
- messageIds: admission.sourceMessages.map((source) => source.messageId),
120
- });
121
- }
122
- }
123
- else {
124
- if (plan.rootReplayAdmission === admission)
110
+ if (plan.rootReplayAdmission &&
111
+ !(await this.bindRecoveryCapabilities(sessionId, plan.rootReplayAdmission.execution)))
112
+ continue;
113
+ try {
114
+ for (const admission of plan.admissions) {
115
+ const run = await this.readRunIfPresent(sessionId, admission.runId);
116
+ if (!run)
125
117
  continue;
126
- if (admission.execution.kind !== 'safe_boundary_continuation') {
127
- throw new Error(`Startup recovery left Turn ${admission.turnId} non-terminal`);
118
+ await this.assertRunMatchesDurableExecution(run, admission.turnId, admission.execution);
119
+ const snapshot = await this.readCanonicalSnapshot(sessionId, admission.turnId, admission.runId, run);
120
+ if (isTerminalSnapshot(snapshot)) {
121
+ if (admission.sourceMessages.length > 0) {
122
+ await this.messages.materializeMessageHandoffsForRun({
123
+ sessionId,
124
+ turnId: admission.turnId,
125
+ runId: admission.runId,
126
+ messageIds: admission.sourceMessages.map((source) => source.messageId),
127
+ });
128
+ }
128
129
  }
129
- this.parkContinuationAdmission(admission);
130
- }
131
- }
132
- const admission = plan.rootReplayAdmission;
133
- if (!admission)
134
- continue;
135
- // Session recovery may have materialized this Run after the replay plan was prepared.
136
- const existingRun = await this.readRunIfPresent(sessionId, admission.runId);
137
- const pendingHandoff = existingRun &&
138
- (await readLogicalRuntimeExecution(this.stores.runtimeEventStore, admission, existingRun))
139
- ?.pendingHandoff;
140
- if (existingRun && !pendingHandoff)
141
- continue;
142
- const input = activationInputForAdmission(admission);
143
- const disposition = await this.sessionAdmission.run(sessionId, async (lease) => {
144
- if (admission.execution.kind === 'safe_boundary_continuation') {
145
- const header = await this.stores.sessionStore.readHeaderSnapshot(sessionId);
146
- if (runtimeHostSafeBoundaryContinuationUnavailableReason(header)) {
130
+ else {
131
+ if (plan.rootReplayAdmission === admission)
132
+ continue;
133
+ if (admission.execution.kind !== 'safe_boundary_continuation') {
134
+ throw new Error(`Startup recovery left Turn ${admission.turnId} non-terminal`);
135
+ }
147
136
  this.parkContinuationAdmission(admission);
148
- return undefined;
149
137
  }
150
138
  }
151
- const continuation = admission.execution.kind === 'safe_boundary_continuation' && !pendingHandoff
152
- ? await this.reconstructAdmittedContinuation(admission)
153
- : undefined;
154
- if (continuation?.disposition === 'parked') {
155
- if (continuation.plan.reason === 'safety_check_failed' ||
156
- continuation.plan.reason === 'resume_feature_disabled' ||
157
- continuation.plan.reason === 'continuation_authority_unavailable' ||
158
- continuation.plan.reason === 'safety_observation_unavailable') {
159
- this.parkContinuationAdmission(admission);
160
- return undefined;
139
+ const admission = plan.rootReplayAdmission;
140
+ if (!admission)
141
+ continue;
142
+ // Session recovery may have materialized this Run after the replay plan was prepared.
143
+ const existingRun = await this.readRunIfPresent(sessionId, admission.runId);
144
+ const pendingHandoff = existingRun &&
145
+ (await readLogicalRuntimeExecution(this.stores.runtimeEventStore, admission, existingRun))
146
+ ?.pendingHandoff;
147
+ if (existingRun && !pendingHandoff)
148
+ continue;
149
+ const input = activationInputForAdmission(admission);
150
+ const disposition = await this.sessionAdmission.run(sessionId, async (lease) => {
151
+ if (admission.execution.kind === 'safe_boundary_continuation') {
152
+ const header = await this.stores.sessionStore.readHeaderSnapshot(sessionId);
153
+ if (runtimeHostSafeBoundaryContinuationUnavailableReason(header)) {
154
+ this.parkContinuationAdmission(admission);
155
+ return undefined;
156
+ }
161
157
  }
162
- throw new Error(`Unable to recover admitted Turn ${admission.turnId}: ${continuation.plan.reason}`);
163
- }
164
- await this.messages.handoffRootSources({
165
- sessionId,
166
- turnId: admission.turnId,
167
- runId: admission.runId,
168
- messageIds: admission.sourceMessages.map((source) => source.messageId),
158
+ const continuation = admission.execution.kind === 'safe_boundary_continuation' && !pendingHandoff
159
+ ? await this.reconstructAdmittedContinuation(admission)
160
+ : undefined;
161
+ if (continuation?.disposition === 'parked') {
162
+ if (continuation.plan.reason === 'safety_check_failed' ||
163
+ continuation.plan.reason === 'resume_feature_disabled' ||
164
+ continuation.plan.reason === 'continuation_authority_unavailable' ||
165
+ continuation.plan.reason === 'safety_observation_unavailable') {
166
+ this.parkContinuationAdmission(admission);
167
+ return undefined;
168
+ }
169
+ throw new Error(`Unable to recover admitted Turn ${admission.turnId}: ${continuation.plan.reason}`);
170
+ }
171
+ await this.messages.handoffRootSources({
172
+ sessionId,
173
+ turnId: admission.turnId,
174
+ runId: admission.runId,
175
+ messageIds: admission.sourceMessages.map((source) => source.messageId),
176
+ });
177
+ return this.prepareAdmittedTurn(input, admission, this.acquireRecoveryResidency, lease, undefined, undefined, undefined, continuation?.continuation);
169
178
  });
170
- return this.prepareAdmittedTurn(input, admission, this.acquireRecoveryResidency, lease, undefined, undefined, undefined, continuation?.continuation);
171
- });
172
- if (!disposition)
173
- continue;
174
- const outcome = await this.resolveStartDisposition(input, disposition);
175
- if (!outcome.ok) {
176
- throw new Error(`Unable to recover admitted Turn ${admission.turnId}: ${outcome.error.code}`);
179
+ if (!disposition)
180
+ continue;
181
+ const outcome = await this.resolveStartDisposition(input, disposition);
182
+ if (!outcome.ok) {
183
+ throw new Error(`Unable to recover admitted Turn ${admission.turnId}: ${outcome.error.code}`);
184
+ }
185
+ }
186
+ finally {
187
+ this.#recoveryPlansBySession.delete(sessionId);
177
188
  }
178
189
  }
179
- this.#recoveryPlansBySession.clear();
190
+ }
191
+ async bindRecoveryCapabilities(sessionId, execution) {
192
+ const header = await this.stores.sessionStore.readHeaderSnapshot(sessionId);
193
+ if (header.toolProfile !== 'workhub-coordination-v2')
194
+ return true;
195
+ // Older admissions without authenticated provider evidence stay pending.
196
+ // Neither registration order nor a tool name can establish Desktop ownership.
197
+ if (execution.kind !== 'workhub_coordination' ||
198
+ !execution.capabilityBinding ||
199
+ !this.clientCapabilities)
200
+ return false;
201
+ return this.clientCapabilities.bindRecoveredSession(sessionId, execution.capabilityBinding, hostedExecutionRunProfile(header.toolProfile).toolNames.filter((name) => name.startsWith('mcp__')));
180
202
  }
181
203
  async close() {
182
204
  this.#cancelHandoff?.();
@@ -202,6 +224,15 @@ export class RootTurnCoordinator {
202
224
  }
203
225
  async readSessionHeader(sessionId) {
204
226
  if (isWorkHubCoordinationSessionId(sessionId)) {
227
+ const active = this.#executions.get(sessionId);
228
+ if (active?.descriptor.kind === 'workhub_coordination' &&
229
+ !active.descriptor.operation &&
230
+ !active.stopRequested) {
231
+ const header = await this.stores.sessionStore.readHeaderSnapshot(sessionId);
232
+ if (header.toolProfile === 'workhub-coordination-v2') {
233
+ return { isArchived: header.isArchived, activeTurnOnly: true };
234
+ }
235
+ }
205
236
  return {
206
237
  isArchived: false,
207
238
  unavailableReason: WORKHUB_COORDINATION_EXECUTION_UNAVAILABLE_REASON,
@@ -236,7 +267,9 @@ export class RootTurnCoordinator {
236
267
  runId: active.runId,
237
268
  };
238
269
  }
239
- return this.#handoffHold || this.#admissions.has(sessionId)
270
+ return this.#handoffHold ||
271
+ this.#admissions.has(sessionId) ||
272
+ this.#recoveryPlansBySession.get(sessionId)?.rootReplayAdmission
240
273
  ? { kind: 'reserved' }
241
274
  : { kind: 'idle' };
242
275
  }
@@ -270,7 +303,7 @@ export class RootTurnCoordinator {
270
303
  }, context);
271
304
  }
272
305
  reserveRootTurn(sessionId) {
273
- if (this.#handoffHold)
306
+ if (this.#handoffHold || this.#recoveryPlansBySession.get(sessionId)?.rootReplayAdmission)
274
307
  return undefined;
275
308
  return this.#admissions.reserve(sessionId);
276
309
  }
@@ -920,14 +953,27 @@ export class RootTurnCoordinator {
920
953
  return { error: 'A root Turn is still active' };
921
954
  }
922
955
  const header = await this.stores.sessionStore.readHeaderSnapshot(input.sessionId);
923
- const unavailableReason = runtimeHostExternalTurnUnavailableReason(header);
956
+ const turnId = input.rootIdentity?.turnId ?? randomUUID();
957
+ const previous = this.rootAdmissionOwner.latestAdmission(input.sessionId)?.execution;
958
+ let execution = {
959
+ kind: isWorkHubCoordinationSessionId(header.id)
960
+ ? 'workhub_coordination'
961
+ : 'external_message',
962
+ inputDigest: messageContentDigest(input.submittedContent),
963
+ ...(previous?.kind === 'workhub_coordination' && previous.capabilityBinding
964
+ ? { capabilityBinding: previous.capabilityBinding }
965
+ : {}),
966
+ };
967
+ if (!(await this.bindRecoveryCapabilities(input.sessionId, execution)))
968
+ return { deferred: true };
969
+ execution = await this.prepareFreshWorkHubExecution(header, turnId, input.content, execution);
970
+ const unavailableReason = runtimeHostExecutionUnavailableReason(header, execution);
924
971
  if (unavailableReason)
925
972
  return { error: unavailableReason };
926
973
  const reservation = this.reserveRootTurn(input.sessionId);
927
974
  if (!reservation)
928
975
  return { error: 'Another root Turn is being admitted' };
929
976
  try {
930
- const turnId = input.rootIdentity?.turnId ?? randomUUID();
931
977
  // The recovered Message asked for this mode before the Host stopped;
932
978
  // admitting without it would run a different Turn than was requested.
933
979
  const turnOrchestration = input.submittedIntent?.turnOrchestration;
@@ -937,10 +983,7 @@ export class RootTurnCoordinator {
937
983
  turnId,
938
984
  proposedRunId: input.rootIdentity?.runId ?? randomUUID(),
939
985
  proposedUserMessageId: input.sources.length === 1 ? input.sources[0].messageId : null,
940
- execution: {
941
- kind: 'external_message',
942
- inputDigest: messageContentDigest(input.submittedContent),
943
- },
986
+ execution,
944
987
  normalizedInput: input.content,
945
988
  ...(turnOrchestration ? { turnOrchestration } : {}),
946
989
  sourceMessages: input.sources,
@@ -967,6 +1010,20 @@ export class RootTurnCoordinator {
967
1010
  }
968
1011
  });
969
1012
  }
1013
+ async prepareFreshWorkHubExecution(header, turnId, content, execution, inputClosedSignal) {
1014
+ if (execution.kind !== 'workhub_coordination' || !this.prepareWorkHubRoutingDecision) {
1015
+ return execution;
1016
+ }
1017
+ return {
1018
+ ...execution,
1019
+ routingDecision: await this.prepareWorkHubRoutingDecision({
1020
+ header,
1021
+ turnId,
1022
+ content,
1023
+ ...(inputClosedSignal ? { inputClosedSignal } : {}),
1024
+ }),
1025
+ };
1026
+ }
970
1027
  prepareMessage(input) {
971
1028
  return this.runCommand(async () => {
972
1029
  const content = normalizeMessageContent(input.content);
@@ -1167,7 +1224,11 @@ export class RootTurnCoordinator {
1167
1224
  };
1168
1225
  }
1169
1226
  /** Accepts a model action against the exact live WorkHub root and its durable user input. */
1170
- readActiveWorkHubRequest(turnId) {
1227
+ async readActiveWorkHubRequest(turnId) {
1228
+ return (await this.readActiveWorkHubRoutingRequest(turnId))?.content;
1229
+ }
1230
+ /** Reads both user authority and the advisory routing decision of the exact live WorkHub Turn. */
1231
+ readActiveWorkHubRoutingRequest(turnId) {
1171
1232
  const sessionId = WORKHUB_COORDINATION_SESSION_ID;
1172
1233
  return this.sessionAdmission.run(sessionId, async () => {
1173
1234
  const active = this.#executions.get(sessionId);
@@ -1182,7 +1243,12 @@ export class RootTurnCoordinator {
1182
1243
  admission.execution.kind !== 'workhub_coordination' ||
1183
1244
  header.toolProfile !== 'workhub-coordination-v2')
1184
1245
  return undefined;
1185
- return requireHostedExecutionMessageContent(admission);
1246
+ return {
1247
+ content: requireHostedExecutionMessageContent(admission),
1248
+ ...(admission.execution.routingDecision
1249
+ ? { decision: admission.execution.routingDecision }
1250
+ : {}),
1251
+ };
1186
1252
  });
1187
1253
  }
1188
1254
  startRootMessage(request, context) {
@@ -1271,15 +1337,30 @@ export class RootTurnCoordinator {
1271
1337
  const attachmentError = await this.attachmentValidator?.validateTurnAttachments(request.sessionId, attachments);
1272
1338
  if (attachmentError)
1273
1339
  return completedStart(operationConflict(attachmentError));
1274
- const binding = request.execution.kind === 'workhub_coordination' &&
1275
- header.toolProfile === 'workhub-coordination-v1'
1276
- ? undefined
1277
- : prepared.commitCapabilityBinding
1278
- ? await prepared.commitCapabilityBinding()
1279
- : await this.clientCapabilities?.bindSession(request.sessionId, context.connectionId);
1340
+ const isWorkHubV2 = request.execution.kind === 'workhub_coordination' &&
1341
+ header.toolProfile === 'workhub-coordination-v2';
1342
+ const workHubBinding = isWorkHubV2
1343
+ ? await this.clientCapabilities?.bindSession(request.sessionId, context.connectionId, hostedExecutionRunProfile(header.toolProfile).toolNames.filter((name) => name.startsWith('mcp__')))
1344
+ : undefined;
1345
+ const binding = isWorkHubV2
1346
+ ? workHubBinding
1347
+ : request.execution.kind === 'workhub_coordination' &&
1348
+ header.toolProfile === 'workhub-coordination-v1'
1349
+ ? undefined
1350
+ : prepared.commitCapabilityBinding
1351
+ ? await prepared.commitCapabilityBinding()
1352
+ : await this.clientCapabilities?.bindSession(request.sessionId, context.connectionId);
1280
1353
  if (binding && !binding.ok) {
1281
1354
  return completedStart(operationConflict(binding.message));
1282
1355
  }
1356
+ const capabilityBinding = workHubBinding?.ok ? workHubBinding.capabilityBinding : undefined;
1357
+ if (isWorkHubV2 && !capabilityBinding) {
1358
+ return completedStart(operationUnavailable('WorkHub Desktop capability binding is unavailable'));
1359
+ }
1360
+ const freshExecution = await this.prepareFreshWorkHubExecution(header, request.turnId, canonicalContent.content, {
1361
+ ...request.execution,
1362
+ ...(capabilityBinding ? { capabilityBinding } : {}),
1363
+ }, context.inputClosedSignal);
1283
1364
  if (!this.beginRootAdmission(reservation)) {
1284
1365
  return completedStart(sessionBusy('Root Turn reservation is no longer current'));
1285
1366
  }
@@ -1296,7 +1377,7 @@ export class RootTurnCoordinator {
1296
1377
  // Turn kinds do not carry a user message and retain their own
1297
1378
  // generated admission identity.
1298
1379
  proposedUserMessageId: request.execution.kind === 'external_message' ? request.turnId : randomUUID(),
1299
- execution: request.execution,
1380
+ execution: freshExecution,
1300
1381
  normalizedInput: canonicalContent.content,
1301
1382
  ...(request.turnOrchestration ? { turnOrchestration: request.turnOrchestration } : {}),
1302
1383
  ...(prepared.skillInvocation ? { skillInvocation: prepared.skillInvocation } : {}),
@@ -2143,15 +2224,22 @@ export class RootTurnCoordinator {
2143
2224
  const turnId = randomUUID();
2144
2225
  const header = await this.stores.sessionStore.readHeaderSnapshot(batch.sessionId);
2145
2226
  await this.prepareFreshAgentGraphEpoch(header);
2227
+ const execution = await this.prepareFreshWorkHubExecution(header, turnId, batch.content, {
2228
+ kind: previous.descriptor.kind === 'workhub_coordination'
2229
+ ? 'workhub_coordination'
2230
+ : 'external_message',
2231
+ inputDigest: messageContentDigest(batch.submittedContent),
2232
+ ...(previous.descriptor.kind === 'workhub_coordination' &&
2233
+ previous.descriptor.capabilityBinding
2234
+ ? { capabilityBinding: previous.descriptor.capabilityBinding }
2235
+ : {}),
2236
+ });
2146
2237
  const admitted = await this.rootAdmissionOwner.admitRootTurn({
2147
2238
  sessionId: batch.sessionId,
2148
2239
  turnId,
2149
2240
  proposedRunId: randomUUID(),
2150
2241
  proposedUserMessageId: batch.sources.length === 1 ? batch.sources[0].messageId : null,
2151
- execution: {
2152
- kind: 'external_message',
2153
- inputDigest: messageContentDigest(batch.submittedContent),
2154
- },
2242
+ execution,
2155
2243
  normalizedInput: batch.content,
2156
2244
  sourceMessages: batch.sources,
2157
2245
  admittedAt: Date.now(),
@@ -2284,13 +2372,22 @@ function throwHostedStopError(sessionId, outcome) {
2284
2372
  throw new RuntimeHostedRootUnavailableError(sessionId, outcome.error.message);
2285
2373
  }
2286
2374
  }
2287
- /** Compatibility may omit only the action identity absent from an older admission. */
2375
+ /** Compare the request identity separately from its Host-selected capability binding. */
2288
2376
  function rootExecutionMatches(stored, incoming) {
2289
- if (stored.kind === 'workhub_coordination' &&
2290
- incoming.kind === 'workhub_coordination' &&
2291
- stored.actionId === undefined) {
2292
- const { actionId: _actionId, ...legacyIncoming } = incoming;
2293
- return isDeepStrictEqual(stored, legacyIncoming);
2377
+ if (stored.kind === 'workhub_coordination' && incoming.kind === 'workhub_coordination') {
2378
+ const { capabilityBinding: _storedBinding, routingDecision: _storedDecision, ...storedIdentity } = stored;
2379
+ const { capabilityBinding: _incomingBinding, routingDecision: _incomingDecision, actionId, ...incomingIdentity } = incoming;
2380
+ if (incoming.routingDecision === undefined) {
2381
+ return isDeepStrictEqual(storedIdentity, {
2382
+ ...incomingIdentity,
2383
+ ...(stored.actionId === undefined ? {} : { actionId }),
2384
+ });
2385
+ }
2386
+ return isDeepStrictEqual({ ...storedIdentity, routingDecision: stored.routingDecision }, {
2387
+ ...incomingIdentity,
2388
+ ...(actionId === undefined ? {} : { actionId }),
2389
+ routingDecision: incoming.routingDecision,
2390
+ });
2294
2391
  }
2295
2392
  return isDeepStrictEqual(stored, incoming);
2296
2393
  }
@@ -27,10 +27,9 @@ export function canonicalRuntimeResources(resources) {
27
27
  left.sourceToolCallId.localeCompare(right.sourceToolCallId));
28
28
  }
29
29
  function boundedRuntimeResourceUpdate(update) {
30
- return {
31
- ...structuredClone(update),
32
- result: boundedState(update.result),
33
- };
30
+ const bounded = structuredClone(update);
31
+ shrinkStateToFit(bounded.result);
32
+ return bounded;
34
33
  }
35
34
  export function runtimeResourceRevision(resources) {
36
35
  return `sha256:${createHash('sha256').update(JSON.stringify(resources)).digest('hex')}`;
@@ -83,11 +82,6 @@ export function runtimeResourceSnapshotFromResult(result) {
83
82
  const { operation: _operation, ...snapshot } = result;
84
83
  return snapshot;
85
84
  }
86
- function boundedState(state) {
87
- const bounded = structuredClone(state);
88
- shrinkStateToFit(bounded);
89
- return bounded;
90
- }
91
85
  function shrinkStateToFit(state) {
92
86
  while (Buffer.byteLength(JSON.stringify(state), 'utf8') > RUNTIME_RESOURCE_SNAPSHOT_MAX_BYTES) {
93
87
  const fields = mutableTextFields(state).sort((left, right) => Buffer.byteLength(right.value(), 'utf8') - Buffer.byteLength(left.value(), 'utf8'));
@@ -131,13 +131,11 @@ export class SessionContinuityCoordinator {
131
131
  if (this.#connections.has(connectionId)) {
132
132
  throw new Error(`Duplicate Runtime Host connection: ${connectionId}`);
133
133
  }
134
- const closed = signal();
135
134
  this.#connections.set(connectionId, {
136
135
  sink,
137
136
  subscriptionIds: new Set(),
138
137
  pendingOpenCount: 0,
139
- closed: closed.promise,
140
- resolveClosed: closed.resolve,
138
+ closed: new AbortController(),
141
139
  });
142
140
  let attached = true;
143
141
  return {
@@ -639,12 +637,7 @@ export class SessionContinuityCoordinator {
639
637
  const throughSequence = await this.#transcriptReader.readDurableHighWater(sessionId);
640
638
  cachedTranscriptOverlay = this.#prepareTranscriptOverlay(committed.state, sessionId, throughSequence, preparationPermit);
641
639
  cachedTranscriptOverlay.pendingConsumers += 1;
642
- retainedTranscriptOverlay = await Promise.race([
643
- cachedTranscriptOverlay.prepared,
644
- connection.closed.then(() => {
645
- throw new Error('Runtime Host connection closed during subscription open');
646
- }),
647
- ]);
640
+ retainedTranscriptOverlay = await waitForConnectionOpen(cachedTranscriptOverlay.prepared, connection.closed.signal);
648
641
  const snapshot = projectSessionSnapshot(committed.value, identity.principalKind);
649
642
  const created = await createSessionTranscriptBootstrap({
650
643
  reader: this.#transcriptReader,
@@ -918,12 +911,7 @@ export class SessionContinuityCoordinator {
918
911
  const ticket = this.#queueTranscriptOverlayPreparation();
919
912
  let release;
920
913
  try {
921
- release = await Promise.race([
922
- ticket.ready,
923
- connection.closed.then(() => {
924
- throw new Error('Runtime Host connection closed during subscription open');
925
- }),
926
- ]);
914
+ release = await waitForConnectionOpen(ticket.ready, connection.closed.signal);
927
915
  }
928
916
  catch (error) {
929
917
  this.#cancelTranscriptOverlayPreparation(ticket.waiter);
@@ -1118,7 +1106,7 @@ export class SessionContinuityCoordinator {
1118
1106
  const connection = this.#connections.get(connectionId);
1119
1107
  if (!connection)
1120
1108
  return;
1121
- connection.resolveClosed();
1109
+ connection.closed.abort(new Error('Runtime Host connection closed during subscription open'));
1122
1110
  for (const subscriptionId of [...connection.subscriptionIds]) {
1123
1111
  const subscriber = this.#ownedSubscriber(connectionId, subscriptionId);
1124
1112
  if (subscriber)
@@ -1794,10 +1782,21 @@ function toolStartShellRunRef(event) {
1794
1782
  return undefined;
1795
1783
  }
1796
1784
  }
1797
- function signal() {
1798
- let resolve;
1799
- const promise = new Promise((settle) => {
1800
- resolve = settle;
1785
+ function waitForConnectionOpen(task, closed) {
1786
+ // A race against a connection-lifetime Promise retains every winning overlay
1787
+ // until disconnect. Remove the close listener as soon as this wait finishes.
1788
+ return new Promise((resolve, reject) => {
1789
+ const onClose = () => reject(closed.reason);
1790
+ if (closed.aborted)
1791
+ onClose();
1792
+ else
1793
+ closed.addEventListener('abort', onClose, { once: true });
1794
+ void task.then((value) => {
1795
+ closed.removeEventListener('abort', onClose);
1796
+ resolve(value);
1797
+ }, (error) => {
1798
+ closed.removeEventListener('abort', onClose);
1799
+ reject(error);
1800
+ });
1801
1801
  });
1802
- return { promise, resolve };
1803
1802
  }
@@ -126,7 +126,7 @@ export async function readSessionTranscriptPage(input) {
126
126
  const storage = state.projection === 'shared'
127
127
  ? await readSharedDurablePage(input.reader, state.sessionId, durableRequest, position.rangeBoundarySequence)
128
128
  : await input.reader.readDurablePage(state.sessionId, durableRequest);
129
- const selected = storageSelection(storage);
129
+ const selected = selectionThroughRangeBoundary(storageSelection(storage), request.direction, position.rangeBoundarySequence);
130
130
  const rangeEdges = await readRangeEdges({
131
131
  reader: input.reader,
132
132
  state,
@@ -275,7 +275,7 @@ async function readRangeEdges(input) {
275
275
  const fragments = input.selected.fragments.filter((fragment) => fragment.kind === 'durable' && retainedSequences.has(fragment.sequence));
276
276
  return {
277
277
  fragments,
278
- rawBytes: fragments.reduce((sum, fragment) => sum + Buffer.from(fragment.data, 'base64').byteLength, 0),
278
+ rawBytes: fragments.reduce((sum, fragment) => sum + Buffer.byteLength(fragment.data, 'base64'), 0),
279
279
  next: { position: rangeRecords[retainedEnd].sequence, byteOffset: null },
280
280
  };
281
281
  })();
@@ -440,6 +440,28 @@ function storageSelection(storage) {
440
440
  next: storage.next,
441
441
  };
442
442
  }
443
+ function selectionThroughRangeBoundary(selected, direction, rangeBoundarySequence) {
444
+ if (rangeBoundarySequence === null)
445
+ return selected;
446
+ // RuntimeEvent-backed message sequences are sparse, so a continuation's
447
+ // message limit cannot infer how many records remain from sequence distance.
448
+ const firstOmittedIndex = selected.fragments.findIndex((fragment) => fragment.kind === 'durable' &&
449
+ (direction === 'older'
450
+ ? fragment.sequence < rangeBoundarySequence
451
+ : fragment.sequence > rangeBoundarySequence));
452
+ if (firstOmittedIndex === -1)
453
+ return selected;
454
+ const firstOmitted = selected.fragments[firstOmittedIndex];
455
+ if (firstOmitted.kind !== 'durable') {
456
+ throw new Error('Session transcript durable range contained an overlay fragment');
457
+ }
458
+ const fragments = selected.fragments.slice(0, firstOmittedIndex);
459
+ return {
460
+ fragments,
461
+ rawBytes: fragments.reduce((sum, fragment) => sum + Buffer.from(fragment.data, 'base64').byteLength, 0),
462
+ next: { position: firstOmitted.sequence, byteOffset: null },
463
+ };
464
+ }
443
465
  function selectOverlay(messages, direction, position, byteOffset, maxBytes, maxMessages = SESSION_TRANSCRIPT_PAGE_MAX_MESSAGES) {
444
466
  const fragments = [];
445
467
  let rawBytes = 0;
@@ -18,6 +18,14 @@
18
18
  */
19
19
  import { SkillCatalogRepositoryError, } from './skill-catalog-repository.js';
20
20
  import { WorkspaceResolutionError, } from './workspace-resolver.js';
21
+ export class SkillCatalogInvocableContextError extends Error {
22
+ code;
23
+ name = 'SkillCatalogInvocableContextError';
24
+ constructor(code, message) {
25
+ super(message);
26
+ this.code = code;
27
+ }
28
+ }
21
29
  /** Serialized single authority lane for catalog recovery, reads, and mutations. */
22
30
  export class HostSkillCatalogCoordinator {
23
31
  handlers = {
@@ -58,6 +66,14 @@ export class HostSkillCatalogCoordinator {
58
66
  return this.#admitProtocolOperation('skill.catalog.invocable.query', async () => {
59
67
  const resolved = await this.#resolveInvocableContext(input, context);
60
68
  return this.#repository.queryInvocable(repositoryInvocableQueryInput(input), { projectRoot: resolved.projectRoot }, resolved.host);
69
+ }, (error) => {
70
+ if (error instanceof SkillCatalogInvocableContextError) {
71
+ return {
72
+ ok: false,
73
+ error: { code: error.code, message: error.message },
74
+ };
75
+ }
76
+ return repositoryFailure('skill.catalog.invocable.query', error);
61
77
  });
62
78
  }
63
79
  mutate(input) {
@@ -83,7 +99,7 @@ export class HostSkillCatalogCoordinator {
83
99
  this.#closePromise = this.#tail;
84
100
  return this.#closePromise;
85
101
  }
86
- #admitProtocolOperation(operation, run) {
102
+ #admitProtocolOperation(operation, run, onFailure = (error) => repositoryFailure(operation, error)) {
87
103
  if (!this.#accepting) {
88
104
  return Promise.resolve({
89
105
  ok: false,
@@ -95,7 +111,7 @@ export class HostSkillCatalogCoordinator {
95
111
  return { ok: true, result: await run() };
96
112
  }
97
113
  catch (error) {
98
- return repositoryFailure(operation, error);
114
+ return onFailure(error);
99
115
  }
100
116
  });
101
117
  }