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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  28. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  29. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  30. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  31. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  32. package/node_modules/@maka/core/dist/bot-events.js +18 -63
  33. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  34. package/node_modules/@maka/core/dist/model-call-attempt.js +0 -82
  35. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -186
  36. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  37. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  38. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  39. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  40. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  41. package/node_modules/@maka/core/dist/record-schema.js +22 -2
  42. package/node_modules/@maka/core/dist/redaction.js +41 -58
  43. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  44. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  45. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  46. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  47. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  48. package/node_modules/@maka/core/dist/session-trace.js +5 -1
  49. package/node_modules/@maka/core/dist/session.js +54 -52
  50. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  51. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  52. package/node_modules/@maka/core/dist/usage-ledger-merge.js +7 -9
  53. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  54. package/node_modules/@maka/core/dist/workhub-creation-intent.js +34 -20
  55. package/node_modules/@maka/core/package.json +4 -0
  56. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +2 -1
  57. package/node_modules/@maka/mcp/dist/index.js +131 -1
  58. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  59. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  60. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  61. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +155 -134
  62. package/node_modules/@maka/runtime/dist/bots/base-adapter.js +17 -0
  63. package/node_modules/@maka/runtime/dist/bots/bot-test.js +38 -22
  64. package/node_modules/@maka/runtime/dist/bots/dingtalk-bridge.js +7 -5
  65. package/node_modules/@maka/runtime/dist/bots/discord-bridge.js +4 -4
  66. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +4 -5
  67. package/node_modules/@maka/runtime/dist/bots/qq-bridge.js +6 -4
  68. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +3 -4
  69. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +4 -5
  70. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +17 -19
  71. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +5 -6
  72. package/node_modules/@maka/runtime/dist/bots/ws-bridge-base.js +2 -3
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  75. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  76. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  77. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  78. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  79. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  80. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  81. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  82. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  83. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  84. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  85. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  86. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  87. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  88. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  89. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  90. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  91. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  92. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  93. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  94. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  95. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  96. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  97. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  98. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  99. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  100. package/node_modules/@maka/runtime/dist/session-trace-projection.js +3 -30
  101. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  102. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  103. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  104. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  105. package/node_modules/@maka/runtime/package.json +1 -0
  106. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  107. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +4 -1
  108. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  109. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  110. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  111. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  112. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  113. package/node_modules/@maka/runtime-host/dist/client/index.js +3 -1
  114. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  115. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +13 -0
  116. package/node_modules/@maka/runtime-host/dist/client/registered-host-termination.js +0 -59
  117. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  118. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  119. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  120. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  121. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +28 -16
  122. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +4 -0
  123. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +29 -12
  124. package/node_modules/@maka/runtime-host/dist/protocol/index.js +37 -1
  125. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
  126. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +28 -1
  127. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  128. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  129. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  130. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  131. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +33 -0
  132. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +26 -1
  133. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +6 -1
  134. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  135. package/node_modules/@maka/runtime-host/dist/server/canonical-usage-reader.js +24 -11
  136. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  137. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +7 -4
  138. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +168 -28
  139. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  140. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  141. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +6 -3
  142. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  143. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +108 -23
  144. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  145. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  146. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  147. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +85 -8
  148. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +7 -0
  149. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +344 -71
  150. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  151. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  152. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +201 -12
  153. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  154. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  155. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  156. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  157. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  158. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  159. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  160. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +4 -11
  161. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -15
  162. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +6 -2
  163. package/node_modules/@maka/storage/dist/agent-run-store.js +44 -0
  164. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  165. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  166. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  167. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  168. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  169. package/node_modules/@maka/storage/dist/conversation-operational-state.js +4 -0
  170. package/node_modules/@maka/storage/dist/execution-stores.js +11 -7
  171. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  172. package/node_modules/@maka/storage/dist/model-call-ledger.js +199 -32
  173. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +136 -0
  174. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  175. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  176. package/node_modules/@maka/storage/dist/operational-state-store-public.js +1 -1
  177. package/node_modules/@maka/storage/dist/operational-state-store.js +5 -3
  178. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  179. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  180. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  181. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  182. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  183. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  184. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  185. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  186. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +17 -1
  187. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  188. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  189. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  190. package/node_modules/@maka/storage/dist/sqlite-usage-schema.js +200 -20
  191. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  192. package/node_modules/@maka/storage/dist/usage-stores.js +6 -2
  193. package/node_modules/@maka/storage/package.json +2 -0
  194. package/package.json +1 -1
