@sema-agent/core 7.57.0 → 7.59.0

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 (399) hide show
  1. package/CHANGELOG.md +1161 -0
  2. package/README.md +6 -4
  3. package/dist/agents/cc-peer-directory.js +8 -8
  4. package/dist/agents/child-model-seat.d.ts +4 -2
  5. package/dist/agents/child-model-seat.js +5 -3
  6. package/dist/agents/peer-directory.d.ts +9 -0
  7. package/dist/agents/peer-directory.js +6 -2
  8. package/dist/agents/send-message-tool.js +21 -12
  9. package/dist/agents/subagent-steps.js +2 -4
  10. package/dist/agents/subagent.js +33 -34
  11. package/dist/brain/anthropic.js +161 -45
  12. package/dist/brain/errors.d.ts +9 -3
  13. package/dist/brain/errors.js +7 -1
  14. package/dist/brain/failover.js +2 -1
  15. package/dist/brain/open-responses.js +3 -3
  16. package/dist/brain/openai.js +103 -53
  17. package/dist/brain/provider-dialect.d.ts +11 -0
  18. package/dist/brain/provider-dialect.js +5 -2
  19. package/dist/brain/reasoning-request.js +5 -4
  20. package/dist/brain/reasoning.d.ts +19 -0
  21. package/dist/brain/reasoning.js +17 -2
  22. package/dist/brain/request-route.d.ts +4 -1
  23. package/dist/brain/request-route.js +4 -1
  24. package/dist/brain/route-adjudicator.d.ts +84 -18
  25. package/dist/brain/route-adjudicator.js +89 -22
  26. package/dist/brain/route-conformance.js +1 -1
  27. package/dist/brain/stream-engine.js +84 -49
  28. package/dist/brain/stream-shared.d.ts +30 -0
  29. package/dist/brain/stream-shared.js +34 -1
  30. package/dist/brain/timeout.d.ts +62 -5
  31. package/dist/brain/timeout.js +93 -6
  32. package/dist/core/a2a.d.ts +2 -1
  33. package/dist/core/a2a.js +23 -10
  34. package/dist/core/account-row.d.ts +61 -0
  35. package/dist/core/account-row.js +51 -0
  36. package/dist/core/advisor-verdict.d.ts +2 -1
  37. package/dist/core/advisor-verdict.js +1 -1
  38. package/dist/core/allow-entry.d.ts +20 -7
  39. package/dist/core/allow-entry.js +18 -9
  40. package/dist/core/approval-object.d.ts +29 -15
  41. package/dist/core/approval-object.js +47 -19
  42. package/dist/core/ask-origin.d.ts +21 -2
  43. package/dist/core/ask-origin.js +5 -1
  44. package/dist/core/auto-compaction.d.ts +4 -0
  45. package/dist/core/auto-compaction.js +2 -2
  46. package/dist/core/auto-mode-directive.d.ts +29 -5
  47. package/dist/core/auto-mode-directive.js +38 -8
  48. package/dist/core/background-agent-store.d.ts +16 -3
  49. package/dist/core/checkpoint-requirements.d.ts +19 -1
  50. package/dist/core/checkpoint-requirements.js +5 -1
  51. package/dist/core/checkpoint-store.d.ts +85 -23
  52. package/dist/core/checkpoint-store.js +31 -9
  53. package/dist/core/child-clamp-seats.d.ts +29 -0
  54. package/dist/core/child-clamp-seats.js +56 -1
  55. package/dist/core/compliance.d.ts +2 -2
  56. package/dist/core/compliance.js +1 -1
  57. package/dist/core/effective-path-target.d.ts +8 -2
  58. package/dist/core/effective-path-target.js +8 -3
  59. package/dist/core/engine-notice.d.ts +99 -9
  60. package/dist/core/engine-notice.js +19 -5
  61. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  62. package/dist/core/fs-write-gate-policy.js +7 -3
  63. package/dist/core/gate-fold.js +7 -4
  64. package/dist/core/gate-lanes.js +19 -6
  65. package/dist/core/gate-outcome.d.ts +32 -3
  66. package/dist/core/gate-outcome.js +19 -1
  67. package/dist/core/git-worktree-env.d.ts +53 -11
  68. package/dist/core/git-worktree-env.js +96 -12
  69. package/dist/core/governance-codes.d.ts +9 -1
  70. package/dist/core/governance-codes.js +13 -0
  71. package/dist/core/hooks.d.ts +35 -4
  72. package/dist/core/hooks.js +17 -11
  73. package/dist/core/human-input-projection.d.ts +1 -0
  74. package/dist/core/human-input-projection.js +3 -0
  75. package/dist/core/image-admission.d.ts +6 -5
  76. package/dist/core/image-admission.js +18 -14
  77. package/dist/core/locked-config.d.ts +20 -3
  78. package/dist/core/locked-config.js +40 -3
  79. package/dist/core/mailbox-store.d.ts +45 -1
  80. package/dist/core/mailbox-store.js +53 -9
  81. package/dist/core/mcp-call-meta.d.ts +66 -0
  82. package/dist/core/mcp-call-meta.js +103 -0
  83. package/dist/core/mcp-connection-pool.d.ts +3 -1
  84. package/dist/core/mcp-connection-pool.js +3 -1
  85. package/dist/core/mcp-failure.d.ts +117 -15
  86. package/dist/core/mcp-failure.js +71 -3
  87. package/dist/core/mcp-probe.d.ts +4 -0
  88. package/dist/core/mcp-probe.js +1 -1
  89. package/dist/core/mcp-server-link.d.ts +27 -3
  90. package/dist/core/mcp-server-link.js +25 -1
  91. package/dist/core/mcp-server-spec.d.ts +46 -18
  92. package/dist/core/mcp-server-spec.js +1 -18
  93. package/dist/core/mcp.d.ts +16 -20
  94. package/dist/core/mcp.js +112 -55
  95. package/dist/core/memory-engine/consolidation-driver.d.ts +2 -4
  96. package/dist/core/memory-engine/consolidation-driver.js +3 -3
  97. package/dist/core/memory-engine/consolidation.d.ts +4 -0
  98. package/dist/core/memory-engine/consolidation.js +1 -0
  99. package/dist/core/memory-engine/delegation-settlement.js +5 -12
  100. package/dist/core/memory-engine/distiller.js +2 -2
  101. package/dist/core/memory-engine/dual-root.d.ts +50 -1
  102. package/dist/core/memory-engine/dual-root.js +44 -1
  103. package/dist/core/memory-engine/engine.d.ts +67 -14
  104. package/dist/core/memory-engine/engine.js +384 -212
  105. package/dist/core/memory-engine/export-bundle.d.ts +23 -0
  106. package/dist/core/memory-engine/export-bundle.js +23 -4
  107. package/dist/core/memory-engine/file-backend.d.ts +128 -55
  108. package/dist/core/memory-engine/file-backend.js +290 -117
  109. package/dist/core/memory-engine/index.d.ts +1 -1
  110. package/dist/core/memory-engine/layout.d.ts +59 -11
  111. package/dist/core/memory-engine/layout.js +190 -40
  112. package/dist/core/memory-engine/memory-backend-contract.d.ts +1 -1
  113. package/dist/core/memory-engine/memory-backend-contract.js +39 -2
  114. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  115. package/dist/core/memory-engine/scope-contract.js +80 -11
  116. package/dist/core/memory-engine/sync-client.d.ts +9 -1
  117. package/dist/core/memory-engine/sync-client.js +31 -8
  118. package/dist/core/memory-engine/sync.d.ts +5 -0
  119. package/dist/core/memory-engine/types.d.ts +6 -0
  120. package/dist/core/mode-policy.d.ts +8 -5
  121. package/dist/core/mode-policy.js +5 -4
  122. package/dist/core/mods/classic-events.d.ts +5 -1
  123. package/dist/core/mods/host.js +1 -1
  124. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  125. package/dist/core/mods/kernel/dispatch.js +12 -9
  126. package/dist/core/mods/kernel/events.d.ts +6 -1
  127. package/dist/core/mods/kernel/events.js +2 -2
  128. package/dist/core/mods/kernel/registration.d.ts +9 -1
  129. package/dist/core/mods/kernel/registration.js +3 -0
  130. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  131. package/dist/core/mods/kernel/site-rules.js +10 -0
  132. package/dist/core/mods/package.d.ts +23 -0
  133. package/dist/core/mods/package.js +118 -0
  134. package/dist/core/mods/stations.d.ts +33 -12
  135. package/dist/core/mods/stations.js +45 -11
  136. package/dist/core/mods/tool-call.d.ts +5 -1
  137. package/dist/core/mods/tool-call.js +13 -4
  138. package/dist/core/parent-spec-seat.d.ts +8 -3
  139. package/dist/core/parent-spec-seat.js +2 -0
  140. package/dist/core/park-selfcheck.js +6 -0
  141. package/dist/core/path-guard-rows.d.ts +20 -0
  142. package/dist/core/path-guard-rows.js +11 -0
  143. package/dist/core/peer-seat.d.ts +248 -0
  144. package/dist/core/peer-seat.js +439 -0
  145. package/dist/core/permission-rule-consent.js +10 -4
  146. package/dist/core/permission-rule-model.d.ts +16 -0
  147. package/dist/core/permission-rule-model.js +1 -1
  148. package/dist/core/present-plan-tool.d.ts +20 -3
  149. package/dist/core/present-plan-tool.js +48 -4
  150. package/dist/core/protocol-http-auth.d.ts +40 -29
  151. package/dist/core/protocol-http-auth.js +30 -32
  152. package/dist/core/redaction-marks.d.ts +16 -0
  153. package/dist/core/redaction-marks.js +16 -0
  154. package/dist/core/redaction-passes.js +8 -9
  155. package/dist/core/resume-startup-cause.js +1 -0
  156. package/dist/core/retention.d.ts +41 -15
  157. package/dist/core/retention.js +59 -12
  158. package/dist/core/rewrite-rejudge.d.ts +38 -0
  159. package/dist/core/rewrite-rejudge.js +42 -2
  160. package/dist/core/roles.d.ts +34 -2
  161. package/dist/core/roles.js +43 -4
  162. package/dist/core/run-origin.d.ts +40 -0
  163. package/dist/core/run-origin.js +37 -0
  164. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  165. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  166. package/dist/core/runner/announce-once-ledger.d.ts +5 -4
  167. package/dist/core/runner/announce-once-ledger.js +4 -2
  168. package/dist/core/runner/call-hook-stations.js +2 -2
  169. package/dist/core/runner/compaction-restate.d.ts +15 -6
  170. package/dist/core/runner/compaction-restate.js +28 -2
  171. package/dist/core/runner/contracts.d.ts +33 -21
  172. package/dist/core/runner/credential-origin-seat.js +4 -3
  173. package/dist/core/runner/cwd-alignment-probe.d.ts +20 -0
  174. package/dist/core/runner/cwd-alignment-probe.js +21 -0
  175. package/dist/core/runner/decide-continuation.d.ts +2 -2
  176. package/dist/core/runner/gate-exit.d.ts +30 -8
  177. package/dist/core/runner/gate-exit.js +15 -8
  178. package/dist/core/runner/image-removed-seat.d.ts +12 -0
  179. package/dist/core/runner/image-removed-seat.js +19 -0
  180. package/dist/core/runner/inline-image.js +1 -1
  181. package/dist/core/runner/memory-consolidation-driver.js +3 -3
  182. package/dist/core/runner/park-commit.d.ts +1 -1
  183. package/dist/core/runner/park-commit.js +3 -0
  184. package/dist/core/runner/prepare-ask-lane.d.ts +1 -1
  185. package/dist/core/runner/prepare-ask-lane.js +2 -1
  186. package/dist/core/runner/prepare-boundary-parks.js +2 -2
  187. package/dist/core/runner/prepare-caps-and-workflow.d.ts +5 -5
  188. package/dist/core/runner/prepare-caps-and-workflow.js +3 -1
  189. package/dist/core/runner/prepare-config-doors.d.ts +8 -5
  190. package/dist/core/runner/prepare-config-doors.js +14 -10
  191. package/dist/core/runner/prepare-context-lane.js +2 -0
  192. package/dist/core/runner/prepare-delegation-surface.d.ts +8 -0
  193. package/dist/core/runner/prepare-delegation-surface.js +16 -18
  194. package/dist/core/runner/prepare-gate-stations.js +1 -1
  195. package/dist/core/runner/prepare-hands-readface.d.ts +11 -3
  196. package/dist/core/runner/prepare-hands-readface.js +9 -1
  197. package/dist/core/runner/prepare-inherited-gate.d.ts +1 -3
  198. package/dist/core/runner/prepare-inherited-gate.js +14 -27
  199. package/dist/core/runner/prepare-memory.d.ts +3 -0
  200. package/dist/core/runner/prepare-memory.js +26 -37
  201. package/dist/core/runner/prepare-park-ask.d.ts +1 -1
  202. package/dist/core/runner/prepare-park-ask.js +2 -1
  203. package/dist/core/runner/prepare-policy-chain.d.ts +7 -7
  204. package/dist/core/runner/prepare-policy-chain.js +18 -15
  205. package/dist/core/runner/prepare-project-context.d.ts +2 -2
  206. package/dist/core/runner/prepare-project-context.js +2 -2
  207. package/dist/core/runner/prepare-prompt-inputs.d.ts +1 -1
  208. package/dist/core/runner/prepare-prompt-inputs.js +8 -19
  209. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  210. package/dist/core/runner/prepare-protocol-tools.js +11 -3
  211. package/dist/core/runner/prepare-run-refs.d.ts +2 -3
  212. package/dist/core/runner/prepare-run-refs.js +4 -1
  213. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  214. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  215. package/dist/core/runner/prepare-task.js +28 -13
  216. package/dist/core/runner/prepare-wiring-manifest.d.ts +2 -1
  217. package/dist/core/runner/prepare-wiring-manifest.js +4 -3
  218. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  219. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  220. package/dist/core/runner/reply-pricing.d.ts +30 -0
  221. package/dist/core/runner/reply-pricing.js +19 -0
  222. package/dist/core/runner/resume-admission.js +5 -3
  223. package/dist/core/runner/resume-apply.js +6 -1
  224. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  225. package/dist/core/runner/resume-policy-outcome.js +5 -5
  226. package/dist/core/runner/role-seat-defaulted.d.ts +44 -0
  227. package/dist/core/runner/role-seat-defaulted.js +40 -0
  228. package/dist/core/runner/run-brain-sinks.js +2 -0
  229. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  230. package/dist/core/runner/run-harness-handlers.js +1 -8
  231. package/dist/core/runner/run-identity-wiring.d.ts +2 -5
  232. package/dist/core/runner/run-identity-wiring.js +6 -4
  233. package/dist/core/runner/run-leg.d.ts +2 -0
  234. package/dist/core/runner/run-leg.js +42 -29
  235. package/dist/core/runner/run-notification-lane.js +3 -0
  236. package/dist/core/runner/run-stop-and-final-verify.js +2 -2
  237. package/dist/core/runner/run-terminal-adoption.d.ts +2 -5
  238. package/dist/core/runner/run-terminal-adoption.js +9 -3
  239. package/dist/core/runner/run-turn-boundary.js +77 -70
  240. package/dist/core/runner/runtask.d.ts +1 -1
  241. package/dist/core/runner/runtask.js +2 -2
  242. package/dist/core/runner/side-call-account.d.ts +1 -1
  243. package/dist/core/runner/side-call-account.js +3 -18
  244. package/dist/core/runner/sub-agent-deny-lists.d.ts +24 -0
  245. package/dist/core/runner/sub-agent-deny-lists.js +10 -0
  246. package/dist/core/runner/terminal-account.js +3 -3
  247. package/dist/core/runner/tool-end-body.js +2 -1
  248. package/dist/core/runner/tool-occurrence.d.ts +5 -2
  249. package/dist/core/runner/tool-occurrence.js +4 -3
  250. package/dist/core/runner/turn-attachments.d.ts +26 -22
  251. package/dist/core/runner/turn-attachments.js +24 -26
  252. package/dist/core/runner/write-protection-station.d.ts +8 -2
  253. package/dist/core/runner/write-protection-station.js +2 -0
  254. package/dist/core/runner-deps.d.ts +3 -3
  255. package/dist/core/secret-env.d.ts +32 -2
  256. package/dist/core/secret-env.js +65 -3
  257. package/dist/core/sensitive-path-policy.js +9 -10
  258. package/dist/core/session-log-transfer.d.ts +24 -0
  259. package/dist/core/session-log-transfer.js +166 -0
  260. package/dist/core/session-policy-store.d.ts +3 -1
  261. package/dist/core/session-policy-store.js +13 -9
  262. package/dist/core/session-store.d.ts +86 -24
  263. package/dist/core/session-store.js +162 -24
  264. package/dist/core/session.d.ts +92 -1
  265. package/dist/core/shell-read-silence.js +1 -0
  266. package/dist/core/side-query.d.ts +11 -1
  267. package/dist/core/side-query.js +9 -0
  268. package/dist/core/skill-grant-binding.d.ts +31 -2
  269. package/dist/core/skill-grant-binding.js +31 -1
  270. package/dist/core/skill-grant.d.ts +8 -5
  271. package/dist/core/skill-grant.js +6 -6
  272. package/dist/core/steer-replay.d.ts +4 -2
  273. package/dist/core/steer-replay.js +2 -1
  274. package/dist/core/store-contracts/background-agent-store-contract.js +27 -0
  275. package/dist/core/store-contracts/checkpoint-store-contract.js +20 -2
  276. package/dist/core/store-contracts/mailbox-store-contract.js +31 -1
  277. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  278. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  279. package/dist/core/store-contracts/session-store-contract.js +236 -2
  280. package/dist/core/synthetic-read-verdict.js +2 -1
  281. package/dist/core/task-event.d.ts +92 -8
  282. package/dist/core/task-notification.js +16 -10
  283. package/dist/core/task-registry-agent.js +1 -0
  284. package/dist/core/task-registry-shared.d.ts +7 -1
  285. package/dist/core/task-spec.d.ts +49 -1
  286. package/dist/core/task-stream.d.ts +2 -1
  287. package/dist/core/terminal-cause.d.ts +11 -1
  288. package/dist/core/tool-catalog-entries.js +1 -0
  289. package/dist/core/tool-check-reading.d.ts +1 -0
  290. package/dist/core/tool-check-reading.js +3 -3
  291. package/dist/core/tool-policy.d.ts +16 -0
  292. package/dist/core/tool-result-store.d.ts +17 -10
  293. package/dist/core/tool-result-store.js +3 -1
  294. package/dist/core/tool-roster.d.ts +112 -5
  295. package/dist/core/tool-roster.js +42 -1
  296. package/dist/core/tool-spec.d.ts +3 -1
  297. package/dist/core/types.d.ts +3 -3
  298. package/dist/core/types.js +1 -1
  299. package/dist/core/untrusted-egress.d.ts +0 -2
  300. package/dist/core/untrusted-egress.js +10 -14
  301. package/dist/core/user-attachment.js +1 -1
  302. package/dist/core/wiring-manifest.d.ts +18 -6
  303. package/dist/core/wiring-manifest.js +4 -3
  304. package/dist/core/workspace-snapshot.d.ts +44 -0
  305. package/dist/core/workspace-snapshot.js +34 -0
  306. package/dist/core/write-protect.d.ts +43 -3
  307. package/dist/core/write-protect.js +43 -16
  308. package/dist/engine/compaction/compaction.js +29 -3
  309. package/dist/engine/execution-env/node-execution-env.d.ts +4 -3
  310. package/dist/engine/execution-env/node-execution-env.js +24 -23
  311. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  312. package/dist/engine/harness/agent-harness.d.ts +30 -2
  313. package/dist/engine/harness/agent-harness.js +43 -12
  314. package/dist/engine/harness/messages.d.ts +3 -1
  315. package/dist/engine/harness/messages.js +3 -2
  316. package/dist/engine/harness/types.d.ts +56 -7
  317. package/dist/engine/harness/types.js +5 -1
  318. package/dist/engine/llm/rejected-images.d.ts +46 -0
  319. package/dist/engine/llm/rejected-images.js +54 -0
  320. package/dist/engine/llm/tool-turns.d.ts +2 -1
  321. package/dist/engine/llm/types.d.ts +30 -10
  322. package/dist/engine/llm/types.js +1 -1
  323. package/dist/engine/loop/agent-loop.d.ts +8 -0
  324. package/dist/engine/loop/agent-loop.js +52 -15
  325. package/dist/engine/loop/types.d.ts +3 -1
  326. package/dist/engine/session/import-validate.js +3 -0
  327. package/dist/engine/session/memory-repo.d.ts +17 -9
  328. package/dist/engine/session/memory-repo.js +44 -34
  329. package/dist/engine/session/path-to-root.d.ts +38 -0
  330. package/dist/engine/session/path-to-root.js +39 -0
  331. package/dist/engine/session/repo-utils.d.ts +22 -4
  332. package/dist/engine/session/repo-utils.js +49 -1
  333. package/dist/engine/session/storage-base.d.ts +10 -1
  334. package/dist/engine/session/storage-base.js +11 -22
  335. package/dist/index.d.ts +29 -16
  336. package/dist/index.js +21 -11
  337. package/dist/internal/harness-types.d.ts +2 -2
  338. package/dist/internal/harness.d.ts +3 -2
  339. package/dist/internal/harness.js +2 -2
  340. package/dist/internal/llm.d.ts +1 -0
  341. package/dist/orchestration/workflow-observe.d.ts +17 -1
  342. package/dist/orchestration/workflow-observe.js +20 -0
  343. package/dist/orchestration/workflow-types.d.ts +32 -7
  344. package/dist/orchestration/workflow.js +739 -489
  345. package/dist/shell/counting-pass.d.ts +50 -0
  346. package/dist/shell/counting-pass.js +502 -0
  347. package/dist/shell/lex.d.ts +4 -2
  348. package/dist/shell/lex.js +93 -34
  349. package/dist/shell/shell-words.d.ts +1 -1
  350. package/dist/shell/shell-words.js +7 -6
  351. package/dist/stores/file/index.d.ts +4 -1
  352. package/dist/stores/file/index.js +4 -1
  353. package/dist/stores/file/mailbox-store.js +6 -10
  354. package/dist/stores/file/session-store.d.ts +15 -8
  355. package/dist/stores/file/session-store.js +28 -13
  356. package/dist/tools/fs/fs-bash.d.ts +6 -0
  357. package/dist/tools/fs/fs-bash.js +6 -3
  358. package/dist/tools/fs/fs-write.d.ts +6 -3
  359. package/dist/tools/fs/fs-write.js +8 -7
  360. package/dist/tools/fs/index.d.ts +3 -0
  361. package/dist/tools/fs/index.js +7 -3
  362. package/dist/tools/fs/program-read-model.d.ts +13 -0
  363. package/dist/tools/fs/program-read-model.js +15 -0
  364. package/dist/tools/fs/program-read-model.rows.js +1 -1
  365. package/dist/tools/fs/read-deny.d.ts +13 -10
  366. package/dist/tools/fs/read-deny.js +25 -5
  367. package/dist/tools/fs/read-floor.d.ts +19 -0
  368. package/dist/tools/fs/read-floor.js +23 -0
  369. package/dist/tools/fs/safety.js +40 -8
  370. package/dist/tools/fs/search.js +6 -24
  371. package/dist/tools/fs/shell-read-check.d.ts +9 -2
  372. package/dist/tools/fs/shell-read-check.js +61 -16
  373. package/dist/tools/fs/shell-read-establish.js +2 -1
  374. package/dist/tools/fs/shell-read-identity.js +1 -1
  375. package/dist/tools/fs/shell-read-judge.d.ts +26 -9
  376. package/dist/tools/fs/shell-read-judge.js +10 -6
  377. package/dist/tools/fs/shell-read-plan.d.ts +6 -1
  378. package/dist/tools/fs/shell-read-plan.js +22 -15
  379. package/dist/tools/fs/shell-read-start.js +1 -0
  380. package/dist/tools/fs/shell-reentry-text.d.ts +15 -1
  381. package/dist/tools/fs/shell-reentry-text.js +25 -3
  382. package/dist/tools/monitor.d.ts +4 -0
  383. package/dist/tools/monitor.js +2 -0
  384. package/dist/tools/worktree.d.ts +42 -15
  385. package/dist/tools/worktree.js +60 -32
  386. package/package.json +5 -2
  387. package/test/export-surface.snapshot.json +149 -1
  388. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  389. package/wire-changes/core-stores-sql@7.59.0.json +29 -0
  390. package/wire-changes/core@7.58.0.json +2188 -0
  391. package/wire-changes/core@7.59.0.json +2459 -0
  392. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  393. package/wire-changes/mods-kernel@7.59.0.json +29 -0
  394. package/wire-changes/primitives@7.58.0.json +29 -0
  395. package/wire-changes/primitives@7.59.0.json +29 -0
  396. package/dist/primitives/credential-ref.d.ts +0 -89
  397. package/dist/primitives/credential-ref.js +0 -125
  398. package/dist/primitives/index.d.ts +0 -2
  399. package/dist/primitives/index.js +0 -1
