@sema-agent/core 7.61.0 → 7.62.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 (176) hide show
  1. package/CHANGELOG.md +312 -0
  2. package/dist/agents/cascade.d.ts +11 -3
  3. package/dist/agents/cascade.js +1 -1
  4. package/dist/agents/peer-held-queue.d.ts +27 -4
  5. package/dist/agents/peer-held-queue.js +81 -36
  6. package/dist/agents/peer-session-drain.js +13 -3
  7. package/dist/agents/subagent.d.ts +6 -1
  8. package/dist/agents/subagent.js +66 -12
  9. package/dist/agents/suspend-guard.d.ts +38 -16
  10. package/dist/agents/suspend-guard.js +9 -4
  11. package/dist/agents/verify.js +4 -3
  12. package/dist/core/checkpoint-features.d.ts +722 -0
  13. package/dist/core/checkpoint-features.js +98 -0
  14. package/dist/core/checkpoint-requirements.d.ts +9 -2
  15. package/dist/core/checkpoint-requirements.js +9 -4
  16. package/dist/core/checkpoint-row-verdict.d.ts +99 -0
  17. package/dist/core/checkpoint-row-verdict.js +225 -0
  18. package/dist/core/checkpoint-store.d.ts +55 -745
  19. package/dist/core/checkpoint-store.js +39 -141
  20. package/dist/core/engine-notice.d.ts +19 -3
  21. package/dist/core/engine-notice.js +9 -2
  22. package/dist/core/gate-fold.js +2 -2
  23. package/dist/core/governance-codes.d.ts +3 -1
  24. package/dist/core/governance-codes.js +3 -0
  25. package/dist/core/hooks.d.ts +13 -0
  26. package/dist/core/human-input-projection.d.ts +1 -0
  27. package/dist/core/human-input-projection.js +3 -0
  28. package/dist/core/image-admission.d.ts +1 -1
  29. package/dist/core/locked-config.d.ts +2 -2
  30. package/dist/core/mcp-host-seat.js +6 -1
  31. package/dist/core/memory-engine/consolidation-driver.d.ts +1 -1
  32. package/dist/core/memory-vector.d.ts +1 -1
  33. package/dist/core/memory.d.ts +10 -10
  34. package/dist/core/mode-policy.js +1 -1
  35. package/dist/core/mods/classic-events.d.ts +9 -1
  36. package/dist/core/mods/dollar.d.ts +32 -1
  37. package/dist/core/mods/dollar.js +13 -1
  38. package/dist/core/mods/kernel/events.d.ts +11 -3
  39. package/dist/core/mods/kernel/events.js +13 -10
  40. package/dist/core/mods/lifecycle-stations.d.ts +36 -4
  41. package/dist/core/mods/lifecycle-stations.js +44 -9
  42. package/dist/core/mods/session-append.d.ts +4 -1
  43. package/dist/core/mods/session-append.js +7 -0
  44. package/dist/core/mods/session-receive.js +12 -15
  45. package/dist/core/mods/stations.d.ts +51 -6
  46. package/dist/core/mods/stations.js +124 -0
  47. package/dist/core/own-property-receipt.d.ts +7 -0
  48. package/dist/core/own-property-receipt.js +3 -0
  49. package/dist/core/read-root-candidate.js +1 -1
  50. package/dist/core/resume-startup-cause.d.ts +5 -4
  51. package/dist/core/runner/compact-session.js +5 -2
  52. package/dist/core/runner/contracts.d.ts +18 -8
  53. package/dist/core/runner/delegation-owner.d.ts +43 -0
  54. package/dist/core/runner/delegation-owner.js +59 -0
  55. package/dist/core/runner/lineage-reroot-view.d.ts +56 -0
  56. package/dist/core/runner/lineage-reroot-view.js +108 -0
  57. package/dist/core/runner/permission-rule-lanes.d.ts +2 -1
  58. package/dist/core/runner/permission-rule-lanes.js +2 -2
  59. package/dist/core/runner/person-path-rows.d.ts +15 -0
  60. package/dist/core/runner/person-path-rows.js +26 -3
  61. package/dist/core/runner/prepare-acquire-reconcile.d.ts +4 -1
  62. package/dist/core/runner/prepare-acquire-reconcile.js +7 -2
  63. package/dist/core/runner/prepare-caps-and-workflow.d.ts +1 -0
  64. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  65. package/dist/core/runner/prepare-config-doors.d.ts +6 -6
  66. package/dist/core/runner/prepare-config-doors.js +3 -4
  67. package/dist/core/runner/prepare-hands-readface.d.ts +1 -1
  68. package/dist/core/runner/prepare-hands-readface.js +28 -7
  69. package/dist/core/runner/prepare-inherited-gate.d.ts +2 -0
  70. package/dist/core/runner/prepare-inherited-gate.js +7 -3
  71. package/dist/core/runner/prepare-task.js +10 -7
  72. package/dist/core/runner/resume-admission.d.ts +3 -3
  73. package/dist/core/runner/resume-admission.js +6 -3
  74. package/dist/core/runner/resume-apply.d.ts +4 -0
  75. package/dist/core/runner/resume-apply.js +11 -4
  76. package/dist/core/runner/resume-checkpoint-screen.d.ts +9 -0
  77. package/dist/core/runner/resume-checkpoint-screen.js +4 -84
  78. package/dist/core/runner/run-git-lane.d.ts +2 -0
  79. package/dist/core/runner/run-git-lane.js +4 -1
  80. package/dist/core/runner/run-harness-handlers.d.ts +2 -0
  81. package/dist/core/runner/run-harness-handlers.js +3 -2
  82. package/dist/core/runner/run-leg.js +24 -7
  83. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  84. package/dist/core/runner/run-stop-and-final-verify.js +2 -1
  85. package/dist/core/runner/run-turn-boundary.js +7 -4
  86. package/dist/core/runner/runtask.js +6 -6
  87. package/dist/core/runner/steering-preview.d.ts +9 -0
  88. package/dist/core/runner/steering-preview.js +5 -0
  89. package/dist/core/runner/stream-steer-verb.js +8 -0
  90. package/dist/core/runner/tool-face-overlay.js +2 -0
  91. package/dist/core/runner/turn-attachments.d.ts +5 -0
  92. package/dist/core/runner/turn-attachments.js +1 -1
  93. package/dist/core/runner-deps.d.ts +2 -2
  94. package/dist/core/secret-env.d.ts +8 -5
  95. package/dist/core/secret-env.js +37 -18
  96. package/dist/core/session-store.d.ts +1 -1
  97. package/dist/core/session-store.js +5 -1
  98. package/dist/core/session.d.ts +14 -4
  99. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +6 -0
  100. package/dist/core/store-contracts/checkpoint-store-contract.js +68 -0
  101. package/dist/core/store-contracts/session-store-contract.js +22 -8
  102. package/dist/core/task-event.d.ts +7 -1
  103. package/dist/core/task-notification.js +2 -1
  104. package/dist/core/task-registry-agent.d.ts +27 -7
  105. package/dist/core/task-registry-agent.js +12 -5
  106. package/dist/core/task-registry-shared.d.ts +7 -0
  107. package/dist/core/task-registry-workflow.js +4 -3
  108. package/dist/core/task-registry.d.ts +13 -2
  109. package/dist/core/task-registry.js +11 -4
  110. package/dist/core/task-result.d.ts +5 -5
  111. package/dist/core/task-spec.d.ts +1 -1
  112. package/dist/core/terminal-cause.d.ts +6 -6
  113. package/dist/core/tool-face.d.ts +6 -2
  114. package/dist/core/tool-face.js +1 -1
  115. package/dist/core/tool-policy.d.ts +2 -1
  116. package/dist/core/tool-roster.d.ts +4 -4
  117. package/dist/core/tool-spec.d.ts +4 -0
  118. package/dist/core/types.d.ts +1 -1
  119. package/dist/core/types.js +1 -1
  120. package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
  121. package/dist/engine/execution-env/node-execution-env.js +12 -5
  122. package/dist/engine/harness/types.d.ts +11 -0
  123. package/dist/engine/session/parent-chain-guard.d.ts +3 -3
  124. package/dist/engine/session/parent-chain-guard.js +1 -1
  125. package/dist/engine/session/path-to-root.d.ts +18 -3
  126. package/dist/engine/session/path-to-root.js +15 -1
  127. package/dist/engine/session/repo-utils.d.ts +12 -1
  128. package/dist/engine/session/repo-utils.js +41 -0
  129. package/dist/engine/session/session.js +1 -1
  130. package/dist/engine/session/storage-base.d.ts +20 -0
  131. package/dist/engine/session/storage-base.js +28 -9
  132. package/dist/index.d.ts +9 -8
  133. package/dist/index.js +4 -4
  134. package/dist/internal/harness.d.ts +4 -3
  135. package/dist/internal/harness.js +3 -2
  136. package/dist/orchestration/run-workflow-tool.d.ts +3 -0
  137. package/dist/orchestration/run-workflow-tool.js +27 -11
  138. package/dist/orchestration/workflow-governance.d.ts +1 -1
  139. package/dist/orchestration/workflow.d.ts +3 -0
  140. package/dist/orchestration/workflow.js +2 -7
  141. package/dist/stores/file/checkpoint-store.d.ts +2 -0
  142. package/dist/stores/file/checkpoint-store.js +7 -6
  143. package/dist/stores/file/fs-atomic.d.ts +0 -22
  144. package/dist/stores/file/fs-atomic.js +0 -17
  145. package/dist/stores/file/index.d.ts +2 -9
  146. package/dist/stores/file/index.js +2 -4
  147. package/dist/stores/file/session-store.d.ts +13 -7
  148. package/dist/stores/file/session-store.js +40 -17
  149. package/dist/tools/fs/bash-program-position.d.ts +3 -2
  150. package/dist/tools/fs/bash-program-position.js +7 -7
  151. package/dist/tools/fs/removal-targets.js +2 -2
  152. package/dist/tools/fs/shell-read-argv.d.ts +4 -2
  153. package/dist/tools/fs/shell-read-argv.js +14 -3
  154. package/dist/tools/fs/shell-read-bindings.d.ts +18 -2
  155. package/dist/tools/fs/shell-read-bindings.js +148 -68
  156. package/dist/tools/fs/shell-read-check.js +20 -4
  157. package/dist/tools/fs/shell-read-establish.js +22 -8
  158. package/dist/tools/fs/shell-read-functions.js +2 -2
  159. package/dist/tools/fs/shell-read-object-path.d.ts +59 -0
  160. package/dist/tools/fs/shell-read-object-path.js +119 -0
  161. package/dist/tools/fs/shell-read-plan.d.ts +8 -0
  162. package/dist/tools/fs/shell-read-plan.js +47 -30
  163. package/dist/tools/fs/shell-read-start.d.ts +66 -13
  164. package/dist/tools/fs/shell-read-start.js +89 -17
  165. package/dist/tools/fs/shell-read-workdir.d.ts +29 -8
  166. package/dist/tools/fs/shell-read-workdir.js +31 -8
  167. package/package.json +2 -2
  168. package/test/export-surface.snapshot.json +21 -33
  169. package/wire-changes/core-stores-sql@7.62.0.json +30 -0
  170. package/wire-changes/core@7.62.0.json +2181 -0
  171. package/wire-changes/mods-kernel@7.62.0.json +42 -0
  172. package/wire-changes/primitives@7.62.0.json +30 -0
  173. package/dist/core/consolidate-scope.d.ts +0 -93
  174. package/dist/core/consolidate-scope.js +0 -98
  175. package/dist/core/runner/memory-consolidation.d.ts +0 -109
  176. package/dist/core/runner/memory-consolidation.js +0 -251
