@sema-agent/core 7.56.0 → 7.58.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 (319) hide show
  1. package/CHANGELOG.md +926 -0
  2. package/LICENSE +1 -1
  3. package/dist/agents/org-delivery-gate.js +3 -4
  4. package/dist/agents/peer-held-queue.d.ts +69 -49
  5. package/dist/agents/peer-held-queue.js +255 -106
  6. package/dist/agents/peer-session-drain.js +63 -43
  7. package/dist/agents/send-message-tool.js +3 -2
  8. package/dist/agents/subagent-steps.js +2 -4
  9. package/dist/agents/subagent.js +8 -8
  10. package/dist/brain/anthropic.js +16 -8
  11. package/dist/brain/open-responses.js +10 -8
  12. package/dist/brain/openai.js +11 -9
  13. package/dist/brain/provider-dialect.d.ts +3 -2
  14. package/dist/brain/provider-dialect.js +2 -2
  15. package/dist/brain/request-params.d.ts +6 -0
  16. package/dist/brain/request-params.js +14 -1
  17. package/dist/brain/route-adjudicator.js +2 -1
  18. package/dist/brain/stream-engine.d.ts +9 -0
  19. package/dist/brain/stream-engine.js +24 -10
  20. package/dist/brain/stream-shared.d.ts +5 -4
  21. package/dist/brain/stream-shared.js +4 -4
  22. package/dist/core/a2a.d.ts +2 -1
  23. package/dist/core/a2a.js +23 -10
  24. package/dist/core/allow-entry.d.ts +5 -11
  25. package/dist/core/allow-entry.js +19 -26
  26. package/dist/core/approval-object.d.ts +21 -5
  27. package/dist/core/approval-object.js +44 -17
  28. package/dist/core/ask-origin.d.ts +23 -4
  29. package/dist/core/ask-origin.js +5 -1
  30. package/dist/core/auto-compaction.d.ts +75 -6
  31. package/dist/core/auto-compaction.js +43 -27
  32. package/dist/core/auto-mode-directive.d.ts +29 -5
  33. package/dist/core/auto-mode-directive.js +38 -8
  34. package/dist/core/background-agent-store.d.ts +6 -2
  35. package/dist/core/background-agent-store.js +1 -1
  36. package/dist/core/checkpoint-requirements.d.ts +13 -1
  37. package/dist/core/checkpoint-requirements.js +4 -0
  38. package/dist/core/checkpoint-store.d.ts +44 -40
  39. package/dist/core/checkpoint-store.js +32 -14
  40. package/dist/core/cross-boundary-taint.js +4 -2
  41. package/dist/core/engine-notice.d.ts +4 -3
  42. package/dist/core/engine-notice.js +6 -0
  43. package/dist/core/file-history-store.d.ts +14 -8
  44. package/dist/core/file-history-store.js +14 -4
  45. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  46. package/dist/core/fs-write-gate-policy.js +7 -3
  47. package/dist/core/gate-fold.js +6 -3
  48. package/dist/core/gate-lanes.js +13 -5
  49. package/dist/core/git-worktree-env.d.ts +53 -11
  50. package/dist/core/git-worktree-env.js +96 -12
  51. package/dist/core/hooks.d.ts +6 -3
  52. package/dist/core/hooks.js +12 -5
  53. package/dist/core/human-input-projection.d.ts +1 -0
  54. package/dist/core/human-input-projection.js +3 -0
  55. package/dist/core/locked-config.d.ts +15 -1
  56. package/dist/core/locked-config.js +38 -2
  57. package/dist/core/mailbox-store.d.ts +62 -1
  58. package/dist/core/mailbox-store.js +59 -0
  59. package/dist/core/mcp-call-meta.d.ts +66 -0
  60. package/dist/core/mcp-call-meta.js +103 -0
  61. package/dist/core/mcp-connection-pool.d.ts +3 -1
  62. package/dist/core/mcp-connection-pool.js +3 -1
  63. package/dist/core/mcp-failure.d.ts +7 -1
  64. package/dist/core/mcp-failure.js +10 -0
  65. package/dist/core/mcp-name-judge.d.ts +46 -0
  66. package/dist/core/mcp-name-judge.js +61 -0
  67. package/dist/core/mcp-probe.d.ts +5 -1
  68. package/dist/core/mcp-probe.js +3 -6
  69. package/dist/core/mcp-server-link.d.ts +5 -2
  70. package/dist/core/mcp-server-spec.d.ts +46 -18
  71. package/dist/core/mcp-server-spec.js +1 -18
  72. package/dist/core/mcp.d.ts +6 -14
  73. package/dist/core/mcp.js +85 -65
  74. package/dist/core/memory-engine/consolidation-driver.js +4 -3
  75. package/dist/core/memory-engine/distiller.js +26 -17
  76. package/dist/core/memory-engine/layout.js +5 -2
  77. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  78. package/dist/core/memory-engine/scope-contract.js +80 -11
  79. package/dist/core/mode-policy.d.ts +8 -5
  80. package/dist/core/mode-policy.js +5 -4
  81. package/dist/core/mods/host.js +1 -1
  82. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  83. package/dist/core/mods/kernel/dispatch.js +10 -8
  84. package/dist/core/mods/kernel/events.d.ts +5 -1
  85. package/dist/core/mods/kernel/events.js +1 -1
  86. package/dist/core/mods/kernel/registration.d.ts +5 -1
  87. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  88. package/dist/core/mods/kernel/site-rules.js +10 -0
  89. package/dist/core/mods/package.d.ts +23 -0
  90. package/dist/core/mods/package.js +118 -0
  91. package/dist/core/mods/stations.d.ts +2 -2
  92. package/dist/core/mods/stations.js +1 -1
  93. package/dist/core/mods/tool-call.d.ts +5 -1
  94. package/dist/core/mods/tool-call.js +12 -3
  95. package/dist/core/park-selfcheck.js +2 -0
  96. package/dist/core/path-guard-rows.d.ts +20 -0
  97. package/dist/core/path-guard-rows.js +11 -0
  98. package/dist/core/peer-seat.d.ts +186 -0
  99. package/dist/core/peer-seat.js +307 -0
  100. package/dist/core/permission-rule-consent.d.ts +5 -3
  101. package/dist/core/permission-rule-consent.js +20 -15
  102. package/dist/core/permission-rule-model.d.ts +43 -2
  103. package/dist/core/permission-rule-model.js +52 -8
  104. package/dist/core/permission-rule-org.js +1 -1
  105. package/dist/core/present-plan-tool.d.ts +10 -1
  106. package/dist/core/present-plan-tool.js +46 -2
  107. package/dist/core/protocol-http-auth.d.ts +56 -31
  108. package/dist/core/protocol-http-auth.js +71 -42
  109. package/dist/core/protocol-naming.d.ts +20 -0
  110. package/dist/core/protocol-naming.js +20 -3
  111. package/dist/core/read-only-shell.d.ts +20 -5
  112. package/dist/core/read-only-shell.js +29 -14
  113. package/dist/core/redaction-marks.d.ts +16 -0
  114. package/dist/core/redaction-marks.js +16 -0
  115. package/dist/core/redaction-passes.js +8 -9
  116. package/dist/core/remote-env.d.ts +37 -1
  117. package/dist/core/remote-env.js +11 -0
  118. package/dist/core/resume-startup-cause.d.ts +24 -2
  119. package/dist/core/resume-startup-cause.js +20 -1
  120. package/dist/core/retention.d.ts +41 -15
  121. package/dist/core/retention.js +59 -12
  122. package/dist/core/rewrite-rejudge.d.ts +37 -0
  123. package/dist/core/rewrite-rejudge.js +40 -0
  124. package/dist/core/roles.js +50 -7
  125. package/dist/core/run-origin.d.ts +40 -0
  126. package/dist/core/run-origin.js +37 -0
  127. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  128. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  129. package/dist/core/runner/compact-session.d.ts +10 -0
  130. package/dist/core/runner/compact-session.js +202 -0
  131. package/dist/core/runner/compaction-call-options.d.ts +2 -2
  132. package/dist/core/runner/compaction-restate.d.ts +15 -6
  133. package/dist/core/runner/compaction-restate.js +28 -2
  134. package/dist/core/runner/compaction-seams.d.ts +21 -1
  135. package/dist/core/runner/compaction-seams.js +11 -8
  136. package/dist/core/runner/contracts.d.ts +36 -21
  137. package/dist/core/runner/derived-route-fallback.d.ts +13 -0
  138. package/dist/core/runner/derived-route-fallback.js +6 -0
  139. package/dist/core/runner/env-capability-census.d.ts +3 -2
  140. package/dist/core/runner/env-capability-census.js +9 -3
  141. package/dist/core/runner/gate-exit.d.ts +18 -4
  142. package/dist/core/runner/gate-exit.js +5 -1
  143. package/dist/core/runner/permission-rule-lanes.d.ts +7 -7
  144. package/dist/core/runner/permission-rule-lanes.js +17 -11
  145. package/dist/core/runner/prepare-acquire-reconcile.d.ts +3 -0
  146. package/dist/core/runner/prepare-acquire-reconcile.js +2 -1
  147. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  148. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  149. package/dist/core/runner/prepare-config-doors.d.ts +14 -5
  150. package/dist/core/runner/prepare-config-doors.js +16 -13
  151. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  152. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  153. package/dist/core/runner/prepare-gate-stations.js +1 -1
  154. package/dist/core/runner/prepare-hands-readface.d.ts +10 -4
  155. package/dist/core/runner/prepare-hands-readface.js +6 -1
  156. package/dist/core/runner/prepare-memory.d.ts +3 -0
  157. package/dist/core/runner/prepare-memory.js +19 -23
  158. package/dist/core/runner/prepare-park-ask.d.ts +2 -0
  159. package/dist/core/runner/prepare-park-ask.js +2 -2
  160. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  161. package/dist/core/runner/prepare-policy-chain.js +4 -6
  162. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  163. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  164. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  165. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  166. package/dist/core/runner/prepare-task.d.ts +4 -1
  167. package/dist/core/runner/prepare-task.js +46 -37
  168. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +13 -0
  169. package/dist/core/runner/prepare-tool-disclosure-mount.js +13 -7
  170. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  171. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  172. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  173. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  174. package/dist/core/runner/resume-admission.js +1 -1
  175. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  176. package/dist/core/runner/rewind-files.d.ts +2 -5
  177. package/dist/core/runner/rewind-files.js +9 -51
  178. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  179. package/dist/core/runner/run-harness-handlers.js +1 -8
  180. package/dist/core/runner/run-identity-wiring.js +1 -0
  181. package/dist/core/runner/run-leg.js +15 -22
  182. package/dist/core/runner/run-notification-lane.d.ts +2 -0
  183. package/dist/core/runner/run-notification-lane.js +5 -2
  184. package/dist/core/runner/run-recovery-lanes.js +3 -4
  185. package/dist/core/runner/run-settle-and-teardown.js +5 -11
  186. package/dist/core/runner/run-terminal-adoption.js +3 -4
  187. package/dist/core/runner/run-turn-boundary.js +3 -5
  188. package/dist/core/runner/runtask.d.ts +8 -1
  189. package/dist/core/runner/runtask.js +28 -34
  190. package/dist/core/runner/send-message-continuation.js +1 -1
  191. package/dist/core/runner/session-verb-doors.d.ts +28 -0
  192. package/dist/core/runner/session-verb-doors.js +48 -0
  193. package/dist/core/runner/session-write-ledger.d.ts +30 -0
  194. package/dist/core/runner/session-write-ledger.js +101 -0
  195. package/dist/core/runner/stream-settle-backstop.js +11 -14
  196. package/dist/core/runner/sub-agent-deny-lists.d.ts +25 -3
  197. package/dist/core/runner/sub-agent-deny-lists.js +21 -10
  198. package/dist/core/runner/teardown-bounded.d.ts +1 -0
  199. package/dist/core/runner/teardown-bounded.js +1 -0
  200. package/dist/core/runner/terminal-account.js +3 -3
  201. package/dist/core/runner/tool-end-body.js +1 -0
  202. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  203. package/dist/core/runner/tool-occurrence.js +2 -1
  204. package/dist/core/runner/write-protection-station.d.ts +8 -2
  205. package/dist/core/runner/write-protection-station.js +2 -0
  206. package/dist/core/runner-deps.d.ts +4 -4
  207. package/dist/core/secret-env.d.ts +4 -0
  208. package/dist/core/secret-env.js +3 -0
  209. package/dist/core/sensitive-path-policy.js +6 -7
  210. package/dist/core/session-log-transfer.d.ts +24 -0
  211. package/dist/core/session-log-transfer.js +166 -0
  212. package/dist/core/session-policy-store.d.ts +7 -2
  213. package/dist/core/session-policy-store.js +1 -1
  214. package/dist/core/session-store.d.ts +84 -19
  215. package/dist/core/session-store.js +162 -24
  216. package/dist/core/session.d.ts +92 -1
  217. package/dist/core/shell-read-silence.js +1 -0
  218. package/dist/core/shell-wrapper-projection.d.ts +1 -1
  219. package/dist/core/steer-replay.d.ts +4 -2
  220. package/dist/core/steer-replay.js +2 -1
  221. package/dist/core/store-contracts/background-agent-store-contract.js +1 -0
  222. package/dist/core/store-contracts/checkpoint-store-contract.js +19 -1
  223. package/dist/core/store-contracts/file-history-store-contract.js +9 -0
  224. package/dist/core/store-contracts/mailbox-store-contract.js +49 -1
  225. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  226. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  227. package/dist/core/store-contracts/session-store-contract.js +236 -2
  228. package/dist/core/task-event.d.ts +68 -8
  229. package/dist/core/task-registry-agent.d.ts +8 -4
  230. package/dist/core/task-registry-agent.js +14 -8
  231. package/dist/core/task-registry-shared.d.ts +36 -6
  232. package/dist/core/task-registry-shared.js +11 -0
  233. package/dist/core/task-registry.d.ts +1 -1
  234. package/dist/core/task-registry.js +1 -1
  235. package/dist/core/task-spec.d.ts +37 -0
  236. package/dist/core/task-stream.d.ts +2 -1
  237. package/dist/core/terminal-cause.d.ts +1 -1
  238. package/dist/core/tool-catalog-entries.d.ts +6 -0
  239. package/dist/core/tool-catalog-entries.js +2 -0
  240. package/dist/core/tool-name-aliases.d.ts +32 -2
  241. package/dist/core/tool-name-aliases.js +23 -0
  242. package/dist/core/tool-name-readings.d.ts +4 -0
  243. package/dist/core/tool-name-readings.js +1 -0
  244. package/dist/core/tool-policy.d.ts +10 -6
  245. package/dist/core/tool-policy.js +4 -7
  246. package/dist/core/tool-result-store.d.ts +17 -10
  247. package/dist/core/tool-result-store.js +3 -1
  248. package/dist/core/trace.d.ts +4 -1
  249. package/dist/core/trace.js +2 -1
  250. package/dist/core/types.d.ts +1 -1
  251. package/dist/core/untrusted-egress.d.ts +18 -0
  252. package/dist/core/untrusted-egress.js +82 -12
  253. package/dist/core/wiring-manifest.d.ts +12 -3
  254. package/dist/core/wiring-manifest.js +4 -3
  255. package/dist/core/workspace-snapshot.d.ts +44 -0
  256. package/dist/core/workspace-snapshot.js +34 -0
  257. package/dist/core/write-protect.d.ts +43 -3
  258. package/dist/core/write-protect.js +43 -16
  259. package/dist/engine/execution-env/node-execution-env.js +15 -11
  260. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  261. package/dist/engine/harness/agent-harness.d.ts +12 -5
  262. package/dist/engine/harness/agent-harness.js +13 -2
  263. package/dist/engine/harness/types.d.ts +48 -7
  264. package/dist/engine/harness/types.js +5 -1
  265. package/dist/engine/llm/types.d.ts +12 -3
  266. package/dist/engine/llm/types.js +1 -1
  267. package/dist/engine/loop/agent-loop.d.ts +1 -4
  268. package/dist/engine/loop/agent-loop.js +26 -4
  269. package/dist/engine/session/import-validate.js +3 -0
  270. package/dist/engine/session/memory-repo.d.ts +17 -9
  271. package/dist/engine/session/memory-repo.js +44 -34
  272. package/dist/engine/session/repo-utils.d.ts +22 -4
  273. package/dist/engine/session/repo-utils.js +49 -1
  274. package/dist/engine/session/storage-base.d.ts +10 -1
  275. package/dist/engine/session/storage-base.js +7 -1
  276. package/dist/index.d.ts +23 -11
  277. package/dist/index.js +15 -6
  278. package/dist/internal/harness-types.d.ts +1 -1
  279. package/dist/internal/harness.d.ts +4 -3
  280. package/dist/internal/harness.js +3 -2
  281. package/dist/stores/file/checkpoint-store.d.ts +0 -4
  282. package/dist/stores/file/checkpoint-store.js +0 -1
  283. package/dist/stores/file/file-history-store.js +12 -4
  284. package/dist/stores/file/index.d.ts +4 -1
  285. package/dist/stores/file/index.js +4 -1
  286. package/dist/stores/file/mailbox-store.d.ts +2 -1
  287. package/dist/stores/file/mailbox-store.js +26 -1
  288. package/dist/stores/file/session-store.d.ts +15 -8
  289. package/dist/stores/file/session-store.js +28 -13
  290. package/dist/tools/fs/bash-readonly-classifier.d.ts +15 -19
  291. package/dist/tools/fs/bash-readonly-classifier.js +5 -10
  292. package/dist/tools/fs/fs-bash.js +10 -3
  293. package/dist/tools/fs/fs-write.d.ts +6 -3
  294. package/dist/tools/fs/fs-write.js +8 -7
  295. package/dist/tools/fs/index.d.ts +3 -0
  296. package/dist/tools/fs/index.js +1 -1
  297. package/dist/tools/fs/pattern-kill-guard.d.ts +3 -2
  298. package/dist/tools/fs/pattern-kill-guard.js +68 -36
  299. package/dist/tools/fs/safety.js +40 -8
  300. package/dist/tools/fs/search.js +6 -24
  301. package/dist/tools/fs/shell-read-check.d.ts +18 -1
  302. package/dist/tools/fs/shell-read-check.js +66 -16
  303. package/dist/tools/fs/shell-read-establish.js +2 -1
  304. package/dist/tools/fs/shell-read-identity.d.ts +12 -9
  305. package/dist/tools/fs/shell-read-identity.js +10 -5
  306. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  307. package/dist/tools/web.js +9 -7
  308. package/dist/tools/worktree.d.ts +42 -15
  309. package/dist/tools/worktree.js +60 -32
  310. package/package.json +4 -2
  311. package/test/export-surface.snapshot.json +141 -3
  312. package/wire-changes/core-stores-sql@7.57.0.json +29 -0
  313. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  314. package/wire-changes/core@7.57.0.json +1487 -0
  315. package/wire-changes/core@7.58.0.json +2188 -0
  316. package/wire-changes/mods-kernel@7.57.0.json +29 -0
  317. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  318. package/wire-changes/primitives@7.57.0.json +245 -0
  319. package/wire-changes/primitives@7.58.0.json +29 -0