@@ -8,6 +8,8 @@ import { egressThrownText, egressValue } from "../../core/untrusted-egress.js";
8
8
  import { remoteWords } from "../../core/protocol-http-auth.js";
9
9
  import { types } from "node:util";
10
10
  import { admitToolResultMedia } from "../../core/image-admission.js";
11
+ import { IMAGE_REFUSAL_KIND, imageRefusalRemoves } from "../llm/rejected-images.js";
12
+ const IMAGE_REFUSAL_RETRIES = 3;
11
13
  function appendTextDeltaToAssistantMessage(message, contentIndex, delta) {
12
14
  const content = [...message.content];
13
15
  const currentContent = content[contentIndex];
@@ -366,6 +368,30 @@ async function runTurnPhases(state, signal, turnController, publishSeat, retract
366
368
  }
367
369
  raiseFatalCancellation(executor);
368
370
  let interruptedInRecovery = false;
371
+ let imageRetries = 0;
372
+ const resendWithoutRefusedImages = async () => {
373
+ while (message.stopReason === "error" &&
374
+ message.errorKind === IMAGE_REFUSAL_KIND &&
375
+ !signal?.aborted &&
376
+ !turnController.signal.aborted &&
377
+ isBlankFailureContent(message) &&
378
+ executor.admittedCount === 0 &&
379
+ imageRetries < IMAGE_REFUSAL_RETRIES &&
380
+ state.context.messages[state.context.messages.length - 1] === message &&
381
+ imageRefusalRemoves(state.context.messages, message)) {
382
+ imageRetries++;
383
+ trace?.({ kind: "continue", reason: "image_refusal_retry" });
384
+ executor = new StreamToolExecutor(state.context, state.config, turnController.signal, emit);
385
+ try {
386
+ ({ message, cutAtSettle: cutAtFinalSettle } = await streamAssistantResponse(state.context, state.config, turnController.signal, withhold?.sink ?? emit, streamFn, runtime, executor, staticReasoningCutDowngrade));
387
+ }
388
+ finally {
389
+ await executor.settle();
390
+ }
391
+ raiseFatalCancellation(executor);
392
+ }
393
+ };
394
+ await resendWithoutRefusedImages();
369
395
  {
370
396
  if (ptl) {
371
397
  const detect = ptlDetect;
@@ -418,6 +444,7 @@ async function runTurnPhases(state, signal, turnController, publishSeat, retract
418
444
  }
419
445
  }
420
446
  }
447
+ await resendWithoutRefusedImages();
421
448
  const unrecoveredPtlFailureUnderInterrupt = ptl !== undefined &&
422
449
  message.stopReason === "error" &&
423
450
  ptlDetect(message) &&
@@ -831,7 +858,7 @@ export async function runToolCall(currentContext, assistantMessage, toolCall, co
831
858
  await emit({ type: "tool_execution_start", toolCallId: toolCall.id, toolName: toolCall.name, args: toolCall.arguments });
832
859
  const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
833
860
  const finalized = preparation.kind === "immediate"
834
- ? { toolCall, result: preparation.result, isError: preparation.isError }
861
+ ? { toolCall, result: preparation.result, isError: preparation.isError, ...(preparation.notExecuted === true ? { notExecuted: true } : {}) }
835
862
  : await executePreparedWithDisclosure(currentContext, assistantMessage, preparation, config, signal, emit);
836
863
  await emitToolExecutionEnd(finalized, emit);
837
864
  return { finalized, ...(preparation.kind === "immediate" && preparation.halt !== undefined ? { halt: preparation.halt } : {}) };
@@ -973,7 +1000,7 @@ async function executeToolCallsPartitioned(currentContext, assistantMessage, too
973
1000
  });
974
1001
  const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
975
1002
  if (preparation.kind === "immediate") {
976
- const finalized = { toolCall, result: preparation.result, isError: preparation.isError };
1003
+ const finalized = { toolCall, result: preparation.result, isError: preparation.isError, ...(preparation.notExecuted === true ? { notExecuted: true } : {}) };
977
1004
  await emitToolExecutionEnd(finalized, emit);
978
1005
  entries.push({ finalized, toolCall });
979
1006
  if (preparation.halt !== undefined) {
@@ -1147,7 +1174,7 @@ async function finalizeStreamEntry(currentContext, assistantMessage, entry, conf
1147
1174
  result: createErrorToolResult("in-stream execution produced no outcome"),
1148
1175
  isError: true,
1149
1176
  };
1150
- return { toolCall: entry.toolCall, result: immediate.result, isError: immediate.isError };
1177
+ return { toolCall: entry.toolCall, result: immediate.result, isError: immediate.isError, ...(immediate.notExecuted === true ? { notExecuted: true } : {}) };
1151
1178
  }
1152
1179
  async function closeOrphanedStreamEntry(entry, emit) {
1153
1180
  await emit({
@@ -1320,6 +1347,9 @@ function validationRefusedOutcome(tool, refusal) {
1320
1347
  isError: true,
1321
1348
  };
1322
1349
  }
1350
+ function neverStartedIf(neverStarted, outcome) {
1351
+ return neverStarted ? { ...outcome, notExecuted: true } : outcome;
1352
+ }
1323
1353
  async function prepareToolCall(currentContext, assistantMessage, toolCall, config, signal) {
1324
1354
  const tool = findToolByName(currentContext.tools, toolCall.name);
1325
1355
  if (!tool) {
@@ -1341,6 +1371,7 @@ async function prepareToolCall(currentContext, assistantMessage, toolCall, confi
1341
1371
  isError: true,
1342
1372
  };
1343
1373
  }
1374
+ let gateLetGo = false;
1344
1375
  try {
1345
1376
  const preparedToolCall = prepareToolCallArguments(tool, toolCall);
1346
1377
  let finalArgs = validateToolArguments(tool, preparedToolCall);
@@ -1370,6 +1401,7 @@ async function prepareToolCall(currentContext, assistantMessage, toolCall, confi
1370
1401
  }
1371
1402
  return { kind: "immediate", result: blocked, isError: true };
1372
1403
  }
1404
+ gateLetGo = true;
1373
1405
  const rewritten = beforeResult?.updatedInput;
1374
1406
  if (rewritten !== undefined) {
1375
1407
  const judged = structuredClone(rewritten);
@@ -1380,16 +1412,16 @@ async function prepareToolCall(currentContext, assistantMessage, toolCall, confi
1380
1412
  if (!sameToolArgs(validatedArgs, finalArgs)) {
1381
1413
  const rewrittenRefusal = await runInputValidation(tool, finalArgs, toolCall.id, signal, config.onToolInputValidationFault);
1382
1414
  if (rewrittenRefusal !== undefined)
1383
- return validationRefusedOutcome(tool, rewrittenRefusal);
1415
+ return neverStartedIf(true, validationRefusedOutcome(tool, rewrittenRefusal));
1384
1416
  }
1385
1417
  }
1386
1418
  }
1387
1419
  if (signal?.aborted) {
1388
- return {
1420
+ return neverStartedIf(gateLetGo, {
1389
1421
  kind: "immediate",
1390
1422
  result: createErrorToolResult("Operation aborted"),
1391
1423
  isError: true,
1392
- };
1424
+ });
1393
1425
  }
1394
1426
  return {
1395
1427
  kind: "prepared",
@@ -1399,21 +1431,22 @@ async function prepareToolCall(currentContext, assistantMessage, toolCall, confi
1399
1431
  };
1400
1432
  }
1401
1433
  catch (error) {
1402
- return {
1434
+ return neverStartedIf(gateLetGo, {
1403
1435
  kind: "immediate",
1404
1436
  result: thrownErrorToolResult(error),
1405
1437
  isError: true,
1406
- };
1438
+ });
1407
1439
  }
1408
1440
  }
1409
1441
  async function executePreparedToolCall(prepared, signal, emit, executeTool, abortResultDetails, onLateCancellation) {
1410
1442
  const updateEvents = [];
1411
1443
  let acceptingUpdates = true;
1412
1444
  if (signal?.aborted) {
1413
- return { result: createErrorToolResult("operation aborted before execution", { details: safeAbortDetails(abortResultDetails) }), isError: true };
1445
+ return { result: createErrorToolResult("operation aborted before execution", { details: safeAbortDetails(abortResultDetails) }), isError: true, notExecuted: true };
1414
1446
  }
1415
1447
  const work = (async () => {
1416
1448
  let outcome;
1449
+ let bodyStarted = false, bodyClosed = false;
1417
1450
  try {
1418
1451
  const body = () => prepared.tool.execute(prepared.toolCall.id, prepared.args, signal, (partialResult) => {
1419
1452
  if (!acceptingUpdates) {
@@ -1438,14 +1471,17 @@ async function executePreparedToolCall(prepared, signal, emit, executeTool, abor
1438
1471
  });
1439
1472
  updateEvents.push(delivery);
1440
1473
  });
1441
- const result = executeTool !== undefined ? await executeTool({ toolCall: prepared.toolCall, tool: prepared.tool, args: prepared.args }, body, signal) : await body();
1442
- outcome = { result, isError: result.isError === true };
1474
+ const startBody = () => (bodyClosed ? Promise.resolve(Object.assign(createErrorToolResult("operation not executed: the execution station had already settled this call without running its body"), { isError: true })) : ((bodyStarted = true), body()));
1475
+ const result = executeTool !== undefined ? await executeTool({ toolCall: prepared.toolCall, tool: prepared.tool, args: prepared.args }, startBody, signal) : await body();
1476
+ bodyClosed = !bodyStarted;
1477
+ outcome = neverStartedIf(executeTool !== undefined && !bodyStarted, { result, isError: result.isError === true });
1443
1478
  }
1444
1479
  catch (error) {
1445
- outcome = {
1480
+ bodyClosed = !bodyStarted;
1481
+ outcome = neverStartedIf(executeTool !== undefined && !bodyStarted, {
1446
1482
  result: thrownErrorToolResult(error),
1447
1483
  isError: true,
1448
- };
1484
+ });
1449
1485
  }
1450
1486
  acceptingUpdates = false;
1451
1487
  const deliveryFailure = await settleUpdateDeliveries(updateEvents);
@@ -1455,7 +1491,7 @@ async function executePreparedToolCall(prepared, signal, emit, executeTool, abor
1455
1491
  const details = annotateDeliveryFailure(outcome.result, {
1456
1492
  message: egressThrownText("same-principal", reason),
1457
1493
  });
1458
- return details === UNANNOTATED ? outcome : { result: { ...outcome.result, details }, isError: outcome.isError };
1494
+ return details === UNANNOTATED ? outcome : { ...outcome, result: { ...outcome.result, details } };
1459
1495
  })();
1460
1496
  return work;
1461
1497
  }
@@ -1574,7 +1610,7 @@ export async function finalizeToolOutcome(toolCall, executed, after, onMediaRefu
1574
1610
  }
1575
1611
  }
1576
1612
  }
1577
- return { toolCall, result, isError };
1613
+ return { toolCall, result, isError, ...(executed.notExecuted === true ? { notExecuted: true } : {}) };
1578
1614
  }
1579
1615
  function safeAbortDetails(fn) {
1580
1616
  try {
@@ -1613,6 +1649,7 @@ async function emitToolExecutionEnd(finalized, emit) {
1613
1649
  toolName: finalized.toolCall.name,
1614
1650
  result: finalized.result,
1615
1651
  isError: finalized.isError,
1652
+ ...(finalized.notExecuted === true ? { notExecuted: true } : {}),
1616
1653
  });
1617
1654
  }
1618
1655
  function createToolResultMessage(finalized) {
@@ -884,7 +884,9 @@ export type AgentEvent = {
884
884
  /**
885
885
  * Present (`true`) exactly when this end frame closes a call the loop settled WITHOUT
886
886
  * executing it — a never-started sibling under a batch-halt directive (see
887
- * {@link BeforeToolCallResult.haltRemaining}). LOOP-AUTHORED: it rides the event, never the
887
+ * {@link BeforeToolCallResult.haltRemaining}), or a call the loop itself refused after `beforeToolCall` had let it go and
888
+ * before its body started (the arguments the gate cleared failed the loop's own re-validation or re-reading, or the run
889
+ * was aborted in that gap). LOOP-AUTHORED: it rides the event, never the
888
890
  * tool result, so a tool cannot claim it about itself; a consumer that scopes
889
891
  * post-execution machinery to executed calls (batch observers, execution audits) keys on
890
892
  * this the way it keys on its own blocked-call records. Absent on every executed call.
@@ -2,6 +2,7 @@ import { SessionError, normalizeAnnouncedListing, normalizeReminderMark, normali
2
2
  import { leafIdAfterEntry } from "./storage-base.js";
3
3
  import { parseSessionTimestampMs } from "./timestamps.js";
4
4
  import { flattenableUserText, normalizeEngineSegments } from "../../core/untrusted-text.js";
5
+ import { isRunOrigin } from "../../core/run-origin.js";
5
6
  import { readStoredPromptEpoch } from "../../prompt-assembly/epoch.js";
6
7
  import { MAX_MINTED_TOOL_RESULT_REF_CHARS } from "../../core/tool-result-store.js";
7
8
  import { PERSISTED_OUTPUT_REFS_MAX_ENTRIES, SKILL_RETENTION_PER_SKILL_MAX_CHARS, SKILL_RETENTION_TOTAL_MAX_CHARS, } from "../compaction/utils.js";
@@ -284,6 +285,8 @@ function normalizeEngineProvenanceStamp(message, preserveActorAssertions = false
284
285
  }
285
286
  if (m.attachment !== undefined)
286
287
  delete m.attachment;
288
+ if (m.runOrigin !== undefined && !isRunOrigin(m.runOrigin))
289
+ delete m.runOrigin;
287
290
  if (m.engineMinted !== undefined && m.engineMinted !== true)
288
291
  delete m.engineMinted;
289
292
  if (m.provenance !== undefined && m.provenance !== "engine-note")
@@ -1,29 +1,37 @@
1
- import { type Session, type SessionCreateOptions, type SessionForkOptions, type SessionHead, type SessionMetadata, type SessionRepo, type SessionRow, type SessionTreeEntry } from "../harness/types.js";
1
+ import { type Session, type SessionCreateOptions, type SessionForkOptions, type SessionHead, type SessionMetadata, type SessionRepo, type SessionRow, type SessionRowExpectation, type SessionRowRead, type SessionTreeEntry } from "../harness/types.js";
2
2
  export declare class InMemorySessionRepo implements SessionRepo<SessionMetadata, SessionCreateOptions> {
3
- private sessions;
3
+ private rows;
4
4
  /** Each row's last touch (epoch ms). */
5
5
  private touched;
6
6
  create(options?: SessionCreateOptions): Promise<Session>;
7
7
  open(metadata: SessionMetadata): Promise<Session>;
8
- /** The row's head off the one session object that IS the row: every cell comes from that object, so a delete and re-create of the
9
- * id while this reads cannot mix two generations. */
8
+ /** The row's head off the one row that IS it: every cell comes from that row, so a delete and re-create of the id while this reads
9
+ * cannot mix two generations. */
10
10
  headOf(sessionId: string): Promise<SessionHead | undefined>;
11
+ /** The row in one synchronous read: its metadata, its head and a copy of its log, from the one row that is it. */
12
+ readRow(sessionId: string): Promise<SessionRowRead | undefined>;
11
13
  /** Every row, with its last {@link touch} as its activity time where it has one. This repo hands its sessions' storages out and never
12
14
  * sees their writes (an entry's own `timestamp` is the writer's data, not the time of the write), so a row never touched carries none
13
15
  * and a reader takes its `createdAt`. */
14
16
  list(): Promise<SessionRow[]>;
15
17
  /** Record activity on the row now (a missing row: nothing to record). The time lives and dies with the row: `delete` drops it. */
16
18
  touch(sessionId: string): Promise<void>;
17
- delete(metadata: SessionMetadata): Promise<void>;
19
+ /** Remove the row; with `expect`, only the row the expectation names, judged and removed in one synchronous step. */
20
+ delete(metadata: SessionMetadata, expect?: SessionRowExpectation): Promise<void>;
18
21
  fork(sourceMetadata: SessionMetadata, options: SessionForkOptions & SessionCreateOptions): Promise<Session>;
19
- /** 2c session-sync: the FULL log for export. InMemory holds everything (no F3 floor), so
20
- * `getEntries()` IS the full oldest-first log with `id`/`parentId` verbatim. */
22
+ /** 2c session-sync: the FULL log for export — {@link readRow}'s log (InMemory holds everything, no F3 floor: the full oldest-first log
23
+ * with `id`/`parentId` verbatim). A missing row is `not_found`. */
21
24
  exportEntries(sessionId: string): Promise<SessionTreeEntry[]>;
22
25
  /** 2c session-sync: import a verbatim log into `sessionId`. The single invariant gate runs first
23
- * ({@link validateEntriesForImport}, fail-closed); a new row records `owner`, an existing row keeps its metadata whole.
26
+ * ({@link validateEntriesForImport}, fail-closed); then, in one synchronous step, the row standing now is judged — the expectation
27
+ * (`options.expect`, {@link sessionRowMatches}) and the write law (`importRowCells`: a new row records `owner`, an existing row keeps its
28
+ * metadata whole and must already be `owner`'s) — and the log replaced; the head answered is the new row's.
24
29
  * design/171: the operator's trusted-import flag is forwarded to the gate that persists — see
25
30
  * SessionRepo.importEntries. */
26
31
  importEntries(sessionId: string, owner: string | undefined, entries: SessionTreeEntry[], options?: {
27
32
  preserveActorAssertions?: boolean;
28
- }): Promise<void>;
33
+ expect?: SessionRowExpectation;
34
+ }): Promise<SessionHead>;
35
+ /** Lay a row down under its id: one storage, one session over it, the metadata it was built with. */
36
+ private lay;
29
37
  }
@@ -1,15 +1,16 @@
1
1
  import { SessionError } from "../harness/types.js";
2
2
  import { validateEntriesForImport } from "./import-validate.js";
3
3
  import { InMemorySessionStorage } from "./memory-storage.js";
4
- import { assertForkTarget, createSessionId, createTimestamp, forkRowCells, frozenRow, getEntriesToFork, headOfSession, importRowCells, incarnationCell, ownerCell, toSession } from "./repo-utils.js";
4
+ import { resolveLeafId } from "./storage-base.js";
5
+ import { assertForkTarget, createSessionId, createTimestamp, forkRowCells, frozenRow, getEntriesToFork, headOfSession, importRowCells, incarnationCell, ownerCell, rowExpectationMissed, sessionRowMatches, toSession } from "./repo-utils.js";
5
6
  export class InMemorySessionRepo {
6
- sessions = new Map();
7
+ rows = new Map();
7
8
  touched = new Map();
8
9
  async create(options = {}) {
9
10
  if (options.id !== undefined) {
10
- const existing = this.sessions.get(options.id);
11
+ const existing = this.rows.get(options.id);
11
12
  if (existing)
12
- return existing;
13
+ return existing.session;
13
14
  }
14
15
  const metadata = frozenRow({
15
16
  id: options.id ?? createSessionId(),
@@ -17,35 +18,41 @@ export class InMemorySessionRepo {
17
18
  ...incarnationCell(undefined),
18
19
  ...ownerCell(options.owner),
19
20
  });
20
- const storage = new InMemorySessionStorage({ metadata });
21
- const session = toSession(storage);
22
- this.sessions.set(metadata.id, session);
23
- return session;
21
+ return this.lay(metadata, []).session;
24
22
  }
25
23
  async open(metadata) {
26
- const session = this.sessions.get(metadata.id);
27
- if (!session) {
24
+ const row = this.rows.get(metadata.id);
25
+ if (!row) {
28
26
  throw new SessionError("not_found", `Session not found: ${metadata.id}`);
29
27
  }
30
- return session;
28
+ return row.session;
31
29
  }
32
30
  async headOf(sessionId) {
33
- const row = this.sessions.get(sessionId);
34
- return row === undefined ? undefined : headOfSession(row);
31
+ const row = this.rows.get(sessionId);
32
+ return row === undefined ? undefined : headOfSession(row.session);
33
+ }
34
+ async readRow(sessionId) {
35
+ const row = this.rows.get(sessionId);
36
+ if (row === undefined)
37
+ return undefined;
38
+ const entries = await row.storage.getEntries();
39
+ return { metadata: row.metadata, head: { owner: row.metadata.owner ?? null, incarnation: row.metadata.incarnation, leafId: resolveLeafId(entries) }, entries };
35
40
  }
36
41
  async list() {
37
- return Promise.all([...this.sessions.entries()].map(async ([id, session]) => {
38
- const meta = await session.getMetadata();
42
+ return [...this.rows.entries()].map(([id, row]) => {
39
43
  const touched = this.touched.get(id);
40
- return touched !== undefined ? { ...meta, lastActiveAt: touched } : meta;
41
- }));
44
+ return touched !== undefined ? { ...row.metadata, lastActiveAt: touched } : row.metadata;
45
+ });
42
46
  }
43
47
  async touch(sessionId) {
44
- if (this.sessions.has(sessionId))
48
+ if (this.rows.has(sessionId))
45
49
  this.touched.set(sessionId, Date.now());
46
50
  }
47
- async delete(metadata) {
48
- this.sessions.delete(metadata.id);
51
+ async delete(metadata, expect) {
52
+ const row = this.rows.get(metadata.id);
53
+ if (!sessionRowMatches(expect, row?.metadata, () => row.storage.logMarkNow()))
54
+ throw rowExpectationMissed(metadata.id, "delete");
55
+ this.rows.delete(metadata.id);
49
56
  this.touched.delete(metadata.id);
50
57
  }
51
58
  async fork(sourceMetadata, options) {
@@ -57,25 +64,28 @@ export class InMemorySessionRepo {
57
64
  createdAt: createTimestamp(),
58
65
  ...forkRowCells(await source.getMetadata(), options.owner),
59
66
  });
60
- const storage = new InMemorySessionStorage({ metadata, entries: forkedEntries });
61
- const session = toSession(storage);
62
- this.sessions.set(metadata.id, session);
63
- return session;
67
+ return this.lay(metadata, forkedEntries).session;
64
68
  }
65
69
  async exportEntries(sessionId) {
66
- const session = await this.open({ id: sessionId, createdAt: "" });
67
- return session.getStorage().getEntries();
70
+ const row = await this.readRow(sessionId);
71
+ if (row === undefined)
72
+ throw new SessionError("not_found", `Session not found: ${sessionId}`);
73
+ return row.entries;
68
74
  }
69
75
  async importEntries(sessionId, owner, entries, options) {
70
76
  ownerCell(owner);
71
77
  const validated = validateEntriesForImport(entries, options);
72
- let prior = this.sessions.get(sessionId);
73
- let header = prior !== undefined ? await prior.getMetadata() : undefined;
74
- while (this.sessions.get(sessionId) !== prior) {
75
- prior = this.sessions.get(sessionId);
76
- header = prior !== undefined ? await prior.getMetadata() : undefined;
77
- }
78
- const metadata = frozenRow(importRowCells(sessionId, owner, header, createTimestamp()));
79
- this.sessions.set(sessionId, toSession(new InMemorySessionStorage({ metadata, entries: validated })));
78
+ const prior = this.rows.get(sessionId);
79
+ if (!sessionRowMatches(options?.expect, prior?.metadata, () => prior.storage.logMarkNow()))
80
+ throw rowExpectationMissed(sessionId, "import");
81
+ const metadata = frozenRow(importRowCells(sessionId, owner, prior?.metadata, createTimestamp()));
82
+ this.lay(metadata, validated);
83
+ return { owner: metadata.owner ?? null, incarnation: metadata.incarnation, leafId: resolveLeafId(validated) };
84
+ }
85
+ lay(metadata, entries) {
86
+ const storage = new InMemorySessionStorage({ metadata, entries });
87
+ const row = { session: toSession(storage), storage, metadata };
88
+ this.rows.set(metadata.id, row);
89
+ return row;
80
90
  }
81
91
  }
@@ -0,0 +1,38 @@
1
+ /** The fork point a store copies up to: `{}` is the whole log, `{ entryId, position: "at" }` the path from the root down to that entry. It is the answer
2
+ * `settledForkOptions` gives, and the question `selectForkRows` takes. */
3
+ export interface ForkPoint {
4
+ entryId?: string;
5
+ position?: "at";
6
+ }
7
+ /** How the walk reads a log: the row an id names (`undefined` = the log holds none), a row's own id, and the id of its parent (`null` or `undefined` = it has none). */
8
+ export interface ParentLinks<T> {
9
+ read(id: string): T | undefined;
10
+ idOf(row: T): string;
11
+ parentOf(row: T): string | null | undefined;
12
+ }
13
+ /**
14
+ * The one walk up a log's parent chain: the rows from the root down to `start`, root first. The chain ends at a row with no parent, or at `floorId`
15
+ * (a bounded window's root — its parent is not required to exist). A parent the log does not hold is `invalid_session` naming it, a chain that
16
+ * returns to a row it already stood on is refused by the shared guard; neither is followed.
17
+ */
18
+ export declare function pathToRoot<T>(start: T, links: ParentLinks<T>, floorId?: string | null): T[];
19
+ /** How a log row is read by `selectForkRows`: its entry id and its parent's (`null` = a root). */
20
+ export interface ForkRowShape<R> {
21
+ idOf(row: R): string;
22
+ parentOf(row: R): string | null;
23
+ }
24
+ /**
25
+ * Picks the rows a fork copies out of a whole log (oldest first) and the new session's leaf — for a store that moves rows as bytes and has no
26
+ * `SessionRepo.fork` to hand the answer to. `point` is `settledForkOptions`' answer: `{}` copies every row (other branches too) and keeps
27
+ * `sourceLeafId`; `{ entryId, position: "at" }` copies the rows on the path from the root to that entry (the path, not a prefix of the log: other
28
+ * branches stay behind) and the leaf is that entry. The rows keep their order.
29
+ *
30
+ * Refusals are the engine's, word for word: a fork point the log does not hold is `invalid_fork_target`, a parent missing part-way up the path (an empty
31
+ * parent id included) or a chain that returns to a row it stood on is `invalid_session` (the sentence `getPathToRoot` gives), and a fork point that
32
+ * names an entry with a `position` other than `at` is refused `invalid_fork_target` — rows are copied only for the point the judge answers. A point with
33
+ * no entry id is the whole-log form whatever else it carries, as `getEntriesToFork` reads it.
34
+ */
35
+ export declare function selectForkRows<R>(rows: readonly R[], sourceLeafId: string | null, point: ForkPoint, shape: ForkRowShape<R>): {
36
+ rows: R[];
37
+ leafId: string | null;
38
+ };
@@ -0,0 +1,39 @@
1
+ import { SessionError } from "../harness/types.js";
2
+ import { ParentChainGuard } from "./parent-chain-guard.js";
3
+ export function pathToRoot(start, links, floorId) {
4
+ const path = [];
5
+ const chain = new ParentChainGuard();
6
+ let current = start;
7
+ while (current !== undefined) {
8
+ const id = links.idOf(current);
9
+ chain.stepOnto(id);
10
+ path.push(current);
11
+ if (id === floorId)
12
+ break;
13
+ const parentId = links.parentOf(current);
14
+ if (parentId === null || parentId === undefined)
15
+ break;
16
+ const parent = parentId === "" ? undefined : links.read(parentId);
17
+ if (parent === undefined) {
18
+ throw new SessionError("invalid_session", `Entry ${parentId} not found`);
19
+ }
20
+ current = parent;
21
+ }
22
+ return path.reverse();
23
+ }
24
+ export function selectForkRows(rows, sourceLeafId, point, shape) {
25
+ if (point.entryId === undefined)
26
+ return { rows: [...rows], leafId: sourceLeafId };
27
+ if (point.position !== "at") {
28
+ throw new SessionError("invalid_fork_target", `fork point ${point.entryId} comes with a position the copy does not select rows for (${String(point.position)}) — only "at" is`);
29
+ }
30
+ const byId = new Map();
31
+ for (const row of rows)
32
+ byId.set(shape.idOf(row), row);
33
+ const target = byId.get(point.entryId);
34
+ if (target === undefined)
35
+ throw new SessionError("invalid_fork_target", `Entry ${point.entryId} not found`);
36
+ const links = { read: (id) => byId.get(id), idOf: (row) => shape.idOf(row), parentOf: (row) => shape.parentOf(row) };
37
+ const onPath = new Set(pathToRoot(target, links).map((row) => shape.idOf(row)));
38
+ return { rows: rows.filter((row) => onPath.has(shape.idOf(row))), leafId: point.entryId };
39
+ }
@@ -1,4 +1,4 @@
1
- import { type SessionHead, type SessionMetadata, type SessionStorage, type SessionTreeEntry } from "../harness/types.js";
1
+ import { SessionError, type SessionHead, type SessionLogMark, type SessionMetadata, type SessionRowExpectation, type SessionStorage, type SessionTreeEntry } from "../harness/types.js";
2
2
  import type { Session } from "../harness/types.js";
3
3
  export declare function createSessionId(): string;
4
4
  /** The {@link SessionMetadata.incarnation} cell for a write laying a row's metadata down — the bundled repos' ONE mint point.
@@ -20,15 +20,33 @@ export declare function compareOccupants(before: {
20
20
  } | undefined, after: {
21
21
  readonly incarnation?: SessionHead["incarnation"];
22
22
  } | undefined): "same" | "different" | "unknown";
23
+ /**
24
+ * THE judge of a conditional row write ({@link SessionRowExpectation}), called by the repo inside the write's own atomic step with the
25
+ * row as it stands there — its owner and occupant cell (`undefined` = no row) and a reading of its log's mark, asked for only when the
26
+ * log binds: no expectation ⇒ no precondition; `row: null` ⇒ the row must be absent; otherwise the row must be there with the same owner
27
+ * and the same occupant cell and — when `log` is given — a log of the same mark ({@link sessionLogMarkOf}). The occupant cell is compared
28
+ * as written, an absent token equal to an absent one: this asks whether any write changed the row since the read the expectation came
29
+ * from, not whether two parties name one occupant ({@link compareOccupants}, where unknown is never the same) — and since every write
30
+ * that creates a row mints a token, a row without one cannot be created again, so an absent cell is one generation. An expectation that
31
+ * is not of this shape is refused (a `TypeError` naming the member), never read as no precondition.
32
+ */
33
+ export declare function sessionRowMatches(expect: SessionRowExpectation | undefined, row: {
34
+ readonly owner?: string | null;
35
+ readonly incarnation?: string | undefined;
36
+ } | undefined, logNow: () => SessionLogMark): boolean;
37
+ /** The refusal of a conditional row write whose expectation the row does not meet: nothing was written. */
38
+ export declare function rowExpectationMissed(sessionId: string, what: string): SessionError;
23
39
  /** The {@link SessionHead} a session object shows: its metadata's owner and occupant and its storage's leaf, off that one object. */
24
40
  export declare function headOfSession(session: Session): Promise<SessionHead>;
25
41
  /** The {@link SessionMetadata.owner} cell the write creating a row records: `owner` (a principal name, or `null`; `undefined` = none
26
42
  * named = `null`). An `owner` that is neither is refused before the write, so no row ever holds an owner cell that reads as neither
27
43
  * — a blank string included: it names nobody, so it is no owner and not anonymous either. */
28
44
  export declare function ownerCell(owner: unknown): Pick<SessionMetadata, "owner">;
29
- /** The metadata an import lays down. An import replaces the log, never the row: an existing row keeps its metadata whole (its creation
30
- * time, lineage, placement, occupant and owner were recorded by the write that created it); an absent id is a new row recording `owner`
31
- * and a fresh occupant. `owner` is judged either way. */
45
+ /** The metadata an import lays down, and the import's refusals — one reading for every repo that replaces a log. An import replaces
46
+ * the log, never the row: an absent id is a new row recording `owner` and a fresh occupant; an existing row keeps its metadata whole
47
+ * (its creation time, lineage, placement, occupant and owner were recorded by the write that created it), and only a row that is
48
+ * already the importer's takes the log — owners compared null-safe, `undefined` naming `null` — so another owner's row is refused
49
+ * `conflict` and a placed row `placement_refused`, before anything is written. `owner` is judged either way. */
32
50
  export declare function importRowCells(sessionId: string, owner: unknown, existing: SessionMetadata | undefined, createdAt: string): SessionMetadata;
33
51
  /** The one decoding of a stored owner cell: a principal name is the owner; absence (`undefined`, `null`) is anonymous. A cell that is
34
52
  * there but is neither (a blank string included) cannot be read as anyone's, and reading it as anonymous would admit every
@@ -32,6 +32,48 @@ export function compareOccupants(before, after) {
32
32
  return "unknown";
33
33
  return a === b ? "same" : "different";
34
34
  }
35
+ export function sessionRowMatches(expect, row, logNow) {
36
+ if (expect === undefined)
37
+ return true;
38
+ const want = readRowExpectation(expect);
39
+ if (want.row === null)
40
+ return row === undefined;
41
+ if (row === undefined || (row.owner ?? null) !== want.row.owner || row.incarnation !== want.row.incarnation)
42
+ return false;
43
+ if (want.log === undefined)
44
+ return true;
45
+ const now = logNow();
46
+ return now.length === want.log.length && now.lastEntryId === want.log.lastEntryId;
47
+ }
48
+ function readRowExpectation(expect) {
49
+ if (typeof expect !== "object" || expect === null)
50
+ throw new TypeError(`a session row expectation must be an object { row, log? }, got ${expect === null ? "null" : typeof expect}`);
51
+ const { row, log } = expect;
52
+ const mark = log === undefined ? undefined : readLogMark(log);
53
+ if (row === null)
54
+ return { row: null, ...(mark !== undefined ? { log: mark } : {}) };
55
+ if (typeof row !== "object" || row === undefined)
56
+ throw new TypeError(`a session row expectation's row must be the row's owner and occupant, or null (no row), got ${typeof row}`);
57
+ const { owner, incarnation } = row;
58
+ if (owner !== null && typeof owner !== "string")
59
+ throw new TypeError(`a session row expectation's row.owner must be a principal name or null, got ${typeof owner}`);
60
+ if (incarnation !== undefined && typeof incarnation !== "string")
61
+ throw new TypeError(`a session row expectation's row.incarnation must be a string or absent, got ${typeof incarnation}`);
62
+ return { row: { owner, incarnation }, ...(mark !== undefined ? { log: mark } : {}) };
63
+ }
64
+ function readLogMark(log) {
65
+ if (typeof log !== "object" || log === null)
66
+ throw new TypeError(`a session row expectation's log must be a log mark { length, lastEntryId }, got ${log === null ? "null" : typeof log}`);
67
+ const { length, lastEntryId } = log;
68
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0)
69
+ throw new TypeError(`a session row expectation's log.length must be an integer ≥ 0`);
70
+ if (lastEntryId !== null && typeof lastEntryId !== "string")
71
+ throw new TypeError(`a session row expectation's log.lastEntryId must be an entry id or null, got ${typeof lastEntryId}`);
72
+ return { length, lastEntryId };
73
+ }
74
+ export function rowExpectationMissed(sessionId, what) {
75
+ return new SessionError("conflict", `session ${sessionId} is not the row the ${what} expected (it was deleted, created again, or written since it was read) — nothing was written; read the row again`);
76
+ }
35
77
  export async function headOfSession(session) {
36
78
  const meta = await session.getMetadata();
37
79
  return { owner: meta.owner ?? null, incarnation: meta.incarnation, leafId: await session.getStorage().getLeafId() };
@@ -49,7 +91,13 @@ export function ownerCell(owner) {
49
91
  }
50
92
  export function importRowCells(sessionId, owner, existing, createdAt) {
51
93
  const named = ownerCell(owner);
52
- return existing ?? { id: sessionId, createdAt, ...incarnationCell(undefined), ...named };
94
+ if (existing === undefined)
95
+ return { id: sessionId, createdAt, ...incarnationCell(undefined), ...named };
96
+ if (existing.placement !== undefined)
97
+ throw new SessionError("placement_refused", `session ${sessionId} belongs to the ${existing.placement.kind} placement partition — an import cannot replace its log`);
98
+ if ((existing.owner ?? null) !== named.owner)
99
+ throw new SessionError("conflict", `session ${sessionId} is not the importer's row — an import replaces only a log whose row the importer owns (or an anonymous row, by an anonymous import); nothing was written`);
100
+ return existing;
53
101
  }
54
102
  export function readOwnerCell(raw, sessionId) {
55
103
  if (raw === undefined || raw === null)
@@ -1,6 +1,12 @@
1
- import { type LeafEntry, type SessionMetadata, type SessionStorage, type SessionTreeEntry, type SessionWriteOptions } from "../harness/types.js";
1
+ import { type LeafEntry, type SessionLogMark, type SessionMetadata, type SessionStorage, type SessionTreeEntry, type SessionWriteOptions } from "../harness/types.js";
2
2
  /** Return the effective branch leaf after applying a session tree entry. */
3
3
  export declare function leafIdAfterEntry(entry: SessionTreeEntry): string | null;
4
+ /** A log's {@link SessionLogMark}: its length and its last entry's id — the one reading of the mark, for the reader that marks a log it
5
+ * read and for the repo that judges the log it is about to write over. */
6
+ export declare function sessionLogMarkOf(entries: readonly SessionTreeEntry[]): SessionLogMark;
7
+ /** The leaf a log leaves its session on: the leaf after its last entry (`null` for an empty log) — what a storage replaying the log
8
+ * answers, and so what a repo answers as the head of a row whose log it has just written or read whole. */
9
+ export declare function resolveLeafId(entries: readonly SessionTreeEntry[]): string | null;
4
10
  export declare abstract class BaseSessionStorage<TMetadata extends SessionMetadata = SessionMetadata> implements SessionStorage<TMetadata> {
5
11
  private readonly metadata;
6
12
  private readonly entries;
@@ -15,6 +21,9 @@ export declare abstract class BaseSessionStorage<TMetadata extends SessionMetada
15
21
  getFloorId(): string | null;
16
22
  getMetadata(): Promise<TMetadata>;
17
23
  getLeafId(): Promise<string | null>;
24
+ /** The log's mark ({@link sessionLogMarkOf}) as it stands at this instant, read synchronously: for a repo judging a row and writing it in
25
+ * one step with no await between them (an await would let a write through this storage land between the judgement and the write). */
26
+ logMarkNow(): SessionLogMark;
18
27
  protected createLeafEntry(leafId: string | null): LeafEntry;
19
28
  createEntryId(): Promise<string>;
20
29
  /**