@sema-agent/core 7.62.0 → 7.64.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 (320) hide show
  1. package/CHANGELOG.md +936 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  23. package/dist/agents/subagent-transcript-placement.js +14 -0
  24. package/dist/agents/subagent.js +102 -54
  25. package/dist/brain/route-adjudicator.js +9 -4
  26. package/dist/core/allow-entry.d.ts +4 -0
  27. package/dist/core/approval-object.js +1 -1
  28. package/dist/core/arg-summary.js +1 -1
  29. package/dist/core/ask-origin.d.ts +1 -1
  30. package/dist/core/ask-origin.js +2 -2
  31. package/dist/core/ask-question.d.ts +2 -2
  32. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  33. package/dist/core/ask-unresolvable-notice.js +10 -3
  34. package/dist/core/auto-compaction.d.ts +7 -5
  35. package/dist/core/background-agent-store.d.ts +7 -0
  36. package/dist/core/background-agent-store.js +3 -0
  37. package/dist/core/canonical-json.d.ts +23 -13
  38. package/dist/core/canonical-json.js +4 -4
  39. package/dist/core/checkpoint-queries.d.ts +50 -4
  40. package/dist/core/checkpoint-queries.js +42 -17
  41. package/dist/core/checkpoint-requirements.d.ts +3 -3
  42. package/dist/core/checkpoint-requirements.js +2 -1
  43. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  44. package/dist/core/checkpoint-row-verdict.js +22 -2
  45. package/dist/core/checkpoint-store.d.ts +28 -11
  46. package/dist/core/checkpoint-store.js +45 -4
  47. package/dist/core/compliance.d.ts +6 -2
  48. package/dist/core/compliance.js +3 -3
  49. package/dist/core/context-settings.d.ts +40 -9
  50. package/dist/core/context-settings.js +32 -10
  51. package/dist/core/engine-attestation.d.ts +27 -7
  52. package/dist/core/engine-attestation.js +5 -1
  53. package/dist/core/engine-notice.d.ts +43 -5
  54. package/dist/core/extension-requester.d.ts +9 -0
  55. package/dist/core/extension-requester.js +7 -0
  56. package/dist/core/file-history-store.d.ts +28 -0
  57. package/dist/core/file-history-store.js +48 -5
  58. package/dist/core/fs-write-gate-policy.js +1 -1
  59. package/dist/core/gate-fold.js +2 -0
  60. package/dist/core/gate-lanes.js +2 -0
  61. package/dist/core/gate-outcome.d.ts +39 -2
  62. package/dist/core/gate-outcome.js +20 -1
  63. package/dist/core/git-worktree-env.d.ts +62 -3
  64. package/dist/core/git-worktree-env.js +91 -30
  65. package/dist/core/governance-codes.d.ts +9 -3
  66. package/dist/core/governance-codes.js +17 -3
  67. package/dist/core/leg-identity.d.ts +19 -1
  68. package/dist/core/leg-identity.js +12 -0
  69. package/dist/core/mailbox-store.d.ts +39 -4
  70. package/dist/core/mailbox-store.js +14 -2
  71. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  72. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  73. package/dist/core/memory-engine/consolidation.d.ts +74 -10
  74. package/dist/core/memory-engine/consolidation.js +183 -11
  75. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  76. package/dist/core/memory-engine/control-objects.js +151 -0
  77. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  78. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  79. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  80. package/dist/core/memory-engine/data-plane.js +11 -6
  81. package/dist/core/memory-engine/delegation-settlement.d.ts +58 -40
  82. package/dist/core/memory-engine/delegation-settlement.js +270 -85
  83. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  84. package/dist/core/memory-engine/dual-root.js +11 -7
  85. package/dist/core/memory-engine/engine.d.ts +136 -58
  86. package/dist/core/memory-engine/engine.js +491 -394
  87. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  88. package/dist/core/memory-engine/entry-scan.js +3 -0
  89. package/dist/core/memory-engine/file-backend.d.ts +62 -60
  90. package/dist/core/memory-engine/file-backend.js +122 -198
  91. package/dist/core/memory-engine/index.d.ts +8 -7
  92. package/dist/core/memory-engine/index.js +7 -6
  93. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  94. package/dist/core/memory-engine/landing-admission.js +3 -3
  95. package/dist/core/memory-engine/layout.d.ts +127 -46
  96. package/dist/core/memory-engine/layout.js +264 -109
  97. package/dist/core/memory-engine/memory-backend-contract.d.ts +26 -1
  98. package/dist/core/memory-engine/memory-backend-contract.js +476 -0
  99. package/dist/core/memory-engine/memory-deployment.d.ts +42 -11
  100. package/dist/core/memory-engine/memory-deployment.js +54 -15
  101. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  102. package/dist/core/memory-engine/origin-clearance.js +68 -9
  103. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  104. package/dist/core/memory-engine/scope-contract.js +68 -19
  105. package/dist/core/memory-engine/session-write-home.d.ts +37 -2
  106. package/dist/core/memory-engine/session-write-home.js +38 -11
  107. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  108. package/dist/core/memory-engine/sync-client.js +7 -0
  109. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  110. package/dist/core/memory-engine/sync-report.js +6 -2
  111. package/dist/core/memory-engine/tools.d.ts +2 -2
  112. package/dist/core/memory-engine/tools.js +10 -10
  113. package/dist/core/memory-engine/types.d.ts +155 -19
  114. package/dist/core/memory-engine/types.js +2 -0
  115. package/dist/core/memory.js +15 -6
  116. package/dist/core/mode-policy.js +3 -3
  117. package/dist/core/mods/agent-stations.d.ts +18 -0
  118. package/dist/core/mods/agent-stations.js +8 -6
  119. package/dist/core/mods/extension-call.d.ts +4 -0
  120. package/dist/core/mods/extension-call.js +8 -0
  121. package/dist/core/mods/stations.d.ts +20 -1
  122. package/dist/core/mods/stations.js +21 -2
  123. package/dist/core/mods/tool-call.js +3 -4
  124. package/dist/core/parent-spec-seat.d.ts +2 -2
  125. package/dist/core/park-selfcheck.js +2 -2
  126. package/dist/core/pause-registry.d.ts +2 -0
  127. package/dist/core/pause-registry.js +3 -0
  128. package/dist/core/peer-channel.d.ts +5 -0
  129. package/dist/core/permission-rule-consent.d.ts +26 -8
  130. package/dist/core/permission-rule-consent.js +76 -36
  131. package/dist/core/permission-rule-store.d.ts +72 -13
  132. package/dist/core/permission-rule-store.js +29 -8
  133. package/dist/core/read-only-shell.js +3 -2
  134. package/dist/core/redaction-marks.d.ts +8 -0
  135. package/dist/core/redaction-marks.js +6 -0
  136. package/dist/core/refusal-echo.d.ts +20 -0
  137. package/dist/core/refusal-echo.js +33 -0
  138. package/dist/core/remote-env.d.ts +12 -1
  139. package/dist/core/remote-env.js +3 -0
  140. package/dist/core/retention.d.ts +180 -10
  141. package/dist/core/retention.js +45 -0
  142. package/dist/core/retired-keys.d.ts +5 -0
  143. package/dist/core/retired-keys.js +3 -0
  144. package/dist/core/rule-offer-read.d.ts +0 -4
  145. package/dist/core/rule-offer-read.js +2 -18
  146. package/dist/core/runner/child-tree.d.ts +29 -3
  147. package/dist/core/runner/child-tree.js +39 -16
  148. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  149. package/dist/core/runner/classifier-ladder.js +4 -2
  150. package/dist/core/runner/compact-session.js +10 -7
  151. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  152. package/dist/core/runner/compaction-call-options.js +3 -2
  153. package/dist/core/runner/contracts.d.ts +39 -11
  154. package/dist/core/runner/delegation-owner.d.ts +10 -3
  155. package/dist/core/runner/delegation-owner.js +4 -1
  156. package/dist/core/runner/gate-exit.d.ts +6 -0
  157. package/dist/core/runner/gate-exit.js +13 -4
  158. package/dist/core/runner/inherited-ask-grants.js +1 -1
  159. package/dist/core/runner/memory-consolidation-driver.d.ts +10 -5
  160. package/dist/core/runner/memory-consolidation-driver.js +12 -9
  161. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  162. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  163. package/dist/core/runner/person-path-rows.d.ts +8 -3
  164. package/dist/core/runner/person-path-rows.js +5 -1
  165. package/dist/core/runner/placement-fence.d.ts +12 -0
  166. package/dist/core/runner/placement-fence.js +20 -6
  167. package/dist/core/runner/prepare-ask-lane.js +5 -5
  168. package/dist/core/runner/prepare-caps-and-workflow.d.ts +7 -2
  169. package/dist/core/runner/prepare-caps-and-workflow.js +7 -4
  170. package/dist/core/runner/prepare-config-doors.js +4 -0
  171. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  172. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  173. package/dist/core/runner/prepare-execution-env.js +17 -6
  174. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  175. package/dist/core/runner/prepare-gate-stations.js +5 -5
  176. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  177. package/dist/core/runner/prepare-hands-readface.js +5 -4
  178. package/dist/core/runner/prepare-inherited-gate.d.ts +13 -9
  179. package/dist/core/runner/prepare-inherited-gate.js +12 -6
  180. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  181. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  182. package/dist/core/runner/prepare-memory.d.ts +7 -2
  183. package/dist/core/runner/prepare-memory.js +41 -39
  184. package/dist/core/runner/prepare-park-ask.js +4 -3
  185. package/dist/core/runner/prepare-policy-chain.js +7 -7
  186. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  187. package/dist/core/runner/prepare-task.js +26 -18
  188. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  189. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  190. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  191. package/dist/core/runner/resume-admission.d.ts +2 -2
  192. package/dist/core/runner/resume-admission.js +2 -23
  193. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  194. package/dist/core/runner/role-resolution-table.js +62 -0
  195. package/dist/core/runner/run-compaction-machinery.js +2 -2
  196. package/dist/core/runner/run-identity-wiring.js +12 -9
  197. package/dist/core/runner/run-leg.js +9 -5
  198. package/dist/core/runner/run-notification-lane.js +22 -22
  199. package/dist/core/runner/run-recovery-lanes.js +3 -3
  200. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  201. package/dist/core/runner/run-terminal-adoption.js +1 -1
  202. package/dist/core/runner/run-turn-boundary.js +14 -15
  203. package/dist/core/runner/runtask.js +1 -1
  204. package/dist/core/runner/terminal-account.js +1 -1
  205. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  206. package/dist/core/runner/tool-occurrence.js +2 -2
  207. package/dist/core/runner-deps.d.ts +7 -3
  208. package/dist/core/secret-env.d.ts +1 -1
  209. package/dist/core/secret-env.js +4 -4
  210. package/dist/core/session-checkout.d.ts +168 -0
  211. package/dist/core/session-checkout.js +579 -0
  212. package/dist/core/session-store.d.ts +12 -4
  213. package/dist/core/session-store.js +23 -3
  214. package/dist/core/session.d.ts +16 -2
  215. package/dist/core/session.js +3 -0
  216. package/dist/core/shell-read-silence.js +8 -0
  217. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  218. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  219. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  220. package/dist/core/store-contracts/session-store-contract.js +39 -0
  221. package/dist/core/task-event.d.ts +30 -5
  222. package/dist/core/task-notification.d.ts +119 -32
  223. package/dist/core/task-notification.js +186 -100
  224. package/dist/core/task-registry-agent.d.ts +25 -2
  225. package/dist/core/task-registry-agent.js +56 -22
  226. package/dist/core/task-registry-shared.d.ts +33 -11
  227. package/dist/core/task-registry.d.ts +33 -9
  228. package/dist/core/task-registry.js +36 -18
  229. package/dist/core/task-spec-members.js +1 -1
  230. package/dist/core/task-spec.d.ts +27 -2
  231. package/dist/core/tool-errors.d.ts +14 -6
  232. package/dist/core/tool-errors.js +1 -1
  233. package/dist/core/tool-policy.d.ts +32 -13
  234. package/dist/core/tool-policy.js +27 -17
  235. package/dist/core/tool-result-store.d.ts +20 -0
  236. package/dist/core/tool-spec.d.ts +42 -19
  237. package/dist/core/trace.d.ts +3 -2
  238. package/dist/core/types.d.ts +1 -1
  239. package/dist/core/untrusted-egress.d.ts +15 -4
  240. package/dist/core/untrusted-egress.js +23 -22
  241. package/dist/core/workflow-journal-store.d.ts +11 -0
  242. package/dist/core/workflow-journal-store.js +7 -0
  243. package/dist/core/workflow-run-store.d.ts +9 -0
  244. package/dist/core/workflow-run-store.js +6 -0
  245. package/dist/core/workspace-snapshot.d.ts +3 -1
  246. package/dist/core/workspace-snapshot.js +1 -0
  247. package/dist/engine/compaction/compaction.d.ts +2 -1
  248. package/dist/engine/harness/types.d.ts +67 -1
  249. package/dist/engine/harness/types.js +108 -0
  250. package/dist/engine/session/import-validate.js +6 -1
  251. package/dist/engine/session/session.d.ts +30 -1
  252. package/dist/engine/session/session.js +48 -1
  253. package/dist/index.d.ts +12 -7
  254. package/dist/index.js +12 -7
  255. package/dist/internal/harness-types.d.ts +1 -1
  256. package/dist/orchestration/run-workflow-tool.d.ts +8 -1
  257. package/dist/orchestration/run-workflow-tool.js +8 -0
  258. package/dist/orchestration/workflow-types.d.ts +2 -1
  259. package/dist/orchestration/workflow.d.ts +6 -0
  260. package/dist/orchestration/workflow.js +5 -2
  261. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  262. package/dist/stores/file/checkpoint-store.js +4 -1
  263. package/dist/stores/file/file-history-store.d.ts +13 -0
  264. package/dist/stores/file/file-history-store.js +75 -13
  265. package/dist/stores/file/index.d.ts +11 -1
  266. package/dist/stores/file/index.js +7 -11
  267. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  268. package/dist/stores/file/permission-rule-store.js +75 -7
  269. package/dist/stores/file/session-store.js +2 -1
  270. package/dist/stores/file/tool-result-store.d.ts +14 -0
  271. package/dist/stores/file/tool-result-store.js +39 -2
  272. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  273. package/dist/stores/file/workflow-journal-store.js +17 -0
  274. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  275. package/dist/stores/file/workflow-run-store.js +15 -0
  276. package/dist/tools/fs/bash-program-position.js +3 -3
  277. package/dist/tools/fs/program-read-model.d.ts +34 -10
  278. package/dist/tools/fs/program-read-model.js +37 -7
  279. package/dist/tools/fs/program-read-model.rows.js +13 -2
  280. package/dist/tools/fs/read-deny.d.ts +28 -3
  281. package/dist/tools/fs/read-deny.js +18 -2
  282. package/dist/tools/fs/removal-targets.js +3 -3
  283. package/dist/tools/fs/safety.d.ts +2 -0
  284. package/dist/tools/fs/safety.js +1 -1
  285. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  286. package/dist/tools/fs/shell-read-argv.js +34 -29
  287. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  288. package/dist/tools/fs/shell-read-bindings.js +5 -1
  289. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  290. package/dist/tools/fs/shell-read-brace.js +79 -0
  291. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  292. package/dist/tools/fs/shell-read-check.js +16 -14
  293. package/dist/tools/fs/shell-read-establish.js +23 -16
  294. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  295. package/dist/tools/fs/shell-read-judge.js +3 -3
  296. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  297. package/dist/tools/fs/shell-read-plan.js +189 -93
  298. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  299. package/dist/tools/fs/shell-read-start.js +20 -12
  300. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  301. package/dist/tools/fs/shell-read-word.js +9 -5
  302. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  303. package/dist/tools/fs/shell-read-workdir.js +73 -12
  304. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  305. package/dist/tools/worktree.d.ts +3 -2
  306. package/dist/tools/worktree.js +7 -35
  307. package/package.json +3 -2
  308. package/test/export-surface.snapshot.json +135 -11
  309. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  310. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  311. package/wire-changes/core@7.63.0.json +3523 -0
  312. package/wire-changes/core@7.64.0.json +2653 -0
  313. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  314. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  315. package/wire-changes/primitives@7.63.0.json +445 -0
  316. package/wire-changes/primitives@7.64.0.json +30 -0
  317. package/dist/core/credential-vocabulary.d.ts +0 -176
  318. package/dist/core/credential-vocabulary.js +0 -190
  319. package/dist/core/redaction-passes.d.ts +0 -82
  320. package/dist/core/redaction-passes.js +0 -377