@@ -59,6 +59,7 @@ export async function runLeg(input) {
59
59
  let abortedLive = false;
60
60
  let userInterruptedLive = false;
61
61
  let strandedHumanAnswers = [];
62
+ const legRunOrigin = prepared.wiringManifest.leg?.runOrigin;
62
63
  try {
63
64
  if (prepared.abortController.signal.aborted) {
64
65
  const e = new Error("run aborted");
@@ -69,7 +70,6 @@ export async function runLeg(input) {
69
70
  const walltimeExhaustedResume = effectiveTimeoutMs !== undefined && effectiveTimeoutMs <= 0;
70
71
  const approvalWords = approvalWordsOf(resume.outcome);
71
72
  const approvalFrames = owedApprovalWords(approvalWords, uuidv7());
72
- let approvalCommitted = false;
73
73
  prepared.undeliveredContinuationRef.current.parkedSteers.push(...approvalFrames);
74
74
  const resumeWindowRetryAfterMs = !walltimeExhaustedResume && prepared.usageGovernance !== undefined ? await prepared.usageGovernance.check(Date.now()) : undefined;
75
75
  if (resumeWindowRetryAfterMs !== undefined) {
@@ -225,6 +225,7 @@ export async function runLeg(input) {
225
225
  ...(steer.actor !== undefined ? { actor: steer.actor } : {}),
226
226
  ...(steer.actor?.issuer !== undefined ? { issuer: steer.actor.issuer } : {}),
227
227
  ...(spec.principal !== undefined ? { principal: spec.principal } : {}),
228
+ ...(steer.runOrigin !== undefined ? { runOrigin: steer.runOrigin } : {}),
228
229
  }),
229
230
  ...ident(),
230
231
  });
@@ -244,10 +245,10 @@ export async function runLeg(input) {
244
245
  (steer.trusted ? formatHookFeedback(projected, prepared.reminderMark) : delimitUntrusted("supervisor steering message", projected));
245
246
  if (steer.trusted)
246
247
  engineSegments.push({ start, end: continuation.length });
247
- appliedEvents.push({
248
- ...buildAppliedHumanInputEvent({ carrier: source, source, sessionSeq: nextHumanInputSeq(prepared.harness), inputId: steer.inputId, actor: steer.actor, principal: spec.principal }),
248
+ appliedEvents.push(() => ({
249
+ ...buildAppliedHumanInputEvent({ carrier: source, source, sessionSeq: nextHumanInputSeq(prepared.harness), inputId: steer.inputId, actor: steer.actor, principal: spec.principal, runOrigin: steer.runOrigin }),
249
250
  ...ident(),
250
- });
251
+ }));
251
252
  }
252
253
  if (approvalWords !== undefined)
253
254
  continuation = withApprovalWords(continuation, engineSegments, approvalWords);
@@ -259,8 +260,6 @@ export async function runLeg(input) {
259
260
  prepared.batchHaltRef.current = { rejectedToolCallId: pending.toolCallId };
260
261
  prepared.undeliveredContinuationRef.current = { parkedSteers: [...resumeFrames.map(({ entry }) => entry).filter((e) => !withheldSteerIds.has(e.inputId)), ...approvalFrames], orphanTasks };
261
262
  if (!prepared.abortController.signal.aborted) {
262
- if (resume !== undefined)
263
- resume.decisionDelivered = true;
264
263
  registerAdvisorReceipt(prepared, continuation);
265
264
  if (gitResumeDelivered !== undefined) {
266
265
  const delivered = gitResumeDelivered;
@@ -284,24 +283,15 @@ export async function runLeg(input) {
284
283
  prepared.frameReceipts.pending.push({ source: "posture", text: continuation, commit: () => undefined });
285
284
  if (unavailableResume !== undefined)
286
285
  prepared.frameReceipts.pending.push({ source: "mcp_unavailable", text: continuation, commit: () => void (settleMcpUnavailable(prepared, unavailableResume.entries), queue.push({ type: "steering_injected", source: "mcp_unavailable", preview: redactThenCut(unavailableResume.body, 220), ...ident() }), (rs.attach.attachmentsInjected += 1)) });
287
- if (approvalFrames.length > 0) {
288
- prepared.frameReceipts.pending.push({
289
- source: "approval_feedback",
290
- text: continuation,
291
- commit: () => {
292
- approvalCommitted = true;
293
- const seat = prepared.undeliveredContinuationRef.current;
294
- seat.parkedSteers = seat.parkedSteers.filter((f) => !approvalFrames.includes(f));
295
- },
296
- });
297
- }
298
286
  final = await withBrainSinks(() => prepared.harness.prompt(continuation, {
299
287
  engineSegments,
300
288
  settleUnansweredToolCalls: rejectionHalt !== undefined ? { halt: rejectionHalt } : {},
301
- onDelivered: () => {
302
- prepared.undeliveredContinuationRef.current = { parkedSteers: approvalCommitted ? [] : [...approvalFrames], orphanTasks: [] };
303
- for (const e of appliedEvents)
304
- queue.push(e);
289
+ onCommitted: () => {
290
+ if (resume !== undefined)
291
+ resume.decisionDelivered = true;
292
+ prepared.undeliveredContinuationRef.current = { parkedSteers: [], orphanTasks: [] };
293
+ for (const applied of appliedEvents)
294
+ queue.push(applied());
305
295
  },
306
296
  }));
307
297
  await flushGitMirror();
@@ -505,6 +495,7 @@ export async function runLeg(input) {
505
495
  ...(objectiveActor?.issuer !== undefined ? { issuer: objectiveActor.issuer } : {}),
506
496
  ...(spec.principal !== undefined ? { principal: spec.principal } : {}),
507
497
  ...(attachmentFrames.length > 0 ? { attachments: humanInputAttachmentsOf(attachmentFrames) } : {}),
498
+ ...(legRunOrigin !== undefined ? { runOrigin: legRunOrigin } : {}),
508
499
  }),
509
500
  ...ident(),
510
501
  });
@@ -513,6 +504,7 @@ export async function runLeg(input) {
513
504
  ...(enginePrefixChars > 0 ? { enginePrefixChars } : {}),
514
505
  ...(attachmentFrames.length > 0 ? { trailing: attachmentFrames.map((f) => f.seed) } : {}),
515
506
  ...(objectiveActor !== undefined ? { actor: objectiveActor } : {}),
507
+ ...(legRunOrigin !== undefined ? { runOrigin: legRunOrigin } : {}),
516
508
  }));
517
509
  await flushGitMirror();
518
510
  if (prepared.gitStatusRef.announced?.pending === true)
@@ -830,7 +822,8 @@ async function resolvePendingCall(runner, prepared, resume, emit, emitCommitted,
830
822
  for (;;) {
831
823
  const { targetReading: _belts, ...unread } = beltReq();
832
824
  const targetReading = (await prepared.stampCallTarget?.(unread, prepared.abortController.signal))?.targetReading;
833
- const atExecution = judgeApprovalObject(pendingAction, { tool: mounted().entry, args: executedArgs, skills: prepared.skillSpecs, skillToolName: SKILL_TOOL_NAME, ...(humanRewrite !== undefined ? { decided: resolvedArgs } : {}), targetReading }, "execution");
825
+ const reads = prepared.shellReadLandings?.(pendingAction.toolCallId);
826
+ const atExecution = judgeApprovalObject(pendingAction, { tool: mounted().entry, args: executedArgs, skills: prepared.skillSpecs, skillToolName: SKILL_TOOL_NAME, ...(humanRewrite !== undefined ? { decided: resolvedArgs } : {}), targetReading, reads }, "execution");
834
827
  if (atExecution !== "match")
835
828
  return atExecution.disposition === "reopen" ? reopen(atExecution) : vetoApproval(atExecution);
836
829
  tool = mounted().tool;
@@ -19,6 +19,8 @@ export interface RunNotificationLaneInput<R> {
19
19
  taskIdRef: TaskIdRef | undefined;
20
20
  /** borrowed-readonly — the stream layer's session-lock verb, handed to prepare; absent when the spec named its session. */
21
21
  holdSessionLock: ((sessionId: string) => Promise<void>) | undefined;
22
+ /** borrowed-mutable (the Runner's) — this leg's view of the session write ledger, handed to prepare; the stream layer closes it at the leg's end. */
23
+ legWrites: import("./session-write-ledger.js").LegWrites;
22
24
  /** borrowed-readonly — the Runner's deployment deps, read LIVE (`onError` in the park closure — after the run, on a swapped
23
25
  * catalog it is still the CURRENT sink; `models` and prepare's `deps` at the natural-snapshot pin); the one home of why it
24
26
  * is a seat and not a captured object is {@link RunnerDepsSeat}. */
@@ -1,5 +1,7 @@
1
1
  import { createPeerInboundChainRef, createPeerSelfRef } from "../../agents/peer-admission.js";
2
2
  import { boundInputHashOf } from "../canonical-json.js";
3
+ import { readPendingSteerQueue } from "../checkpoint-store.js";
4
+ import { wakeOpening } from "../run-origin.js";
3
5
  import { createLiveNotificationLane, DurableAppendObligations, injectionLaneOf, isDelegatedAgentTerminal, isTerminalTaskNotification, renderTaskNotificationXml, routeOrParkNotification, SystemInjectionQueue, taskNotificationDedupKey } from "../task-notification.js";
4
6
  import { ToolDetachHub } from "../tool-detach.js";
5
7
  import { pendingContentAskCallId } from "./decide-continuation.js";
@@ -8,13 +10,14 @@ export function runNotificationLane(input) {
8
10
  return obligations.run(() => runNotificationLaneAs(input, obligations));
9
11
  }
10
12
  async function runNotificationLaneAs(input, obligations) {
11
- const { spec, queue, resume, internals, taskIdRef, holdSessionLock, runner, self, sessions, sessionReadStates, sessionModeSeats, pendingSessionNotifications, prepareTask, next } = input;
13
+ const { spec, queue, resume, internals, taskIdRef, holdSessionLock, legWrites, runner, self, sessions, sessionReadStates, sessionModeSeats, pendingSessionNotifications, prepareTask, next } = input;
12
14
  const prepareResume = resume
13
15
  ? {
14
16
  leafId: resume.cp.leafId,
15
17
  suspendedBatch: new Set(resume.cp.pendingAction.kind === "tool_approval" ? resume.cp.pendingAction.batchToolCallIds : []),
16
18
  seed: resume.cp.state,
17
19
  outcome: resume.outcome,
20
+ ...((opening) => (opening !== undefined ? { opening } : {}))(resume.outcome.gate === "wake" ? wakeOpening(readPendingSteerQueue(resume.cp.state), resume.wakeMessage) : undefined),
18
21
  ...(resume.legMods !== undefined ? { legMods: resume.legMods } : {}),
19
22
  priorSuspendCount: resume.cp.suspendCount,
20
23
  priorLedger: resume.cp.resourceLedger,
@@ -128,7 +131,7 @@ async function runNotificationLaneAs(input, obligations) {
128
131
  }
129
132
  return injectTaskNotification(notification, opts);
130
133
  },
131
- }, self, taskIdRef, holdSessionLock);
134
+ }, self, taskIdRef, holdSessionLock, legWrites);
132
135
  pendingSessionNotifications.bindSessionBox(prepared.sessionId, prepared.sessionBox);
133
136
  const notificationLane = {
134
137
  get harness() { return notificationHarness; }, set harness(h) { notificationHarness = h; },
@@ -2,7 +2,7 @@ import { compactionKindOf } from "../task-notification.js";
2
2
  import { planRejectionClears } from "../context-edit.js";
3
3
  import { rosterToolName } from "../tool-roster.js";
4
4
  import { landStaleResultClears } from "./prepare-context-lane.js";
5
- import { compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, maybeCompact, mintCompactedEvent } from "../auto-compaction.js";
5
+ import { compactionFailureReason, compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, maybeCompact, mintCompactedEvent } from "../auto-compaction.js";
6
6
  import { emitTrace } from "../trace.js";
7
7
  import { isDegenerateCutMessage } from "../../brain/terminal-cause.js";
8
8
  import { rebaseCadenceWindows } from "./turn-attachments.js";
@@ -11,7 +11,7 @@ import { compactionEnabled } from "../context-settings.js";
11
11
  import { compactionRestateOptions } from "./compaction-restate.js";
12
12
  import { COMPACTION_FREED_EPSILON, COMPACTION_REGROWTH_FACTOR, MAX_CONSECUTIVE_COMPACTION_FAILURES } from "./compaction-knobs.js";
13
13
  import { compactionHookOptions, recordCompactionReuse, seamCCompactionOptions } from "./compaction-seams.js";
14
- import { asThrownError, thrownText } from "../thrown-value.js";
14
+ import { asThrownError } from "../thrown-value.js";
15
15
  export function runRecoveryLanes(input) {
16
16
  const { spec, prepared, queue, rs, ident, compactionBrain, compactionBreaker, windowSafetyOptions, callerStop, runner } = input;
17
17
  const runForcedCompactionPass = async (lane, turnSignal) => {
@@ -102,8 +102,7 @@ export function runRecoveryLanes(input) {
102
102
  }
103
103
  compactionBreaker.failures += 1;
104
104
  runner.deps.onError?.(asThrownError(err), { phase: "compaction", sessionId: prepared.sessionId });
105
- const msg = thrownText(err);
106
- queue.push({ type: "compaction_outcome", outcome: "failed", trigger: "forced", reason: msg.length > 512 ? `${msg.slice(0, 512)}…` : msg, ...passReport.end, ...ident() });
105
+ queue.push({ type: "compaction_outcome", outcome: "failed", trigger: "forced", reason: compactionFailureReason(err), ...passReport.end, ...ident() });
107
106
  return false;
108
107
  }
109
108
  };
@@ -5,7 +5,7 @@ import { adjudicateDerivedRoute, fallbackToPrimaryNotice, sameRouteIdentity } fr
5
5
  import { isDegenerateCutMessage } from "../../brain/terminal-cause.js";
6
6
  import { hasBackgroundShell, sweepRunBoundaryBackgroundShells } from "../background-shell.js";
7
7
  import { resolveCheckpointStore } from "../checkpoint-store.js";
8
- import { reopenReasonOf, reopenedUnstartedSentence, resumeStartupCauseOf } from "../resume-startup-cause.js";
8
+ import { compensateUnstarted, reopenReasonOf, resumeStartupCauseOf, unstartedRowSentence } from "../resume-startup-cause.js";
9
9
  import { classicEventBase, observeClassic } from "../mods/stations.js";
10
10
  import { modelCostToPricing } from "../pricing.js";
11
11
  import { hasDestroy, isIsolated } from "../remote-env.js";
@@ -139,17 +139,11 @@ export async function runSettleAndTeardown(input) {
139
139
  resume.pendingActionStarted !== true &&
140
140
  result.terminal.kind !== "completed" &&
141
141
  result.terminal.kind !== "paused" &&
142
- !(resumeDecisionWasNegative(resume) && resume.decisionDelivered === true) &&
143
- resume.onEnvRestoreFailed !== undefined) {
142
+ !(resumeDecisionWasNegative(resume) && resume.decisionDelivered === true)) {
144
143
  const reopenReason = reopenReasonOf(resumeStartupCauseOf(result.terminal.kind === "failed" ? result.terminal.code : undefined));
145
- try {
146
- await resume.onEnvRestoreFailed(reopenReason);
147
- rowReturned = true;
148
- amendTerminal(result, "resume.reopened_unstarted", (m) => `${m ?? "the resume leg did not complete"} — ${reopenedUnstartedSentence(reopenReason)}`);
149
- }
150
- catch {
151
- amendTerminal(result, "resume.reopen_failed_unstarted", (m) => `${m ?? "the resume leg did not complete"} — the approved action never started, and reopening the checkpoint FAILED: its state is unprovable from here. Re-read it before deciding; do NOT issue a fresh approval on the assumption the old one is dead`);
152
- }
144
+ const row = await compensateUnstarted(resume.reopenUnstarted, reopenReason);
145
+ rowReturned = row.kind === "reopened";
146
+ amendTerminal(result, rowReturned ? "resume.reopened_unstarted" : "resume.reopen_failed_unstarted", (m) => `${m ?? "the resume leg did not complete"} — ${unstartedRowSentence(row)}`);
153
147
  }
154
148
  settleOwedUserInput(owedUserInput, rowReturned, { taskId: spec.taskId ?? prepared.sessionId, sessionId: prepared.sessionId, runId: prepared.runId, parent: parentLegIds(internals) }, runner.deps.onNotice);
155
149
  prepared.sealReadStateSeat?.(ownCommittedTailRef.current);
@@ -1,4 +1,4 @@
1
- import { compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, maybeCompact } from "../auto-compaction.js";
1
+ import { compactionFailureReason, compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, maybeCompact } from "../auto-compaction.js";
2
2
  import { eventDefaultOn } from "../../prompt-assembly/event-registry.js";
3
3
  import { appendInterruptionMarker, reconcileInterruptedSession } from "../session-reconcile.js";
4
4
  import { emitTrace } from "../trace.js";
@@ -11,7 +11,7 @@ import { compactionRestateOptions } from "./compaction-restate.js";
11
11
  import { MAX_CONSECUTIVE_COMPACTION_FAILURES } from "./compaction-knobs.js";
12
12
  import { emitSettled, reconciledEnd } from "./tool-end-body.js";
13
13
  import { isApprovalWordsFrame } from "./approval-feedback.js";
14
- import { asThrownError, thrownText } from "../thrown-value.js";
14
+ import { asThrownError } from "../thrown-value.js";
15
15
  export async function runTerminalAdoption(input) {
16
16
  const { spec, queue, prepared, rs, stats, ident, emitCommitted, startedToolCallIds, toolLabels, timeout, compactionBrain, compactionBreaker, windowSafetyOptions, undrainedUserAtEnd, userInputLostAtEnd, final, abortedLive, userInterruptedLive, callerStop, runner, sessions, next } = input;
17
17
  let { threw } = input;
@@ -185,8 +185,7 @@ async function finish(spec, prepared, opts, runner, sessions) {
185
185
  opts?.onCompactionOutcome?.("mooted", "cancelled", opts.passReport.end);
186
186
  }
187
187
  else {
188
- const failMsg = thrownText(err);
189
- const failReason = failMsg.length > 512 ? `${failMsg.slice(0, 512)}…` : failMsg;
188
+ const failReason = compactionFailureReason(err);
190
189
  emitTrace(opts?.telemetry?.tracer ?? spec.tracer ?? runner.deps.tracer, () => ({
191
190
  kind: "compaction.failed",
192
191
  version: 1,
@@ -1,7 +1,7 @@
1
1
  import { compactionKindOf } from "../task-notification.js";
2
2
  import { mintSystemReminder } from "../reminder-mint.js";
3
3
  import { eventDefaultOn } from "../../prompt-assembly/event-registry.js";
4
- import { compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, maybeCompact, mintCompactedEvent, nextTrimForceBackoff, recordCompactionAndCheckRapidRefill } from "../auto-compaction.js";
4
+ import { compactionFailureReason, compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, manualCompactOutcomeOf, maybeCompact, mintCompactedEvent, nextTrimForceBackoff, recordCompactionAndCheckRapidRefill } from "../auto-compaction.js";
5
5
  import { emitTrace } from "../trace.js";
6
6
  import { redactThenCut } from "../../agents/subagent-steps.js";
7
7
  import { ATTACHMENT_BYTE_CAP, CHANGED_FILES_MAX, TOTAL_TOKENS_REMINDER_DEFAULT_MODE, attachmentEnvelopeTags, clipToBytes, collectDateChange, collectDueAttachments, collectInstructionsChange, commitAgentListing, commitInstructionsChange, commitSkillsListing, isIntactSource, rebaseCadenceWindows, renderAgentListingFrame, renderMcpDroppedTools, renderMcpInstructionsDelta, selectMcpDroppedBatch, renderSkillsListingFrame, renderToolsDelta } from "./turn-attachments.js";
@@ -18,7 +18,6 @@ import { COMPACTION_FREED_EPSILON, COMPACTION_REGROWTH_FACTOR, MAX_CONSECUTIVE_C
18
18
  import { compactionHookOptions, recordCompactionReuse, seamCCompactionOptions } from "./compaction-seams.js";
19
19
  import { contextUsageSections } from "../../prompt-assembly/section-usage.js";
20
20
  import { asThrownError } from "../thrown-value.js";
21
- import { egressThrownText } from "../untrusted-egress.js";
22
21
  const BATCH_CONTEXT_MIN_KEEP_BYTES = 160;
23
22
  const BATCH_TRUNCATION_MARKER = "\n…[truncated]";
24
23
  export function createTurnBoundary(input) {
@@ -614,7 +613,7 @@ export function createTurnBoundary(input) {
614
613
  ts: Date.now(),
615
614
  }));
616
615
  }
617
- manualOutcome = comp.compacted ? "compacted" : comp.blocked ? "blocked" : comp.disabled ? "disabled" : "noop";
616
+ manualOutcome = manualCompactOutcomeOf(comp);
618
617
  if (forceManual && !comp.compacted && !comp.blocked) {
619
618
  if (comp.disabled) {
620
619
  emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.disabled", version: 1, taskId: rs.telemetry.taskId, ts: Date.now() }));
@@ -671,8 +670,7 @@ export function createTurnBoundary(input) {
671
670
  else if (!prepared.abortController.signal.aborted) {
672
671
  compactionBreaker.failures += 1;
673
672
  runnerHooks.onError?.(err, { phase: "compaction", sessionId: prepared.sessionId });
674
- const msg = egressThrownText("same-principal", err);
675
- const failReason = msg.length > 512 ? `${msg.slice(0, 512)}…` : msg;
673
+ const failReason = compactionFailureReason(err);
676
674
  emitTrace(rs.telemetry.tracer, () => ({
677
675
  kind: "compaction.failed",
678
676
  version: 1,
@@ -8,6 +8,7 @@ import type { AgentDefinition, ModelRef, ModelRoles, RunnerDeps, TaskEvent, Task
8
8
  import { type ContextSettings, type ContextWindowOverlay } from "../context-settings.js";
9
9
  import type { ResumeRun, ResumeTaskConfig, RunInternals, RunnerSelfSeat } from "./contracts.js";
10
10
  export type { ResumeTaskConfig } from "./contracts.js";
11
+ import type { CompactSessionRequest, CompactSessionResult } from "../auto-compaction.js";
11
12
  import type { RewindFilesRequest, RewindFilesResult } from "../file-history-store.js";
12
13
  /**
13
14
  * A stateless task runner. Holds shared deps (the external brain, model catalog) and an
@@ -18,6 +19,10 @@ export declare class Runner implements RunnerSelfSeat {
18
19
  readonly sessions: SessionStore;
19
20
  /** Per-sessionId serialization so two tasks never mutate one session concurrently. */
20
21
  private sessionLocks;
22
+ /** The lock's tail: the session writes this Runner's legs issued that have not settled — a session's next holder starts after them. */
23
+ private readonly sessionWrites;
24
+ /** The session-lock seats every out-of-run verb (`rewindFiles`, `compactSession`) is lent — ONE reading of "busy": a leg holds or awaits the lock, or a write issued to the session has not settled. */
25
+ private readonly verbLockSeats;
21
26
  /** Per-session read-file-state seats (CC parity: readFileState is session-scoped;
22
27
  * sema's map stays per-task, so the session scope lives here). A bounded CACHE, never an
23
28
  * authority: a durable resume's checkpoint seed wins on its leg, and a miss (cross-process,
@@ -134,8 +139,10 @@ export declare class Runner implements RunnerSelfSeat {
134
139
  * the same model resolution as tasks, returns real usage/model. No session, no tool execution, no
135
140
  * policy gate, no accounting — caller-trusted. */
136
141
  sideQuery(spec: SideQuerySpec): Promise<SideQueryResult>;
137
- /** The out-of-run code-only rewind, no model call and no session entry — the contract is {@link rewindSessionFiles}'s (refused while a leg of this Runner holds or awaits the session's lock). */
142
+ /** The out-of-run code-only rewind, no model call and no session entry — the contract is {@link rewindSessionFiles}'s (refused while a leg of this Runner holds or awaits the session's lock, or a write issued to it has not settled). */
138
143
  rewindFiles(request: RewindFilesRequest): Promise<RewindFilesResult>;
144
+ /** The out-of-run manual compaction, no run and no user turn — the contract is {@link compactIdleSession}'s (the one pass every lane runs; refused while a leg of this Runner holds or awaits the session's lock, or a write issued to it has not settled). */
145
+ compactSession(request: CompactSessionRequest): Promise<CompactSessionResult>;
139
146
  /** Run a task and stream live events; await `.result()` for the final TaskResult. `resume` (internal)
140
147
  * drives a durable resume through the same loop instead of a fresh objective prompt.
141
148
  * `internals` (internal) is a TRUSTED run-scoped channel for live per-task state the
@@ -13,7 +13,7 @@ import { announceReadDenySwap, screenSwappableDeps } from "../swappable-deps.js"
13
13
  import { runSideQuery } from "../side-query.js";
14
14
  import { PushQueue } from "../push-queue.js";
15
15
  import { TtlSessionStore } from "../session-store.js";
16
- import { errorCodeOf } from "./terminal-account.js";
16
+ import { compensateUnstarted, unstartedRowSentence } from "../resume-startup-cause.js";
17
17
  import { effectiveDelegationFacts, prepareTask } from "./prepare-task.js";
18
18
  import { SessionReadFileStates } from "./session-read-file-states.js";
19
19
  import { SessionModeSeats } from "./session-mode-seats.js";
@@ -24,6 +24,8 @@ import { PendingSessionNotifications } from "../task-notification.js";
24
24
  import { ToolDetachHub } from "../tool-detach.js";
25
25
  import { assertContextSettingsValue, assertContextSettingsWords, contextOverlayFor } from "../context-settings.js";
26
26
  import { createRunState } from "./initial-run-state.js";
27
+ import { SessionWriteLedger } from "./session-write-ledger.js";
28
+ import { teardownLegBudget } from "./teardown-bounded.js";
27
29
  import { emitSettled, reconciledEnd } from "./tool-end-body.js";
28
30
  import { answerFaceForRedeemedCall } from "./decide-continuation.js";
29
31
  import { createTurnBoundary } from "./run-turn-boundary.js";
@@ -63,11 +65,14 @@ import { runRecoveryLanes } from "./run-recovery-lanes.js";
63
65
  import { runGitLane } from "./run-git-lane.js";
64
66
  import { deploymentCanRerootChild } from "./child-tree.js";
65
67
  import { rewindSessionFiles } from "./rewind-files.js";
66
- import { thrownText } from "../thrown-value.js";
68
+ import { compactIdleSession } from "./compact-session.js";
69
+ import { egressThrownText } from "../untrusted-egress.js";
67
70
  export class Runner {
68
71
  deps;
69
72
  sessions;
70
73
  sessionLocks = new Map();
74
+ sessionWrites = new SessionWriteLedger();
75
+ verbLockSeats = { sessionBusy: (id) => this.sessionLocks.has(id) || this.sessionWrites.busy(id), takeSessionLock: (id) => this.acquireSessionLock(id) };
71
76
  sessionReadStates = new SessionReadFileStates();
72
77
  sessionModeSeats = new SessionModeSeats();
73
78
  pendingSessionNotifications = new PendingSessionNotifications();
@@ -96,7 +101,7 @@ export class Runner {
96
101
  version: 1,
97
102
  sessionId: context.sessionId,
98
103
  phase: context.phase,
99
- reason: (thrownText(sinkErr)).slice(0, 256),
104
+ reason: egressThrownText("same-principal", sinkErr).slice(0, 256),
100
105
  ts: Date.now(),
101
106
  }));
102
107
  }
@@ -159,11 +164,14 @@ export class Runner {
159
164
  const chain = prev.then(() => mine);
160
165
  this.sessionLocks.set(sessionId, chain);
161
166
  await prev.catch(() => { });
162
- return () => {
167
+ const releaseHold = () => {
163
168
  release();
164
169
  if (this.sessionLocks.get(sessionId) === chain)
165
170
  this.sessionLocks.delete(sessionId);
166
171
  };
172
+ if (this.sessionWrites.busy(sessionId))
173
+ await this.sessionWrites.settleBeforeHold(sessionId, teardownLegBudget()).catch((err) => { releaseHold(); throw err; });
174
+ return releaseHold;
167
175
  }
168
176
  swapDeps(next) {
169
177
  const screened = screenSwappableDeps(next);
@@ -233,7 +241,8 @@ export class Runner {
233
241
  sideQuery(spec) {
234
242
  return runWithReasoningWireFacts(() => { }, () => runWithCapabilityWithheld(() => { }, () => runSideQuery(spec, { brain: this.deps.brain, models: this.deps.models, roles: this.deps.roles })));
235
243
  }
236
- rewindFiles(request) { return rewindSessionFiles({ deps: this.deps, sessions: this.sessions, readStates: this.sessionReadStates, sessionBusy: (id) => this.sessionLocks.has(id), takeSessionLock: (id) => this.acquireSessionLock(id) }, request); }
244
+ rewindFiles(request) { return rewindSessionFiles({ deps: this.deps, sessions: this.sessions, readStates: this.sessionReadStates, ...this.verbLockSeats }, request); }
245
+ compactSession(request) { return compactIdleSession({ deps: this.deps, sessions: this.sessions, ...this.verbLockSeats }, request); }
237
246
  runTaskStream(spec, resume, internals) {
238
247
  if (resume !== undefined && (typeof resume !== "object" || resume.outcome === undefined)) {
239
248
  throw new TypeError("runTaskStream: `resume` must be a ResumeRun carrying `outcome` — got a value without one. " +
@@ -281,14 +290,16 @@ export class Runner {
281
290
  return held.taken;
282
291
  };
283
292
  const namedSessionId = spec.sessionId;
293
+ const legWrites = this.sessionWrites.openLeg((err, sessionId) => this.deps.onError?.(err, { phase: "degraded", sessionId }));
284
294
  const run = (async () => {
285
- if (namedSessionId)
286
- await holdSessionLock(namedSessionId);
287
295
  try {
296
+ if (namedSessionId)
297
+ await holdSessionLock(namedSessionId);
288
298
  await this.runLocked({
289
299
  spec,
290
300
  queue,
291
301
  holdSessionLock: namedSessionId ? undefined : holdSessionLock,
302
+ legWrites,
292
303
  setResult: (r) => {
293
304
  resultValue = r;
294
305
  const pcs = internals?.inheritedGate?.parentConstraints;
@@ -331,6 +342,7 @@ export class Runner {
331
342
  });
332
343
  }
333
344
  finally {
345
+ legWrites.close();
334
346
  releaseLock?.();
335
347
  publishReady(handle);
336
348
  manualCompactRef.closed = true;
@@ -382,9 +394,9 @@ export class Runner {
382
394
  };
383
395
  }
384
396
  runLocked(input) {
385
- const { spec, queue, setResult, onSuggestions, onReady, onSuspend, manualCompactRef, taskIdRef, holdSessionLock, resume, internals, notifyRef, captureOptOutRef, mcpRedialRef, entryActor, entryTracer } = input;
397
+ const { spec, queue, setResult, onSuggestions, onReady, onSuspend, manualCompactRef, taskIdRef, holdSessionLock, legWrites, resume, internals, notifyRef, captureOptOutRef, mcpRedialRef, entryActor, entryTracer } = input;
386
398
  return runNotificationLane({
387
- spec, queue, resume, internals, taskIdRef, holdSessionLock,
399
+ spec, queue, resume, internals, taskIdRef, holdSessionLock, legWrites,
388
400
  runner: this.depsSeat, self: this, sessions: this.sessions, sessionReadStates: this.sessionReadStates, sessionModeSeats: this.sessionModeSeats, pendingSessionNotifications: this.pendingSessionNotifications,
389
401
  prepareTask,
390
402
  next: ({ prepared, injectTaskNotification, deliveredAtTurnOpen, peerInboundChainRef, modelCatalog, notificationLane, unsubscribeTaskNotifications }) => {
@@ -527,37 +539,19 @@ export class Runner {
527
539
  preemptSignal: config.preemptSignal?.aborted ? undefined : config.preemptSignal,
528
540
  ...(answerFace !== undefined ? { onQuestion: answerFace } : {}),
529
541
  };
530
- const reopenFn = store.reopen?.bind(store);
542
+ const reopenUnstarted = async (reason) => ((await store.reopen(token, cp.scope, reason)) ? "reopened" : "declined");
531
543
  const recordExecutionOutcome = (gate) => store.recordExecutionOutcome(token, cp.scope, gate);
532
- const onEnvRestoreFailed = reopenFn
533
- ? async (reason) => {
534
- const reopened = await reopenFn(token, cp.scope, reason);
535
- if (!reopened) {
536
- throw new CheckpointError("checkpoint.reopen_failed", "checkpoint could not be reopened for a retry (missing, expired, or changed concurrently) — the resume failure is terminal");
537
- }
538
- }
539
- : undefined;
540
544
  if (resumeSignal?.aborted === true && consumeFlipDone) {
541
545
  throw new CheckpointError("checkpoint.resume_aborted", "the resume was aborted after its row was already claimed — the checkpoint stays consumed and the caller's rollback settles the outcome-unknown terminal (reopening here would strand a pending approval no redemption path can reach)");
542
546
  }
543
547
  if (resumeSignal?.aborted === true) {
544
- let reopenOutcome = "refused";
545
- if (onEnvRestoreFailed !== undefined) {
546
- try {
547
- await onEnvRestoreFailed("env_failed");
548
- reopenOutcome = "reopened";
549
- }
550
- catch (err) {
551
- reopenOutcome = errorCodeOf(err) === "checkpoint.reopen_failed" ? "refused" : "unknown";
552
- }
553
- }
554
- throw reopenOutcome === "reopened"
555
- ? new CheckpointError("checkpoint.resume_aborted", "the resume was aborted before the approved action could run — the checkpoint was reopened, so the same approval can be resumed with a live signal")
556
- : reopenOutcome === "refused"
557
- ? new CheckpointError("checkpoint.reopen_failed", "the resume was aborted before the approved action could run AND the store refused to reopen the checkpoint — the approval is terminally consumed and the suspended work was not executed; a retry needs a fresh approval")
558
- : new CheckpointError("checkpoint.reopen_failed", "the resume was aborted before the approved action could run and the reopen attempt FAILED IN FLIGHT — the checkpoint's state is unprovable from here: it may already be pending again. Re-read it before deciding; do NOT issue a fresh approval on the assumption the old one is dead (the approved action did NOT run either way)");
548
+ const row = await compensateUnstarted(reopenUnstarted, "env_failed");
549
+ const said = `the resume was aborted before the approved action could run — ${unstartedRowSentence(row)}`;
550
+ if (row.kind === "reopened")
551
+ throw new CheckpointError("checkpoint.resume_aborted", said);
552
+ throw new CheckpointError("checkpoint.reopen_failed", said);
559
553
  }
560
- return this.runTaskStream(spec, { cp, outcome: outcomeForStore, onEnvRestoreFailed, recordExecutionOutcome, ...(wakeMessage !== undefined ? { wakeMessage } : {}), ...(wakeHookContext !== undefined ? { wakeMessageHookContext: wakeHookContext } : {}), ...(legMods !== undefined ? { legMods } : {}) }, resumeInternals);
554
+ return this.runTaskStream(spec, { cp, outcome: outcomeForStore, reopenUnstarted, recordExecutionOutcome, ...(wakeMessage !== undefined ? { wakeMessage } : {}), ...(wakeHookContext !== undefined ? { wakeMessageHookContext: wakeHookContext } : {}), ...(legMods !== undefined ? { legMods } : {}) }, resumeInternals);
561
555
  }
562
556
  }
563
557
  export function runTask(spec, deps) {
@@ -9,7 +9,7 @@ function buildTier3ReviveSpawn(delegationForRevive, enrichSpecToolCtx) {
9
9
  prompt: req.prompt,
10
10
  run_in_background: true,
11
11
  ...(req.row.agentType !== undefined ? { subagent_type: req.row.agentType } : {}),
12
- ...(req.row.name !== undefined ? { name: req.row.name } : {}),
12
+ name: req.row.name,
13
13
  ...(req.row.model !== undefined ? { model: req.row.model } : {}),
14
14
  }, enrichSpecToolCtx({ toolCallId: `rv-${randomBytes(8).toString("hex")}`, reviveClaim: { row: req.row, rev: req.rev, ...(req.peerSeed !== undefined ? { peerSeed: req.peerSeed } : {}) } }));
15
15
  const o = (typeof out === "string" ? { content: out } : out);
@@ -0,0 +1,28 @@
1
+ import type { AcquiredSession, SessionStore } from "../session.js";
2
+ /** What the Runner lends an out-of-run verb for the session's lock. */
3
+ export interface SessionLockSeats {
4
+ /** Whether a leg of this Runner holds or awaits `sessionId`'s lock, or a write one issued to it has not settled. */
5
+ sessionBusy(sessionId: string): boolean;
6
+ /** Take `sessionId`'s lock; called synchronously after `sessionBusy` answered false, so nothing slips in between. */
7
+ takeSessionLock(sessionId: string): Promise<() => void>;
8
+ }
9
+ /**
10
+ * The request door: the request must be a plain data object — not a Proxy (its traps are the caller's code, and could
11
+ * answer the caller's read of a member differently from this one), its prototype `Object.prototype` or none (so no
12
+ * member is inherited) — judged before any member is read; its members are then taken from ONE snapshot of its own
13
+ * data properties, so no code of the request itself (a trap, a getter) runs while it is read and nothing read can
14
+ * change what is read next (an accessor member is a bad request); own keys inside the verb's closed set. `bad`
15
+ * throws the verb's own refusal; the member types are the verb's to judge on the returned snapshot.
16
+ */
17
+ export declare function readPlainRequest(request: unknown, keys: ReadonlySet<string>, bad: (what: string) => never): Record<string, unknown>;
18
+ /** A value as a refusal names it: a string clipped, a primitive spelled, anything else by its type. */
19
+ export declare function shownValue(v: unknown): string;
20
+ /**
21
+ * The idle claim: refused with `busy()` when a leg of this Runner is running or queued on the session (its state is
22
+ * not moved under it); otherwise the session's lock is claimed in this same synchronous step and held by the verb
23
+ * until it releases it, so a leg that arrives meanwhile waits for the verb.
24
+ */
25
+ export declare function claimIdleSession(seats: SessionLockSeats, sessionId: string, busy: () => Error): Promise<() => void>;
26
+ /** The session must exist — the same door and code a run with `requireExistingSession` meets. `verb` prefixes the
27
+ * message, `nothingDone` says what the verb did not do. */
28
+ export declare function acquireExistingSession(sessions: SessionStore, sessionId: string, verb: string, nothingDone: string): Promise<AcquiredSession>;
@@ -0,0 +1,48 @@
1
+ import { types } from "node:util";
2
+ import { isPlainRecord } from "../mods/kernel/receive.js";
3
+ import { readMember } from "../thrown-value.js";
4
+ export function readPlainRequest(request, keys, bad) {
5
+ if (typeof request !== "object" || request === null)
6
+ return bad(`the request must be a plain object, got ${request === null ? "null" : typeof request}`);
7
+ if (types.isProxy(request) || !isPlainRecord(request))
8
+ return bad("the request must be a plain data object (not a Proxy, and with no prototype that could supply a member)");
9
+ let descriptors;
10
+ try {
11
+ descriptors = Object.getOwnPropertyDescriptors(request);
12
+ }
13
+ catch {
14
+ return bad("the request could not be read");
15
+ }
16
+ const own = Reflect.ownKeys(descriptors);
17
+ const unknown = own.filter((k) => typeof k !== "string" || !keys.has(k));
18
+ if (unknown.length > 0)
19
+ return bad(`unknown key ${unknown.map((k) => JSON.stringify(String(k))).join(", ")}`);
20
+ const read = {};
21
+ for (const k of own) {
22
+ const d = descriptors[k];
23
+ if (!("value" in d))
24
+ return bad(`member ${JSON.stringify(k)} is an accessor, not a value`);
25
+ read[k] = d.value;
26
+ }
27
+ return read;
28
+ }
29
+ export function shownValue(v) {
30
+ return typeof v === "string" ? JSON.stringify(v.slice(0, 40)) : v === null || typeof v === "boolean" || typeof v === "number" ? String(v) : `a ${typeof v}`;
31
+ }
32
+ export function claimIdleSession(seats, sessionId, busy) {
33
+ if (seats.sessionBusy(sessionId))
34
+ throw busy();
35
+ return seats.takeSessionLock(sessionId);
36
+ }
37
+ export async function acquireExistingSession(sessions, sessionId, verb, nothingDone) {
38
+ try {
39
+ return await sessions.acquire(sessionId, { requireExisting: true });
40
+ }
41
+ catch (err) {
42
+ if (readMember(err, "code") !== "not_found")
43
+ throw err;
44
+ const e = new Error(`${verb}: session "${sessionId}" does not exist — ${nothingDone}`);
45
+ e.code = "resume.session_not_found";
46
+ throw e;
47
+ }
48
+ }
@@ -0,0 +1,30 @@
1
+ import type { SessionStorage } from "../session.js";
2
+ import type { LegWrites } from "./contracts.js";
3
+ export type { LegWrites };
4
+ export declare class SessionWriteLedger {
5
+ #private;
6
+ /** A leg's view. `report` receives the incidents (a refused write, a late settlement); a throwing sink is swallowed. */
7
+ openLeg(report: (err: Error, sessionId: string) => void): LegWrites;
8
+ /**
9
+ * The session's next hold starts here: resolves once `sessionId` has no write in flight, and throws `SessionError("conflict")`
10
+ * — the leg about to start has written nothing — when one is still unsettled after `ms`.
11
+ */
12
+ settleBeforeHold(sessionId: string, ms: number): Promise<void>;
13
+ /**
14
+ * Whether `sessionId` has a write in flight — a synchronous read. The session's next holder asks it before {@link settleBeforeHold}
15
+ * and awaits only on `true`: a session with nothing in flight takes no suspension point at its hold. The two reads sit on one tick,
16
+ * and nothing joins the set between the check and the hold's return — the previous holder's view is closed before its lock is
17
+ * released, the lock serialises holders, and a holder that is no leg (the rewind verb) issues no write through a view.
18
+ */
19
+ busy(sessionId: string): boolean;
20
+ /**
21
+ * Resolves `true` once `sessionId` has no write in flight, `false` when `ms` elapse first. The timer is not unref'd: the
22
+ * caller awaits this in foreground control flow (the teardown-bounded discipline), and it is cleared on settle.
23
+ */
24
+ drained(sessionId: string, ms: number): Promise<boolean>;
25
+ }
26
+ /**
27
+ * The acquired storage as a leg writes it: the two write members go through `leg.issue` (named by the entry type, `leaf` for a
28
+ * leaf move), every other member is the storage's own. Per leg and non-mutating (a Proxy), like the conflict watch above it.
29
+ */
30
+ export declare function writesThroughLeg(storage: SessionStorage, leg: LegWrites, sessionId: string): SessionStorage;