maka-agent 0.2.0-dev.14.20260902 → 0.2.0-dev.16.20260903

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 (160) hide show
  1. package/dist/cli-core.js +0 -1
  2. package/dist/pi-transcript.js +48 -0
  3. package/dist/pi-tui-form-interaction.js +497 -0
  4. package/dist/pi-tui-pickers.js +256 -55
  5. package/dist/pi-tui-runner.js +215 -12
  6. package/dist/runtime-host-cli.js +17 -42
  7. package/dist/runtime-host-lifecycle-transaction.js +31 -13
  8. package/dist/runtime-host-managed-lifecycle-manager.js +1 -1
  9. package/dist/runtime-host-onboarding.js +3 -1
  10. package/dist/runtime-host-openrc-service.js +469 -0
  11. package/dist/runtime-host-run-command.js +6 -2
  12. package/dist/runtime-host-service-command.js +3 -3
  13. package/dist/runtime-host-service-management-command.js +43 -15
  14. package/dist/runtime-host-session-channel.js +3 -0
  15. package/dist/runtime-host-session-driver.js +21 -6
  16. package/dist/runtime-host-setup-command.js +30 -31
  17. package/dist/tui-context-refresh.js +103 -0
  18. package/dist/tui-copy-catalog.js +73 -0
  19. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  20. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  21. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  22. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  23. package/node_modules/@maka/core/dist/chat-model-choice.js +4 -0
  24. package/node_modules/@maka/core/dist/computer-use.js +27 -92
  25. package/node_modules/@maka/core/dist/interaction.js +577 -3
  26. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  27. package/node_modules/@maka/core/dist/local-memory.js +2 -2
  28. package/node_modules/@maka/core/dist/model-call-usage-projection.js +3 -0
  29. package/node_modules/@maka/core/dist/model-metadata.js +26 -7
  30. package/node_modules/@maka/core/dist/model-thinking.js +17 -0
  31. package/node_modules/@maka/core/dist/provider-registry.js +1 -0
  32. package/node_modules/@maka/core/dist/runtime-event.js +23 -1
  33. package/node_modules/@maka/core/dist/scheduled-task.js +4 -0
  34. package/node_modules/@maka/core/dist/session.js +95 -2
  35. package/node_modules/@maka/core/dist/text-sanitize.js +19 -0
  36. package/node_modules/@maka/core/dist/usage-ledger-merge.js +3 -0
  37. package/node_modules/@maka/core/dist/usage-record-schema.js +11 -5
  38. package/node_modules/@maka/core/dist/workhub-creation-intent.js +75 -9
  39. package/node_modules/@maka/core/dist/workhub-session-resolver.js +50 -0
  40. package/node_modules/@maka/core/package.json +2 -0
  41. package/node_modules/@maka/eval/dist/harbor-external-subject.js +2 -1
  42. package/node_modules/@maka/eval/dist/harness-executor.js +3 -2
  43. package/node_modules/@maka/eval/dist/install-preflight.js +39 -10
  44. package/node_modules/@maka/eval/dist/process-termination.js +83 -0
  45. package/node_modules/@maka/mcp/dist/sep-2243.js +3 -3
  46. package/node_modules/@maka/runtime/dist/agent-run.js +6 -3
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +332 -118
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction-contract.js +6 -1
  49. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +171 -341
  50. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +3 -26
  51. package/node_modules/@maka/runtime/dist/bundled-skill-catalog.generated.js +1 -1
  52. package/node_modules/@maka/runtime/dist/computer-use-codec.js +1 -141
  53. package/node_modules/@maka/runtime/dist/computer-use-tools.js +23 -105
  54. package/node_modules/@maka/runtime/dist/context-budget-policy.js +20 -26
  55. package/node_modules/@maka/runtime/dist/context-budget.js +18 -20
  56. package/node_modules/@maka/runtime/dist/conversation-copy.js +23 -19
  57. package/node_modules/@maka/runtime/dist/cua-frame-state.js +1 -69
  58. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +267 -0
  59. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +6 -9
  60. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +67 -23
  61. package/node_modules/@maka/runtime/dist/history-compact-summary-validation.js +11 -18
  62. package/node_modules/@maka/runtime/dist/history-compaction.js +66 -73
  63. package/node_modules/@maka/runtime/dist/interaction-authority.js +69 -0
  64. package/node_modules/@maka/runtime/dist/mcp-tools.js +13 -1
  65. package/node_modules/@maka/runtime/dist/memory-extraction.js +11 -11
  66. package/node_modules/@maka/runtime/dist/model-adapter.js +24 -6
  67. package/node_modules/@maka/runtime/dist/model-factory.js +14 -5
  68. package/node_modules/@maka/runtime/dist/oauth-provider-contracts.js +28 -1
  69. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +7 -6
  70. package/node_modules/@maka/runtime/dist/opencode-session-header.js +29 -0
  71. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +11 -1
  72. package/node_modules/@maka/runtime/dist/runtime-kernel.js +12 -11
  73. package/node_modules/@maka/runtime/dist/runtime-read-model.js +51 -13
  74. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +3 -0
  75. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +26 -0
  76. package/node_modules/@maka/runtime/dist/session-manager.js +1 -0
  77. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +16 -1
  78. package/node_modules/@maka/runtime/dist/stream-graph-projection.js +6 -0
  79. package/node_modules/@maka/runtime/dist/stream-graph-read-model.js +5 -0
  80. package/node_modules/@maka/runtime/dist/stream-usage-fallback-fetch.js +74 -0
  81. package/node_modules/@maka/runtime/dist/subscription-credentials.js +51 -4
  82. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +47 -3
  83. package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +20 -1
  84. package/node_modules/@maka/runtime/dist/test-connection.js +18 -11
  85. package/node_modules/@maka/runtime/dist/tool-runtime.js +183 -0
  86. package/node_modules/@maka/runtime/package.json +1 -0
  87. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +14 -0
  88. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +84 -1
  89. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +68 -51
  90. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  91. package/node_modules/@maka/runtime-host/dist/client/owner-connection-code.js +8 -5
  92. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +342 -36
  93. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +60 -4
  94. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +3 -3
  95. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +1 -1
  96. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +48 -60
  97. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +847 -431
  98. package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +33 -74
  99. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +82 -69
  100. package/node_modules/@maka/runtime-host/dist/peer-reachability/index.js +21 -0
  101. package/node_modules/@maka/runtime-host/dist/peer-reachability/model.js +202 -0
  102. package/node_modules/@maka/runtime-host/dist/peer-reachability/owner.js +119 -0
  103. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +245 -0
  104. package/node_modules/@maka/runtime-host/dist/protocol/agent-graph.js +4 -1
  105. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +68 -0
  106. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +15 -8
  107. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +7 -23
  108. package/node_modules/@maka/runtime-host/dist/protocol/index.js +47 -1
  109. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +25 -1
  110. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  111. package/node_modules/@maka/runtime-host/dist/protocol/peer-mesh.js +14 -31
  112. package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +19 -6
  113. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +36 -1
  114. package/node_modules/@maka/runtime-host/dist/protocol/session-revision.js +11 -2
  115. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +16 -2
  116. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +51 -2
  117. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +35 -2
  118. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  119. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +12 -10
  120. package/node_modules/@maka/runtime-host/dist/server/client-capability-invocation-broker.js +163 -30
  121. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +38 -14
  122. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +45 -22
  123. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +78 -20
  124. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +4 -2
  125. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +2 -1
  126. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +49 -28
  127. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +3 -6
  128. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +130 -27
  129. package/node_modules/@maka/runtime-host/dist/server/interaction-projection.js +30 -1
  130. package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -4
  131. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +16 -3
  132. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +66 -3
  133. package/node_modules/@maka/runtime-host/dist/server/oauth-execution-authority.js +20 -3
  134. package/node_modules/@maka/runtime-host/dist/server/peer-listener.js +8 -21
  135. package/node_modules/@maka/runtime-host/dist/server/peer-mesh-authority.js +1 -1
  136. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -3
  137. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +72 -12
  138. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +48 -18
  139. package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +43 -26
  140. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +15 -1
  141. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +229 -4
  142. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +146 -8
  143. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +32 -6
  144. package/node_modules/@maka/runtime-host/package.json +1 -0
  145. package/node_modules/@maka/storage/dist/agent-run-store.js +18 -5
  146. package/node_modules/@maka/storage/dist/codex-session-adapter.js +14 -0
  147. package/node_modules/@maka/storage/dist/execution-stores.js +5 -0
  148. package/node_modules/@maka/storage/dist/interaction-store.js +13 -1
  149. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +9 -3
  150. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +49 -19
  151. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +3 -1
  152. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +13 -5
  153. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +4 -2
  154. package/node_modules/@maka/storage/dist/session-store.js +39 -6
  155. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +16 -9
  156. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +30 -3
  157. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +117 -0
  158. package/node_modules/@maka/storage/dist/sqlite-usage-store.js +29 -6
  159. package/node_modules/@maka/storage/dist/usage-stores.js +3 -1
  160. package/package.json +1 -1
