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
@@ -54,17 +54,19 @@ export class WorkHubCoordinationActionGate {
54
54
  return candidateSet(await this.#effects.listSessions());
55
55
  }
56
56
  act(input, context, admittedTurnId) {
57
+ const proposal = input.proposal;
57
58
  if (!input.userText.trim()) {
58
59
  return Promise.reject(new WorkHubActionGateFailure('action_conflict', 'WorkHub action text is empty'));
59
60
  }
60
61
  if (input.delegationText !== undefined &&
61
62
  (!input.delegationText.trim() ||
62
- (input.proposal.disposition !== 'delegate_existing' &&
63
- input.proposal.disposition !== 'create_new' &&
64
- input.proposal.disposition !== 'replace'))) {
63
+ !('disposition' in proposal ||
64
+ ('operation' in proposal && proposal.operation === 'correct')))) {
65
65
  return Promise.reject(new WorkHubActionGateFailure('action_conflict', 'Invalid WorkHub delegation text'));
66
66
  }
67
- if (input.proposal.disposition === 'create_new' && !input.proposal.title.trim()) {
67
+ if ('disposition' in proposal &&
68
+ proposal.disposition === 'create_new' &&
69
+ !proposal.title.trim()) {
68
70
  return Promise.reject(new WorkHubActionGateFailure('action_conflict', 'WorkHub creation title is empty'));
69
71
  }
70
72
  const fingerprint = actionFingerprint(input);
@@ -106,7 +108,7 @@ export class WorkHubCoordinationActionGate {
106
108
  }
107
109
  return this.#assign(assignmentInputFromRecord(durable), context);
108
110
  }
109
- if (proposal.disposition === 'stop_work') {
111
+ if ('operation' in proposal && proposal.operation === 'stop') {
110
112
  const source = await this.#stopSource(input.actionId, proposal.expects.targetSessionId);
111
113
  const stopFingerprint = stopActionFingerprint(input, source);
112
114
  await this.#claimAction(input.actionId, 'stop', stopFingerprint, source.delegationId);
@@ -159,7 +161,7 @@ export class WorkHubCoordinationActionGate {
159
161
  });
160
162
  return this.#stop(requested, source);
161
163
  }
162
- if (proposal.disposition === 'resume_work') {
164
+ if ('operation' in proposal && proposal.operation === 'resume') {
163
165
  const source = await this.#effects.readAssignment(proposal.resumesActionId);
164
166
  if (!source || source.targetSessionId !== proposal.expects.targetSessionId) {
165
167
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub resume target delegation changed');
@@ -179,14 +181,14 @@ export class WorkHubCoordinationActionGate {
179
181
  };
180
182
  return this.#effects.resume({ actionId: input.actionId, source, validateFreshTarget }, context);
181
183
  }
182
- if (proposal.disposition === 'create_new') {
184
+ if ('disposition' in proposal && proposal.disposition === 'create_new') {
183
185
  if (!input.create) {
184
186
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub creation context is unavailable');
185
187
  }
186
188
  const sessionId = workHubCreatedSessionId(input.actionId);
187
189
  return this.#assign(delegationAssignment(input, fingerprint, sessionId, proposal.title), context);
188
190
  }
189
- if (proposal.disposition === 'replace') {
191
+ if ('operation' in proposal && proposal.operation === 'correct') {
190
192
  const replaced = await this.#effects.readAssignment(proposal.replacesActionId);
191
193
  if (!replaced) {
192
194
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub can replace only a durable delegation it owns');
@@ -341,7 +343,7 @@ export class WorkHubCoordinationActionGate {
341
343
  }
342
344
  }
343
345
  async #replacementAssignment(input, replaced) {
344
- if (input.proposal.disposition !== 'replace') {
346
+ if (!('operation' in input.proposal) || input.proposal.operation !== 'correct') {
345
347
  throw new WorkHubActionGateFailure('action_conflict', 'Invalid WorkHub replacement');
346
348
  }
347
349
  const target = input.proposal.target;
@@ -465,7 +467,8 @@ export class WorkHubCoordinationActionGate {
465
467
  }
466
468
  }
467
469
  async #assertReplacementReplayTarget(input, targetSessionId) {
468
- if (input.proposal.disposition !== 'replace' ||
470
+ if (!('operation' in input.proposal) ||
471
+ input.proposal.operation !== 'correct' ||
469
472
  input.proposal.target.disposition !== 'delegate_existing' ||
470
473
  input.candidateSetId === undefined) {
471
474
  return;
@@ -581,8 +584,7 @@ function candidateRef(candidateSetId, sessionId) {
581
584
  }
582
585
  function delegationAssignment(input, actionFingerprint, targetSessionId, targetSessionName) {
583
586
  const create = input.create;
584
- if (input.proposal.disposition !== 'delegate_existing' &&
585
- input.proposal.disposition !== 'create_new') {
587
+ if (!('disposition' in input.proposal)) {
586
588
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub local action cannot create a delegation intent');
587
589
  }
588
590
  const base = {
@@ -636,34 +638,41 @@ function digest(value) {
636
638
  return `sha256:${hash(JSON.stringify(value))}`;
637
639
  }
638
640
  function actionFingerprint(input) {
639
- return digest({
641
+ const common = {
640
642
  userText: input.userText,
641
643
  ...(input.attachments ? { attachments: input.attachments } : {}),
642
644
  ...(input.newWorkDefaults ? { newWorkDefaults: input.newWorkDefaults } : {}),
643
645
  ...(input.delegationText === undefined ? {} : { delegationText: input.delegationText }),
644
- disposition: input.proposal.disposition,
645
- ...(input.proposal.disposition === 'delegate_existing'
646
- ? { candidateRef: input.proposal.candidateRef }
647
- : {}),
648
- ...(input.proposal.disposition === 'create_new'
649
- ? {
650
- title: input.proposal.title,
651
- workspace: input.create?.workspace,
652
- }
653
- : {}),
654
- ...(input.proposal.disposition === 'replace'
655
- ? {
656
- replacesActionId: input.proposal.replacesActionId,
657
- target: input.proposal.target,
658
- ...(input.proposal.target.disposition === 'create_new'
659
- ? { workspace: input.create?.workspace }
660
- : {}),
661
- }
662
- : {}),
646
+ };
647
+ const proposal = input.proposal;
648
+ if ('disposition' in proposal) {
649
+ return digest({
650
+ ...common,
651
+ disposition: proposal.disposition,
652
+ ...(proposal.disposition === 'delegate_existing'
653
+ ? { candidateRef: proposal.candidateRef }
654
+ : { title: proposal.title, workspace: input.create?.workspace }),
655
+ });
656
+ }
657
+ if (proposal.operation === 'correct') {
658
+ return digest({
659
+ ...common,
660
+ disposition: 'replace',
661
+ replacesActionId: proposal.replacesActionId,
662
+ target: proposal.target,
663
+ ...(proposal.target.disposition === 'create_new'
664
+ ? { workspace: input.create?.workspace }
665
+ : {}),
666
+ });
667
+ }
668
+ // Preserve durable action fingerprints across the transient proposal rename.
669
+ return digest({
670
+ ...common,
671
+ disposition: proposal.operation === 'stop' ? 'stop_work' : 'resume_work',
663
672
  });
664
673
  }
665
674
  function replacementActionFingerprint(input, targetSessionId) {
666
- if (input.proposal.disposition !== 'replace') {
675
+ if (!('operation' in input.proposal) || input.proposal.operation !== 'correct') {
667
676
  throw new WorkHubActionGateFailure('action_conflict', 'Invalid WorkHub replacement replay');
668
677
  }
669
678
  return digest({
@@ -671,7 +680,7 @@ function replacementActionFingerprint(input, targetSessionId) {
671
680
  ...(input.attachments ? { attachments: input.attachments } : {}),
672
681
  ...(input.newWorkDefaults ? { newWorkDefaults: input.newWorkDefaults } : {}),
673
682
  ...(input.delegationText === undefined ? {} : { delegationText: input.delegationText }),
674
- disposition: input.proposal.disposition,
683
+ disposition: 'replace',
675
684
  replacesActionId: input.proposal.replacesActionId,
676
685
  target: {
677
686
  disposition: input.proposal.target.disposition,
@@ -683,7 +692,7 @@ function replacementActionFingerprint(input, targetSessionId) {
683
692
  });
684
693
  }
685
694
  function stopActionFingerprint(input, source) {
686
- if (input.proposal.disposition !== 'stop_work') {
695
+ if (!('operation' in input.proposal) || input.proposal.operation !== 'stop') {
687
696
  throw new WorkHubActionGateFailure('action_conflict', 'Invalid WorkHub stop replay');
688
697
  }
689
698
  return digest({
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
20
  import { mkdir } from 'node:fs/promises';
21
- import { join } from 'node:path';
21
+ import { basename, join } from 'node:path';
22
22
  import { isDeepStrictEqual } from 'node:util';
23
23
  import { normalizeMessageContent } from '@maka/core/events';
24
24
  import { WORKHUB_COORDINATION_SESSION_ID, WORKHUB_COORDINATION_SESSION_ROLE, WORKHUB_COORDINATION_REPLACEMENT_SCHEMA_VERSION, WORKHUB_COORDINATION_STOP_SCHEMA_VERSION, isWorkHubCoordinationSession, isWorkHubCoordinationSessionId, } from '@maka/core/session';
@@ -39,6 +39,9 @@ const TURN_IDENTITY_CONFLICT_MESSAGE = 'WorkHub Coordination Turn identity belon
39
39
  const JSON_ESCAPE_MAX_BYTES_PER_INPUT_BYTE = 6;
40
40
  const COORDINATION_SUMMARY_READ_MAX_BYTES = JSON_ESCAPE_MAX_BYTES_PER_INPUT_BYTE * (WORKHUB_COORDINATION_TEXT_MAX_BYTES + 8 * 1024) +
41
41
  16 * 1024;
42
+ const WORKHUB_ROUTING_TIMEOUT_MS = 15_000;
43
+ export const WORKHUB_ROUTING_HISTORY_MAX_MESSAGES = 32;
44
+ export const WORKHUB_ROUTING_HISTORY_MAX_STORED_BYTES = 64 * 1024;
42
45
  /** Resolves the one durable Coordination Session owned by this Runtime Host. */
43
46
  export class HostWorkHubCoordinationCoordinator {
44
47
  handlers = {
@@ -59,9 +62,11 @@ export class HostWorkHubCoordinationCoordinator {
59
62
  #resolveCreateTarget;
60
63
  #requestDrain;
61
64
  #actionGate;
65
+ #routingModel;
62
66
  #readDelegationRetirement;
63
67
  constructor(options) {
64
68
  this.#configureModel = options.configureModel;
69
+ this.#routingModel = options.routingModel;
65
70
  this.#transitionConfiguration = options.transitionConfiguration;
66
71
  this.#coordinationCwd = join(options.stateRoot, COORDINATION_CWD_DIRECTORY);
67
72
  this.#stores = options.stores;
@@ -328,9 +333,9 @@ export class HostWorkHubCoordinationCoordinator {
328
333
  }
329
334
  }
330
335
  async #actFromTurn(input, context) {
331
- let content;
336
+ let request;
332
337
  try {
333
- content = await this.#executions.readActiveWorkHubRequest(input.turnId);
338
+ request = await this.#executions.readActiveWorkHubRoutingRequest(input.turnId);
334
339
  }
335
340
  catch {
336
341
  return {
@@ -341,7 +346,7 @@ export class HostWorkHubCoordinationCoordinator {
341
346
  },
342
347
  };
343
348
  }
344
- if (!content) {
349
+ if (!request) {
345
350
  return {
346
351
  ok: false,
347
352
  error: {
@@ -351,17 +356,25 @@ export class HostWorkHubCoordinationCoordinator {
351
356
  };
352
357
  }
353
358
  const { turnId: _turnId, ...action } = input;
354
- const carriesAttachments = action.proposal.disposition === 'delegate_existing' ||
355
- action.proposal.disposition === 'create_new' ||
356
- action.proposal.disposition === 'replace';
359
+ if (request.decision && !routingDecisionAllowsProposal(request.decision, action)) {
360
+ return {
361
+ ok: false,
362
+ error: {
363
+ code: 'operation_conflict',
364
+ message: 'WorkHub action does not match the routing decision bound to this Turn',
365
+ },
366
+ };
367
+ }
368
+ const carriesAttachments = 'disposition' in action.proposal ||
369
+ ('operation' in action.proposal && action.proposal.operation === 'correct');
357
370
  try {
358
371
  return {
359
372
  ok: true,
360
373
  result: await this.#actionGate.act({
361
374
  ...action,
362
- userText: content.text,
363
- ...(carriesAttachments && content.attachments
364
- ? { attachments: content.attachments }
375
+ userText: request.content.text,
376
+ ...(carriesAttachments && request.content.attachments
377
+ ? { attachments: request.content.attachments }
365
378
  : {}),
366
379
  }, context, input.turnId),
367
380
  };
@@ -520,6 +533,60 @@ export class HostWorkHubCoordinationCoordinator {
520
533
  }, context);
521
534
  return outcome.ok ? { ok: true, result: { turnId: input.turnId } } : outcome;
522
535
  }
536
+ async prepareRoutingDecision(input) {
537
+ try {
538
+ if (!this.#routingModel)
539
+ throw new Error('WorkHub routing model is unavailable');
540
+ const page = await this.#stores.readMessagesAfter(WORKHUB_COORDINATION_SESSION_ID, {
541
+ beforeSequence: Number.MAX_SAFE_INTEGER,
542
+ maxMessages: WORKHUB_ROUTING_HISTORY_MAX_MESSAGES,
543
+ maxStoredBytes: WORKHUB_ROUTING_HISTORY_MAX_STORED_BYTES,
544
+ });
545
+ const transcript = [...page.records]
546
+ .reverse()
547
+ .flatMap(({ message }) => message.type === 'user' || message.type === 'assistant'
548
+ ? [{ role: message.type, text: message.text }]
549
+ : [])
550
+ .slice(-8);
551
+ return await this.#routingModel.decide({
552
+ turnId: input.turnId,
553
+ header: input.header,
554
+ userText: input.content.text,
555
+ transcript,
556
+ resolveCandidates: async () => {
557
+ const outcome = await this.#candidates();
558
+ if (!outcome.ok)
559
+ throw new Error(outcome.error.message);
560
+ const now = Date.now();
561
+ return {
562
+ candidateSetId: outcome.result.candidateSetId,
563
+ candidates: outcome.result.candidates.map((candidate) => ({
564
+ candidateRef: candidate.candidateRef,
565
+ sessionName: candidate.sessionName,
566
+ workspaceName: basename(candidate.workspace.hostCwd),
567
+ state: candidate.state,
568
+ recency: now - candidate.updatedAt < 24 * 60 * 60 * 1_000
569
+ ? 'today'
570
+ : now - candidate.updatedAt < 7 * 24 * 60 * 60 * 1_000
571
+ ? 'this_week'
572
+ : 'older',
573
+ })),
574
+ };
575
+ },
576
+ abortSignal: input.inputClosedSignal
577
+ ? AbortSignal.any([
578
+ input.inputClosedSignal,
579
+ AbortSignal.timeout(WORKHUB_ROUTING_TIMEOUT_MS),
580
+ ])
581
+ : AbortSignal.timeout(WORKHUB_ROUTING_TIMEOUT_MS),
582
+ });
583
+ }
584
+ catch {
585
+ // Invalid output, unavailable candidates, or provider failure cannot
586
+ // silently become creation or bind an arbitrary existing Session.
587
+ return { kind: 'routing', disposition: 'clarify' };
588
+ }
589
+ }
523
590
  /** Reads a historical v1 summary to preserve its durable Turn identity. */
524
591
  async #readSummaryMessages(turnId) {
525
592
  const throughSequence = await this.#stores.readTranscriptHighWaterSnapshot(WORKHUB_COORDINATION_SESSION_ID);
@@ -620,6 +687,21 @@ function validCoordinationHeader(header) {
620
687
  function digest(value) {
621
688
  return `sha256:${createHash('sha256').update(JSON.stringify(value)).digest('hex')}`;
622
689
  }
690
+ function routingDecisionAllowsProposal(decision, action) {
691
+ if (decision.kind === 'linked') {
692
+ return 'operation' in action.proposal && action.proposal.operation === decision.operation;
693
+ }
694
+ if (decision.disposition === 'delegate_existing') {
695
+ return ('disposition' in action.proposal &&
696
+ action.proposal.disposition === 'delegate_existing' &&
697
+ action.proposal.candidateRef === decision.candidateRef &&
698
+ action.candidateSetId === decision.candidateSetId);
699
+ }
700
+ if (decision.disposition === 'create_new') {
701
+ return 'disposition' in action.proposal && action.proposal.disposition === 'create_new';
702
+ }
703
+ return false;
704
+ }
623
705
  function workHubDestructiveClaimIdentitySuffix(delegationId) {
624
706
  return createHash('sha256').update(delegationId, 'utf8').digest('hex').slice(0, 48);
625
707
  }
@@ -137,7 +137,10 @@ export class FramedByteStreamTransport {
137
137
  break;
138
138
  }
139
139
  const encoded = this.#buffered.subarray(0, encodedBytes);
140
- this.#buffered = this.#buffered.subarray(encodedBytes);
140
+ this.#buffered =
141
+ encodedBytes === this.#buffered.byteLength
142
+ ? Buffer.alloc(0)
143
+ : this.#buffered.subarray(encodedBytes);
141
144
  const frames = this.#decoder.push(encoded);
142
145
  if (frames.length !== 1) {
143
146
  throw new Error('Runtime Host decoder did not produce one complete frame');
@@ -35,8 +35,10 @@ export class LocalIpcProtocolFrameDecoder {
35
35
  if (this.#pending.byteLength + segment.byteLength > RUNTIME_HOST_MAX_MESSAGE_BYTES) {
36
36
  throw new RuntimeHostProtocolError('frame_too_large', 'Runtime Host message exceeds the byte limit');
37
37
  }
38
- if (segment.byteLength > 0)
39
- this.#pending = Buffer.concat([this.#pending, segment]);
38
+ if (segment.byteLength > 0) {
39
+ this.#pending =
40
+ this.#pending.byteLength === 0 ? segment : Buffer.concat([this.#pending, segment]);
41
+ }
40
42
  if (newline === -1)
41
43
  break;
42
44
  frames.push(this.#decodePending());
@@ -157,7 +157,7 @@ async function readBoundedJsonLine(stream, maxBytes, label) {
157
157
  const encoded = buffered.subarray(0, newline);
158
158
  return {
159
159
  value: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(encoded)),
160
- remainder: buffered.subarray(newline + 1),
160
+ remainder: newline + 1 === buffered.length ? Buffer.alloc(0) : buffered.subarray(newline + 1),
161
161
  };
162
162
  }
163
163
  if (buffered.byteLength >= maxBytes) {
@@ -176,18 +176,16 @@ export class RuntimeHostPeerByteStream {
176
176
  #endListeners = new Set();
177
177
  #errorListeners = new Set();
178
178
  #stream;
179
- #initialData;
180
179
  #resolveClosed;
181
180
  #resume;
182
181
  #paused = false;
183
182
  #closed = false;
184
183
  constructor(stream, initialData = Buffer.alloc(0)) {
185
184
  this.#stream = stream;
186
- this.#initialData = initialData;
187
185
  this.closed = new Promise((resolve) => {
188
186
  this.#resolveClosed = resolve;
189
187
  });
190
- queueMicrotask(() => void this.#pump());
188
+ queueMicrotask(() => void this.#pump(initialData));
191
189
  }
192
190
  onData(listener) {
193
191
  this.#dataListeners.add(listener);
@@ -221,10 +219,11 @@ export class RuntimeHostPeerByteStream {
221
219
  this.#resume?.();
222
220
  this.#resume = undefined;
223
221
  }
224
- async #pump() {
222
+ async #pump(initialData) {
225
223
  try {
226
- if (this.#initialData.byteLength > 0)
227
- this.#emitData(this.#initialData);
224
+ if (initialData.byteLength > 0)
225
+ this.#emitData(initialData);
226
+ initialData = Buffer.alloc(0);
228
227
  while (!this.#closed) {
229
228
  if (this.#paused) {
230
229
  await new Promise((resolve) => {
@@ -233,13 +232,15 @@ export class RuntimeHostPeerByteStream {
233
232
  if (this.#closed)
234
233
  return;
235
234
  }
236
- const chunk = await this.#stream.read();
235
+ let chunk = await this.#stream.read();
237
236
  if (!chunk) {
238
237
  for (const listener of this.#endListeners)
239
238
  listener();
240
239
  return;
241
240
  }
242
241
  this.#emitData(chunk);
242
+ // Listeners own any data they retain; the read loop no longer needs it.
243
+ chunk = null;
243
244
  }
244
245
  }
245
246
  catch (error) {
@@ -111,7 +111,8 @@ export class ResumablePeerStream {
111
111
  }
112
112
  const old = this.#path;
113
113
  const path = {
114
- ...attachment,
114
+ stream: attachment.stream,
115
+ received: attachment.received,
115
116
  sent: this.#acknowledged,
116
117
  acknowledged: -1,
117
118
  pong: undefined,
@@ -123,7 +124,7 @@ export class ResumablePeerStream {
123
124
  this.#recoveryStarted = undefined;
124
125
  old?.stream.abort();
125
126
  this.#notify();
126
- void this.#pumpRead(path).catch((error) => this.#pathFailed(path, error));
127
+ void this.#pumpRead(path, attachment.remainder).catch((error) => this.#pathFailed(path, error));
127
128
  void this.#pumpWrite(path).catch((error) => this.#pathFailed(path, error));
128
129
  }
129
130
  async read() {
@@ -223,16 +224,17 @@ export class ResumablePeerStream {
223
224
  this.#outgoing.shift();
224
225
  this.#notify();
225
226
  }
226
- async #pumpRead(path) {
227
- let buffered = path.remainder;
227
+ async #pumpRead(path, buffered) {
228
+ // Suspended reads retain locals: drop consumed chunks and backing-buffer views before awaiting.
228
229
  while (this.#path === path && !this.#ended) {
229
230
  if (buffered.length < HEADER_BYTES) {
230
- const chunk = await path.stream.read();
231
+ let chunk = await path.stream.read();
231
232
  if (!chunk)
232
233
  throw new Error('Peer path ended');
233
234
  if (this.#path !== path)
234
235
  return;
235
236
  buffered = Buffer.concat([buffered, chunk]);
237
+ chunk = null;
236
238
  continue;
237
239
  }
238
240
  const type = buffered[0];
@@ -244,17 +246,16 @@ export class ResumablePeerStream {
244
246
  throw new PeerResumeRejectedError('Invalid peer stream frame');
245
247
  }
246
248
  if (buffered.length < HEADER_BYTES + size) {
247
- const chunk = await path.stream.read();
249
+ let chunk = await path.stream.read();
248
250
  if (!chunk)
249
251
  throw new Error('Peer path ended inside frame');
250
252
  if (this.#path !== path)
251
253
  return;
252
254
  buffered = Buffer.concat([buffered, chunk]);
255
+ chunk = null;
253
256
  continue;
254
257
  }
255
258
  const offset = Number(wideOffset);
256
- const bytes = buffered.subarray(HEADER_BYTES, HEADER_BYTES + size);
257
- buffered = buffered.subarray(HEADER_BYTES + size);
258
259
  switch (type) {
259
260
  case DATA:
260
261
  if (size === 0 || this.#remoteFin)
@@ -263,7 +264,7 @@ export class ResumablePeerStream {
263
264
  break; // Lost ACK: already retained/delivered.
264
265
  if (offset !== this.#received || this.#received - this.#consumed + size > WINDOW_BYTES)
265
266
  throw new PeerResumeRejectedError('Peer stream receive window violated');
266
- this.#incoming.push(Buffer.from(bytes));
267
+ this.#incoming.push(Buffer.from(buffered.subarray(HEADER_BYTES, HEADER_BYTES + size)));
267
268
  this.#received += size;
268
269
  break;
269
270
  case ACK:
@@ -289,6 +290,10 @@ export class ResumablePeerStream {
289
290
  default:
290
291
  throw new PeerResumeRejectedError('Unknown peer stream frame');
291
292
  }
293
+ buffered =
294
+ buffered.length === HEADER_BYTES + size
295
+ ? Buffer.alloc(0)
296
+ : buffered.subarray(HEADER_BYTES + size);
292
297
  this.#notify();
293
298
  }
294
299
  }
@@ -1183,7 +1183,9 @@ function assertRootTurnAdmissionContract(admission) {
1183
1183
  const execution = admission.execution;
1184
1184
  const providerRetry = execution.kind === 'linked_child_provider_retry';
1185
1185
  const inputlessExecution = execution.kind === 'safe_boundary_continuation' || execution.kind === 'context_compact';
1186
- const sourceBatch = execution.kind === 'external_message' && admission.sourceMessages.length > 1;
1186
+ const allowsQueueSources = execution.kind === 'external_message' ||
1187
+ (execution.kind === 'workhub_coordination' && execution.operation !== 'action');
1188
+ const sourceBatch = allowsQueueSources && admission.sourceMessages.length > 1;
1187
1189
  const messageLessExecution = inputlessExecution || providerRetry || sourceBatch;
1188
1190
  if (execution.kind === 'agent_graph_supervisor_wake') {
1189
1191
  if (admission.turnOrchestration?.mode !== 'graph' ||
@@ -1200,7 +1202,7 @@ function assertRootTurnAdmissionContract(admission) {
1200
1202
  if ((admission.normalizedInput === null) !== inputlessExecution) {
1201
1203
  throw new Error('Invalid root turn admission contract: execution has an invalid input requirement');
1202
1204
  }
1203
- if (execution.kind !== 'external_message' && admission.sourceMessages.length !== 0) {
1205
+ if (!allowsQueueSources && admission.sourceMessages.length !== 0) {
1204
1206
  throw new Error('Invalid root turn admission contract: host-authored execution cannot have source messages');
1205
1207
  }
1206
1208
  if (admission.skillInvocation && execution.kind !== 'external_message') {
@@ -1347,14 +1349,18 @@ function normalizeRootExecutionDescriptor(value) {
1347
1349
  });
1348
1350
  }
1349
1351
  if (value.kind === 'workhub_coordination') {
1350
- if (!hasExactKeys(value, value.operation === undefined
1351
- ? ['kind', 'inputDigest']
1352
- : [
1353
- 'kind',
1354
- 'inputDigest',
1355
- 'operation',
1356
- ...(value.actionId === undefined ? [] : ['actionId']),
1357
- ]) ||
1352
+ const routingDecision = normalizeWorkHubRoutingDecision(value.routingDecision);
1353
+ if (!hasExactKeys(value, [
1354
+ 'kind',
1355
+ 'inputDigest',
1356
+ ...(value.capabilityBinding === undefined ? [] : ['capabilityBinding']),
1357
+ ...(value.routingDecision === undefined ? [] : ['routingDecision']),
1358
+ ...(value.operation === undefined ? [] : ['operation']),
1359
+ ...(value.actionId === undefined ? [] : ['actionId']),
1360
+ ]) ||
1361
+ (value.capabilityBinding !== undefined && !isSha256Digest(value.capabilityBinding)) ||
1362
+ (value.actionId !== undefined && value.operation !== 'action') ||
1363
+ (value.operation !== undefined && routingDecision !== undefined) ||
1358
1364
  (value.operation !== undefined && value.operation !== 'action') ||
1359
1365
  (value.actionId !== undefined &&
1360
1366
  (typeof value.actionId !== 'string' || !isSafeId(value.actionId))) ||
@@ -1365,7 +1371,11 @@ function normalizeRootExecutionDescriptor(value) {
1365
1371
  kind: 'workhub_coordination',
1366
1372
  ...(value.operation === 'action' ? { operation: 'action' } : {}),
1367
1373
  inputDigest: value.inputDigest,
1374
+ ...(isSha256Digest(value.capabilityBinding)
1375
+ ? { capabilityBinding: value.capabilityBinding }
1376
+ : {}),
1368
1377
  ...(typeof value.actionId === 'string' ? { actionId: value.actionId } : {}),
1378
+ ...(routingDecision ? { routingDecision } : {}),
1369
1379
  });
1370
1380
  }
1371
1381
  if (value.kind === 'regenerate') {
@@ -1533,6 +1543,40 @@ function normalizeRootExecutionDescriptor(value) {
1533
1543
  sourceRunId: value.sourceRunId,
1534
1544
  });
1535
1545
  }
1546
+ function normalizeWorkHubRoutingDecision(value) {
1547
+ if (value === undefined)
1548
+ return undefined;
1549
+ if (!isPlainRecord(value) || typeof value.kind !== 'string') {
1550
+ throw new Error('Invalid WorkHub routing decision');
1551
+ }
1552
+ if (value.kind === 'routing' &&
1553
+ (value.disposition === 'answer_here' ||
1554
+ value.disposition === 'create_new' ||
1555
+ value.disposition === 'clarify') &&
1556
+ hasExactKeys(value, ['kind', 'disposition'])) {
1557
+ return Object.freeze({ kind: 'routing', disposition: value.disposition });
1558
+ }
1559
+ if (value.kind === 'routing' &&
1560
+ value.disposition === 'delegate_existing' &&
1561
+ typeof value.candidateSetId === 'string' &&
1562
+ /^sha256:[a-f0-9]{64}$/.test(value.candidateSetId) &&
1563
+ typeof value.candidateRef === 'string' &&
1564
+ isSafeId(value.candidateRef) &&
1565
+ hasExactKeys(value, ['kind', 'disposition', 'candidateSetId', 'candidateRef'])) {
1566
+ return Object.freeze({
1567
+ kind: 'routing',
1568
+ disposition: 'delegate_existing',
1569
+ candidateSetId: value.candidateSetId,
1570
+ candidateRef: value.candidateRef,
1571
+ });
1572
+ }
1573
+ if (value.kind === 'linked' &&
1574
+ (value.operation === 'correct' || value.operation === 'stop' || value.operation === 'resume') &&
1575
+ hasExactKeys(value, ['kind', 'operation'])) {
1576
+ return Object.freeze({ kind: 'linked', operation: value.operation });
1577
+ }
1578
+ throw new Error('Invalid WorkHub routing decision');
1579
+ }
1536
1580
  function deepFreezeRootTurnMessageContent(content) {
1537
1581
  for (const attachment of content.attachments ?? []) {
1538
1582
  Object.freeze(attachment.ref);