@@ -0,0 +1,109 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing,
13
+ * software distributed under the License is distributed on an
14
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
+ * KIND, either express or implied. See the License for the
16
+ * specific language governing permissions and limitations
17
+ * under the License.
18
+ */
19
+ const ACTIVE_DELAY_MS = 100;
20
+ const IDLE_DELAY_MS = 60_000;
21
+ const MAX_BATCH_ITEMS = 64;
22
+ const MAX_BATCH_BYTES = 16 * 1024 * 1024;
23
+ /** Physical cleanup is optional work, admitted only after the Host publishes Ready. */
24
+ export class HostStorageMaintenance {
25
+ #lanes;
26
+ #onError;
27
+ #started = false;
28
+ #draining = false;
29
+ constructor(input) {
30
+ this.#onError = input.onError;
31
+ let after;
32
+ this.#lanes = [
33
+ {
34
+ name: 'artifact upgrade cleanup',
35
+ failures: 0,
36
+ run: async () => {
37
+ const result = await input.artifacts.reclaimUpgradeResidue({
38
+ after,
39
+ maxPaths: MAX_BATCH_ITEMS,
40
+ });
41
+ after = result.nextAfter ?? undefined;
42
+ if (result.failedPaths > 0) {
43
+ this.#report('artifact upgrade cleanup', new Error(`${result.failedPaths} paths remain pending`));
44
+ }
45
+ return result.nextAfter !== null;
46
+ },
47
+ },
48
+ ];
49
+ const context = input.contextOffload;
50
+ if (context)
51
+ this.#lanes.push({
52
+ name: 'context garbage collection',
53
+ failures: 0,
54
+ run: async () => (await context.collectGarbage({
55
+ olderThan: Date.now(),
56
+ maxBlobs: MAX_BATCH_ITEMS,
57
+ maxBytes: MAX_BATCH_BYTES,
58
+ })).hasMore,
59
+ });
60
+ }
61
+ start() {
62
+ if (this.#started || this.#draining)
63
+ return;
64
+ this.#started = true;
65
+ for (const lane of this.#lanes)
66
+ this.#schedule(lane, ACTIVE_DELAY_MS);
67
+ }
68
+ beginDrain() {
69
+ this.#draining = true;
70
+ for (const lane of this.#lanes)
71
+ clearTimeout(lane.timer);
72
+ }
73
+ async close() {
74
+ this.beginDrain();
75
+ await Promise.all(this.#lanes.map((lane) => lane.pending));
76
+ }
77
+ #schedule(lane, delay) {
78
+ if (this.#draining)
79
+ return;
80
+ lane.timer = setTimeout(() => {
81
+ lane.pending = this.#run(lane);
82
+ }, delay);
83
+ lane.timer.unref();
84
+ }
85
+ async #run(lane) {
86
+ if (this.#draining)
87
+ return;
88
+ let delay;
89
+ try {
90
+ const more = await lane.run();
91
+ lane.failures = 0;
92
+ delay = more ? ACTIVE_DELAY_MS : IDLE_DELAY_MS;
93
+ }
94
+ catch (error) {
95
+ lane.failures = Math.min(lane.failures + 1, 7);
96
+ delay = Math.min(IDLE_DELAY_MS, 1000 * 2 ** (lane.failures - 1));
97
+ this.#report(lane.name, error);
98
+ }
99
+ this.#schedule(lane, delay);
100
+ }
101
+ #report(name, error) {
102
+ try {
103
+ this.#onError(name, error);
104
+ }
105
+ catch {
106
+ // Diagnostics must not terminate a maintenance lane or poison Host readiness.
107
+ }
108
+ }
109
+ }
@@ -23,7 +23,7 @@ import { BUILTIN_PRICING } from '@maka/runtime/telemetry';
23
23
  import { authenticateInteractiveUsageStoresWriter, classifyInteractiveUsageStoresFailure, } from '@maka/storage/usage-stores';
24
24
  import { isSessionNotFoundError } from '@maka/storage/execution-stores';
25
25
  import { encodePricingQueryResult, encodeUsageQueryResult, PRICING_PAGE_MAX_BYTES, PRICING_PAGE_MAX_ITEMS, USAGE_PAGE_MAX_BYTES, USAGE_PAGE_MAX_ITEMS, USAGE_PROJECTION_TEXT_MAX_BYTES, } from '../protocol/index.js';
26
- import { readCanonicalUsage } from './canonical-usage-reader.js';
26
+ import { readCanonicalUsageBuckets, readCanonicalUsageLogs, readCanonicalUsageSummary, } from './canonical-usage-reader.js';
27
27
  /** Root-scoped projection over the authentic lease-bound usage stores. */
28
28
  export class HostUsagePricingCoordinator {
29
29
  handlers = {
@@ -75,18 +75,11 @@ export class HostUsagePricingCoordinator {
75
75
  }));
76
76
  return titles;
77
77
  }
78
- /**
79
- * Reads the canonical ledger for the window a query addresses (#1679). The
80
- * range is resolved once here so both sources answer the same window.
81
- */
82
- async #canonicalUsage(query, now, repair = true) {
83
- return readCanonicalUsage(this.#stores, query, now, repair);
84
- }
85
78
  async #queryUsage(input) {
86
79
  try {
87
80
  const now = Date.now();
88
81
  if (input.kind === 'summary') {
89
- const merged = mergeUsageSummary(await this.#stores.telemetry.summary(input.query), await this.#canonicalUsage(input.query, now), input.query, now);
82
+ const merged = mergeUsageSummary(await this.#stores.telemetry.summary(input.query), await readCanonicalUsageSummary(this.#stores, input.query, now));
90
83
  // Tool executions are in their own ledger, not the model-call one, so
91
84
  // their totals ride beside the merged summary rather than inside it —
92
85
  // the same owner split the tool buckets path already follows. A
@@ -117,7 +110,7 @@ export class HostUsagePricingCoordinator {
117
110
  ? { buckets: [...legacy], provenance: EMPTY_PROVENANCE }
118
111
  : mergeUsageBuckets(legacy,
119
112
  // Only the first page repairs; later pages reuse it.
120
- await this.#canonicalUsage(input.query, now, offset === 0), input.query, input.groupBy, now);
113
+ await readCanonicalUsageBuckets(this.#stores, input.query, input.groupBy, now, offset === 0));
121
114
  if (offset > merged.buckets.length)
122
115
  return invalidUsageOffset();
123
116
  return {
@@ -142,7 +135,7 @@ export class HostUsagePricingCoordinator {
142
135
  const legacy = await this.#stores.telemetry.logs(input.query, 0, offset + limit);
143
136
  const merged = mergeUsageLogs(legacy,
144
137
  // Only the first page repairs; later pages reuse it.
145
- await this.#canonicalUsage(input.query, now, offset === 0), input.query, now, offset, limit);
138
+ await readCanonicalUsageLogs(this.#stores, input.query, now, offset + limit, offset === 0), offset, limit);
146
139
  if (offset > merged.total)
147
140
  return invalidUsageOffset();
148
141
  const titles = await this.#resolveSessionTitles(merged.rows);
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
20
  import { WORKHUB_COORDINATION_SESSION_ID, isWorkHubCoordinationSessionTarget, } from '@maka/core/session';
21
- import { readWorkHubRequestIntent, workHubCorrectionTargetsSession, workHubCreationAuthorizesTitle, } from '@maka/core/workhub-creation-intent';
21
+ import { readWorkHubRequestIntent, workHubCorrectionTargetsSession, workHubCreationAuthorizesTitle, workHubNamedDelegationActionTargetsSession, } from '@maka/core/workhub-creation-intent';
22
22
  import { WORKHUB_COORDINATION_CANDIDATE_MAX_ITEMS } from '../protocol/index.js';
23
23
  const SIDE_CONVERSATION_LABEL = 'mode:side_conversation';
24
24
  const ACTION_REPLAY_MAX_ITEMS = 256;
@@ -74,9 +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; the durable action
78
- // claim, not this map, is what owns the identity across that retry and
79
- // across restarts.
77
+ // the slot so admission can retry. Durable identity belongs to the
78
+ // owning operation: action claims for coordination writes, Host Turn
79
+ // admission for resume.
80
80
  void result.catch(() => {
81
81
  if (this.#actions.get(input.actionId) === action) {
82
82
  this.#actions.delete(input.actionId);
@@ -177,6 +177,26 @@ export class WorkHubCoordinationActionGate {
177
177
  });
178
178
  return this.#stop(requested, source);
179
179
  }
180
+ if (proposal.disposition === 'resume_work') {
181
+ if (!requestIntent.resume.imperative) {
182
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub resume requires an explicit named command in trusted user text');
183
+ }
184
+ const candidates = await this.candidates();
185
+ const target = candidates.candidates.find((candidate) => candidate.sessionId === proposal.expects.targetSessionId);
186
+ if (!target)
187
+ throw new WorkHubActionGateFailure('candidate_unavailable', 'WorkHub resume target is unavailable');
188
+ this.#assertTarget(target);
189
+ const source = await this.#soleWorkingDelegation(target.sessionId, 'resume');
190
+ if (source.actionId !== proposal.resumesActionId) {
191
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub resume target delegation changed');
192
+ }
193
+ const currentTargetName = target.sessionName;
194
+ if (!currentTargetName ||
195
+ !workHubNamedDelegationActionTargetsSession(requestIntent.resume, currentTargetName)) {
196
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub resume target is not affirmed in trusted user text');
197
+ }
198
+ return this.#effects.resume({ actionId: input.actionId, source }, context);
199
+ }
180
200
  if (proposal.disposition === 'create_new') {
181
201
  if (!input.create || !workHubCreationAuthorizesTitle(requestIntent, proposal.title)) {
182
202
  throw new WorkHubActionGateFailure('action_conflict', 'WorkHub creation requires an unambiguous instruction and creation context');
@@ -259,9 +279,22 @@ export class WorkHubCoordinationActionGate {
259
279
  return claimed;
260
280
  }
261
281
  }
282
+ const resolved = await this.#soleWorkingDelegation(targetSessionId, 'stop');
283
+ // A claim with no request behind it resolves from the active links like a
284
+ // first attempt, but only while those links still name the delegation it
285
+ // bound itself to. If that one left and another took its place, the
286
+ // fingerprint derived here would no longer match the claim, and since
287
+ // claims are never deleted the refusal would be permanent and unexplained.
288
+ // Say why instead: the identity is spent, and the retry needs a new one.
289
+ if (claim?.operation === 'stop' && resolved.delegationId !== claim.subject) {
290
+ throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop identity is already bound to a different delegation');
291
+ }
292
+ return resolved;
293
+ }
294
+ async #soleWorkingDelegation(targetSessionId, operation) {
262
295
  const onTarget = await this.#effects.listActiveAssignments(targetSessionId);
263
296
  if (onTarget.length === 0) {
264
- throw new WorkHubActionGateFailure('action_conflict', 'WorkHub has no active durable delegation to stop on that Session');
297
+ throw new WorkHubActionGateFailure('action_conflict', `WorkHub has no active durable delegation to ${operation} on that Session`);
265
298
  }
266
299
  // One link is the answer whatever state its work is in. Whether that work
267
300
  // finished, or was never WorkHub's to stop, is what the stop resolves to —
@@ -281,19 +314,10 @@ export class WorkHubCoordinationActionGate {
281
314
  }
282
315
  }
283
316
  if (holdingWork.length !== 1) {
284
- throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop target does not identify one active durable delegation');
317
+ throw new WorkHubActionGateFailure('action_conflict', `WorkHub ${operation} target does not identify one active durable delegation`);
285
318
  }
286
319
  resolved = holdingWork[0];
287
320
  }
288
- // A claim with no request behind it resolves from the active links like a
289
- // first attempt, but only while those links still name the delegation it
290
- // bound itself to. If that one left and another took its place, the
291
- // fingerprint derived here would no longer match the claim, and since
292
- // claims are never deleted the refusal would be permanent and unexplained.
293
- // Say why instead: the identity is spent, and the retry needs a new one.
294
- if (claim?.operation === 'stop' && resolved.delegationId !== claim.subject) {
295
- throw new WorkHubActionGateFailure('action_conflict', 'WorkHub stop identity is already bound to a different delegation');
296
- }
297
321
  return resolved;
298
322
  }
299
323
  async #stop(request, source) {
@@ -608,6 +632,11 @@ function delegationAssignment(input, actionFingerprint, targetSessionId, targetS
608
632
  function workHubCreatedSessionId(actionId) {
609
633
  return `whs_${hash(`create\0${actionId}`).slice(0, 48)}`;
610
634
  }
635
+ // One request cannot resume a later interruption after a lost response and restart.
636
+ // Host admission rejects reuse of this Turn id for a different source boundary.
637
+ export function workHubResumedTurnId(actionId) {
638
+ return `wht_${hash(`resume\0${actionId}`).slice(0, 48)}`;
639
+ }
611
640
  function workspaceProjection(session) {
612
641
  return {
613
642
  target: typeof session.projectId === 'string'
@@ -110,6 +110,11 @@ export class HostWorkHubCoordinationCoordinator {
110
110
  resolveStop: (input) => this.#resolveStop(input),
111
111
  readDelegationRetirement: options.sessionActions.readDelegationRetirement,
112
112
  retireDelegation: options.sessionActions.retireDelegation,
113
+ resume: async (input, context) => ({
114
+ disposition: 'resume_work',
115
+ targetSessionId: input.source.targetSessionId,
116
+ ...(await options.sessionActions.resumeDelegation(input.source, context, input.actionId)),
117
+ }),
113
118
  });
114
119
  }
115
120
  #prepareReplacement(input) {
@@ -342,7 +347,7 @@ export class HostWorkHubCoordinationCoordinator {
342
347
  return {
343
348
  ok: false,
344
349
  error: {
345
- code: error.code === 'unauthorized' ? 'operation_unavailable' : error.code,
350
+ code: error.code,
346
351
  message: error.message,
347
352
  },
348
353
  };
@@ -614,7 +619,6 @@ function coordinationSummaryMessages(input) {
614
619
  turnId: input.turnId,
615
620
  ts: ts + 2,
616
621
  status: 'completed',
617
- partialOutputRetained: false,
618
622
  },
619
623
  ];
620
624
  }
@@ -258,6 +258,26 @@ class SqliteAgentRunStore {
258
258
  if (readSqliteRootTurnStartRejection(this.#lease.database, admission.sessionId, admission.turnId)) {
259
259
  throw new Error('Root Turn identity is already rejected');
260
260
  }
261
+ if (admission.execution.kind === 'safe_boundary_continuation') {
262
+ const sourceOwner = this.#lease.database
263
+ .prepare(`
264
+ SELECT turn_id
265
+ FROM core_root_turn_admissions
266
+ WHERE session_id = ?
267
+ AND json_extract(record_json, '$.execution.sourceTurnId') = ?
268
+ AND json_extract(record_json, '$.execution.sourceRunId') = ?
269
+ AND json_extract(record_json, '$.execution.kind') = 'safe_boundary_continuation'
270
+ ORDER BY admitted_at, turn_id
271
+ LIMIT 1
272
+ `)
273
+ .get(admission.sessionId, admission.execution.sourceTurnId, admission.execution.sourceRunId);
274
+ if (typeof sourceOwner?.turn_id === 'string') {
275
+ const owner = readSqliteRootTurnAdmission(this.#lease.database, admission.sessionId, sourceOwner.turn_id);
276
+ if (!owner)
277
+ throw new Error('Root continuation index has no durable admission');
278
+ return { kind: 'conflict', admission: owner };
279
+ }
280
+ }
261
281
  for (const source of admission.sourceMessages) {
262
282
  const proof = this.#lease.database
263
283
  .prepare(`
@@ -293,6 +313,30 @@ class SqliteAgentRunStore {
293
313
  assertSafeId(turnId, 'Invalid turn id');
294
314
  return readSqliteRootTurnAdmission(this.#lease.database, sessionId, turnId);
295
315
  }
316
+ async readRootTurnContinuationAdmission(sessionId, sourceTurnId, sourceRunId) {
317
+ assertSafeId(sessionId, 'Invalid session id');
318
+ assertSafeId(sourceTurnId, 'Invalid source turn id');
319
+ assertSafeId(sourceRunId, 'Invalid source run id');
320
+ const row = this.#lease.database
321
+ .prepare(`
322
+ SELECT turn_id, record_json
323
+ FROM core_root_turn_admissions
324
+ WHERE session_id = ?
325
+ AND json_extract(record_json, '$.execution.sourceTurnId') = ?
326
+ AND json_extract(record_json, '$.execution.sourceRunId') = ?
327
+ AND json_extract(record_json, '$.execution.kind') = 'safe_boundary_continuation'
328
+ ORDER BY admitted_at, turn_id
329
+ LIMIT 1
330
+ `)
331
+ .get(sessionId, sourceTurnId, sourceRunId);
332
+ if (!row)
333
+ return undefined;
334
+ if (typeof row.turn_id !== 'string' || typeof row.record_json !== 'string') {
335
+ throw new Error('Invalid SQLite root turn continuation admission row');
336
+ }
337
+ const admission = normalizeRootTurnAdmission(JSON.parse(row.record_json), sessionId, row.turn_id);
338
+ return admission;
339
+ }
296
340
  async readRootTurnStartRejection(sessionId, turnId) {
297
341
  assertSafeId(sessionId, 'Invalid session id');
298
342
  assertSafeId(turnId, 'Invalid turn id');
@@ -240,18 +240,22 @@ class SqliteArtifactStore {
240
240
  * once its file is gone, and a file that will not go keeps only its own note
241
241
  * rather than holding up the ones behind it.
242
242
  */
243
- async reclaimUpgradeResidue() {
244
- await this.enqueueMutation(async () => {
245
- await this.prepareMutationUnlocked();
246
- const recorded = this.metadataRepository.readUpgradeOrphanPaths();
247
- if (recorded.length === 0)
248
- return;
249
- const claimed = new Set(this.records.map((record) => record.relativePath));
243
+ async reclaimUpgradeResidue(input) {
244
+ if (!Number.isSafeInteger(input.maxPaths) || input.maxPaths < 1 || input.maxPaths > 1024) {
245
+ throw new TypeError('Artifact cleanup path limit must be between 1 and 1024');
246
+ }
247
+ const after = input.after ?? '';
248
+ const maxPaths = input.maxPaths;
249
+ return this.enqueueMutation(async () => {
250
+ const recorded = this.metadataRepository.readUpgradeOrphanPaths(after, maxPaths + 1);
251
+ const selected = recorded.slice(0, maxPaths);
250
252
  const directories = new Set();
251
253
  const discharged = [];
254
+ let failedPaths = 0;
252
255
  try {
253
- for (const relativePath of recorded) {
254
- if (claimed.has(relativePath) || !isSafeRelativeArtifactPath(relativePath)) {
256
+ for (const relativePath of selected) {
257
+ if (this.metadataRepository.hasRelativePath(relativePath) ||
258
+ !isSafeRelativeArtifactPath(relativePath)) {
255
259
  discharged.push(relativePath);
256
260
  continue;
257
261
  }
@@ -261,8 +265,10 @@ class SqliteArtifactStore {
261
265
  directories.add(dirname(target));
262
266
  }
263
267
  catch (error) {
264
- if (!isNotFound(error))
268
+ if (!isNotFound(error)) {
269
+ failedPaths += 1;
265
270
  continue;
271
+ }
266
272
  }
267
273
  discharged.push(relativePath);
268
274
  }
@@ -273,6 +279,11 @@ class SqliteArtifactStore {
273
279
  }
274
280
  if (discharged.length > 0)
275
281
  this.metadataRepository.forgetUpgradeOrphanPaths(discharged);
282
+ return {
283
+ nextAfter: recorded.length > selected.length ? selected.at(-1) : null,
284
+ processedPaths: selected.length,
285
+ failedPaths,
286
+ };
276
287
  });
277
288
  }
278
289
  async replayExistingArtifactUnlocked(existing, input, canonical) {
@@ -103,7 +103,7 @@ function createWriterFacade(lease, authority) {
103
103
  return run(() => store.copyConversationArtifacts(acceptedInput));
104
104
  },
105
105
  purgeSessionArtifacts: (sessionId) => run(() => store.purgeSessionArtifacts(sessionId)),
106
- reclaimUpgradeResidue: () => run(() => store.reclaimUpgradeResidue()),
106
+ reclaimUpgradeResidue: (input) => run(() => store.reclaimUpgradeResidue(input)),
107
107
  deleteUserArtifactInSession: (sessionId, artifactId) => run(() => store.deleteUserArtifactInSession(sessionId, artifactId)),
108
108
  close: () => {
109
109
  if (writerByLease.get(lease) === facade)
@@ -393,7 +393,6 @@ export function convertTranscript(sessionId, rawRecords) {
393
393
  status: 'aborted',
394
394
  abortedAt: turn.lastTs,
395
395
  abortSource: 'claude-code.interrupt',
396
- partialOutputRetained: true,
397
396
  });
398
397
  }
399
398
  else if (turn.failed) {
@@ -404,7 +403,6 @@ export function convertTranscript(sessionId, rawRecords) {
404
403
  ts: turn.lastTs,
405
404
  status: 'failed',
406
405
  errorClass: 'claude_code_api_error',
407
- partialOutputRetained: true,
408
406
  });
409
407
  }
410
408
  else if (turn.terminalStop) {
@@ -414,7 +412,6 @@ export function convertTranscript(sessionId, rawRecords) {
414
412
  turnId: turn.turnId,
415
413
  ts: turn.lastTs,
416
414
  status: 'completed',
417
- partialOutputRetained: true,
418
415
  });
419
416
  }
420
417
  else {
@@ -426,7 +423,6 @@ export function convertTranscript(sessionId, rawRecords) {
426
423
  status: 'aborted',
427
424
  abortedAt: turn.lastTs,
428
425
  abortSource: EXTERNAL_SNAPSHOT_ABORT_SOURCE,
429
- partialOutputRetained: true,
430
426
  });
431
427
  }
432
428
  turn = undefined;
@@ -378,7 +378,6 @@ function convertCodexRollout(text, expectedSessionId, fallbackName, fallbackCwd)
378
378
  ts: timestampFor(record),
379
379
  status: failed ? 'failed' : 'completed',
380
380
  ...(failed ? { errorClass: 'codex_error' } : {}),
381
- partialOutputRetained: true,
382
381
  });
383
382
  failedTurnIds.delete(turnId);
384
383
  if (activeTurnId === turnId) {
@@ -398,7 +397,6 @@ function convertCodexRollout(text, expectedSessionId, fallbackName, fallbackCwd)
398
397
  status: 'aborted',
399
398
  abortedAt: normalizeEpochMs(payload.completed_at) ?? ts,
400
399
  abortSource: stringField(payload, 'reason') ?? 'codex',
401
- partialOutputRetained: true,
402
400
  });
403
401
  if (activeTurnId === turnId) {
404
402
  activeTurnId = undefined;