@@ -7,6 +7,7 @@ import { delimitUntrusted } from "./untrusted-text.js";
7
7
  import { boundedRedactedSummary } from "./untrusted-egress.js";
8
8
  import { mintCompletionId, commitCompletionIdIfEmpty, clipTaskOutput, assertOwnership, sleepPollStep, alreadyTerminalStopNote, canAccess, normalizeAgentName, engineAgentName, chosenAgentName, DURABLE_AGENT_HEARTBEAT_MS, DURABLE_AGENT_HANDLE_RE, BG_AGENT_REAP_STOP_ERROR, } from "./task-registry-shared.js";
9
9
  import { thrownLabel } from "./thrown-value.js";
10
+ import { readExtensionRequester } from "./extension-requester.js";
10
11
  import { closestName } from "./closest-name.js";
11
12
  import { agentStateSourceOfHandle, agentStateSummary, readAgentState } from "./agent-state.js";
12
13
  export function activeDelegationHandlesLane(core, scope, rootSessionId) {
@@ -25,7 +26,8 @@ export function activeDelegationOccupantsLane(core, scope, rootSessionId, caller
25
26
  const root = bh.rootSessionId ?? bh.parentSessionId ?? (bh.sessionScoped ? bh.owner : undefined);
26
27
  if (root !== rootSessionId)
27
28
  continue;
28
- out.push({ id: h.id, name: bh.name, reachable: caller !== undefined && canAccess(h, { ...caller, scope }) });
29
+ const requestedBy = readExtensionRequester(bh.requestedBy);
30
+ out.push({ id: h.id, name: bh.name, ...(requestedBy !== undefined ? { requestedBy } : {}), reachable: caller !== undefined && canAccess(h, { ...caller, scope }) });
29
31
  }
30
32
  return out;
31
33
  }
