maka-agent 0.2.0-dev.23.20260906 → 0.2.0-dev.25.20260908

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 (215) hide show
  1. package/README.md +38 -19
  2. package/README.zh-CN.md +34 -19
  3. package/dist/acp/maka-acp-agent.js +2 -1
  4. package/dist/acp/session-configuration.js +143 -0
  5. package/dist/acp/session-registry.js +90 -4
  6. package/dist/cli-core.js +2 -0
  7. package/dist/pi-transcript-tools.js +6 -0
  8. package/dist/pi-transcript.js +5 -12
  9. package/dist/pi-tui-layout.js +56 -10
  10. package/dist/pi-tui-pickers.js +102 -1
  11. package/dist/pi-tui-runner.js +230 -46
  12. package/dist/pi-tui-todo.js +221 -0
  13. package/dist/pi-tui-transcript-viewer.js +134 -7
  14. package/dist/runtime-host-cli-context.js +224 -78
  15. package/dist/runtime-host-cli-installation.js +8 -2
  16. package/dist/runtime-host-cli.js +31 -1
  17. package/dist/runtime-host-handoff-surface.js +106 -0
  18. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  19. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  20. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  21. package/dist/runtime-host-local-handoff.js +48 -5
  22. package/dist/runtime-host-local-managed-activation.js +84 -0
  23. package/dist/runtime-host-local-source-retirement.js +18 -2
  24. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  25. package/dist/runtime-host-operator-retirement.js +50 -0
  26. package/dist/runtime-host-service-manager.js +3 -3
  27. package/dist/runtime-host-session-channel.js +13 -0
  28. package/dist/runtime-host-session-driver.js +46 -26
  29. package/dist/runtime-host-session-update.js +62 -0
  30. package/dist/runtime-host-tui-command.js +38 -73
  31. package/dist/runtime-host-tui-context.js +1 -0
  32. package/dist/runtime-host-tui-owner.js +226 -0
  33. package/dist/tui-copy-catalog.js +219 -6
  34. package/dist/tui-host-owner-copy.js +24 -0
  35. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  36. package/node_modules/@maka/core/dist/agent-run.js +1 -0
  37. package/node_modules/@maka/core/dist/attachments.js +3 -0
  38. package/node_modules/@maka/core/dist/canonical-json.js +27 -0
  39. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  40. package/node_modules/@maka/core/dist/capabilities.js +35 -0
  41. package/node_modules/@maka/core/dist/computer-use.js +0 -1
  42. package/node_modules/@maka/core/dist/display-redaction.js +18 -0
  43. package/node_modules/@maka/core/dist/llm-connections.js +13 -0
  44. package/node_modules/@maka/core/dist/model-call-attempt.js +2 -0
  45. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  46. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  47. package/node_modules/@maka/core/dist/model-metadata.js +7 -3
  48. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  49. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  50. package/node_modules/@maka/core/dist/record-schema.js +9 -2
  51. package/node_modules/@maka/core/dist/redaction.js +35 -0
  52. package/node_modules/@maka/core/dist/run-composition.js +77 -2
  53. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  54. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  55. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  56. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  57. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  58. package/node_modules/@maka/core/dist/session.js +84 -56
  59. package/node_modules/@maka/core/dist/slash-command-catalog.js +3 -0
  60. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  61. package/node_modules/@maka/core/dist/tool-result-record-schema.js +2 -1
  62. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  63. package/node_modules/@maka/core/package.json +5 -0
  64. package/node_modules/@maka/eval/dist/experiment-directory.js +4 -13
  65. package/node_modules/@maka/mcp/dist/index.js +131 -1
  66. package/node_modules/@maka/runtime/dist/agent-run-inspect.js +0 -13
  67. package/node_modules/@maka/runtime/dist/agent-run.js +351 -105
  68. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +29 -13
  69. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  70. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +184 -183
  71. package/node_modules/@maka/runtime/dist/archive-read-tool.js +2 -2
  72. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +0 -16
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +158 -15
  75. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +3 -3
  76. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  77. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  78. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  79. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  80. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +174 -0
  81. package/node_modules/@maka/runtime/dist/mcp-tools.js +7 -2
  82. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  83. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  84. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  85. package/node_modules/@maka/runtime/dist/model-fetcher.js +49 -2
  86. package/node_modules/@maka/runtime/dist/model-history.js +0 -112
  87. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  88. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  89. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  90. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  91. package/node_modules/@maka/runtime/dist/plugin-runtime.js +20 -10
  92. package/node_modules/@maka/runtime/dist/plugin-tool-service.js +205 -0
  93. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  94. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +76 -109
  95. package/node_modules/@maka/runtime/dist/request-shape.js +23 -0
  96. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  97. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +83 -55
  98. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +121 -159
  99. package/node_modules/@maka/runtime/dist/runtime-kernel.js +157 -112
  100. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  101. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  102. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  103. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  104. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  105. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  106. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +21 -0
  107. package/node_modules/@maka/runtime/dist/stream-graph-supervisor-tools.js +0 -5
  108. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  109. package/node_modules/@maka/runtime/dist/test-connection.js +16 -17
  110. package/node_modules/@maka/runtime/dist/tool-activation-identity.js +41 -0
  111. package/node_modules/@maka/runtime/dist/tool-availability.js +11 -1
  112. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  113. package/node_modules/@maka/runtime/dist/tool-result-archive-resource.js +63 -1
  114. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +42 -12
  115. package/node_modules/@maka/runtime/dist/tool-result-archive.js +27 -4
  116. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  117. package/node_modules/@maka/runtime/package.json +2 -0
  118. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  119. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  120. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  121. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +179 -0
  122. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +275 -0
  123. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  124. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -0
  125. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  126. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  127. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +46 -5
  128. package/node_modules/@maka/runtime-host/dist/control/endpoint.js +1 -3
  129. package/node_modules/@maka/runtime-host/dist/node-error.js +22 -0
  130. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  131. package/node_modules/@maka/runtime-host/dist/operator/managed-deployment.js +1 -3
  132. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  133. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +0 -1
  134. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +1 -1
  135. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +1 -3
  136. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +21 -12
  137. package/node_modules/@maka/runtime-host/dist/protocol/index.js +29 -1
  138. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  139. package/node_modules/@maka/runtime-host/dist/protocol/plan.js +1 -0
  140. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +27 -5
  141. package/node_modules/@maka/runtime-host/dist/protocol/project-catalog.js +2 -2
  142. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  143. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  144. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  145. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  146. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +31 -2
  147. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  148. package/node_modules/@maka/runtime-host/dist/server/agent-graph-coordinator.js +0 -3
  149. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  150. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  151. package/node_modules/@maka/runtime-host/dist/server/execution-artifacts.js +32 -32
  152. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +144 -33
  153. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  154. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +45 -16
  155. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  156. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +96 -17
  157. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  158. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  159. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  160. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +47 -22
  161. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +76 -6
  162. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  163. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +6 -0
  164. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +325 -73
  165. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  166. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  167. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +50 -7
  168. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  169. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +5 -2
  170. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +12 -55
  171. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  172. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  173. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  174. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  175. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  176. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +20 -2
  177. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +13 -4
  178. package/node_modules/@maka/runtime-host/dist/server/workhub-message-attachments.js +46 -0
  179. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  180. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  181. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -5
  182. package/node_modules/@maka/storage/dist/codex-session-adapter.js +284 -198
  183. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  184. package/node_modules/@maka/storage/dist/execution-stores.js +9 -7
  185. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  186. package/node_modules/@maka/storage/dist/git-exec.js +61 -0
  187. package/node_modules/@maka/storage/dist/git-worktree-child-executor.js +8 -35
  188. package/node_modules/@maka/storage/dist/goal-authority.js +2 -2
  189. package/node_modules/@maka/storage/dist/interaction-store.js +2 -2
  190. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  191. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  192. package/node_modules/@maka/storage/dist/project-catalog.js +2 -23
  193. package/node_modules/@maka/storage/dist/runtime-event-invariants.js +2 -2
  194. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  195. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +8 -3
  196. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  197. package/node_modules/@maka/storage/dist/scheduled-task-store.js +249 -283
  198. package/node_modules/@maka/storage/dist/session-bundle-manifest.js +5 -17
  199. package/node_modules/@maka/storage/dist/session-bundle-policy.js +26 -5
  200. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +2 -1
  201. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  202. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  203. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  204. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  205. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  206. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +7 -1
  207. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  208. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +130 -27
  209. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  210. package/node_modules/@maka/storage/dist/storage-id.js +28 -0
  211. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +138 -0
  212. package/node_modules/@maka/storage/dist/workspace-identity.js +2 -15
  213. package/node_modules/@maka/storage/dist/workspace-version-authority-internal.js +1 -8
  214. package/node_modules/@maka/storage/package.json +2 -0
  215. package/package.json +1 -1