@@ -214,9 +214,18 @@ export class HostSessionRevisionCoordinator {
214
214
  catch {
215
215
  return copyFailure('persistence_failed', 'Source conversation ledger is unavailable');
216
216
  }
217
- const slice = createConversationCopySlice(source.messages, input.sourceTurnId, kind === 'revision' ? 'before' : 'through');
218
- if (!slice) {
219
- return copyFailure('invalid_request', 'Source turn does not exist');
217
+ // An empty copy carries no source transcript: skip the slice so a side
218
+ // conversation can fork before the source has any settled turn.
219
+ let slice;
220
+ if (input.sourceTurnId === undefined) {
221
+ slice = { messages: [], turnIds: [] };
222
+ }
223
+ else {
224
+ const throughSlice = createConversationCopySlice(source.messages, input.sourceTurnId, kind === 'revision' ? 'before' : 'through');
225
+ if (!throughSlice) {
226
+ return copyFailure('invalid_request', 'Source turn does not exist');
227
+ }
228
+ slice = throughSlice;
220
229
  }
221
230
  let plan;
222
231
  let sessionHeaders;
@@ -395,7 +404,8 @@ export class HostSessionRevisionCoordinator {
395
404
  await this.#sessionTodo.initializeCopy({
396
405
  sourceSessionId: input.sourceSessionId,
397
406
  targetSessionId: input.targetSessionId,
398
- copyCurrent: kind === 'branch' && slice.beforeTs === undefined,
407
+ // An empty copy carries no source state, including no in-progress Todo.
408
+ copyCurrent: kind === 'branch' && slice.beforeTs === undefined && input.sourceTurnId !== undefined,
399
409
  });
400
410
  if (copiedMessages.length > 0) {
401
411
  await this.#stores.sessionStore.appendMessages(input.targetSessionId, [...copiedMessages]);
@@ -471,7 +481,7 @@ export class HostSessionRevisionCoordinator {
471
481
  conversationCopy: {
472
482
  kind: persistedConversationCopyKind(kind),
473
483
  sourceSessionId: input.sourceSessionId,
474
- sourceTurnId: input.sourceTurnId,
484
+ ...(input.sourceTurnId === undefined ? {} : { sourceTurnId: input.sourceTurnId }),
475
485
  requestFingerprint,
476
486
  state: 'preparing',
477
487
  ...(kind === 'side_conversation' ? { intent: kind } : {}),
@@ -479,12 +489,18 @@ export class HostSessionRevisionCoordinator {
479
489
  status: 'active',
480
490
  };
481
491
  if (kind !== 'revision') {
492
+ // An empty copy records provenance but fabricates no branch turn.
482
493
  return {
483
494
  ...common,
484
495
  parentSessionId: input.sourceSessionId,
485
- branchOfTurnId: input.sourceTurnId,
496
+ ...(input.sourceTurnId === undefined ? {} : { branchOfTurnId: input.sourceTurnId }),
486
497
  };
487
498
  }
499
+ // Revision copies always carry a turn boundary (enforced at decode).
500
+ if (input.sourceTurnId === undefined) {
501
+ throw new Error('Session revision copy requires a turn boundary');
502
+ }
503
+ const revisionOfTurnId = input.sourceTurnId;
488
504
  const revisionRootSessionId = source.revisionRootSessionId ?? input.sourceSessionId;
489
505
  const family = (await this.#stores.sessionStore.listHeaders()).filter((candidate) => candidate.conversationCopy?.state !== 'preparing' &&
490
506
  (candidate.id === revisionRootSessionId ||
@@ -496,7 +512,7 @@ export class HostSessionRevisionCoordinator {
496
512
  ...(source.branchOfTurnId ? { branchOfTurnId: source.branchOfTurnId } : {}),
497
513
  revisionRootSessionId,
498
514
  revisionParentSessionId: input.sourceSessionId,
499
- revisionOfTurnId: input.sourceTurnId,
515
+ revisionOfTurnId,
500
516
  revisionIndex,
501
517
  revisionState: 'preparing',
502
518
  };
@@ -615,28 +631,42 @@ function conversationCopyFingerprint(kind, input) {
615
631
  kind,
616
632
  input.sourceSessionId,
617
633
  input.targetSessionId,
634
+ // Absent for an empty copy. JSON.stringify renders the missing element as
635
+ // null, so an empty copy gets a distinct identity while through_turn and
636
+ // revision hashes stay byte-identical to a required sourceTurnId.
618
637
  input.sourceTurnId,
619
638
  ];
620
639
  return `sha256:${createHash('sha256').update(JSON.stringify(identity)).digest('hex')}`;
621
640
  }
622
641
  function conversationCopyStartNote(kind, input, createInput) {
623
- return {
642
+ const base = {
624
643
  type: 'system_note',
625
644
  id: randomUUID(),
626
645
  ts: Date.now(),
627
646
  kind: 'session_start',
628
- data: kind !== 'revision'
629
- ? {
647
+ };
648
+ if (kind !== 'revision') {
649
+ // Empty copies record provenance without a branch turn.
650
+ return {
651
+ ...base,
652
+ data: {
630
653
  parentSessionId: input.sourceSessionId,
631
- branchOfTurnId: input.sourceTurnId,
632
- }
633
- : {
634
- revisionRootSessionId: createInput.revisionRootSessionId,
635
- revisionParentSessionId: input.sourceSessionId,
636
- revisionOfTurnId: input.sourceTurnId,
637
- revisionIndex: createInput.revisionIndex,
638
- revisionState: 'preparing',
654
+ ...(input.sourceTurnId === undefined ? {} : { branchOfTurnId: input.sourceTurnId }),
639
655
  },
656
+ };
657
+ }
658
+ if (input.sourceTurnId === undefined) {
659
+ throw new Error('Session revision copy requires a turn boundary');
660
+ }
661
+ return {
662
+ ...base,
663
+ data: {
664
+ revisionRootSessionId: createInput.revisionRootSessionId,
665
+ revisionParentSessionId: input.sourceSessionId,
666
+ revisionOfTurnId: input.sourceTurnId,
667
+ revisionIndex: createInput.revisionIndex,
668
+ revisionState: 'preparing',
669
+ },
640
670
  };
641
671
  }
642
672
  function conversationCopySemanticKind(kind, input) {
@@ -19,6 +19,7 @@
19
19
  export class SessionTurnAccessRequestCoordinator {
20
20
  #authority;
21
21
  #startTurn;
22
+ #regenerateTurn;
22
23
  #acquireResidency;
23
24
  #requestDrain;
24
25
  #whenIdle;
@@ -29,6 +30,7 @@ export class SessionTurnAccessRequestCoordinator {
29
30
  constructor(input) {
30
31
  this.#authority = input.authority;
31
32
  this.#startTurn = input.startTurn;
33
+ this.#regenerateTurn = input.regenerateTurn;
32
34
  this.#acquireResidency = input.acquireResidency;
33
35
  this.#requestDrain = input.requestDrain;
34
36
  this.#whenIdle = input.whenIdle;
@@ -79,34 +81,11 @@ export class SessionTurnAccessRequestCoordinator {
79
81
  acquireResidency: this.#acquireResidency,
80
82
  };
81
83
  try {
82
- let outcome;
83
- for (;;) {
84
- try {
85
- outcome = await this.#startTurn(request.intent, context);
86
- }
87
- catch {
88
- this.#requestDrain();
89
- return;
90
- }
91
- if (outcome.ok || outcome.error.code !== 'session_busy')
92
- break;
93
- const whenIdle = this.#whenIdle(request.intent.sessionId);
94
- if (whenIdle) {
95
- try {
96
- await whenIdle;
97
- }
98
- catch {
99
- this.#requestDrain();
100
- return;
101
- }
102
- }
103
- if (this.#draining)
104
- return;
105
- }
106
- if (this.#draining && !outcome.ok)
84
+ const admission = await this.#run(request, context);
85
+ if (!admission)
107
86
  return;
108
87
  try {
109
- await this.#authority.completeTurnAccessRequest(request.requestId, outcome.ok ? outcome.result.kind : 'failed');
88
+ await this.#authority.completeTurnAccessRequest(request.requestId, admission);
110
89
  }
111
90
  catch {
112
91
  this.#requestDrain();
@@ -116,6 +95,44 @@ export class SessionTurnAccessRequestCoordinator {
116
95
  residency.release();
117
96
  }
118
97
  }
98
+ async #run(request, context) {
99
+ for (;;) {
100
+ try {
101
+ if ('content' in request.intent) {
102
+ const outcome = await this.#startTurn(request.intent, context);
103
+ if (outcome.ok)
104
+ return outcome.result.kind;
105
+ if (outcome.error.code !== 'session_busy') {
106
+ return this.#draining ? undefined : 'failed';
107
+ }
108
+ }
109
+ else {
110
+ const outcome = await this.#regenerateTurn(request.intent, context);
111
+ if (outcome.ok)
112
+ return 'started';
113
+ if (outcome.error.code !== 'session_busy') {
114
+ return this.#draining ? undefined : 'failed';
115
+ }
116
+ }
117
+ }
118
+ catch {
119
+ this.#requestDrain();
120
+ return undefined;
121
+ }
122
+ const whenIdle = this.#whenIdle(request.intent.sessionId);
123
+ if (whenIdle) {
124
+ try {
125
+ await whenIdle;
126
+ }
127
+ catch {
128
+ this.#requestDrain();
129
+ return undefined;
130
+ }
131
+ }
132
+ if (this.#draining)
133
+ return undefined;
134
+ }
135
+ }
119
136
  #settled() {
120
137
  return Promise.all(this.#tasks.values()).then(() => undefined);
121
138
  }
@@ -87,10 +87,24 @@ export class HostUsagePricingCoordinator {
87
87
  const now = Date.now();
88
88
  if (input.kind === 'summary') {
89
89
  const merged = mergeUsageSummary(await this.#stores.telemetry.summary(input.query), await this.#canonicalUsage(input.query, now), input.query, now);
90
+ // Tool executions are in their own ledger, not the model-call one, so
91
+ // their totals ride beside the merged summary rather than inside it —
92
+ // the same owner split the tool buckets path already follows. A
93
+ // connection-scoped query is refused instead of answered: tool rows
94
+ // that predate connection attribution cannot be scoped, and a ring
95
+ // built from an unscoped subset would quietly contradict the model
96
+ // totals beside it.
90
97
  const { provenance, ...summary } = merged;
98
+ const toolUsage = input.query.connectionSlug === undefined
99
+ ? await this.#stores.telemetry.toolSummary(input.query)
100
+ : undefined;
91
101
  return {
92
102
  ok: true,
93
- result: encodeUsageQueryResult({ kind: 'summary', summary, provenance }),
103
+ result: encodeUsageQueryResult({
104
+ kind: 'summary',
105
+ summary: { ...summary, toolUsage },
106
+ provenance,
107
+ }),
94
108
  };
95
109
  }
96
110
  if (input.kind === 'buckets') {
@@ -74,8 +74,9 @@ export class WorkHubCoordinationActionGate {
74
74
  const action = { requestFingerprint, result };
75
75
  this.#actions.set(input.actionId, action);
76
76
  // Successful actions remain a Host-lifetime fast path. Rejections release
77
- // the slot so a pre-assignment admission can retry; once assigned, SQLite
78
- // independently owns the durable action identity.
77
+ // the slot so a pre-assignment admission can retry; the durable action
78
+ // claim, not this map, is what owns the identity across that retry and
79
+ // across restarts.
79
80
  void result.catch(() => {
80
81
  if (this.#actions.get(input.actionId) === action) {
81
82
  this.#actions.delete(input.actionId);
@@ -107,11 +108,13 @@ export class WorkHubCoordinationActionGate {
107
108
  }
108
109
  if (proposal.disposition === 'answer_here') {
109
110
  const turnId = coordinationTurnId(input.actionId, 'answer');
111
+ await this.#claimAction(input.actionId, 'answer_here', fingerprint, turnId);
110
112
  await this.#effects.answer({ turnId, text: input.userText }, context);
111
113
  return { disposition: 'answer_here', coordinationTurnId: turnId };
112
114
  }
113
115
  if (proposal.disposition === 'clarify') {
114
116
  const turnId = coordinationTurnId(input.actionId, 'clarify');
117
+ await this.#claimAction(input.actionId, 'clarify', fingerprint, turnId);
115
118
  await this.#effects.clarify({
116
119
  turnId,
117
120
  userText: input.userText,
@@ -119,6 +122,61 @@ export class WorkHubCoordinationActionGate {
119
122
  });
120
123
  return { disposition: 'clarify', coordinationTurnId: turnId };
121
124
  }
125
+ if (proposal.disposition === 'stop_work') {
126
+ if (input.confirmation?.kind !== 'user_stop' || !requestIntent.stop.imperative) {
127
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop requires an explicit named command in trusted user text');
128
+ }
129
+ const source = await this.#stopSource(input.actionId, proposal.expects.targetSessionId);
130
+ const stopFingerprint = stopActionFingerprint(input, source);
131
+ await this.#claimAction(input.actionId, 'stop', stopFingerprint, source.delegationId);
132
+ const existing = await this.#effects.readStopRequest(source.delegationId);
133
+ if (existing) {
134
+ if (existing.actionId !== input.actionId) {
135
+ // `not_owned` deliberately leaves the delegation active, so the user
136
+ // can and will try again with a fresh request. That later attempt has
137
+ // its own identity and must converge on the immutable non-destructive
138
+ // outcome instead of colliding with the first attempt's stop claim.
139
+ const resolved = await this.#effects.readStopResolution(source.delegationId);
140
+ if (resolved?.outcome === 'not_owned')
141
+ return stopResult(resolved);
142
+ }
143
+ assertStopReplay(existing, input, source, stopFingerprint);
144
+ return this.#stop(existing, source);
145
+ }
146
+ const sessions = await this.#effects.listSessions();
147
+ const sessionNameById = new Map(sessions.map((session) => [session.id, session.name]));
148
+ // Only this delegation's target has to be visible. A delegation whose
149
+ // Session the user deleted stays in the active set forever — nothing
150
+ // retires it — so proving visibility over the whole set would let one
151
+ // deleted Session block every stop in the system from then on.
152
+ //
153
+ // Sole active delegation is not reproved here. `#stopSource` derived this
154
+ // `source` from the active links a moment ago by that same rule, and the
155
+ // replay branch above returned before reaching this line, so a second
156
+ // pass would re-read the transcript to reach the answer it started from.
157
+ // The proof that decides is the coordinator's, under the admission lease.
158
+ const currentTargetName = sessionNameById.get(source.targetSessionId);
159
+ if (!currentTargetName) {
160
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop target is unavailable');
161
+ }
162
+ if (await this.#effects.readSupersession(source.delegationId)) {
163
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub delegation has already been superseded');
164
+ }
165
+ if (await this.#effects.readReplacement(source.delegationId)) {
166
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub delegation already has a replacement claim');
167
+ }
168
+ const requested = await this.#effects.prepareStop({
169
+ actionId: input.actionId,
170
+ actionFingerprint: stopFingerprint,
171
+ stopsActionId: source.actionId,
172
+ stopsDelegationId: source.delegationId,
173
+ targetSessionId: source.targetSessionId,
174
+ targetMessageId: source.targetMessageId,
175
+ targetSessionName: currentTargetName,
176
+ userText: input.userText,
177
+ });
178
+ return this.#stop(requested, source);
179
+ }
122
180
  if (proposal.disposition === 'create_new') {
123
181
  if (!input.create || !workHubCreationAuthorizesTitle(requestIntent, proposal.title)) {
124
182
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub creation requires an unambiguous instruction and creation context');
@@ -148,9 +206,11 @@ export class WorkHubCoordinationActionGate {
148
206
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub delegation already has a different replacement intent');
149
207
  }
150
208
  await this.#assertReplacementReplayTarget(input, prepared.targetSessionId);
209
+ await this.#claimAction(prepared.actionId, 'replace', prepared.actionFingerprint, prepared.replacesDelegationId);
151
210
  return this.#replace(prepared, context);
152
211
  }
153
212
  const replacement = await this.#replacementAssignment(input, replaced);
213
+ await this.#claimAction(replacement.actionId, 'replace', replacement.actionFingerprint, replacement.replacesDelegationId);
154
214
  const intent = await this.#effects.prepareReplacement(replacement);
155
215
  return this.#replace(intent, context);
156
216
  }
@@ -165,6 +225,122 @@ export class WorkHubCoordinationActionGate {
165
225
  this.#assertTarget(target);
166
226
  return this.#assign(delegationAssignment(input, fingerprint, target.sessionId, target.sessionName), context);
167
227
  }
228
+ /**
229
+ * The delegation a stop names, by the only two keys that can name it.
230
+ *
231
+ * A stop carries its target Session and its own action identity; it never
232
+ * carries the delegation, because a client cannot prove which link is live.
233
+ *
234
+ * Replay reads the claim first. A resolved stop takes its delegation out of
235
+ * the active set, so re-deriving after one succeeded would find nothing and
236
+ * turn a converging replay into a conflict. The claim records the delegation
237
+ * this exact action already bound itself to, and it is written before any
238
+ * effect, so whatever the first attempt reached is reachable again.
239
+ *
240
+ * A first attempt has no claim and resolves from the active links: exactly
241
+ * one delegation on that Session must still hold work a stop could reach.
242
+ * Zero or several is the same refusal admission has always made, from the
243
+ * same durable state, rather than a client's guess about either.
244
+ */
245
+ async #stopSource(actionId, targetSessionId) {
246
+ const claim = await this.#effects.readActionClaim(actionId);
247
+ if (claim?.operation === 'stop') {
248
+ // The request records which delegation this action bound itself to. It is
249
+ // written after the claim, so a crash between the two leaves a claim with
250
+ // nothing to converge on — and nothing destructive happened either, so
251
+ // that case resolves from the active links below, subject to the claim
252
+ // still naming what they resolve to.
253
+ const requested = await this.#effects.readStopRequest(claim.subject);
254
+ if (requested) {
255
+ const claimed = await this.#effects.readAssignment(requested.stopsActionId);
256
+ if (!claimed || claimed.targetSessionId !== targetSessionId) {
257
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop identity is already bound to a different delegation');
258
+ }
259
+ return claimed;
260
+ }
261
+ }
262
+ const active = await this.#effects.listActiveAssignments();
263
+ const onTarget = active.filter((assignment) => assignment.targetSessionId === targetSessionId);
264
+ if (onTarget.length === 0) {
265
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub has no active durable delegation to stop on that Session');
266
+ }
267
+ // One link is the answer whatever state its work is in. Whether that work
268
+ // finished, or was never WorkHub's to stop, is what the stop resolves to —
269
+ // `already_terminal` and `not_owned` are outcomes, not reasons to refuse
270
+ // the request before it is recorded.
271
+ //
272
+ // Only several links need separating, and then the rule is the same one
273
+ // competition uses: a delegation whose work already finished is still
274
+ // linked but is no longer a stop target, so it cannot make a Session that
275
+ // was delegated to twice permanently unstoppable.
276
+ let resolved = onTarget[0];
277
+ if (onTarget.length > 1) {
278
+ const holdingWork = [];
279
+ for (const assignment of onTarget) {
280
+ if ((await this.#effects.readDelegationRetirement(assignment)) !== 'retired') {
281
+ holdingWork.push(assignment);
282
+ }
283
+ }
284
+ if (holdingWork.length !== 1) {
285
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop target does not identify one active durable delegation');
286
+ }
287
+ resolved = holdingWork[0];
288
+ }
289
+ // A claim with no request behind it resolves from the active links like a
290
+ // first attempt, but only while those links still name the delegation it
291
+ // bound itself to. If that one left and another took its place, the
292
+ // fingerprint derived here would no longer match the claim, and since
293
+ // claims are never deleted the refusal would be permanent and unexplained.
294
+ // Say why instead: the identity is spent, and the retry needs a new one.
295
+ if (claim?.operation === 'stop' && resolved.delegationId !== claim.subject) {
296
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop identity is already bound to a different delegation');
297
+ }
298
+ return resolved;
299
+ }
300
+ async #stop(request, source) {
301
+ const resolved = await this.#effects.readStopResolution(source.delegationId);
302
+ if (resolved)
303
+ return stopResultFromRecord(resolved, request);
304
+ const retirement = await this.#effects.retireDelegation(source, {
305
+ cancellationClaimId: request.actionId,
306
+ cause: 'direct_stop',
307
+ });
308
+ const outcome = retirement.outcome === 'recovering'
309
+ ? await this.#removedTargetOutcome(source)
310
+ : retirement.outcome;
311
+ if (!outcome) {
312
+ throw new WorkHubActionEffectFailure('operation_unavailable', 'WorkHub is still resolving the delegated Message owner');
313
+ }
314
+ const targetTurnId = retirement.outcome === outcome ? retirement.targetTurnId : undefined;
315
+ const resolution = await this.#effects.resolveStop({
316
+ request,
317
+ outcome,
318
+ ...(targetTurnId ? { targetTurnId } : {}),
319
+ });
320
+ return stopResultFromRecord(resolution, request);
321
+ }
322
+ /**
323
+ * A removed target Session takes its Message-ownership proof with it, so a
324
+ * committed stop claim would otherwise recover forever. The removal tombstone
325
+ * outlives that Session and proves the delegated work ended; a target that is
326
+ * merely unreadable, or an identity that never existed here, stays unresolved
327
+ * rather than being reported as stopped.
328
+ */
329
+ async #removedTargetOutcome(source) {
330
+ const lifetime = await this.#effects.probeTargetRemoval(source.targetSessionId);
331
+ return lifetime === 'removed' ? 'already_terminal' : undefined;
332
+ }
333
+ async #claimAction(actionId, operation, actionFingerprint, subject) {
334
+ const outcome = await this.#effects.claimAction({
335
+ actionId,
336
+ operation,
337
+ actionFingerprint,
338
+ subject,
339
+ });
340
+ if (outcome === 'conflict') {
341
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub action identity already owns a different operation');
342
+ }
343
+ }
168
344
  async #replacementAssignment(input, replaced) {
169
345
  if (input.proposal.disposition !== 'replace') {
170
346
  throw new WorkHubActionGateFailure('action_conflict', 'Invalid WorkHub replacement');
@@ -248,8 +424,15 @@ export class WorkHubCoordinationActionGate {
248
424
  if (retirement === 'not_retired' && replacement.disposition === 'delegate_existing') {
249
425
  await this.#replacementTarget(replacement);
250
426
  }
251
- if (retirement === 'not_retired')
252
- await this.#effects.retireDelegation(source);
427
+ if (retirement === 'not_retired') {
428
+ const result = await this.#effects.retireDelegation(source, {
429
+ cancellationClaimId: replacement.actionId,
430
+ cause: 'replacement',
431
+ });
432
+ if (result.outcome === 'recovering') {
433
+ throw new WorkHubActionEffectFailure('operation_unavailable', 'WorkHub is still resolving the delegated Message owner');
434
+ }
435
+ }
253
436
  try {
254
437
  if (replacement.disposition === 'delegate_existing') {
255
438
  // Retirement can await cancellation or Stop long enough for display
@@ -324,6 +507,7 @@ export class WorkHubCoordinationActionGate {
324
507
  }
325
508
  }
326
509
  async #assign(assignment, context) {
510
+ await this.#claimAction(assignment.actionId, assignment.replacesDelegationId ? 'replace' : assignment.disposition, assignment.actionFingerprint, assignment.replacesDelegationId ?? assignment.targetSessionId);
327
511
  const admitted = await this.#effects.assign(assignment, context);
328
512
  if (assignment.replacesDelegationId) {
329
513
  return {
@@ -486,6 +670,47 @@ function replacementActionFingerprint(input, targetSessionId) {
486
670
  },
487
671
  });
488
672
  }
673
+ function stopActionFingerprint(input, source) {
674
+ if (input.proposal.disposition !== 'stop_work') {
675
+ throw new WorkHubActionGateFailure('action_conflict', 'Invalid WorkHub stop replay');
676
+ }
677
+ return digest({
678
+ userText: input.userText,
679
+ disposition: 'stop_work',
680
+ stopsActionId: source.actionId,
681
+ stopsDelegationId: source.delegationId,
682
+ targetSessionId: source.targetSessionId,
683
+ targetMessageId: source.targetMessageId,
684
+ });
685
+ }
686
+ function assertStopReplay(request, input, source, fingerprint) {
687
+ if (request.actionId !== input.actionId ||
688
+ request.actionFingerprint !== fingerprint ||
689
+ request.stopsActionId !== source.actionId ||
690
+ request.stopsDelegationId !== source.delegationId ||
691
+ request.targetSessionId !== source.targetSessionId ||
692
+ request.targetMessageId !== source.targetMessageId) {
693
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub delegation already has a different stop claim');
694
+ }
695
+ }
696
+ function stopResult(resolution) {
697
+ return {
698
+ disposition: 'stop_work',
699
+ outcome: resolution.outcome,
700
+ targetSessionId: resolution.targetSessionId,
701
+ ...(resolution.targetTurnId ? { targetTurnId: resolution.targetTurnId } : {}),
702
+ };
703
+ }
704
+ function stopResultFromRecord(resolution, request) {
705
+ if (resolution.actionId !== request.actionId ||
706
+ resolution.actionFingerprint !== request.actionFingerprint ||
707
+ resolution.stopsActionId !== request.stopsActionId ||
708
+ resolution.stopsDelegationId !== request.stopsDelegationId ||
709
+ resolution.targetSessionId !== request.targetSessionId) {
710
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop has a different durable resolution');
711
+ }
712
+ return stopResult(resolution);
713
+ }
489
714
  function assignmentInputFromRecord(assignment) {
490
715
  return {
491
716
  actionId: assignment.actionId,