@@ -372,6 +374,7 @@ export function registerBackgroundAgentLane(core, input) {
372
374
  throw new Error(`TaskRegistry: background-agent id ${JSON.stringify(input.id)} does not match the a<hex> handle form`);
373
375
  }
374
376
  const id = input.id ?? core.mintTaskId("background_agent");
377
+ let carriedCompletionSink;
375
378
  if (input.durableSeed !== undefined) {
376
379
  const prior = core.handles.get(id);
377
380
  if (prior !== undefined) {
@@ -382,6 +385,8 @@ export function registerBackgroundAgentLane(core, input) {
382
385
  const priorLane = prior.durable;
383
386
  if (priorLane !== undefined)
384
387
  priorLane.poisoned = true;
388
+ if (parkedHandoff)
389
+ carriedCompletionSink = prior.parkedCompletionSink;
385
390
  core.handles.delete(id);
386
391
  }
387
392
  }
@@ -392,16 +397,19 @@ export function registerBackgroundAgentLane(core, input) {
392
397
  throw new Error(`TaskRegistry: background-agent name must be a non-empty string (got ${JSON.stringify(input.name)}); omit it to take the derived one`);
393
398
  }
394
399
  const name = input.name ?? engineAgentName(id);
400
+ const requestedBy = readExtensionRequester(input.requestedBy);
395
401
  core.handles.set(id, {
396
402
  id,
397
403
  type: "background_agent",
398
404
  status: input.initialStatus ?? "running",
399
405
  ...(input.parkedCheckpointToken !== undefined ? { parkedCheckpointToken: input.parkedCheckpointToken } : {}),
400
406
  ...(input.resolveParkedStop !== undefined ? { resolveParkedStop: input.resolveParkedStop } : {}),
407
+ ...(carriedCompletionSink !== undefined ? { parkedCompletionSink: carriedCompletionSink } : {}),
401
408
  ...(input.sessionScoped ? { sessionScoped: true } : {}),
402
409
  ...(input.description !== undefined ? { description: input.description } : {}),
403
410
  name,
404
411
  ...(input.agentType !== undefined ? { agentType: input.agentType } : {}),
412
+ ...(requestedBy !== undefined ? { requestedBy } : {}),
405
413
  ...(input.parentTaskId !== undefined ? { parentTaskId: input.parentTaskId } : {}),
406
414
  ...(input.parentSessionId !== undefined ? { parentSessionId: input.parentSessionId } : {}),
407
415
  ...(input.rootSessionId !== undefined ? { rootSessionId: input.rootSessionId } : {}),
@@ -445,6 +453,7 @@ export function registerBackgroundAgentLane(core, input) {
445
453
  ...(input.parentTaskId !== undefined ? { parentTaskId: input.parentTaskId } : {}),
446
454
  name,
447
455
  ...(input.agentType !== undefined ? { agentType: input.agentType } : {}),
456
+ ...(requestedBy !== undefined ? { requestedBy } : {}),
448
457
  ...(input.description !== undefined ? { description: input.description } : {}),
449
458
  ...(input.model !== undefined ? { model: input.model } : {}),
450
459
  ...(input.policyFloor !== undefined ? { policyFloor: input.policyFloor } : {}),
@@ -474,6 +483,7 @@ export function parkBackgroundAgentLane(core, id, park) {
474
483
  handle.status = "parked";
475
484
  handle.parkedCheckpointToken = park.checkpointToken;
476
485
  handle.resolveParkedStop = park.resolveStop;
486
+ handle.parkedCompletionSink = park.completionSink;
477
487
  handle.notify = undefined;
478
488
  for (const [, , qResolve] of handle.preAttachQueue ?? [])
479
489
  qResolve?.({ ok: false, reason: "not_running" });
@@ -542,18 +552,18 @@ export async function reconcileParkedAgentsLane(core, stores, scope, now, opts)
542
552
  else {
543
553
  continue;
544
554
  }
545
- if (handle.status !== "parked")
555
+ const held = heldPark(core, handle.id, token);
556
+ if (held === undefined)
546
557
  continue;
547
- if (handle.parkedCheckpointToken !== token)
548
- continue;
549
- handle.status = "failed";
550
- handle.error = error;
551
- handle.parkedCheckpointToken = undefined;
552
- handle.resolveParkedStop = undefined;
553
- handle.updatedAt = now;
554
- mintCompletionId(handle);
555
- core.pokeBgQuiescence(handle.owner);
556
- durableAgentWriteLane(handle, { status: "failed", error: handle.error, settledAt: now, stoppedBy: "system", completionId: handle.completionId }, ["parkedCheckpointToken", "parkClaimId", "parkedAt"]);
558
+ held.status = "failed";
559
+ held.error = error;
560
+ held.parkedCheckpointToken = undefined;
561
+ held.resolveParkedStop = undefined;
562
+ held.updatedAt = now;
563
+ mintCompletionId(held);
564
+ core.pokeBgQuiescence(held.owner);
565
+ announceParkedEnding(core, held, { status: "failed", error });
566
+ durableAgentWriteLane(held, { status: "failed", error: held.error, settledAt: now, stoppedBy: "system", completionId: held.completionId }, ["parkedCheckpointToken", "parkClaimId", "parkedAt"]);
557
567
  liveFailed++;
558
568
  }
559
569
  const { reconcileParkedAgents: storeReconcile } = await import("./background-agent-store.js");
@@ -636,6 +646,8 @@ export async function rollbackParkedClaimLane(core, stores, ticket) {
636
646
  h.error = error;
637
647
  h.parkedCheckpointToken = undefined;
638
648
  h.resolveParkedStop = undefined;
649
+ h.parkedCompletionSink = undefined;
650
+ h.terminalNotifier = undefined;
639
651
  h.updatedAt = now;
640
652
  commitCompletionIdIfEmpty(h, rollbackCompletionIdCandidate);
641
653
  core.pokeBgQuiescence(h.owner);
@@ -789,6 +801,7 @@ export async function consumeParkedFlipLane(core, id, stores, ticket) {
789
801
  handle.status = "running";
790
802
  handle.parkedCheckpointToken = undefined;
791
803
  handle.resolveParkedStop = undefined;
804
+ handle.parkedCompletionSink = undefined;
792
805
  handle.updatedAt = Date.now();
793
806
  handle.completionId = undefined;
794
807
  handle.terminalNotified = undefined;
@@ -842,7 +855,7 @@ export function settleBackgroundAgentLane(core, id, outcome) {
842
855
  handle.status = outcome.status;
843
856
  mintCompletionId(handle);
844
857
  handle.notify = undefined;
845
- handle.onReapTerminal = undefined;
858
+ handle.terminalNotifier = undefined;
846
859
  for (const [, , qResolve] of handle.preAttachQueue ?? [])
847
860
  qResolve?.({ ok: false, reason: "not_running" });
848
861
  handle.preAttachQueue = undefined;
@@ -1141,7 +1154,7 @@ export function noteBackgroundAgentActivityLane(core, id, now = Date.now()) {
1141
1154
  return;
1142
1155
  handle.updatedAt = now;
1143
1156
  }
1144
- export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.now(), onTerminal) {
1157
+ export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.now()) {
1145
1158
  if (!Number.isFinite(staleMs) || staleMs <= 0) {
1146
1159
  throw new Error(`reapStaleSessionBackgroundAgents: staleMs must be a positive finite number of milliseconds (got ${String(staleMs)})`);
1147
1160
  }
@@ -1152,21 +1165,35 @@ export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.n
1152
1165
  if (now - handle.updatedAt <= staleMs)
1153
1166
  continue;
1154
1167
  core.markStopSource(handle.id, "system");
1155
- const reapTerminalNote = handle.onReapTerminal;
1168
+ const reapTerminalNote = handle.terminalNotifier;
1156
1169
  handle.abort.abort();
1157
1170
  settleBackgroundAgentLane(core, handle.id, {
1158
1171
  status: "killed",
1159
1172
  error: STALE_RUNNING_REAP_ATTRIBUTION,
1160
1173
  cycle: handle.reviveCycle ?? 0,
1161
1174
  });
1162
- if (reapTerminalNote !== undefined && handle.terminalNotified !== true) {
1163
- handle.terminalNotified = true;
1164
- onTerminal?.(reapTerminalNote);
1165
- }
1175
+ announceLandedAgentTerminal(core, handle, reapTerminalNote, { status: "killed" });
1166
1176
  reaped++;
1167
1177
  }
1168
1178
  return reaped;
1169
1179
  }
1180
+ export function announceLandedAgentTerminal(core, handle, notifier, ending) {
1181
+ if (notifier === undefined)
1182
+ return;
1183
+ core.notifyTerminalOnce(handle, () => notifier(ending));
1184
+ }
1185
+ function heldPark(core, id, token) {
1186
+ const h = core.handles.get(id);
1187
+ return h?.type === "background_agent" && h.status === "parked" && h.parkedCheckpointToken === token ? h : undefined;
1188
+ }
1189
+ function announceParkedEnding(core, handle, ending) {
1190
+ const parkLane = handle.parkedCompletionSink;
1191
+ const notifier = handle.terminalNotifier;
1192
+ handle.parkedCompletionSink = undefined;
1193
+ handle.terminalNotifier = undefined;
1194
+ if (parkLane !== undefined)
1195
+ announceLandedAgentTerminal(core, handle, notifier, { ...ending, parkLane });
1196
+ }
1170
1197
  export function unmarkRetainedContinuationLane(core, id) {
1171
1198
  const handle = core.handles.get(id);
1172
1199
  if (handle && handle.type === "background_agent")
@@ -1309,6 +1336,9 @@ export function notFoundRunningAgentsTail(footer) {
1309
1336
  return ((footer.named.length > 0 ? `. Running named agents: ${footer.named.join(", ")}` : "") +
1310
1337
  (footer.background.length > 0 ? `. Running background agents: ${footer.background.join(", ")}` : ""));
1311
1338
  }
1339
+ export function agentOutcomeIsError(status) {
1340
+ return status === "failed";
1341
+ }
1312
1342
  export function buildAgentPollDetails(input) {
1313
1343
  const failed = input.status === "failed";
1314
1344
  return {
@@ -1365,7 +1395,7 @@ ${clipTaskOutput(row.finalOutputFull ?? row.finalOutput)}` : "(no result text)"}
1365
1395
  ...(row.completionId !== undefined ? { completionId: row.completionId } : {}),
1366
1396
  ...(agentState !== undefined ? { agentState } : {}),
1367
1397
  }),
1368
- ...(row.status === "failed" ? { isError: true } : {}),
1398
+ ...(agentOutcomeIsError(row.status) ? { isError: true } : {}),
1369
1399
  };
1370
1400
  }
1371
1401
  export async function pollBackgroundAgentLane(handle, deadline, signal, checkpointSeat) {
@@ -1436,7 +1466,7 @@ ${resultText}` : "(no result text)"}`;
1436
1466
  ...(snap.completionId !== undefined ? { completionId: snap.completionId } : {}),
1437
1467
  agentState,
1438
1468
  }),
1439
- ...(snap.status === "failed" ? { isError: true } : {}),
1469
+ ...(agentOutcomeIsError(snap.status) ? { isError: true } : {}),
1440
1470
  };
1441
1471
  }
1442
1472
  export async function stopBackgroundAgentLane(core, handle) {
@@ -1451,6 +1481,7 @@ export async function stopBackgroundAgentLane(core, handle) {
1451
1481
  }
1452
1482
  let stopWon = false;
1453
1483
  let arbiterUnreachable = false;
1484
+ const parkedToken = handle.parkedCheckpointToken;
1454
1485
  try {
1455
1486
  stopWon = await arbiter();
1456
1487
  }
@@ -1458,7 +1489,9 @@ export async function stopBackgroundAgentLane(core, handle) {
1458
1489
  stopWon = false;
1459
1490
  arbiterUnreachable = true;
1460
1491
  }
1461
- if (stopWon && handle.status === "parked") {
1492
+ const landed = stopWon ? heldPark(core, handle.id, parkedToken) : undefined;
1493
+ if (landed !== undefined) {
1494
+ handle = landed;
1462
1495
  core.markStopSource(handle.id, "parent");
1463
1496
  handle.status = "killed";
1464
1497
  handle.stoppedBy = handle.stopSource ?? "parent";
@@ -1467,6 +1500,7 @@ export async function stopBackgroundAgentLane(core, handle) {
1467
1500
  handle.parkedCheckpointToken = undefined;
1468
1501
  handle.resolveParkedStop = undefined;
1469
1502
  core.pokeBgQuiescence(handle.owner);
1503
+ announceParkedEnding(core, handle, { status: "killed" });
1470
1504
  {
1471
1505
  const lane = handle.durable;
1472
1506
  if (lane !== undefined) {
@@ -4,6 +4,7 @@ import { type WorkflowRunStore } from "./workflow-run-store.js";
4
4
  import type { BackgroundAgentRecord, BackgroundAgentStore } from "./background-agent-store.js";
5
5
  import type { WorkflowHandle, WorkflowRun } from "../orchestration/workflow.js";
6
6
  import type { TaskNotificationPayload } from "./task-notification.js";
7
+ import type { ExtensionRequester } from "./task-event.js";
7
8
  import type { TaskArtifactSeat } from "./tool-result-store.js";
8
9
  import type { AssertAllKeysHandled } from "./ask-origin.js";
9
10
  export type SemaTaskType = "background_bash" | "workflow" | "background_agent" | "monitor";
@@ -271,6 +272,8 @@ export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
271
272
  parentTaskId?: string;
272
273
  parentSessionId?: string;
273
274
  rootSessionId?: string;
275
+ /** Who started the agent when an extension did ({@link RegisterBackgroundAgentInput.requestedBy}); absent otherwise. */
276
+ requestedBy?: ExtensionRequester;
274
277
  /** design/151 S1a — the child's store session id (transcript/resume anchor), bound once the child
275
278
  * session is minted ({@link TaskRegistry.bindBackgroundAgentSession}) and removed — together with the
276
279
  * durable record's copy — by the successful release of that session
@@ -313,6 +316,12 @@ export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
313
316
  * Absent (cross-process row, no live park context) ⇒ TaskStop refuses honestly: the durable
314
317
  * approval inbox (server /decide) owns that arbitration. */
315
318
  resolveParkedStop?: () => Promise<boolean>;
319
+ /** #3334 — the completion sink the parked cycle's terminal frame is owed to (the lane its spawn or redemption completed
320
+ * into), recorded by the park beside {@link resolveParkedStop} and carried by the parked-resume handoff: the redemption
321
+ * completes there when its own call carries no lane. Absent ⇒ this process holds no park of the handle. */
322
+ parkedCompletionSink?: (n: import("./task-notification.js").TaskNotificationPayload, opts?: {
323
+ priority?: import("./task-notification.js").SystemInjectionPriority;
324
+ }) => unknown;
316
325
  /** S2b — resolvers of DIRECT (post-attach) deliveries currently awaiting the
317
326
  * injector; terminal settle/stop sweep these as not_running so a never-settling adapter can
318
327
  * never pin the sender's tool call. */
@@ -391,19 +400,28 @@ export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
391
400
  /** The LANDED attribution — set exactly when the handle goes `killed`, never rewritten afterwards
392
401
  * (first-writer-wins, same discipline as the terminal status itself). Absent on natural completion/failure. */
393
402
  stoppedBy?: StopSource;
394
- /** RB-375 A1 — the reap-time terminal notifier, hung by the spawn lanes (subagent.ts) right after
395
- * registration: composes and sends the SAME terminal faces (observer sink + parent notification)
396
- * the child's own unwind would, so {@link import("./task-registry.js").TaskRegistry.reapSessionBackground}
397
- * can emit the terminal news AT REAP TIME instead of waiting on the child's unwind (which blocks on
398
- * the in-flight tool actually honoring the abort — unbounded). The bash handle's `onTerminal` twin.
399
- * Cleared at the accepted settle (with `notify`); invoked at most once via {@link terminalNotified}. */
400
- onReapTerminal?: () => void;
403
+ /** The terminal notifier, hung by the spawn lanes (subagent.ts) right after registration: composes and sends the SAME
404
+ * terminal faces (observer sink + parent notification) the cycle's own unwind would, for a terminal the REGISTRY landed
405
+ * without that unwind — a reap of a running cycle (the unwind waits on the in-flight tool honoring the abort, unbounded),
406
+ * or a stop / an expiry of a parked one (its attempt returned at the park and reports nothing more). Called only through
407
+ * {@link import("./task-registry-agent.js").announceLandedAgentTerminal}; the bash handle's `onTerminal` twin. Cleared at
408
+ * the accepted settle and at every registry-landed terminal; invoked at most once via {@link terminalNotified}. */
409
+ terminalNotifier?: (ending: LandedAgentTerminal) => void;
401
410
  /** RB-375 A1 — terminal-notification once-latch (the bash/monitor `terminalNotified` twin): claimed
402
- * by whichever side reaches its emit point first — the session-release reap sweep (synchronous send)
403
- * or the child's own unwind (`TaskRegistry.claimAgentTerminalNotify`). The loser stays silent, so a
404
- * reaped child never double-announces. Cleared on revive (a new stop cycle owns its own terminal). */
411
+ * by whichever side reaches its emit point first — the registry announcing a terminal it landed (a reap, a parked
412
+ * stop or expiry) or the cycle's own unwind (`TaskRegistry.claimAgentTerminalNotify`). The loser stays silent, so a
413
+ * child never double-announces. Cleared on revive (a new stop cycle owns its own terminal). */
405
414
  terminalNotified?: true;
406
415
  }
416
+ /** A background agent's terminal the registry landed without its cycle's attempt, as {@link BackgroundAgentTaskHandle.terminalNotifier}
417
+ * receives it: the landed `status` (and `error`, for a failed one), and — when the ended cycle was PARKED — `parkLane`, the
418
+ * lane the park recorded its debt on ({@link BackgroundAgentTaskHandle.parkedCompletionSink}), where the parent face goes.
419
+ * Absent ⇔ the ended cycle was running: its attempt holds the lane. */
420
+ export interface LandedAgentTerminal {
421
+ status: "killed" | "failed";
422
+ error?: string;
423
+ parkLane?: NonNullable<BackgroundAgentTaskHandle["parkedCompletionSink"]>;
424
+ }
407
425
  /** design/135 G2 (Monitor): injectable timer/clock seam for the monitor watcher — the 200ms batch window
408
426
  * and the timeout/storm checks must be drivable by a test without real sleeps (design/87 discipline).
409
427
  * `setInterval` receives an ASYNC tick (the default adapter fires it void; a fake can await it). */
@@ -776,7 +794,7 @@ export interface RegistryCore {
776
794
  handles: Map<string, RegisteredTaskHandle>;
777
795
  mintTaskId(type: SemaTaskType): string;
778
796
  markStopSource(id: string, source: StopSource): void;
779
- notifyTerminalOnce(handle: BackgroundBashTaskHandle | MonitorTaskHandle, send: () => void): void;
797
+ notifyTerminalOnce(handle: BackgroundBashTaskHandle | MonitorTaskHandle | BackgroundAgentTaskHandle, send: () => void): void;
780
798
  pokeBgQuiescence(owner: string | undefined): void;
781
799
  }
782
800
  /** writer-lease renewal period for armed durable rows (see ensureDurableHeartbeat).
@@ -917,6 +935,10 @@ export interface RegisterBackgroundAgentInput extends TaskAccess {
917
935
  /** the RESOLVED subagent type ("general-purpose"/"fork"/a roster name), persisted
918
936
  * so a REVIVE cycle's observer frames can reproduce the row's TYPE column (never the description). */
919
937
  agentType?: string;
938
+ /** Who started this agent when an extension did: the extension, by its registration name (`$.agent.spawn`) — persisted on the row,
939
+ * so a revival keeps the row's origin. ABSENT = not an extension's spawn (the model's own, the host's): the one reading, with no
940
+ * word for either of those. A display and audit fact only — it decides nothing. */
941
+ requestedBy?: ExtensionRequester;
920
942
  /** the spawn frame's parent linkage, persisted so a REVIVE cycle's spawn frame nests the
921
943
  * revived row exactly like the first spawn did. The caller passes the SAME values it emitted on the
922
944
  * original frame (parentTaskId already-clamped there; parentSessionId always-on). */
@@ -5,11 +5,12 @@ import type { BoundaryLegsGiven } from "./cross-boundary-taint.js";
5
5
  import type { WorkflowRunStore } from "./workflow-run-store.js";
6
6
  import { type BackgroundAgentStore } from "./background-agent-store.js";
7
7
  import type { TaskNotificationPayload } from "./task-notification.js";
8
+ import type { ExtensionRequester } from "./task-event.js";
8
9
  import { type TaskArtifactSeat } from "./tool-result-store.js";
9
10
  import { type SemaTaskType, type StopSource, type SemaTaskStatus, type TaskRetrievalStatus, type UnifiedTaskOutput, type UnifiedTaskResult, type SemaTaskHandle, type TaskAccess, type BackgroundAgentTaskHandle, type MonitorTimers, type RegisterMonitorInput, type RegisterWorkflowInput, canAccessWorkflowRun, clipTaskOutput, MONITOR_BATCH_WINDOW_MS, MONITOR_DEFAULT_TIMEOUT_MS, MONITOR_MAX_TIMEOUT_MS, MONITOR_MAX_BATCHES_PER_MINUTE } from "./task-registry-shared.js";
10
11
  export { normalizeAgentName, DURABLE_AGENT_HEARTBEAT_MS, DURABLE_AGENT_HANDLE_RE, BG_AGENT_REAP_STOP_ERROR, engineAgentName, chosenAgentName } from "./task-registry-shared.js";
11
12
  export type { ParkedClaimTicket, RegisterBackgroundAgentInput } from "./task-registry-shared.js";
12
- import type { RegisterBackgroundAgentInput, ParkedClaimTicket, ChildSessionStore } from "./task-registry-shared.js";
13
+ import type { RegisterBackgroundAgentInput, ParkedClaimTicket, ChildSessionStore, LandedAgentTerminal } from "./task-registry-shared.js";
13
14
  import type { ChildSessionAnchor } from "./task-registry-agent.js";
14
15
  import { type DelegationOccupant } from "./task-registry-agent.js";
15
16
  import { type AgentStateSource } from "./agent-state.js";
@@ -116,6 +117,10 @@ export interface TaskListRow {
116
117
  * session store still holds the session" — the session store answers that. Only this process's
117
118
  * handles are listed: a row known only to the durable store of another process is not here. */
118
119
  sessionId?: string;
120
+ /** The extension that started a `background_agent` row, when one did — its registration name, from the extension's own
121
+ * `$.agent.spawn` (`ExtensionRequester`); ABSENT on every other row (the model's own spawn, the host's, and every row an earlier
122
+ * release registered): the one reading, with no word for either. A display and audit fact only. */
123
+ requestedBy?: ExtensionRequester;
119
124
  createdAt: number;
120
125
  updatedAt: number;
121
126
  }
@@ -157,8 +162,8 @@ export declare class TaskRegistry {
157
162
  * (cap overflow dropped the watcher; the owner's tasks may still be running — the subscriber must
158
163
  * NOT treat this as quiescence). */
159
164
  private bgQuiescenceWatchers;
160
- /** One host-callback isolation scope for this registry's five notification seams (reap terminal
161
- * notifier, session-reap hooks, quiescence fire + cap-overflow eviction, terminal-once send). Same swallow
165
+ /** One host-callback isolation scope for this registry's notification seams (session-reap hooks, quiescence fire +
166
+ * cap-overflow eviction, the terminal-once send every background kind's terminal takes). Same swallow
162
167
  * as the five hand-written try/catches it replaced, now counted per site and readable for diagnostics. */
163
168
  private readonly notifier;
164
169
  /** The read face for this registry's CONTAINED host-callback failures (site → count).
@@ -231,7 +236,11 @@ export declare class TaskRegistry {
231
236
  checkpointToken: string;
232
237
  seq?: number;
233
238
  resolveStop?: () => Promise<boolean>;
239
+ completionSink?: BackgroundAgentTaskHandle["parkedCompletionSink"];
234
240
  }): "parked" | undefined;
241
+ /** #3334 — the completion sink a PARKED handle's cycle is still owed to in this process (the park's own lane), for the
242
+ * redemption to complete into when its call carries none; `undefined` when this process holds no park of `id`. */
243
+ parkedCompletionSink(id: string): BackgroundAgentTaskHandle["parkedCompletionSink"];
235
244
  reconcileParkedAgents(stores: {
236
245
  agentStore: import("./background-agent-store.js").BackgroundAgentStore;
237
246
  checkpointStore: Pick<import("./checkpoint-store.js").CheckpointStore, "get">;
@@ -341,10 +350,10 @@ export declare class TaskRegistry {
341
350
  }): "completed" | "failed" | "killed" | undefined;
342
351
  unmarkRetainedContinuation(id: string): void;
343
352
  attachAgentNotify(id: string, notify: NonNullable<BackgroundAgentTaskHandle["notify"]>, cycle?: number): void;
344
- /** RB-375 A1 — hang the reap-time terminal notifier on a live background-agent row (see
345
- * {@link BackgroundAgentTaskHandle.onReapTerminal}). No-op on unknown/terminal rows: a row that
346
- * already settled has its unwind (or the settle itself) owning the terminal story. */
347
- attachAgentTerminalNotifier(id: string, fn: () => void): void;
353
+ /** RB-375 A1 — hang the terminal notifier on a live background-agent row: what the registry calls, once, when it lands
354
+ * that row's terminal without the cycle's attempt (see {@link BackgroundAgentTaskHandle.terminalNotifier}). No-op on
355
+ * unknown/terminal rows: a row that already settled has its unwind (or the settle itself) owning the terminal story. */
356
+ attachAgentTerminalNotifier(id: string, fn: (ending: LandedAgentTerminal) => void): void;
348
357
  /** RB-375 A1 — the child-unwind side of the terminal-notification once-latch: returns `true` when
349
358
  * the CALLER now owns sending the terminal faces (and claims the latch), `false` when the reap
350
359
  * sweep already sent them (the caller must stay silent — the registry row still takes the settle's
@@ -542,7 +551,7 @@ export declare class TaskRegistry {
542
551
  * (`abortBackgroundAgentsForOwner` in the child's unwind) — this function never sees those rows,
543
552
  * so they are NOT counted here.
544
553
  * RB-375 A1 — a directly reaped `background_agent` row's terminal notification is sent
545
- * SYNCHRONOUSLY by this sweep (through the spawn-lane-hung {@link BackgroundAgentTaskHandle.onReapTerminal},
554
+ * SYNCHRONOUSLY by this sweep (through the spawn-lane-hung {@link BackgroundAgentTaskHandle.terminalNotifier},
546
555
  * once-latched against the child's own unwind), so consumers observe the terminal immediately
547
556
  * instead of after the in-flight tool honors the abort (unbounded). */
548
557
  reapSessionBackground(sessionId: string, scope?: string): number;
@@ -584,6 +593,19 @@ export declare class TaskRegistry {
584
593
  sessionId: string;
585
594
  scope: string;
586
595
  })): BackgroundShellHardKillReceipt[];
596
+ /** How many shell-lane rows (`background_bash` + `monitor`) the exit-boundary hard face would take down if it ran now: the
597
+ * registry's `running` shell rows, over the WHOLE registry — no owner, session, scope or env narrowing — with a retained row
598
+ * counted only under `includeRetained: true` (no default, as on {@link killAllBackgroundShellsNow}). The rows are chosen
599
+ * by the hard face's own reading ({@link hardFaceVisitOf}), so the count and the walk cannot drift. SYNCHRONOUS and READ-ONLY:
600
+ * the count calls no seat and changes no row; like the hard face it reads each row's env declaration of retention (host-provided
601
+ * data), so a host whose env makes that read throw makes the count throw. It counts registry rows, not process truth: a row whose seat later answers `already_gone`
602
+ * or `no_pgid` stays `running` and is counted until its watcher settles it. A row an earlier stop settled `killed` or
603
+ * `failed` is visited by the hard face but is not running, so it is not counted; `completed` rows are not visited.
604
+ * Not {@link list}'s length: `list(access)` is the caller's own reach, capped at `limit`, every task type and status;
605
+ * {@link countRunningBackgroundForOwner} is one owner key's running tasks, agents included. */
606
+ countRunningBackgroundShells(opts: {
607
+ includeRetained: boolean;
608
+ }): number;
587
609
  /** subscribe to `reapSessionBackground` (the design/129 session terminal anchor).
588
610
  * Returns an unsubscribe. Hooks are best-effort observers; a throwing hook is swallowed. */
589
611
  onSessionReap(hook: (sessionId: string, scope?: string) => void): () => void;
@@ -616,7 +638,9 @@ export declare class TaskRegistry {
616
638
  * running-row eviction). Cheap no-op without watchers; fires + removes the owner's whole set only
617
639
  * when the running count is zero (the LAST settling task's poke wins — count-zero judgement). */
618
640
  private pokeBgQuiescence;
619
- /** fidelity R1-3: the terminal-notification once-latch. Checks-and-sets BEFORE sending (single-threaded,
641
+ /** fidelity R1-3: the terminal-notification once-latch — every background kind's (an agent's terminal the registry
642
+ * lands without its cycle's attempt comes through here as well, `announceLandedAgentTerminal`; the attempt's own
643
+ * unwind claims the same latch with `claimAgentTerminalNotify`). Checks-and-sets BEFORE sending (single-threaded,
620
644
  * no await between check and set — atomic), so a racing producer pair (a teardown settle vs an in-flight
621
645
  * watcher tick that passed its status gate before the settle landed) emits exactly ONE terminal notice.
622
646
  * The latch stays set even if the sink throws — a faulty sink must not re-arm it. */
@@ -6,13 +6,14 @@ import { canAccessAgentRecord, } from "./background-agent-store.js";
6
6
  import { delimitUntrusted } from "./untrusted-text.js";
7
7
  import { createSafeNotifier } from "./safe-notify.js";
8
8
  import { stripCwdSentinel } from "../tools/fs/fs-shared.js";
9
+ import { readExtensionRequester } from "./extension-requester.js";
9
10
  import { persistTaskArtifact, taskArtifactOriginOf } from "./tool-result-store.js";
10
11
  import { registerMonitorLane, pollMonitorLane, stopMonitorLane } from "./task-registry-monitor.js";
11
12
  import { registerWorkflowLane, pollWorkflowLane, stopWorkflowLane } from "./task-registry-workflow.js";
12
13
  import { mintCompletionId, taskReadHandleText, canAccessWorkflowRun, formatWorkflowRun, clipTaskOutput, assertOwnership, sleepPollStep, statusFromBackground, rollSpoolText, accountDroppedBytes, renderSpoolBody, stdoutHeadingOf, REPLAY_FACE, SPOOL_REPLAY, INCREMENT_REPLAY, spoolDropNote, droppedGapNote, alreadyTerminalStopNote, terminalTaskSummary, TASK_OUTPUT_MAX_CHARS, MONITOR_BATCH_WINDOW_MS, MONITOR_DEFAULT_TIMEOUT_MS, MONITOR_MAX_TIMEOUT_MS, MONITOR_MAX_BATCHES_PER_MINUTE, canAccess, DURABLE_AGENT_HANDLE_RE, } from "./task-registry-shared.js";
13
14
  export { normalizeAgentName, DURABLE_AGENT_HEARTBEAT_MS, DURABLE_AGENT_HANDLE_RE, BG_AGENT_REAP_STOP_ERROR, engineAgentName, chosenAgentName } from "./task-registry-shared.js";
14
15
  import { TASK_STOP_TOOL_NAME, TASK_STOP_MISSING_ID_MESSAGE, TASK_STOP_PARAMS, TASK_STOP_DESCRIPTION, resolveTaskIdArg } from "./task-tool-shape.js";
15
- import { durableAgentArmedLane, durableAgentRowProbeLane, beginDurableClaimLane, endDurableClaimLane, reapDurableAgentsLane, noteBackgroundAgentActivityLane, reapStaleSessionBackgroundAgentsLane, releaseDurableTranscriptAnchorLane, bindBackgroundAgentSessionLane, childSessionAnchorOf, registerBackgroundAgentLane, recordBackgroundAgentOrgAdmissionLane, parkBackgroundAgentLane, reconcileParkedAgentsLane, claimParkedAgentLane, rollbackParkedClaimLane, consumeParkedFlipLane, finalizeParkedResumeLane, settleBackgroundAgentLane, abortBackgroundAgentsForOwnerLane, serveDurableAgentRowLane, resolveBackgroundAgentByNameLane, backgroundAgentCycleSeqLane, activeDelegationHandlesLane, activeDelegationOccupantsLane, markRetainedContinuationLane, reviveBackgroundAgentLane, settleRevivedAgentLane, unmarkRetainedContinuationLane, attachAgentNotifyLane, deliverToRunningAgentLane, runningBackgroundAgentLabelsLane, runningAgentFooterLane, notFoundRunningAgentsTail, pollBackgroundAgentLane, stopBackgroundAgentLane, } from "./task-registry-agent.js";
16
+ import { durableAgentArmedLane, durableAgentRowProbeLane, beginDurableClaimLane, endDurableClaimLane, reapDurableAgentsLane, noteBackgroundAgentActivityLane, reapStaleSessionBackgroundAgentsLane, announceLandedAgentTerminal, releaseDurableTranscriptAnchorLane, bindBackgroundAgentSessionLane, childSessionAnchorOf, registerBackgroundAgentLane, recordBackgroundAgentOrgAdmissionLane, parkBackgroundAgentLane, reconcileParkedAgentsLane, claimParkedAgentLane, rollbackParkedClaimLane, consumeParkedFlipLane, finalizeParkedResumeLane, settleBackgroundAgentLane, abortBackgroundAgentsForOwnerLane, serveDurableAgentRowLane, resolveBackgroundAgentByNameLane, backgroundAgentCycleSeqLane, activeDelegationHandlesLane, activeDelegationOccupantsLane, markRetainedContinuationLane, reviveBackgroundAgentLane, settleRevivedAgentLane, unmarkRetainedContinuationLane, attachAgentNotifyLane, deliverToRunningAgentLane, runningBackgroundAgentLabelsLane, runningAgentFooterLane, notFoundRunningAgentsTail, pollBackgroundAgentLane, stopBackgroundAgentLane, } from "./task-registry-agent.js";
16
17
  import { mountRuleFace, toolFace } from "./tool-catalog-entries.js";
17
18
  import { thrownText } from "./thrown-value.js";
18
19
  import { agentStateSourceOfHandle, agentStateSourceOfRecord, agentStateSummary, readAgentState } from "./agent-state.js";
@@ -20,6 +21,17 @@ export { canAccessWorkflowRun, clipTaskOutput, MONITOR_BATCH_WINDOW_MS, MONITOR_
20
21
  function shellRowRetained(h) {
21
22
  return retainsBackgroundProcesses({ marked: h.retained === true, env: envDeclaresRetain(h.env) });
22
23
  }
24
+ function hardFaceVisitOf(handle, includeRetained, access) {
25
+ if (handle.type !== "background_bash" && handle.type !== "monitor")
26
+ return undefined;
27
+ if (access !== undefined && !canAccess(handle, access))
28
+ return undefined;
29
+ if (handle.status === "completed")
30
+ return undefined;
31
+ const retained = shellRowRetained(handle);
32
+ const skipped = retained && !includeRetained && handle.status !== "killed";
33
+ return { handle, retained, skipped, reaps: !skipped && handle.status === "running" };
34
+ }
23
35
  const BLOCK_DEFAULT_TIMEOUT_MS = 30_000;
24
36
  const BLOCK_MAX_TIMEOUT_MS = 600_000;
25
37
  function blockDeadline(timeoutMs, now) {
@@ -180,6 +192,10 @@ export class TaskRegistry {
180
192
  parkBackgroundAgent(id, park) {
181
193
  return parkBackgroundAgentLane(this.core, id, park);
182
194
  }
195
+ parkedCompletionSink(id) {
196
+ const handle = this.core.handles.get(id);
197
+ return handle?.type === "background_agent" && handle.status === "parked" ? handle.parkedCompletionSink : undefined;
198
+ }
183
199
  async reconcileParkedAgents(stores, scope, now, opts) {
184
200
  return reconcileParkedAgentsLane(this.core, stores, scope, now, opts);
185
201
  }
@@ -202,9 +218,7 @@ export class TaskRegistry {
202
218
  return noteBackgroundAgentActivityLane(this.core, id, now);
203
219
  }
204
220
  reapStaleSessionBackgroundAgents(staleMs, now) {
205
- return reapStaleSessionBackgroundAgentsLane(this.core, staleMs, now, (note) => {
206
- this.notifier.notify(() => note(), "taskRegistry.reapTerminalNote");
207
- });
221
+ return reapStaleSessionBackgroundAgentsLane(this.core, staleMs, now);
208
222
  }
209
223
  abortBackgroundAgentsForOwner(access, opts) {
210
224
  return abortBackgroundAgentsForOwnerLane(this.core, access, opts);
@@ -252,7 +266,7 @@ export class TaskRegistry {
252
266
  return;
253
267
  if (handle.status !== "running" && handle.status !== "parked" && handle.status !== "pending")
254
268
  return;
255
- handle.onReapTerminal = fn;
269
+ handle.terminalNotifier = fn;
256
270
  }
257
271
  claimAgentTerminalNotify(id) {
258
272
  const handle = this.handles.get(id);
@@ -570,13 +584,10 @@ export class TaskRegistry {
570
584
  if (!canAccess(handle, access))
571
585
  continue;
572
586
  this.markStopSource(handle.id, "system");
573
- const reapTerminalNote = handle.onReapTerminal;
587
+ const reapTerminalNote = handle.terminalNotifier;
574
588
  handle.abort.abort();
575
589
  this.settleBackgroundAgent(handle.id, { status: "killed", error: "session released", cycle: handle.reviveCycle ?? 0 });
576
- if (reapTerminalNote !== undefined && handle.terminalNotified !== true) {
577
- handle.terminalNotified = true;
578
- this.notifier.notify(() => reapTerminalNote(), "taskRegistry.reapTerminalNote");
579
- }
590
+ announceLandedAgentTerminal(this.core, handle, reapTerminalNote, { status: "killed" });
580
591
  reaped++;
581
592
  }
582
593
  this.pokeBgQuiescence(sessionId);
@@ -608,16 +619,13 @@ export class TaskRegistry {
608
619
  const sessionAccess = opts.sessionId !== undefined ? { owner: opts.sessionId, sessionId: opts.sessionId, scope: opts.scope } : undefined;
609
620
  const receipts = [];
610
621
  const settledOwners = new Set();
611
- for (const handle of this.handles.values()) {
612
- if (handle.type !== "background_bash" && handle.type !== "monitor")
613
- continue;
614
- if (sessionAccess !== undefined && !canAccess(handle, sessionAccess))
622
+ for (const row of this.handles.values()) {
623
+ const visit = hardFaceVisitOf(row, opts.includeRetained, sessionAccess);
624
+ if (visit === undefined)
615
625
  continue;
616
- if (handle.status === "completed")
617
- continue;
618
- const retained = shellRowRetained(handle);
626
+ const { handle, retained } = visit;
619
627
  const base = { taskId: handle.id, type: handle.type, ...(handle.owner !== undefined ? { owner: handle.owner } : {}), ...(retained ? { retained: true } : {}) };
620
- if (retained && !opts.includeRetained && handle.status !== "killed") {
628
+ if (visit.skipped) {
621
629
  receipts.push({ ...base, outcome: "retained_skipped" });
622
630
  continue;
623
631
  }
@@ -666,6 +674,14 @@ export class TaskRegistry {
666
674
  this.pokeBgQuiescence(owner);
667
675
  return receipts;
668
676
  }
677
+ countRunningBackgroundShells(opts) {
678
+ let n = 0;
679
+ for (const row of this.handles.values()) {
680
+ if (hardFaceVisitOf(row, opts.includeRetained)?.reaps === true)
681
+ n++;
682
+ }
683
+ return n;
684
+ }
669
685
  onSessionReap(hook) {
670
686
  this.sessionReapHooks.add(hook);
671
687
  return () => void this.sessionReapHooks.delete(hook);
@@ -1046,11 +1062,13 @@ The durable record is still marked running (last update ${new Date(row.updatedAt
1046
1062
  if (!canAccess(h, access))
1047
1063
  continue;
1048
1064
  const childSession = childSessionAnchorOf(h);
1065
+ const requestedBy = h.type === "background_agent" ? readExtensionRequester(h.requestedBy) : undefined;
1049
1066
  out.push({
1050
1067
  task_id: h.id,
1051
1068
  type: h.type,
1052
1069
  status: h.status,
1053
1070
  sessionScoped: h.sessionScoped === true,
1071
+ ...(requestedBy !== undefined ? { requestedBy } : {}),
1054
1072
  ...((h.type === "background_bash" || h.type === "monitor") && shellRowRetained(h) ? { retained: true } : {}),
1055
1073
  ...(h.description !== undefined ? { description: h.description } : {}),
1056
1074
  ...(h.toolUseId !== undefined ? { toolUseId: h.toolUseId } : {}),
@@ -3,7 +3,7 @@ import { thrownText } from "./thrown-value.js";
3
3
  import { strayMembersOf } from "./own-property-receipt.js";
4
4
  export const TASK_SPEC_MEMBERS = Object.keys({
5
5
  taskId: 0, objective: 0, principal: 0, actor: 0, runOrigin: 0, interactionPosture: 0, approvalReach: 0, interactiveQuestionFallback: 0,
6
- images: 0, userAttachments: 0, sessionId: 0, projectId: 0, requireExistingSession: 0, oneShot: 0, clientContext: 0, resumeAt: 0,
6
+ images: 0, userAttachments: 0, sessionId: 0, projectId: 0, workspace: 0, requireExistingSession: 0, oneShot: 0, clientContext: 0, resumeAt: 0,
7
7
  resumeAtMode: 0, model: 0, modelRole: 0, roles: 0, compactionModel: 0, advisorModel: 0, thinking: 0, systemPrompt: 0,
8
8
  promptRole: 0, promptForm: 0, promptBinding: 0, appendSystemPrompt: 0, outputStyle: 0, memory: 0, suggestNextPrompts: 0, fileHistory: 0,
9
9
  projectMemory: 0, restoreFiles: 0, acceptPartialRestore: 0, rewindFilesTo: 0, tools: 0, allowTools: 0, excludeTools: 0, excludeAllTools: 0,
@@ -13,6 +13,7 @@ import type { A2aServerSpec, McpServerSpec } from "./mcp-server-spec.js";
13
13
  import type { ModelRef, ModelRole, ModelRoles } from "./model-seat.js";
14
14
  import type { TaskLimits } from "./task-limits.js";
15
15
  import type { ToolSpec } from "./tool-spec.js";
16
+ import type { WorkspaceDeclaration } from "./session-checkout.js";
16
17
  /** design/169-F — knobs for the opt-in stale tool-result offload (see
17
18
  * `TaskSpec.compaction.staleToolResultOffload`, where the semantics are documented). */
18
19
  export interface StaleToolResultOffloadOptions {
@@ -202,6 +203,25 @@ export interface TaskSpec {
202
203
  * `workspace_changed.project`; read it there rather than re-deriving it. Memory keys only by the marker.
203
204
  */
204
205
  projectId?: string;
206
+ /**
207
+ * The session's workspace — send the SAME declaration on every leg (a resumed leg's config included). The session's first
208
+ * leg turns it into the session's checkout, an immutable record every later leg is judged against:
209
+ * - `isolation: "worktree"`: the session works in its OWN managed tree of the task root's repository, minted on the first
210
+ * leg at `<repository root>/.sema/worktrees/<name>` on branch `sema/<name>` (`name` absent ⇒ derived from the session id;
211
+ * `baseRef`: `"fresh"` default, or `"head"`). Every leg's task root is the task root's place in that tree; the base
212
+ * checkout is outside the leg's write roots. The tree outlives every leg and env; `releaseSessionCheckout` removes it.
213
+ * - `sources`: the commit the session's code starts from, per root (`{ root, remote, sha, ref? }`): checked on the first
214
+ * leg (the checkout at that root must be at `sha`; with isolation the task root's tree is minted at it).
215
+ * Refusals, each before the leg starts: a malformed declaration ⇒ `config.session_workspace_invalid` (also: a writable
216
+ * `additionalDirectories` entry that reaches into the isolated base checkout, a remote carrying a credential); a declaration
217
+ * that differs from the first leg's, appears on a session that already ran without one, or goes missing ⇒
218
+ * `config.session_workspace_changed`; the tree cannot be made ⇒ `workspace.isolation_unavailable` (the reason named,
219
+ * `probeWorktreeCapability` judges the same); a checkout not at the declared commit ⇒ `workspace.source_mismatch`; the
220
+ * record cannot be read ⇒ `workspace.checkout_unavailable`; the tree is gone ⇒ `workspace.checkout_missing` (never a
221
+ * fallback to the base checkout). A fork does not inherit the checkout. Every leg's `workspace_changed` frame carries it
222
+ * (`session`).
223
+ */
224
+ workspace?: WorkspaceDeclaration;
205
225
  /**
206
226
  * design/114 Phase3 — with `sessionId` set, REQUIRE that session to already exist: if it is gone (e.g. a
207
227
  * non-durable store lost it across a restart, or a typo'd id), the run FAILS LOUD (`resume.session_not_found`)
@@ -1328,7 +1348,7 @@ export interface TaskSpec {
1328
1348
  * Override auto-compaction thresholds for this task's session. Compaction (LLM summary, persisted
1329
1349
  * to the session) runs in two places sharing these settings: at every within-task turn boundary
1330
1350
  * (design/64 §25 (A) — the long-single-task case) and once at task end (the between-task case).
1331
- * Defaults: enabled, reserveTokens 16384, keepRecentTokens 0 (design/169-C; 20000 was the
1351
+ * Defaults: both seats on (`autoCompact` / `manualCompact` below), reserveTokens 16384, keepRecentTokens 0 (design/169-C; 20000 was the
1332
1352
  * pre-169 default). A zero budget is NOT "no verbatim tail": the cut-point search has a
1333
1353
  * structural floor under the budget, so the default already leaves the last exchange verbatim
1334
1354
  * after the summary (a trailing tool-result batch keeps its emitting assistant with it) — the
@@ -1366,7 +1386,12 @@ export interface TaskSpec {
1366
1386
  * no-op when the task has no execution env (no hands, nothing to re-read).
1367
1387
  */
1368
1388
  compaction?: {
1369
- enabled?: boolean;
1389
+ /** The passes the engine starts by itself (the lanes: {@link compactionEnabled}); `false` switches them off. Absent ⇒
1390
+ * `RunnerDeps.contextSettings[word].autoCompact`, else on. A non-boolean refuses the run (`config.invalid_argument`). */
1391
+ autoCompact?: boolean;
1392
+ /** The passes a caller asks for; `false` answers each `"disabled"`, no summary call. Absent ⇒ the deployment's
1393
+ * `manualCompact`, else on. The retired `enabled` (both at once) is refused by name (`config.spec_retired_key`). */
1394
+ manualCompact?: boolean;
1370
1395
  withinTask?: boolean;
1371
1396
  reserveTokens?: number;
1372
1397
  keepRecentTokens?: number;