@@ -22,7 +22,7 @@ import { isAbsolute, resolve } from 'node:path';
22
22
  import { MAX_ATTACHMENT_BYTES } from '@maka/core/attachments';
23
23
  import { createToolResultArchiveCapability, } from '@maka/runtime/tool-result-archive-capability';
24
24
  import { isPathInside } from '@maka/runtime/path-containment';
25
- import { stableToolResultArchiveArtifactId } from '@maka/runtime/tool-result-archive';
25
+ import { createLedgerArchivePreparer, createLedgerArchiveResourceReader, createLedgerToolResultArchiveReader, } from '@maka/runtime/ledger-tool-result-archive-reader';
26
26
  export function createHostExecutionArtifactServices(input) {
27
27
  const runWrite = async (operation) => {
28
28
  try {
@@ -58,6 +58,30 @@ export function createHostExecutionArtifactServices(input) {
58
58
  });
59
59
  }
60
60
  };
61
+ const prepareLedger = input.archiveEvidence
62
+ ? createLedgerArchivePreparer(input.archiveEvidence)
63
+ : undefined;
64
+ const readLedger = input.archiveEvidence
65
+ ? createLedgerToolResultArchiveReader(input.archiveEvidence)
66
+ : undefined;
67
+ const readLedgerResource = input.archiveEvidence
68
+ ? createLedgerArchiveResourceReader(input.archiveEvidence)
69
+ : undefined;
70
+ const prepareLedgerForCommit = async (event) => {
71
+ const accepted = { ...event };
72
+ if (!prepareLedger || !(await prepareLedger(accepted)))
73
+ return;
74
+ return {
75
+ ledger: true,
76
+ commitTransition: (transition, persist) => input.sessionAdmission.runOrJoin(accepted.sessionId, async () => {
77
+ if ((await input.sessions.probeSessionRemoval(accepted.sessionId)).kind !== 'present' ||
78
+ !(await prepareLedger(accepted)))
79
+ return false;
80
+ await persist(transition);
81
+ return true;
82
+ }),
83
+ };
84
+ };
61
85
  const services = {
62
86
  recordToolArtifacts,
63
87
  publishChildWorkspacePatch: async ({ sessionId, turnId, binding, patch }) => {
@@ -77,37 +101,13 @@ export function createHostExecutionArtifactServices(input) {
77
101
  return artifact;
78
102
  },
79
103
  toolResultArchive: createToolResultArchiveCapability({
80
- archiveToolResult: (event) => runWrite(async () => {
81
- const artifactId = stableToolResultArchiveArtifactId(event);
82
- const existing = await input.artifacts.getInSession(event.sessionId, artifactId);
83
- if (existing.record) {
84
- const read = await readArchive(input.artifacts, {
85
- artifactId,
86
- sessionId: event.sessionId,
87
- bodySha256: event.bodySha256,
88
- originalBytes: event.originalBytes,
89
- maxBytes: event.originalBytes,
90
- });
91
- if (!read.ok) {
92
- throw new Error(`Tool result archive identity conflict: ${read.reason}`);
93
- }
94
- return { artifactId };
95
- }
96
- const artifact = await input.artifacts.create({
97
- id: artifactId,
98
- sessionId: event.sessionId,
99
- turnId: event.turnId,
100
- name: `archived-${event.toolName}-${event.runtimeEventId}.json`,
101
- kind: 'file',
102
- content: event.serializedResult,
103
- mimeType: 'application/json',
104
- source: 'tool_result_archive',
105
- summary: `Archived ${event.toolName} tool result for context budget replay`,
106
- });
107
- return { artifactId: artifact.id };
108
- }),
109
- readToolResultArchive: (event) => readArchive(input.artifacts, event),
110
- readArchivedToolResultResource: (event) => readArchive(input.artifacts, event),
104
+ archiveToolResult: prepareLedgerForCommit,
105
+ readToolResultArchive: (event) => event.rewriteVersion === 2
106
+ ? (readLedger?.(event) ?? { ok: false, reason: 'read_failed' })
107
+ : readArchive(input.artifacts, event),
108
+ readArchivedToolResultResource: (event) => event.storage === 'ledger'
109
+ ? (readLedgerResource?.(event) ?? { ok: false, reason: 'read_failed' })
110
+ : readArchive(input.artifacts, event),
111
111
  }),
112
112
  };
113
113
  return Object.freeze(services);
@@ -16,12 +16,14 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { copyWorkHubAttachmentsToTarget } from './workhub-message-attachments.js';
19
20
  import { createHash, randomUUID } from 'node:crypto';
20
21
  import { MAX_READ_IMAGE_BYTES } from '@maka/core/attachments';
21
22
  import { messageContentDigest, normalizeMessageContent } from '@maka/core/events';
22
23
  import { NO_REAL_CONNECTION_CODE } from '@maka/core/connection-error-copy';
23
24
  import { generalizedErrorMessage } from '@maka/core/redaction';
24
25
  import { emptyPlanSessionState } from '@maka/core/plan';
26
+ import { readLogicalRuntimeExecutionForRun } from '@maka/core/runtime-logical-execution';
25
27
  import { runtimeInvocationOutcome, } from '@maka/core/runtime-invocation';
26
28
  import { isDeepResearchSession, WORKHUB_COORDINATION_SESSION_ID, WORKHUB_COORDINATION_REPLACEMENT_SCHEMA_VERSION, } from '@maka/core/session';
27
29
  import { AgentGraphCoordinator } from '@maka/runtime/stream-graph-coordinator';
@@ -42,6 +44,9 @@ import { renderAgentSwarmSupervisorWake, shouldWakeAgentSwarmSupervisor, } from
42
44
  import { SessionActivityRegistry } from '@maka/runtime/goal-turn-lifecycle';
43
45
  import { ShellRunProcessManager } from '@maka/runtime/shell-run-manager';
44
46
  import { resolveShellPlan, resolveTurnShellPlan, validateShellPreference, } from '@maka/runtime/shell-detect';
47
+ import { Context } from '@maka/runtime/plugin-kernel';
48
+ import { MakaCompositionLoader } from '@maka/runtime/plugin-composition-loader';
49
+ import { PluginToolService } from '@maka/runtime/plugin-tool-service';
45
50
  import { isHostedExecutionTerminal } from './hosted-execution-authority.js';
46
51
  import { createAgentGraphControlStore } from '@maka/storage/agent-graph-control-store';
47
52
  import { createArtifactAttachmentResourceReader } from '@maka/storage/artifact-stores';
@@ -77,7 +82,7 @@ import { HostGoalCoordinator } from './goal-coordinator.js';
77
82
  import { HostGoalExecutionCoordinator } from './goal-execution-coordinator.js';
78
83
  import { HostHostedExecutionCoordinator } from './hosted-execution-coordinator.js';
79
84
  import { HostHostedExecutionRunner } from './hosted-execution-runner.js';
80
- import { executeHostedExecutionToSettlement } from './hosted-execution-wait.js';
85
+ import { executeHostedExecutionToSettlement, waitForHostedExecutionIdleOrAbort, } from './hosted-execution-wait.js';
81
86
  import { beginRuntimeHostDomainModuleDrain, closeRuntimeHostDomainModules, composeRuntimeHostDomainHandlers, createRuntimeHostDomainModule, recoverRuntimeHostDomainModules, } from './host-composition.js';
82
87
  import { HostInteractionCoordinator } from './interaction-coordinator.js';
83
88
  import { HostInteractiveTurnCoordinator } from './interactive-turn-coordinator.js';
@@ -108,10 +113,11 @@ import { SessionAdmissionGate } from './session-admission-gate.js';
108
113
  import { HostSessionCatalogCoordinator } from './session-catalog-coordinator.js';
109
114
  import { HostWorkspaceResolver } from './workspace-resolver.js';
110
115
  import { HostSessionRetirementCoordinator } from './session-retirement-coordinator.js';
116
+ import { HostStorageMaintenance } from './storage-maintenance.js';
111
117
  import { HostSessionRevisionCoordinator } from './session-revision-coordinator.js';
112
118
  import { HostSessionEffectCoordinator } from './session-effect-coordinator.js';
113
119
  import { SessionContinuityCoordinator } from './session-continuity-coordinator.js';
114
- import { createSessionTranscriptReader } from './session-transcript-reader.js';
120
+ import { createSessionTranscriptReader, } from './session-transcript-reader.js';
115
121
  import { HostSkillCatalogCoordinator } from './skill-catalog-coordinator.js';
116
122
  import { SkillCatalogRepository } from './skill-catalog-repository.js';
117
123
  import { HostSessionTodoCoordinator } from './session-todo-coordinator.js';
@@ -123,6 +129,7 @@ import { WorkHubActionEffectFailure, workHubResumedTurnId, } from './workhub-coo
123
129
  import { createHostWebSearchService, createHostWebSearchToolFromService, resolveHostTavilyWebSearchReadiness, shouldResolveHostTavilyWebSearchReadiness, } from './web-search-tool.js';
124
130
  import { createHostWebFetchService, createHostWebFetchToolFromService } from './web-fetch-tool.js';
125
131
  import { createHostExecutionArtifactServices } from './execution-artifacts.js';
132
+ import { openToolResultArchiveEvidenceReader } from '@maka/storage/tool-result-archive-evidence';
126
133
  import { createRuntimeHostWorkspaceExecutionComposition, RuntimeHostWorkspaceExecutionError, } from './workspace-execution-composition.js';
127
134
  const GIBIBYTE = 1024 * 1024 * 1024;
128
135
  const CONTEXT_OFFLOAD_LIMITS = Object.freeze({
@@ -160,13 +167,21 @@ export async function createExecutionRuntimeHostComposition(context, options = {
160
167
  let sessionEffects;
161
168
  let memoryExtraction;
162
169
  let unsubscribeTranscriptChanges;
170
+ let transcriptReader;
163
171
  let unsubscribeUsageChanges;
164
172
  let workspaceExecution;
165
173
  let goalExecutions;
166
174
  let pluginPlatform;
175
+ let manager;
167
176
  let modelMetadataRefresh;
177
+ let archiveEvidence;
168
178
  try {
169
- pluginPlatform = new HostPluginPlatform(context.owner.controlDirectory);
179
+ const pluginRoot = new Context();
180
+ const pluginTools = new PluginToolService(pluginRoot);
181
+ pluginPlatform = new HostPluginPlatform(context.owner.controlDirectory, {
182
+ composition: new MakaCompositionLoader({ root: pluginRoot }),
183
+ tools: pluginTools,
184
+ });
170
185
  const pluginPlatformCoordinator = new HostPluginPlatformCoordinator(pluginPlatform);
171
186
  const openedProjectCatalog = storage.projectCatalog;
172
187
  const runtimePolicyStores = storage.runtimePolicy;
@@ -198,9 +213,6 @@ export async function createExecutionRuntimeHostComposition(context, options = {
198
213
  cause: storage.contextOffloadUnavailable?.cause,
199
214
  });
200
215
  },
201
- collectGarbage: async () => {
202
- throw new Error('Context-offload Store is unavailable during context garbage collection', { cause: storage.contextOffloadUnavailable?.cause });
203
- },
204
216
  }
205
217
  : undefined;
206
218
  const openedUsageStores = storage.usage;
@@ -229,7 +241,6 @@ export async function createExecutionRuntimeHostComposition(context, options = {
229
241
  const memoryExtractionLane = new MemoryExtractionSessionLane();
230
242
  let runtimeResources;
231
243
  let continuity;
232
- let manager;
233
244
  let graphCoordinator;
234
245
  let graphSupervisorWake;
235
246
  const graphWakeActivities = new SessionActivityRegistry();
@@ -281,7 +292,9 @@ export async function createExecutionRuntimeHostComposition(context, options = {
281
292
  resolveShell: async () => resolveShellPlan((await runtimePolicyStores.runtimePolicy.getSnapshot()).policy.shell),
282
293
  onProjectionChanged: (update) => requireContinuity(continuity).enqueueRuntimeResourceChanged(update),
283
294
  });
295
+ archiveEvidence = await openToolResultArchiveEvidenceReader(context.owner.lease);
284
296
  const executionArtifacts = createHostExecutionArtifactServices({
297
+ archiveEvidence,
285
298
  artifacts: openedArtifactStore,
286
299
  requestDrain: context.requestDrain,
287
300
  sessionAdmission,
@@ -404,6 +417,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
404
417
  hostEpoch: context.hostEpoch,
405
418
  root: rootPort,
406
419
  durableProof: {
420
+ readLogicalExecution: (identity) => readLogicalRuntimeExecutionForRun(stores.runtimeEventStore, identity),
407
421
  readRootTurnSourceMessageReceipt: (sessionId, messageId) => stores.agentRunStore.readRootTurnSourceMessageReceipt(sessionId, messageId),
408
422
  readImmutableSteeringMessageProof: (sessionId, messageId) => stores.runtimeEventStore.readImmutableSteeringMessageProof(sessionId, messageId),
409
423
  },
@@ -425,7 +439,12 @@ export async function createExecutionRuntimeHostComposition(context, options = {
425
439
  const canonicalPermissionOutcomes = new HostCanonicalPermissionOutcomeReader({
426
440
  store: stores.interactionStore,
427
441
  });
428
- continuity = new SessionContinuityCoordinator(context.hostEpoch, (sessionId) => canonicalProjectionReader.read(sessionId), sessionAdmission, context.requestDrain, createSessionTranscriptReader({ stores, canonicalPermissionOutcomes }), (sessionId) => hostChanges.publishSessionCatalog(sessionId), context.sessionAccessAuthority);
442
+ transcriptReader = createSessionTranscriptReader({
443
+ stores,
444
+ canonicalPermissionOutcomes,
445
+ ensureTranscriptLedger: (sessionId) => requireSessionManager(manager).ensureTranscriptLedgerForRead(sessionId),
446
+ });
447
+ continuity = new SessionContinuityCoordinator(context.hostEpoch, (sessionId) => canonicalProjectionReader.read(sessionId), sessionAdmission, context.requestDrain, transcriptReader, (sessionId) => hostChanges.publishSessionCatalog(sessionId), context.sessionAccessAuthority);
429
448
  const continuityCoordinator = continuity;
430
449
  unsubscribeTranscriptChanges = stores.sessionStore.subscribeTranscriptChanges((sessionId) => continuityCoordinator.enqueueCanonicalRefresh(sessionId));
431
450
  unsubscribeUsageChanges = openedUsageStores.subscribeSessionUsageChanges((sessionId) => continuityCoordinator.enqueueSessionDomainChanged(sessionId, 'usage'));
@@ -531,6 +550,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
531
550
  builtinTools,
532
551
  hostTools,
533
552
  resolveRootTools: (sessionId) => requireGraphCoordinator(graphCoordinator).toolsForSession(sessionId),
553
+ resolvePluginTools: (sessionId, coreTools) => pluginTools.resolveContributions(sessionId, coreTools),
534
554
  parentAgentTools: childAgentTools.parentTools,
535
555
  childTools: childAgentTools.childTools,
536
556
  worktreePatchWriteBackAvailable: true,
@@ -713,6 +733,10 @@ export async function createExecutionRuntimeHostComposition(context, options = {
713
733
  throw new Error(preview.message);
714
734
  return preview.value;
715
735
  };
736
+ const recapReadModel = new RuntimeReadModel({
737
+ runtimeEventStore: stores.runtimeEventStore,
738
+ canonicalPermissionOutcomes,
739
+ });
716
740
  const sessionEffectCoordinator = new HostSessionEffectCoordinator({
717
741
  model: createHostSessionEffectModel({
718
742
  runtimePolicy: runtimePolicyStores,
@@ -720,11 +744,14 @@ export async function createExecutionRuntimeHostComposition(context, options = {
720
744
  usage: openedUsageStores,
721
745
  requestDrain: context.requestDrain,
722
746
  }),
723
- readModel: new RuntimeReadModel({
724
- runtimeEventStore: stores.runtimeEventStore,
725
- projectionCache: stores.sessionStore,
726
- canonicalPermissionOutcomes,
727
- }),
747
+ readModel: {
748
+ getSessionView: async (sessionId) => {
749
+ // A Session whose transcript predates the ledger projects an empty
750
+ // view, and a recap of nothing reads as a successful recap.
751
+ await requireSessionManager(manager).ensureTranscriptLedgerForRead(sessionId);
752
+ return recapReadModel.getSessionView(sessionId);
753
+ },
754
+ },
728
755
  artifacts: openedArtifactStore,
729
756
  sessions: stores.sessionStore,
730
757
  readSessionHeader: (sessionId) => stores.sessionStore.readHeaderSnapshot(sessionId),
@@ -842,7 +869,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
842
869
  });
843
870
  };
844
871
  const registerBackendInvalidation = () => {
845
- observeBackendInvalidation(manager.refreshIdleBackends());
872
+ observeBackendInvalidation(requireSessionManager(manager).refreshIdleBackends());
846
873
  };
847
874
  const registerConfigurationMutation = () => {
848
875
  hostChanges.publishConfiguration();
@@ -863,7 +890,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
863
890
  acquireResidency: () => context.acquireResidency('oauth'),
864
891
  invalidateBackends: () => {
865
892
  hostChanges.publishConfiguration();
866
- return manager.refreshIdleBackends();
893
+ return requireSessionManager(manager).refreshIdleBackends();
867
894
  },
868
895
  onFatal: (error) => {
869
896
  if (poisonFailure)
@@ -990,6 +1017,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
990
1017
  goal = new HostGoalCoordinator({
991
1018
  store: openedGoalStore,
992
1019
  stores,
1020
+ readSessionMessages: (sessionId) => requireSessionManager(manager).getMessages(sessionId),
993
1021
  executions: coordinator,
994
1022
  sessionAdmission,
995
1023
  evaluator: createHostGoalEvaluator({
@@ -1022,6 +1050,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1022
1050
  });
1023
1051
  const sessionCatalog = new HostSessionCatalogCoordinator({
1024
1052
  stores: stores.sessionStore,
1053
+ turnIndex: requireTranscriptReader(transcriptReader),
1025
1054
  runtimePolicy: runtimePolicyStores,
1026
1055
  manager,
1027
1056
  admission: sessionAdmission,
@@ -1099,8 +1128,9 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1099
1128
  ? 'Safe-boundary resume is disabled for this Runtime Host'
1100
1129
  : 'WorkHub delegated execution is not resumable');
1101
1130
  }
1102
- if (plan.result.sourceRunId !== source.runId ||
1103
- plan.result.sourceTurnId !== source.turnId) {
1131
+ // Root planning authenticates handoff membership. Its source may be
1132
+ // a physical successor of this same logical Turn, never another Turn.
1133
+ if (plan.result.sourceTurnId !== source.turnId) {
1104
1134
  throw new WorkHubActionEffectFailure('operation_conflict', 'WorkHub resume source lineage changed during planning');
1105
1135
  }
1106
1136
  const targetTurnId = workHubResumedTurnId(actionId);
@@ -1162,7 +1192,17 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1162
1192
  sessionId: input.targetSessionId,
1163
1193
  workspace: input.create.workspace,
1164
1194
  name: input.create.title,
1165
- modelTarget: { kind: 'default' },
1195
+ modelTarget: input.create.defaults?.model
1196
+ ? {
1197
+ kind: 'explicit',
1198
+ connectionId: input.create.defaults.model.llmConnectionId,
1199
+ connectionSlug: input.create.defaults.model.llmConnectionSlug,
1200
+ model: input.create.defaults.model.model,
1201
+ }
1202
+ : { kind: 'default' },
1203
+ ...(input.create.defaults?.permissionMode
1204
+ ? { permissionMode: input.create.defaults.permissionMode }
1205
+ : {}),
1166
1206
  collaborationMode: 'agent',
1167
1207
  orchestrationMode: 'default',
1168
1208
  })
@@ -1172,7 +1212,13 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1172
1212
  .digest('hex')
1173
1213
  .slice(0, 48);
1174
1214
  const messageId = `whm_${suffix}`;
1175
- const content = normalizeMessageContent({ text: input.userText });
1215
+ const targetAttachments = !durable && input.attachments?.length
1216
+ ? await copyWorkHubAttachmentsToTarget(openedArtifactStore, artifacts, input.targetSessionId, input.attachments)
1217
+ : input.attachments;
1218
+ const content = normalizeMessageContent({
1219
+ text: input.userText,
1220
+ ...(targetAttachments ? { attachments: targetAttachments } : {}),
1221
+ });
1176
1222
  const persisted = durable ??
1177
1223
  (await sessionAdmission.runMany([WORKHUB_COORDINATION_SESSION_ID, input.targetSessionId], async (lease) => {
1178
1224
  const rootState = coordinator.readRootState(input.targetSessionId);
@@ -1223,6 +1269,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1223
1269
  delegationId,
1224
1270
  disposition: input.disposition,
1225
1271
  userText: input.userText,
1272
+ ...(input.attachments ? { attachments: input.attachments } : {}),
1226
1273
  ...(steered ? { steered: true } : {}),
1227
1274
  ...(input.create ? { create: input.create } : {}),
1228
1275
  ...(input.replacesActionId && input.replacesDelegationId
@@ -1396,7 +1443,17 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1396
1443
  });
1397
1444
  const hostedExecutions = new HostHostedExecutionCoordinator((input, signal) => hostedExecutionRunner.run(input, signal), context.requestDrain);
1398
1445
  let recoverySessions = [];
1446
+ const storageMaintenance = new HostStorageMaintenance({
1447
+ artifacts: openedArtifactStore,
1448
+ contextOffload: openedContextOffloadStore,
1449
+ onError: (name, error) => console.error(`[runtime-host] ${name} will retry: ${generalizedErrorMessage(error)}`),
1450
+ });
1399
1451
  domainModules = [
1452
+ createRuntimeHostDomainModule({
1453
+ id: 'storage-maintenance',
1454
+ drain: [() => storageMaintenance.beginDrain()],
1455
+ close: [() => storageMaintenance.close()],
1456
+ }),
1400
1457
  createRuntimeHostDomainModule({
1401
1458
  id: 'plugin-platform',
1402
1459
  handlers: [pluginPlatformCoordinator.handlers],
@@ -1458,17 +1515,7 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1458
1515
  configuration.handlers,
1459
1516
  ],
1460
1517
  recovery: {
1461
- state: async () => {
1462
- await skills.recover();
1463
- try {
1464
- await openedArtifactStore.reclaimUpgradeResidue();
1465
- }
1466
- catch (error) {
1467
- // Leftover bytes are not worth refusing to start over; the next
1468
- // start tries again.
1469
- console.error(`[runtime-host] upgrade residue could not be reclaimed: ${generalizedErrorMessage(error)}`);
1470
- }
1471
- },
1518
+ state: () => skills.recover(),
1472
1519
  },
1473
1520
  drain: [
1474
1521
  () => connectionEffects.beginDrain(),
@@ -1476,9 +1523,12 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1476
1523
  () => oauth?.beginDrain(),
1477
1524
  ],
1478
1525
  close: [
1526
+ () => archiveEvidence?.close(),
1479
1527
  () => modelMetadataRefresh?.close(),
1480
1528
  () => connectionEffects.close(),
1481
- () => (backendInvalidationPoisoned ? undefined : manager.refreshIdleBackends()),
1529
+ () => backendInvalidationPoisoned
1530
+ ? undefined
1531
+ : requireSessionManager(manager).refreshIdleBackends(),
1482
1532
  () => skills.close(),
1483
1533
  () => oauth?.close(),
1484
1534
  () => {
@@ -1543,8 +1593,8 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1543
1593
  executions: async () => {
1544
1594
  await coordinator.prepareRecovery();
1545
1595
  await interactions.recoverPendingAfterHostRestart();
1546
- await manager.recoverInterruptedSessionsStrict(stores);
1547
- await manager.recoverChildWorkspacePatches(recoverySessions.flatMap((session) => session.subagentWorkspace ? [session.id] : []));
1596
+ await requireSessionManager(manager).recoverInterruptedSessionsStrict(stores);
1597
+ await requireSessionManager(manager).recoverChildWorkspacePatches(recoverySessions.flatMap((session) => session.subagentWorkspace ? [session.id] : []));
1548
1598
  await coordinator.recover();
1549
1599
  await messages.recoverPendingAfterHostRestart(recoverySessions.map((session) => session.id));
1550
1600
  await turnAccessRequests?.recover();
@@ -1664,17 +1714,73 @@ export async function createExecutionRuntimeHostComposition(context, options = {
1664
1714
  continuity: continuityCoordinator,
1665
1715
  clientCapabilities,
1666
1716
  hostChanges,
1717
+ prepareHandoff: async (hostEpoch, signal) => {
1718
+ if (draining || signal.aborted)
1719
+ return undefined;
1720
+ const goalHold = goal?.holdForHandoff();
1721
+ const scheduleHold = scheduledTasks?.holdForHandoff();
1722
+ let root;
1723
+ let detached = false;
1724
+ const cancel = () => {
1725
+ if (detached)
1726
+ return;
1727
+ root?.cancel();
1728
+ goalHold?.release();
1729
+ scheduleHold?.release();
1730
+ signal.removeEventListener('abort', cancel);
1731
+ };
1732
+ signal.addEventListener('abort', cancel, { once: true });
1733
+ try {
1734
+ if (!goalHold || !scheduleHold) {
1735
+ cancel();
1736
+ return undefined;
1737
+ }
1738
+ await waitForHostedExecutionIdleOrAbort(Promise.all([goalHold.settled(), scheduleHold.settled()]).then(() => undefined), signal);
1739
+ root = await requireRootCoordinator(coordinator).prepareHandoff(hostEpoch, signal);
1740
+ if (!root) {
1741
+ cancel();
1742
+ return undefined;
1743
+ }
1744
+ const prepared = root;
1745
+ return {
1746
+ seal: () => prepared.seal(),
1747
+ residencies: async () => {
1748
+ await waitForHostedExecutionIdleOrAbort(scheduleHold.settled(), signal);
1749
+ const goals = await goalHold.residencies(prepared.executions);
1750
+ const roots = await prepared.residencies();
1751
+ if (!goals || !roots || signal.aborted || draining)
1752
+ return undefined;
1753
+ return [...roots, ...goals, ...scheduleHold.residencies()];
1754
+ },
1755
+ detach: async () => {
1756
+ detached = true;
1757
+ signal.removeEventListener('abort', cancel);
1758
+ await prepared.detach();
1759
+ // Domain holds stay closed until the lifecycle owner drains us.
1760
+ },
1761
+ cancel,
1762
+ };
1763
+ }
1764
+ catch (error) {
1765
+ cancel();
1766
+ if (signal.aborted)
1767
+ return undefined;
1768
+ throw error;
1769
+ }
1770
+ },
1667
1771
  releaseConnection: (connectionId) => {
1668
1772
  for (const module of domainModules)
1669
1773
  module.releaseConnection?.(connectionId);
1670
1774
  },
1671
1775
  beginDrain,
1672
1776
  recover,
1777
+ startMaintenance: () => storageMaintenance.start(),
1673
1778
  close,
1674
1779
  };
1675
1780
  }
1676
1781
  catch (error) {
1677
1782
  const errors = [error];
1783
+ archiveEvidence?.close();
1678
1784
  try {
1679
1785
  await modelMetadataRefresh?.close();
1680
1786
  }
@@ -1871,6 +1977,11 @@ function requireSessionManager(manager) {
1871
1977
  throw new Error('Runtime Host SessionManager is not composed');
1872
1978
  return manager;
1873
1979
  }
1980
+ function requireTranscriptReader(reader) {
1981
+ if (!reader)
1982
+ throw new Error('Runtime Host transcript reader is not composed');
1983
+ return reader;
1984
+ }
1874
1985
  function requireGraphCoordinator(coordinator) {
1875
1986
  if (!coordinator)
1876
1987
  throw new Error('Runtime Host Agent Graph coordinator is not composed');
@@ -27,7 +27,7 @@ import { buildSessionRecapMessages } from '@maka/runtime/session-recap';
27
27
  import { buildSessionTitlePrompt, cleanGeneratedSessionTitle, SESSION_TITLE_GENERATION_TIMEOUT_MS, } from './session-title.js';
28
28
  import { createProxiedFetchTransport, } from '@maka/runtime/network/scoped-fetch-transport';
29
29
  import { generateToolFreeModelCall, generateProviderPrefixModelCall, ProviderPrefixModelCallUnavailableError, } from '@maka/runtime/tool-free-model-call';
30
- import { modelUsesAnthropicMessages } from '@maka/runtime/model-runtime';
30
+ import { resolveModelRuntime } from '@maka/runtime/model-runtime';
31
31
  import { memoryExtractionMaxOutputTokens, } from '@maka/runtime/memory-extraction';
32
32
  import { createHostOAuthModelFetch, OAuthExecutionCredentialError, } from './oauth-execution-authority.js';
33
33
  import { toRuntimePolicyProxy } from './runtime-policy-proxy.js';
@@ -267,7 +267,8 @@ async function runHostAuxiliaryModelCall(authority, input) {
267
267
  let result;
268
268
  try {
269
269
  result = await readDuringBackendCreation(() => {
270
- const providerOptions = buildProviderOptions(target.connection, target.model, input.header.thinkingLevel);
270
+ const runtime = resolveModelRuntime(target.connection, target.model);
271
+ const providerOptions = buildProviderOptions(target.connection, target.model, input.header.thinkingLevel, runtime);
271
272
  const model = getAIModel({
272
273
  sessionId: input.transportContextId,
273
274
  connection: target.connection,
@@ -275,14 +276,13 @@ async function runHostAuxiliaryModelCall(authority, input) {
275
276
  modelId: target.model,
276
277
  fetch: modelFetch,
277
278
  requestHeaders: target.requestHeaders,
279
+ resolvedRuntime: runtime,
278
280
  });
279
281
  return request.tools !== undefined
280
282
  ? generateProviderPrefixModelCall({
281
283
  model,
282
284
  ...request,
283
- toolChoicePolicy: modelUsesAnthropicMessages(target.connection, target.model)
284
- ? 'omit'
285
- : 'none',
285
+ toolChoicePolicy: runtime.wire === 'anthropic-messages' ? 'omit' : 'none',
286
286
  abortSignal: input.abortSignal,
287
287
  providerOptions: request.providerOptions ?? providerOptions,
288
288
  })
@@ -187,20 +187,42 @@ async function buildHostAiSdkBackend(input, target) {
187
187
  });
188
188
  };
189
189
  const recordRunComposition = input.context.recordRunComposition;
190
+ const recordRequestComposition = input.context.recordRequestComposition;
191
+ const resolveModelTools = () => modelComposition.resolveTools?.() ?? modelComposition.tools;
192
+ // RunComposition remains the immutable C0 baseline. Dynamic Tool changes
193
+ // belong exclusively to RequestComposition epochs, so never re-sample them
194
+ // while committing the baseline immediately before provider dispatch.
195
+ const initialModelTools = Object.freeze([...modelComposition.tools]);
196
+ const runCompositionCommits = new Map();
190
197
  const commitRunComposition = recordRunComposition
191
198
  ? async (context) => {
192
- const resolved = await resolveRunPrompt(context);
193
- await recordRunComposition(context.runId, createRunCompositionSnapshot({
194
- composerId: modelComposition.composerId,
195
- composerRevision: modelComposition.composerRevision,
196
- sourceRevisions: resolved.sourceRevisions,
197
- baseSystemPromptHash: stableHash(resolved.text ?? ''),
198
- toolCatalogHash: toolCatalogHash(modelComposition.tools),
199
- toolAvailabilityHash: toolAvailabilityHash(modelComposition.toolAvailability),
200
- baseProviderOptionsHash: stableHash(providerOptions),
201
- toolNames: modelComposition.tools.map(({ name }) => name),
202
- contextWindow: contextWindow ?? null,
203
- }));
199
+ let commit = runCompositionCommits.get(context.runId);
200
+ if (!commit) {
201
+ commit = (async () => {
202
+ const resolved = await resolveRunPrompt(context);
203
+ await recordRunComposition(context.runId, createRunCompositionSnapshot({
204
+ composerId: modelComposition.composerId,
205
+ composerRevision: modelComposition.composerRevision,
206
+ sourceRevisions: resolved.sourceRevisions,
207
+ baseSystemPromptHash: stableHash(resolved.text ?? ''),
208
+ toolCatalogHash: toolCatalogHash(initialModelTools),
209
+ toolAvailabilityHash: toolAvailabilityHash(modelComposition.toolAvailability),
210
+ baseProviderOptionsHash: stableHash(providerOptions),
211
+ toolNames: initialModelTools.map(({ name }) => name),
212
+ contextWindow: contextWindow ?? null,
213
+ }));
214
+ })();
215
+ runCompositionCommits.set(context.runId, commit);
216
+ }
217
+ try {
218
+ await commit;
219
+ }
220
+ catch (error) {
221
+ if (runCompositionCommits.get(context.runId) === commit) {
222
+ runCompositionCommits.delete(context.runId);
223
+ }
224
+ throw error;
225
+ }
204
226
  }
205
227
  : undefined;
206
228
  const planProjectionImage = createReadImageSnapshotPlanner(input.artifacts);
@@ -215,8 +237,9 @@ async function buildHostAiSdkBackend(input, target) {
215
237
  permissionMode: input.context.header.permissionMode,
216
238
  }),
217
239
  },
218
- appendMessage: input.context.appendMessage ??
219
- ((message) => input.context.store.appendMessage(input.context.sessionId, message)),
240
+ ...(input.context.recordSystemNote
241
+ ? { recordSystemNote: input.context.recordSystemNote }
242
+ : {}),
220
243
  readExecutionBoundary: () => input.context.store.readExecutionBoundary(input.context.sessionId),
221
244
  ...(input.context.store.createSandboxBoundaryRequest
222
245
  ? {
@@ -233,7 +256,8 @@ async function buildHostAiSdkBackend(input, target) {
233
256
  apiKey,
234
257
  modelId: target.model,
235
258
  modelFactory,
236
- tools: [...modelComposition.tools],
259
+ tools: [...resolveModelTools()],
260
+ resolveTools: resolveModelTools,
237
261
  toolAvailability: modelComposition.toolAvailability,
238
262
  ...(modelComposition.planTraceContext
239
263
  ? { planTraceContext: modelComposition.planTraceContext }
@@ -292,6 +316,11 @@ async function buildHostAiSdkBackend(input, target) {
292
316
  beforeRunProviderDispatch: commitRunComposition,
293
317
  }
294
318
  : {}),
319
+ ...(recordRequestComposition
320
+ ? {
321
+ recordRequestComposition: (runId, snapshot) => recordRequestComposition(runId, snapshot),
322
+ }
323
+ : {}),
295
324
  systemPrompt: async (context) => {
296
325
  const resolved = await resolveRunPrompt({
297
326
  turnId: context.turnId,
@@ -299,7 +328,7 @@ async function buildHostAiSdkBackend(input, target) {
299
328
  ? { emitSkillCatalogTrace: context.emitSkillCatalogTrace }
300
329
  : {}),
301
330
  });
302
- return resolved.text;
331
+ return { text: resolved.text, sourceRevisions: resolved.sourceRevisions };
303
332
  },
304
333
  lookupPricing: pricing,
305
334
  recordModelCallAttempt,