@@ -128,8 +128,11 @@ export interface CascadeAttempt {
128
128
  export interface CascadeRunResult extends TaskResult {
129
129
  /**
130
130
  * The cascade's conclusion, **distinct from the inherited `status`**: `"passed"` = some rung passed the
131
- * gate; `"exhausted"` = ladder/guards ran out with no rung passing (the last rung's result is returned,
132
- * and its `status` may still be "completed" — judge the cascade by `cascadeOutcome`, not `status`).
131
+ * gate; `"exhausted"` = the cascade ended with no rung passing (the last rung's result is returned, and its
132
+ * `status` may still be "completed" — judge the cascade by `cascadeOutcome`, not `status`). It ends that way
133
+ * when the ladder ran out, when a guard stopped it (escalation cap, cost ceiling, wall-clock budget, the
134
+ * caller's signal), when a rung durably parked (`failed.nestedPause` is on the terminal: {@link resumeCascade}
135
+ * continues it), or when a resumed rung's approved action never started (`failed.unstartedRow`).
133
136
  */
134
137
  cascadeOutcome: "passed" | "exhausted";
135
138
  /** F4: present when a finite `costCeilingMicroUsd` was configured but some rung's spend was unpriced —
@@ -216,11 +219,16 @@ internals?: RunInternals): Promise<CascadeRunResult>;
216
219
  /**
217
220
  * Continue a cascade from a rung's parked card, then climb the rest of the ladder: the resume entry beside {@link runCascade},
218
221
  * as {@link import("./verify.js").resumeWithVerification} is beside its fresh-run entry. A rung that durably parks ends the
219
- * ladder with `cascadeOutcome: "exhausted"` and the pause on `failed.nestedPause` — the host holds the token, and the card's
222
+ * ladder (`cascadeOutcome`, `failed.nestedPause`) — the host holds the token, and the card's
220
223
  * `CheckpointState.compositionLeg` says which rung parked and which host session it belongs to. Once the pause is decided,
221
224
  * the host calls this with the token, the outcome, the ORIGINAL task spec, the ladder config and that `compositionLeg` as the
222
225
  * card records it.
223
226
  *
227
+ * A run whose task spec named no session (`spec.sessionId`) and whose caller handed it no leg through `internals` mints no
228
+ * composition leg, so its card records none: the host supplies `parkedLeg` itself — `{ entry: "cascade", leg: <the parked rung:
229
+ * the result's `finalRung`>, hostSessionId: <a session of its own> }` — and that value is the card's first record. The
230
+ * terminal's sentence says so.
231
+ *
224
232
  * - **One door**: the parked rung is continued through `runner.resume(token, outcome, <rung config>, internals)` — the rung's
225
233
  * config is the one {@link runCascade} derives for that rung (the task spec with the rung's model and overrides), minus the
226
234
  * members a resume does not take (`objective`, `sessionId`, `userAttachments`, `runOrigin`); its internals carry
@@ -178,7 +178,7 @@ async function climbLadder(entryName, runner, spec, config, internals, opening)
178
178
  nestedCostMicro += s.nested.costMicroUsd ?? 0;
179
179
  }
180
180
  if (isDurablePause(result.terminal) || resumeNeverStarted(result)) {
181
- const mapped = mapNestedSuspend(result);
181
+ const mapped = mapNestedSuspend(result, { door: "resumeCascade", legFrom: rungInternals?.compositionLeg === undefined ? "caller" : "card" });
182
182
  attempts.push({ index: i, model: rung.model, passed: false, costMicroUsd: rungCost, status: attemptTerminal(result).status, errorCode: attemptTerminal(mapped).errorCode });
183
183
  return {
184
184
  ...mapped,
@@ -27,6 +27,10 @@ export interface PeerHeldEntry {
27
27
  * waiting for a lease-holding pass — a re-judgment that now refuses still wins); `delivered` (this
28
28
  * queue took the hand-over move and the injection is still owed; a policy that now refuses ends it as `dropped`). */
29
29
  decision: PeerCardDecision;
30
+ /** When this hold resolves to `expired` unless someone answers it first (ms epoch) — present exactly while
31
+ * its expiry timer is armed: a cause in `PEER_HELD_REVIEW_CAUSES`, a finite `dialogExpiry`, the card still
32
+ * `held`. A cause move re-arms or clears it; an approval, a hand-over, the deadline itself or the card leaving clears it. */
33
+ deadlineAt?: number;
30
34
  }
31
35
  /** How an entry left this queue. `retired` — the CARD left this process but no decision was taken: the
32
36
  * record stays held in its box for the next consumer (a queue-local event no receipt announced,
@@ -56,8 +60,10 @@ export interface PeerHeldQueueSink {
56
60
  * deliver never takes a move out of `delivered`. Absent ⇒
57
61
  * the presence of `inject` decides. */
58
62
  canInject?: (entry: PeerHeldEntry) => boolean;
59
- /** The receipt to the sender (the binding routes it into the sender's box). */
60
- receipt: (entry: PeerHeldEntry, state: PeerDeliveryReceiptState) => void;
63
+ /** The receipt to the sender (the binding routes it into the sender's box). Resolves once the receipt is in
64
+ * that box (or has no reader there); rejects when it could not be written. Only {@link PeerHeldQueue.shutdown}
65
+ * waits on it — every other path sends and goes on. */
66
+ receipt: (entry: PeerHeldEntry, state: PeerDeliveryReceiptState) => Promise<void>;
61
67
  /** Does a receipt about this entry reach a sender? A queue-local event (eviction, shutdown, a refused
62
68
  * release) is a decision about the record exactly when it does — the sender is told it is final. */
63
69
  tellsSender: (entry: PeerHeldEntry) => boolean;
@@ -101,7 +107,7 @@ export interface PeerHeldQueue {
101
107
  * At the cap, settles the oldest held card that tells its sender (it is then a decision); arms the
102
108
  * deadline for a hold cause a person could answer.
103
109
  */
104
- hold(entry: Omit<PeerHeldEntry, "heldAt" | "decision">, decision?: PeerCardDecision): Promise<PeerHoldOutcome>;
110
+ hold(entry: Omit<PeerHeldEntry, "heldAt" | "decision" | "deadlineAt">, decision?: PeerCardDecision): Promise<PeerHoldOutcome>;
105
111
  /** Re-judge every entry against current settings (CC `D`): deliverable ⇒ handed over (or kept with no
106
112
  * live run), refused ⇒ refused with a receipt, still held ⇒ re-announced only when the cause moved.
107
113
  * Every move goes through the decision seat. */
@@ -128,7 +134,8 @@ export interface PeerHeldQueue {
128
134
  list(): readonly PeerHeldEntry[];
129
135
  size(): number;
130
136
  /** CC `HBe` — a graceful shutdown settles everything still held as `expired` with receipts (where a
131
- * receipt reaches a sender; elsewhere the cards just leave this process). */
137
+ * receipt reaches a sender; elsewhere the cards just leave this process). Resolves once every receipt it
138
+ * sent has landed; rejects naming the seqs whose receipt did not (every card is settled either way). */
132
139
  shutdown(): Promise<void>;
133
140
  }
134
141
  export declare function createPeerHeldQueue(key: string, opts?: {
@@ -149,5 +156,21 @@ export declare function peerHeldQueueFor(scope: string, sessionId: string, opts?
149
156
  /** The held queue of a session if one exists in this process (a host review face reads through this
150
157
  * without creating state for sessions that never held anything); `box` as in {@link peerHeldQueueFor}. */
151
158
  export declare function peerHeldQueueIfAny(scope: string, sessionId: string, box?: string): PeerHeldQueue | undefined;
159
+ /** One held queue of this process as {@link listPeerHeldQueues} shows it. */
160
+ export interface PeerHeldQueueSnapshot {
161
+ readonly scope: string;
162
+ /** The session that opened the queue (the spelling it first used; the key folds case). */
163
+ readonly sessionId: string;
164
+ /** The box its cards come from: the session's own, or the principal inbox it also drains. */
165
+ readonly box: string;
166
+ readonly size: number;
167
+ /** The cards as {@link PeerHeldQueue.list} shows them, at the same moment as `size`. */
168
+ readonly entries: readonly PeerHeldEntry[];
169
+ }
170
+ /** Every held queue of this process's registry (opened through {@link peerHeldQueueFor}, as every drain opens its
171
+ * queues; a bare {@link createPeerHeldQueue} is not in it), as a read-only snapshot that opens none: a host approval face lists
172
+ * the held cards of all its sessions without keeping its own table of (session, box) coordinates. A row's
173
+ * (scope, sessionId, box) handed to {@link peerHeldQueueIfAny} reaches that queue for its settle face. */
174
+ export declare function listPeerHeldQueues(): readonly PeerHeldQueueSnapshot[];
152
175
  /** Test seam: drop every queue (timers cleared, NO receipts — the crash form). Never called by production code. */
153
176
  export declare function resetPeerHeldQueuesForTests(): void;
@@ -40,25 +40,37 @@ export function createPeerHeldQueue(key, opts = {}) {
40
40
  catch {
41
41
  }
42
42
  };
43
- const clearDeadline = (seq) => {
44
- const h = deadlines.get(seq);
43
+ const clearDeadline = (entry) => {
44
+ const h = deadlines.get(entry.seq);
45
45
  if (h !== undefined) {
46
46
  clock.clearTimeout(h);
47
- deadlines.delete(seq);
47
+ deadlines.delete(entry.seq);
48
48
  }
49
+ delete entry.deadlineAt;
49
50
  };
50
51
  const remove = (entry) => {
51
52
  const i = entries.indexOf(entry);
52
53
  if (i !== -1)
53
54
  entries.splice(i, 1);
54
- clearDeadline(entry.seq);
55
+ clearDeadline(entry);
56
+ };
57
+ const sendReceipt = (sink, entry, state) => {
58
+ let landed;
59
+ try {
60
+ landed = Promise.resolve(sink.receipt(entry, state));
61
+ }
62
+ catch (e) {
63
+ landed = Promise.reject(e);
64
+ }
65
+ landed.catch(() => undefined);
66
+ return landed;
55
67
  };
56
68
  const leave = (entry, settlement, reason, receipt) => {
57
69
  const sink = sinkOrThrow();
58
70
  remove(entry);
59
- if (receipt !== undefined)
60
- safe(() => sink.receipt(entry, receipt));
71
+ const landed = receipt !== undefined ? sendReceipt(sink, entry, receipt) : undefined;
61
72
  safe(() => sink.onSettled?.(entry, settlement, reason, entries.length));
73
+ return landed;
62
74
  };
63
75
  const move = async (entry, next) => {
64
76
  const sink = sinkOrThrow();
@@ -78,13 +90,17 @@ export function createPeerHeldQueue(key, opts = {}) {
78
90
  const adoptCurrent = (entry, current) => {
79
91
  if (!entries.includes(entry))
80
92
  return;
81
- if (current === "gone" || current === "unset")
82
- return leave(entry, "retired", "superseded", undefined);
83
- if (isMailboxDecisionFinal(current))
84
- return leave(entry, current, "decided_elsewhere", undefined);
93
+ if (current === "gone" || current === "unset") {
94
+ leave(entry, "retired", "superseded", undefined);
95
+ return;
96
+ }
97
+ if (isMailboxDecisionFinal(current)) {
98
+ leave(entry, current, "decided_elsewhere", undefined);
99
+ return;
100
+ }
85
101
  if (isMailboxDecisionDeliverable(current) && entry.decision !== current) {
86
102
  entry.decision = current;
87
- clearDeadline(entry.seq);
103
+ clearDeadline(entry);
88
104
  }
89
105
  };
90
106
  const settleLocal = async (entry, settlement, reason) => {
@@ -97,13 +113,16 @@ export function createPeerHeldQueue(key, opts = {}) {
97
113
  tells = false;
98
114
  }
99
115
  const from = settlement === "expired" ? "held" : "delivered";
100
- if (!tells || entry.decision !== from)
101
- return leave(entry, "retired", reason, undefined);
116
+ if (!tells || entry.decision !== from) {
117
+ leave(entry, "retired", reason, undefined);
118
+ return {};
119
+ }
102
120
  const r = await move(entry, settlement);
103
121
  if (r === "won")
104
- leave(entry, settlement, reason, settlement);
105
- else if (r === "fault")
122
+ return { landed: leave(entry, settlement, reason, settlement) };
123
+ if (r === "fault")
106
124
  leave(entry, "retired", reason, undefined);
125
+ return {};
107
126
  };
108
127
  const armDeadline = (entry) => {
109
128
  if (cfg === undefined || cfg.dialogExpiryMs === null || deadlines.has(entry.seq))
@@ -112,8 +131,9 @@ export function createPeerHeldQueue(key, opts = {}) {
112
131
  return;
113
132
  if (!PEER_HELD_REVIEW_CAUSES.includes(entry.cause))
114
133
  return;
134
+ entry.deadlineAt = clock.now() + cfg.dialogExpiryMs;
115
135
  const h = clock.setTimeout(() => {
116
- deadlines.delete(entry.seq);
136
+ clearDeadline(entry);
117
137
  void (async () => {
118
138
  if (!entries.includes(entry))
119
139
  return;
@@ -150,7 +170,7 @@ export function createPeerHeldQueue(key, opts = {}) {
150
170
  if (r === "fault")
151
171
  return "no_leg";
152
172
  entry.decision = "delivered";
153
- clearDeadline(entry.seq);
173
+ clearDeadline(entry);
154
174
  }
155
175
  try {
156
176
  if (sink.inject(entry) === "deferred")
@@ -191,7 +211,7 @@ export function createPeerHeldQueue(key, opts = {}) {
191
211
  if (verdict.verdict === "hold" && verdict.cause !== entry.cause) {
192
212
  entry.cause = verdict.cause;
193
213
  reannounce.push([entry, verdict.cause]);
194
- clearDeadline(entry.seq);
214
+ clearDeadline(entry);
195
215
  armDeadline(entry);
196
216
  }
197
217
  return "held";
@@ -253,7 +273,7 @@ export function createPeerHeldQueue(key, opts = {}) {
253
273
  cfg = next;
254
274
  for (const entry of entries) {
255
275
  if (next.dialogExpiryMs === null)
256
- clearDeadline(entry.seq);
276
+ clearDeadline(entry);
257
277
  else
258
278
  armDeadline(entry);
259
279
  }
@@ -266,8 +286,10 @@ export function createPeerHeldQueue(key, opts = {}) {
266
286
  cfg = { ...cfg, sink: rest };
267
287
  },
268
288
  configured: () => cfg !== undefined,
269
- async hold(input, known) {
289
+ async hold(held, known) {
270
290
  const sink = sinkOrThrow();
291
+ const { deadlineAt: _callerDeadline, ...input } = held;
292
+ void _callerDeadline;
271
293
  if (entries.some((e) => e.box === input.box && e.seq === input.seq))
272
294
  return "adopted";
273
295
  let state = known ?? "held";
@@ -294,7 +316,7 @@ export function createPeerHeldQueue(key, opts = {}) {
294
316
  return fresh ? "held" : "adopted";
295
317
  if (!(await makeRoom())) {
296
318
  if (fresh)
297
- safe(() => sink.receipt({ ...input, heldAt: clock.now(), decision: state }, "held"));
319
+ void sendReceipt(sink, { ...input, heldAt: clock.now(), decision: state }, "held");
298
320
  return "uncarded";
299
321
  }
300
322
  const entry = { ...input, heldAt: clock.now(), decision: state };
@@ -303,7 +325,7 @@ export function createPeerHeldQueue(key, opts = {}) {
303
325
  if (state === "held")
304
326
  safe(() => sink.onHeld?.(entry, entries.length, entry.cause, false));
305
327
  if (fresh)
306
- safe(() => sink.receipt(entry, "held"));
328
+ void sendReceipt(sink, entry, "held");
307
329
  return fresh ? "held" : "adopted";
308
330
  },
309
331
  rejudge,
@@ -322,12 +344,25 @@ export function createPeerHeldQueue(key, opts = {}) {
322
344
  deadlines.clear();
323
345
  return;
324
346
  }
347
+ const owed = [];
325
348
  for (const entry of [...entries]) {
326
349
  await onCard(entry.seq, async () => {
327
- if (entries.includes(entry))
328
- await settleLocal(entry, "expired", "shutdown");
350
+ if (!entries.includes(entry))
351
+ return;
352
+ const { landed } = await settleLocal(entry, "expired", "shutdown");
353
+ if (landed !== undefined)
354
+ owed.push({ seq: entry.seq, landed });
329
355
  });
330
356
  }
357
+ const outcomes = await Promise.allSettled(owed.map((o) => o.landed));
358
+ const unlanded = [];
359
+ outcomes.forEach((outcome, i) => {
360
+ if (outcome.status === "rejected")
361
+ unlanded.push({ seq: owed[i].seq, reason: outcome.reason });
362
+ });
363
+ if (unlanded.length > 0) {
364
+ throw new AggregateError(unlanded.map((u) => u.reason), `PeerHeldQueue.shutdown: every held card was settled, but the expired receipt of seq ${unlanded.map((u) => u.seq).join(", ")} did not reach its sender's box`);
365
+ }
331
366
  },
332
367
  };
333
368
  async function settleCard(seq, decision) {
@@ -371,7 +406,7 @@ export function createPeerHeldQueue(key, opts = {}) {
371
406
  if (r === "lost")
372
407
  return "decided_elsewhere";
373
408
  entry.decision = "approved";
374
- clearDeadline(entry.seq);
409
+ clearDeadline(entry);
375
410
  }
376
411
  if (verdict === undefined)
377
412
  return "released_pending";
@@ -386,25 +421,35 @@ export function createPeerHeldQueue(key, opts = {}) {
386
421
  });
387
422
  return queue;
388
423
  }
424
+ function peerHeldQueueSeat(scope, sessionId, box) {
425
+ const own = peerSessionBoxHandle(sessionId);
426
+ const at = box ?? own;
427
+ return { scope, sessionId, box: at, key: JSON.stringify(at === own ? [scope, own] : [scope, own, at]) };
428
+ }
389
429
  const heldQueues = new Map();
390
430
  export function peerHeldQueueKey(scope, sessionId, box) {
391
- const own = peerSessionBoxHandle(sessionId);
392
- return JSON.stringify(box === undefined || box === own ? [scope, own] : [scope, own, box]);
431
+ return peerHeldQueueSeat(scope, sessionId, box).key;
393
432
  }
394
433
  export function peerHeldQueueFor(scope, sessionId, opts = {}) {
395
- const key = peerHeldQueueKey(scope, sessionId, opts.box);
396
- let q = heldQueues.get(key);
397
- if (q === undefined) {
398
- q = createPeerHeldQueue(key, opts);
399
- heldQueues.set(key, q);
434
+ const seat = peerHeldQueueSeat(scope, sessionId, opts.box);
435
+ let row = heldQueues.get(seat.key);
436
+ if (row === undefined) {
437
+ row = { seat, queue: createPeerHeldQueue(seat.key, opts) };
438
+ heldQueues.set(seat.key, row);
400
439
  }
401
- return q;
440
+ return row.queue;
402
441
  }
403
442
  export function peerHeldQueueIfAny(scope, sessionId, box) {
404
- return heldQueues.get(peerHeldQueueKey(scope, sessionId, box));
443
+ return heldQueues.get(peerHeldQueueKey(scope, sessionId, box))?.queue;
444
+ }
445
+ export function listPeerHeldQueues() {
446
+ return [...heldQueues.values()].map(({ seat, queue }) => {
447
+ const entries = queue.list();
448
+ return { scope: seat.scope, sessionId: seat.sessionId, box: seat.box, size: entries.length, entries };
449
+ });
405
450
  }
406
451
  export function resetPeerHeldQueuesForTests() {
407
- for (const q of heldQueues.values())
408
- crashHandlers.get(q)?.();
452
+ for (const { queue } of heldQueues.values())
453
+ crashHandlers.get(queue)?.();
409
454
  heldQueues.clear();
410
455
  }
@@ -147,14 +147,24 @@ export function createPeerSessionDrain(opts) {
147
147
  _sema_provenance: { kind: "cross_session_notice", from: encodePeerAddress(storedSessionAddress(m.peerMeta?.fromSession) ?? (m.from ?? "unknown")), taskId: boxHandle, seq: m.seq, ...(m.peerMeta !== undefined ? { peerMeta: { ...m.peerMeta } } : {}) },
148
148
  });
149
149
  const receiptAddress = (lane, entry) => (lane.kind === "session" ? entry.peerMeta?.fromSession : undefined);
150
- const receipt = (lane) => (entry, state) => {
150
+ const receipt = (lane) => async (entry, state) => {
151
151
  const to = receiptAddress(lane, entry);
152
152
  if (to === undefined)
153
153
  return;
154
+ const faults = [];
155
+ const via = {
156
+ ...route(),
157
+ onError: (error, ctx) => {
158
+ faults.push(error);
159
+ opts.onError?.(error, ctx);
160
+ },
161
+ };
154
162
  if (state === "dropped")
155
- void routePeerDroppedReceipt(route(), to, entry.seq);
163
+ await routePeerDroppedReceipt(via, to, entry.seq);
156
164
  else
157
- void routePeerDeliveryReceipt(route(), to, state, entry.seq);
165
+ await routePeerDeliveryReceipt(via, to, state, entry.seq);
166
+ if (faults.length > 0)
167
+ throw faults[0];
158
168
  };
159
169
  const settleConsumed = (lane, seq, payload, by, reason) => {
160
170
  lane.ledger.set(seq, { kind: "terminal", why: "consumed" });
@@ -641,8 +641,13 @@ export interface SubagentToolOptions {
641
641
  * milliseconds of minting and the redemption window never exists. The hook must cover the
642
642
  * store the child session ACTUALLY lives in — copy the session tree into the durable store,
643
643
  * then re-verify, and only then resolve.
644
+ *
645
+ * `given.owner` is the child's delegation tree owner (the owner of its tree root's row as the root run read it; for a revived
646
+ * child, its own row's): a promotion that creates the durable row records exactly it — the hook derives no owner of its own.
644
647
  */
645
- ensureChildSessionDurable?: (sessionId: string) => Promise<void>;
648
+ ensureChildSessionDurable?: (sessionId: string, given: {
649
+ owner: string | null;
650
+ }) => Promise<void>;
646
651
  };
647
652
  /** Model the child runs on when neither the call nor the agent definition names one (the tool-level explicit seat).
648
653
  * Omitted too ⇒ the deployment's stated `roles.subagent` tier, else the parent run's effective model (`childModelSeat`). */
@@ -3,7 +3,7 @@ import { isAbsolute } from "node:path";
3
3
  import { backgroundChildTerminal } from "../core/delegation-frames.js";
4
4
  import { bindDelegationName } from "../core/delegation-name.js";
5
5
  import { authoredSteerOf } from "../core/input-author.js";
6
- import { principalNameOf } from "../core/principal-name.js";
6
+ import { DELEGATION_OWNER_UNBOUND, delegationOwnerOf, rowOwnerReading } from "../core/runner/delegation-owner.js";
7
7
  import { resumeRefusalDetailOf, resumeStartupCauseOf } from "../core/resume-startup-cause.js";
8
8
  import { errorCodeOf, thrownFailureOf } from "../core/runner/terminal-account.js";
9
9
  import { applyParentSpecSeat, parentSpecSeatOfCtx } from "../core/parent-spec-seat.js";
@@ -1084,6 +1084,28 @@ function chargeLocalDelegationInFlight(anchor, key) {
1084
1084
  live.delete(key);
1085
1085
  };
1086
1086
  }
1087
+ const REFUSAL_OCCUPANTS_LISTED = 5;
1088
+ function reachableOccupants(registry, scope, root, caller) {
1089
+ const face = registry === undefined ? undefined : registry.activeDelegationOccupants;
1090
+ if (typeof face !== "function")
1091
+ return new Map();
1092
+ try {
1093
+ return new Map(face.call(registry, scope, root, caller).filter((o) => o.reachable).map((o) => [o.id, o.name]));
1094
+ }
1095
+ catch {
1096
+ return new Map();
1097
+ }
1098
+ }
1099
+ function concurrencyOccupants(active, reachable, local) {
1100
+ const listed = active.filter((id) => reachable.has(id)).slice(0, REFUSAL_OCCUPANTS_LISTED);
1101
+ const parts = listed.map((id) => `task_id ${id} (${JSON.stringify(reachable.get(id))})`);
1102
+ const rest = active.length - listed.length;
1103
+ if (rest > 0)
1104
+ parts.push(`${rest} ${listed.length > 0 ? "more " : ""}registered`);
1105
+ if (local > 0)
1106
+ parts.push(`${local} running synchronously inside a call of this tree, no task_id`);
1107
+ return { text: parts.join(", "), stoppable: listed.length > 0 };
1108
+ }
1087
1109
  const spawnAbortedResult = (wt, fault) => notStartedResult({
1088
1110
  isError: true,
1089
1111
  content: `Sub-agent not started: the delegating call was aborted.${wt ? `\n${wt}` : ""}`,
@@ -1119,7 +1141,7 @@ function delegationEntryPool(seat) {
1119
1141
  return { key, occupy: (kind) => (kind === "local" ? chargeLocalDelegationInFlight(seat.poolAnchor, key) : noopRelease) };
1120
1142
  }
1121
1143
  async function openDelegationEntryGate(input) {
1122
- const { poolAnchor, registry, store, root, caps, signal } = input;
1144
+ const { poolAnchor, registry, store, root, caps, signal, caller } = input;
1123
1145
  const pool = delegationEntryPool(input);
1124
1146
  if (root === undefined)
1125
1147
  return { ...pool, admit: () => ({ admitted: true, release: noopRelease }) };
@@ -1143,11 +1165,13 @@ async function openDelegationEntryGate(input) {
1143
1165
  const local = localDelegationInFlightCount(poolAnchor, key);
1144
1166
  const running = active.length + local;
1145
1167
  if (running >= caps.maxConcurrent) {
1168
+ const who = concurrencyOccupants(active, reachableOccupants(registry, scope, root, { ...caller, scope }), local);
1169
+ const stop = who.stoppable ? " or stop a listed one (TaskStop with its task_id)" : "";
1146
1170
  return {
1147
1171
  admitted: false,
1148
1172
  refusal: {
1149
1173
  code: "delegation.concurrency_cap",
1150
- text: `this session tree already has ${running} agents running — the concurrency cap (${caps.maxConcurrent}; RunnerDeps.delegationEntryCaps.maxConcurrent) refuses another. ${kind === "registered" ? "Wait for one to complete (you will be notified) or stop one, then relaunch." : "Wait for one of them to finish or stop one, then try again."}`,
1174
+ text: `this session tree already has ${running} agents running${who.text === "" ? "" : ` (${who.text})`} — the concurrency cap (${caps.maxConcurrent}; RunnerDeps.delegationEntryCaps.maxConcurrent) refuses another. ${kind === "registered" ? `Wait for one to complete (you will be notified)${stop}, then relaunch.` : `Wait for one of them to finish${stop}, then try again.`}`,
1151
1175
  },
1152
1176
  };
1153
1177
  }
@@ -1815,6 +1839,10 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
1815
1839
  ...(cause !== undefined ? { cause: childThrownText(cause) } : {}),
1816
1840
  ...(worktreeFault !== undefined ? { worktreeCause: worktreeFault } : {}),
1817
1841
  });
1842
+ const ownerUnboundResult = async (background, tree) => {
1843
+ const wt = await finishWorktree();
1844
+ return notStartedResult(errorResult(`${background ? "Sub-agent not started in background" : "Sub-agent not started"}: the delegation tree's owner does not bind — ${tree.reason.slice(0, 600)}.${wt ? `\n${wt.slice(0, 1600)}` : ""}`, { error: DELEGATION_OWNER_UNBOUND, code: DELEGATION_OWNER_UNBOUND, ...faultDetails(tree.fault) }));
1845
+ };
1818
1846
  let injectedTools = [];
1819
1847
  let extraToolsNote;
1820
1848
  const treeBudget = extraToolsBudget ?? { used: 0 };
@@ -2143,7 +2171,14 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2143
2171
  ? (reviveClaim.row.rootSessionId ?? reviveClaim.row.parentSessionId ?? (reviveClaim.row.sessionScoped ? reviveClaim.row.owner : undefined))
2144
2172
  : (ctx.rootSessionId ?? ctx.sessionId);
2145
2173
  const entryPoolSeat = { poolAnchor: entryCapPoolAnchor, scope: treeScope, root: entryCapRoot };
2146
- const openEntryGate = () => openDelegationEntryGate({ ...entryPoolSeat, registry: opts.background?.registry, store: opts.background?.agentStore, caps: entryCaps, signal: ctx.signal });
2174
+ const openEntryGate = () => openDelegationEntryGate({
2175
+ ...entryPoolSeat,
2176
+ registry: opts.background?.registry,
2177
+ store: opts.background?.agentStore,
2178
+ caps: entryCaps,
2179
+ signal: ctx.signal,
2180
+ caller: { owner: ctx.taskId ?? opts.background?.owner, ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}) },
2181
+ });
2147
2182
  const provenanceRequest = ctx.delegationProvenanceForChildren?.();
2148
2183
  const childProvenanceRef = provenanceRequest !== undefined ? { current: newDelegationProvenanceAggregate() } : undefined;
2149
2184
  const childAttestation = (completed) => childProvenanceRef !== undefined ? reduceDelegationAttestation(childProvenanceRef.current, { completed }) : undefined;
@@ -2162,6 +2197,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2162
2197
  ...(inheritedAllowedTools !== undefined && inheritedAllowedTools.length > 0 ? { inheritedAllowedTools: [...inheritedAllowedTools] } : {}),
2163
2198
  ...(childProvenanceRef !== undefined && provenanceRequest !== undefined ? { delegationProvenance: { ref: childProvenanceRef, contentSafety: provenanceRequest } } : {}),
2164
2199
  ...(reviveClaim === undefined && ctx.crossBoundaryTreeForChildren !== undefined ? { crossBoundaryTree: ctx.crossBoundaryTreeForChildren } : {}),
2200
+ ...(reviveClaim === undefined && ctx.delegationOwner !== undefined ? { delegationOwner: ctx.delegationOwner } : {}),
2165
2201
  ...(treeScope !== undefined ? { registryScope: treeScope } : {}),
2166
2202
  ...(ctx.checkpointScopeForChildren !== undefined ? { checkpointScope: ctx.checkpointScopeForChildren } : {}),
2167
2203
  ...(ctx.inheritedGateForChildren ? { inheritedGate: ctx.inheritedGateForChildren() } : {}),
@@ -2455,6 +2491,9 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2455
2491
  if (wantsFork) {
2456
2492
  let forkedId;
2457
2493
  let releaseForked;
2494
+ const forkTree = await delegationOwnerOf(ctx.delegationOwner);
2495
+ if (!forkTree.bound)
2496
+ return ownerUnboundResult(false, forkTree);
2458
2497
  try {
2459
2498
  if (ctx.hostSessionFork) {
2460
2499
  const forkHandle = await ctx.hostSessionFork();
@@ -2462,7 +2501,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2462
2501
  releaseForked = forkHandle?.release;
2463
2502
  }
2464
2503
  else {
2465
- forkedId = (await opts.runner.sessions.fork?.(ctx.sessionId, principalNameOf(ctx.principal) ?? null)) ?? null;
2504
+ forkedId = (await opts.runner.sessions.fork?.(ctx.sessionId, forkTree.owner)) ?? null;
2466
2505
  }
2467
2506
  }
2468
2507
  catch (e) {
@@ -2593,7 +2632,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2593
2632
  chargeDelegationEntryHandle(bg.registry, forkEntryGate.key, bg.agentStore, taskId);
2594
2633
  oweTerminalDelivery(notify, { task_id: taskId, task_type: "background_agent" });
2595
2634
  childInternals.peerSelfRef?.addAxis("h", taskId);
2596
- bg.registry.bindBackgroundAgentSession(taskId, forkedId);
2635
+ bg.registry.bindBackgroundAgentSession(taskId, forkedId, opts.runner.sessions);
2597
2636
  stepRecorder.lockTo(taskId);
2598
2637
  const forkBgHangAt = Date.now();
2599
2638
  bg.registry.attachAgentTerminalNotifier(taskId, () => {
@@ -2994,6 +3033,17 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2994
3033
  const shortDesc = reviveRow?.description ?? String(a.description ?? "sub-agent").slice(0, 200);
2995
3034
  const bgOwner = reviveRow !== undefined ? reviveRow.owner : sessionScopedBg ? ctx.sessionId : ctx.taskId ?? bg.owner;
2996
3035
  const bgScope = treeScope;
3036
+ const childTreeOwner = () => (reviveRow !== undefined ? rowOwnerReading(opts.runner.sessions, reviveRow.sessionId) : delegationOwnerOf(ctx.delegationOwner));
3037
+ let placedTreeOwner;
3038
+ if (reviveRow === undefined && bg.agentStore !== undefined && opts.runner.sessions.placements?.subagent !== undefined) {
3039
+ const tree = await childTreeOwner();
3040
+ if (!tree.bound) {
3041
+ dropHostAbortListener();
3042
+ await cancelObserver();
3043
+ return ownerUnboundResult(true, tree);
3044
+ }
3045
+ placedTreeOwner = tree.owner;
3046
+ }
2997
3047
  const bgEntryPool = delegationEntryPool(entryPoolSeat);
2998
3048
  const capLedgerKey = bgEntryPool.key;
2999
3049
  if (reviveRow !== undefined) {
@@ -3139,7 +3189,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3139
3189
  const bgChildSessionId = reviveRow?.sessionId ?? uuidv7();
3140
3190
  const bgStartedAt = Date.now();
3141
3191
  stepRecorder.lockTo(taskId);
3142
- bg.registry.bindBackgroundAgentSession(taskId, bgChildSessionId);
3192
+ bg.registry.bindBackgroundAgentSession(taskId, bgChildSessionId, opts.runner.sessions);
3143
3193
  const bgCycleSeq = bg.registry.backgroundAgentCycleSeq(taskId);
3144
3194
  bg.registry.attachAgentTerminalNotifier(taskId, () => {
3145
3195
  const stoppedByReap = bg.registry.getStopAttribution(taskId) ?? "system";
@@ -3207,7 +3257,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3207
3257
  await origRelease();
3208
3258
  };
3209
3259
  }
3210
- bg.registry.bindBackgroundAgentSession(taskId, bgChildSessionId);
3260
+ bg.registry.bindBackgroundAgentSession(taskId, bgChildSessionId, opts.runner.sessions);
3211
3261
  const forwardDurableApproval = ctx.durableApprovalForChildren !== undefined &&
3212
3262
  bg.agentStore !== undefined &&
3213
3263
  childParkStore !== undefined &&
@@ -3250,15 +3300,16 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3250
3300
  usage: { toolUses: toolStarts },
3251
3301
  });
3252
3302
  }, () => bg.registry.noteBackgroundAgentActivity(taskId));
3253
- const bgPlacementRoot = reviveRow !== undefined ? (reviveRow.rootSessionId ?? reviveRow.parentSessionId) : (ctx.rootSessionId ?? ctx.sessionId);
3254
- const bgPlacementParent = reviveRow !== undefined ? reviveRow.parentSessionId : ctx.sessionId;
3255
- const bgPlacement = bg.agentStore !== undefined && opts.runner.sessions.placements?.subagent !== undefined
3303
+ const bgPlacementRoot = ctx.rootSessionId ?? ctx.sessionId;
3304
+ const bgPlacementParent = ctx.sessionId;
3305
+ const bgPlacement = placedTreeOwner !== undefined
3256
3306
  ? {
3257
3307
  kind: "subagent",
3258
3308
  ...(bgScope !== undefined ? { scope: bgScope } : {}),
3259
3309
  ...(bgPlacementParent !== undefined ? { parentSessionId: bgPlacementParent } : {}),
3260
3310
  ...(bgPlacementRoot !== undefined ? { rootSessionId: bgPlacementRoot } : {}),
3261
3311
  handle: taskId,
3312
+ owner: placedTreeOwner,
3262
3313
  }
3263
3314
  : undefined;
3264
3315
  const bgInternals = bgSink
@@ -3517,7 +3568,10 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3517
3568
  else {
3518
3569
  let attested = false;
3519
3570
  try {
3520
- await bg.ensureChildSessionDurable(bgChildSessionId);
3571
+ const tree = placedTreeOwner !== undefined ? { bound: true, owner: placedTreeOwner } : await childTreeOwner();
3572
+ if (!tree.bound)
3573
+ throw new Error(tree.reason);
3574
+ await bg.ensureChildSessionDurable(bgChildSessionId, { owner: tree.owner });
3521
3575
  attested = true;
3522
3576
  }
3523
3577
  catch {