@sema-agent/core 7.63.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 (204) hide show
  1. package/CHANGELOG.md +408 -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.js +20 -3
  23. package/dist/core/allow-entry.d.ts +4 -0
  24. package/dist/core/ask-origin.d.ts +1 -1
  25. package/dist/core/ask-origin.js +2 -2
  26. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  27. package/dist/core/ask-unresolvable-notice.js +10 -3
  28. package/dist/core/auto-compaction.d.ts +7 -5
  29. package/dist/core/background-agent-store.d.ts +7 -0
  30. package/dist/core/background-agent-store.js +3 -0
  31. package/dist/core/checkpoint-queries.d.ts +9 -6
  32. package/dist/core/checkpoint-queries.js +8 -3
  33. package/dist/core/checkpoint-store.d.ts +5 -1
  34. package/dist/core/context-settings.d.ts +40 -9
  35. package/dist/core/context-settings.js +32 -10
  36. package/dist/core/engine-attestation.d.ts +26 -6
  37. package/dist/core/engine-attestation.js +5 -1
  38. package/dist/core/engine-notice.d.ts +24 -1
  39. package/dist/core/extension-requester.d.ts +9 -0
  40. package/dist/core/extension-requester.js +7 -0
  41. package/dist/core/file-history-store.d.ts +28 -0
  42. package/dist/core/file-history-store.js +48 -5
  43. package/dist/core/fs-write-gate-policy.js +1 -1
  44. package/dist/core/gate-fold.js +2 -0
  45. package/dist/core/gate-lanes.js +2 -0
  46. package/dist/core/gate-outcome.d.ts +39 -2
  47. package/dist/core/gate-outcome.js +20 -1
  48. package/dist/core/governance-codes.d.ts +3 -1
  49. package/dist/core/governance-codes.js +4 -0
  50. package/dist/core/leg-identity.d.ts +19 -1
  51. package/dist/core/leg-identity.js +12 -0
  52. package/dist/core/mailbox-store.d.ts +39 -4
  53. package/dist/core/mailbox-store.js +14 -2
  54. package/dist/core/memory-engine/consolidation.d.ts +3 -2
  55. package/dist/core/memory-engine/consolidation.js +16 -0
  56. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  57. package/dist/core/memory-engine/control-objects.js +151 -0
  58. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  59. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  60. package/dist/core/memory-engine/delegation-settlement.d.ts +21 -5
  61. package/dist/core/memory-engine/delegation-settlement.js +217 -26
  62. package/dist/core/memory-engine/dual-root.js +2 -2
  63. package/dist/core/memory-engine/engine.d.ts +38 -23
  64. package/dist/core/memory-engine/engine.js +14 -14
  65. package/dist/core/memory-engine/file-backend.d.ts +41 -65
  66. package/dist/core/memory-engine/file-backend.js +59 -166
  67. package/dist/core/memory-engine/index.d.ts +3 -2
  68. package/dist/core/memory-engine/index.js +2 -1
  69. package/dist/core/memory-engine/layout.d.ts +6 -1
  70. package/dist/core/memory-engine/layout.js +12 -7
  71. package/dist/core/memory-engine/memory-backend-contract.d.ts +10 -3
  72. package/dist/core/memory-engine/memory-backend-contract.js +158 -2
  73. package/dist/core/memory-engine/memory-deployment.d.ts +11 -3
  74. package/dist/core/memory-engine/memory-deployment.js +31 -6
  75. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  76. package/dist/core/memory-engine/origin-clearance.js +68 -9
  77. package/dist/core/memory-engine/session-write-home.d.ts +34 -1
  78. package/dist/core/memory-engine/session-write-home.js +37 -10
  79. package/dist/core/memory-engine/types.d.ts +44 -7
  80. package/dist/core/memory-engine/types.js +2 -1
  81. package/dist/core/mode-policy.js +3 -3
  82. package/dist/core/mods/agent-stations.d.ts +18 -0
  83. package/dist/core/mods/agent-stations.js +8 -6
  84. package/dist/core/mods/extension-call.d.ts +4 -0
  85. package/dist/core/mods/extension-call.js +8 -0
  86. package/dist/core/mods/tool-call.js +3 -4
  87. package/dist/core/parent-spec-seat.d.ts +2 -2
  88. package/dist/core/peer-channel.d.ts +5 -0
  89. package/dist/core/permission-rule-consent.d.ts +21 -10
  90. package/dist/core/permission-rule-consent.js +50 -23
  91. package/dist/core/permission-rule-store.d.ts +41 -16
  92. package/dist/core/permission-rule-store.js +2 -0
  93. package/dist/core/refusal-echo.d.ts +20 -0
  94. package/dist/core/refusal-echo.js +33 -0
  95. package/dist/core/retention.d.ts +180 -10
  96. package/dist/core/retention.js +45 -0
  97. package/dist/core/retired-keys.d.ts +5 -0
  98. package/dist/core/retired-keys.js +3 -0
  99. package/dist/core/rule-offer-read.d.ts +0 -4
  100. package/dist/core/rule-offer-read.js +2 -18
  101. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  102. package/dist/core/runner/classifier-ladder.js +4 -2
  103. package/dist/core/runner/compact-session.js +10 -7
  104. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  105. package/dist/core/runner/compaction-call-options.js +3 -2
  106. package/dist/core/runner/contracts.d.ts +21 -2
  107. package/dist/core/runner/delegation-owner.d.ts +10 -3
  108. package/dist/core/runner/delegation-owner.js +4 -1
  109. package/dist/core/runner/gate-exit.d.ts +6 -0
  110. package/dist/core/runner/gate-exit.js +11 -2
  111. package/dist/core/runner/memory-consolidation-driver.d.ts +4 -2
  112. package/dist/core/runner/memory-consolidation-driver.js +8 -5
  113. package/dist/core/runner/prepare-ask-lane.js +3 -3
  114. package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -1
  115. package/dist/core/runner/prepare-caps-and-workflow.js +2 -2
  116. package/dist/core/runner/prepare-config-doors.js +4 -0
  117. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  118. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  119. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  120. package/dist/core/runner/prepare-gate-stations.js +5 -5
  121. package/dist/core/runner/prepare-hands-readface.js +1 -1
  122. package/dist/core/runner/prepare-inherited-gate.d.ts +3 -1
  123. package/dist/core/runner/prepare-inherited-gate.js +4 -2
  124. package/dist/core/runner/prepare-memory.d.ts +4 -0
  125. package/dist/core/runner/prepare-memory.js +14 -20
  126. package/dist/core/runner/prepare-policy-chain.js +7 -7
  127. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  128. package/dist/core/runner/prepare-task.js +15 -10
  129. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  130. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  131. package/dist/core/runner/resume-admission.d.ts +2 -2
  132. package/dist/core/runner/resume-admission.js +2 -23
  133. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  134. package/dist/core/runner/role-resolution-table.js +62 -0
  135. package/dist/core/runner/run-compaction-machinery.js +2 -2
  136. package/dist/core/runner/run-identity-wiring.js +12 -9
  137. package/dist/core/runner/run-leg.js +8 -4
  138. package/dist/core/runner/run-notification-lane.js +22 -22
  139. package/dist/core/runner/run-recovery-lanes.js +3 -3
  140. package/dist/core/runner/run-terminal-adoption.js +1 -1
  141. package/dist/core/runner/run-turn-boundary.js +14 -15
  142. package/dist/core/runner/runtask.js +1 -1
  143. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  144. package/dist/core/runner/tool-occurrence.js +2 -2
  145. package/dist/core/runner-deps.d.ts +1 -1
  146. package/dist/core/session-checkout.d.ts +63 -3
  147. package/dist/core/session-checkout.js +152 -58
  148. package/dist/core/shell-read-silence.js +8 -0
  149. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  150. package/dist/core/task-event.d.ts +9 -5
  151. package/dist/core/task-notification.d.ts +110 -31
  152. package/dist/core/task-notification.js +180 -100
  153. package/dist/core/task-registry-agent.d.ts +11 -0
  154. package/dist/core/task-registry-agent.js +11 -3
  155. package/dist/core/task-registry-shared.d.ts +7 -0
  156. package/dist/core/task-registry.d.ts +18 -0
  157. package/dist/core/task-registry.js +27 -8
  158. package/dist/core/task-spec.d.ts +7 -2
  159. package/dist/core/tool-errors.d.ts +14 -6
  160. package/dist/core/tool-errors.js +1 -1
  161. package/dist/core/tool-policy.d.ts +18 -1
  162. package/dist/core/tool-policy.js +16 -7
  163. package/dist/core/tool-result-store.d.ts +20 -0
  164. package/dist/core/tool-spec.d.ts +4 -0
  165. package/dist/core/trace.d.ts +3 -2
  166. package/dist/core/workflow-journal-store.d.ts +11 -0
  167. package/dist/core/workflow-journal-store.js +7 -0
  168. package/dist/core/workflow-run-store.d.ts +9 -0
  169. package/dist/core/workflow-run-store.js +6 -0
  170. package/dist/engine/compaction/compaction.d.ts +2 -1
  171. package/dist/engine/harness/types.d.ts +1 -0
  172. package/dist/engine/session/session.d.ts +7 -1
  173. package/dist/engine/session/session.js +5 -2
  174. package/dist/index.d.ts +7 -5
  175. package/dist/index.js +7 -5
  176. package/dist/orchestration/run-workflow-tool.d.ts +4 -0
  177. package/dist/orchestration/run-workflow-tool.js +7 -0
  178. package/dist/orchestration/workflow-types.d.ts +2 -1
  179. package/dist/orchestration/workflow.d.ts +3 -0
  180. package/dist/orchestration/workflow.js +2 -1
  181. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  182. package/dist/stores/file/checkpoint-store.js +4 -1
  183. package/dist/stores/file/file-history-store.d.ts +13 -0
  184. package/dist/stores/file/file-history-store.js +75 -13
  185. package/dist/stores/file/index.d.ts +11 -1
  186. package/dist/stores/file/index.js +7 -11
  187. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  188. package/dist/stores/file/permission-rule-store.js +75 -7
  189. package/dist/stores/file/tool-result-store.d.ts +14 -0
  190. package/dist/stores/file/tool-result-store.js +39 -2
  191. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  192. package/dist/stores/file/workflow-journal-store.js +17 -0
  193. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  194. package/dist/stores/file/workflow-run-store.js +15 -0
  195. package/dist/tools/fs/read-deny.d.ts +15 -2
  196. package/dist/tools/fs/read-deny.js +10 -2
  197. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  198. package/dist/tools/fs/shell-read-check.js +7 -7
  199. package/package.json +2 -2
  200. package/test/export-surface.snapshot.json +63 -1
  201. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  202. package/wire-changes/core@7.64.0.json +2653 -0
  203. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  204. package/wire-changes/primitives@7.64.0.json +30 -0
@@ -1,11 +1,12 @@
1
- import { isMailboxDecisionFinal, mailboxCrossProcessMountVerdict, moveMailboxDecision } from "../core/mailbox-store.js";
2
- import { decodeEngineFrame, ENGINE_FRAME_CODEC_VERSION, renderTaskNotificationXml, taskNotificationDedupKey } from "../core/task-notification.js";
1
+ import { isMailboxDecisionFinal, moveMailboxDecision, sessionBoxMountVerdict } from "../core/mailbox-store.js";
2
+ import { decodeEngineFrame, deliveryDiscardedNotice, ENGINE_FRAME_CODEC_VERSION, renderTaskNotificationXml, taskNotificationDedupKey } from "../core/task-notification.js";
3
+ import { sameOccupant } from "../core/runner/delegation-owner.js";
3
4
  import { createFrameSettlement, toolResultReceiptKey } from "../core/frame-settlement.js";
4
5
  import { PRINCIPAL_INBOX_HANDLE } from "./cross-session-ref.js";
5
6
  import { isGateMintedRecord, principalInboxConsumerOf } from "./org-delivery-gate.js";
6
7
  import { deliverEngineNotice } from "../core/types.js";
7
8
  import { buildCrossSessionEnvelope, CrossSessionCodecError, encodePeerAddress } from "./cross-session-envelope.js";
8
- import { judgeCrossSessionInbound, principalInboundLayers, resolveCrossSessionInboundSetting } from "./cross-session-judge.js";
9
+ import { isCrossSessionHoldCause, judgeCrossSessionInbound, principalInboundLayers, resolveCrossSessionInboundSetting } from "./cross-session-judge.js";
9
10
  import { judgePeerAdmission, peerAxisToken, resolvePeerLaneConfig } from "./peer-admission.js";
10
11
  import { isPeerSessionId, listPeerDirectory, PEER_SESSION_ID_GRAMMAR, peerSessionBoxHandle } from "./peer-directory.js";
11
12
  import { inlineUntrusted } from "../core/untrusted-text.js";
@@ -13,7 +14,7 @@ import { createListAgentsTool, LIST_AGENTS_TOOL_ALIAS, LIST_AGENTS_TOOL_NAME } f
13
14
  import { foldPermissionModeClass } from "./cross-session-judge.js";
14
15
  import { peerHeldQueueFor } from "./peer-held-queue.js";
15
16
  import { peerIdleMachineFor } from "./peer-idle.js";
16
- import { describePeerIdleSubscription, isPeerDeliveryReceiptState, isPeerIdleNoticeKind, peerIdleNoticeLabel, renderCrossSessionDeliveryNotice, renderCrossSessionDroppedNotice, renderCrossSessionIdleNotice, resolveCrossSessionDialogExpiry } from "./peer-notices.js";
17
+ import { describePeerIdleSubscription, isPeerDeliveryReceiptState, isPeerIdleNoticeKind, peerHeldReceiptStateOf, peerIdleNoticeLabel, renderCrossSessionDeliveryNotice, renderCrossSessionDroppedNotice, renderCrossSessionIdleNotice, resolveCrossSessionDialogExpiry } from "./peer-notices.js";
17
18
  import { routePeerDeliveryReceipt, routePeerDroppedReceipt, routePeerIdleNotice } from "./peer-notice-route.js";
18
19
  import { thrownText } from "../core/thrown-value.js";
19
20
  export const PEER_DRAIN_LEASE_TTL_MS = 5 * 60_000;
@@ -22,13 +23,13 @@ export const PRINCIPAL_INBOX_UNMINTED_CAUSE = "not_minted_by_delivery_gate";
22
23
  export function terminalsDrainPrincipalInbox(deps) {
23
24
  return principalInboxConsumerOf(deps).kind === "terminals";
24
25
  }
25
- export function judgePeerLaneMount(deps, sessionId) {
26
+ export function judgePeerLaneMount(deps, sessionId, sessions) {
26
27
  if (deps.peerDirectory === undefined)
27
28
  return undefined;
28
29
  if (deps.mailboxStore === undefined) {
29
30
  return { ok: false, code: "mailbox.cross_process_unsafe", reason: "RunnerDeps.peerDirectory is wired but RunnerDeps.mailboxStore is not — the cross-session lane parks messages in the recipient's durable session box and has no store to park them in" };
30
31
  }
31
- const store = mailboxCrossProcessMountVerdict(deps.mailboxStore);
32
+ const store = sessionBoxMountVerdict(deps.mailboxStore, sessions);
32
33
  if (!store.ok)
33
34
  return store;
34
35
  if (sessionId !== undefined && !isPeerSessionId(sessionId)) {
@@ -42,9 +43,9 @@ export function judgePeerLaneMount(deps, sessionId) {
42
43
  }
43
44
  export function judgeSessionBoxDrain(deps, leg) {
44
45
  const mailbox = deps.mailboxStore;
45
- if (mailbox === undefined || leg.isDelegatedChild)
46
+ if (mailbox === undefined || leg.isDelegatedChild || leg.unread === true)
46
47
  return undefined;
47
- if (!mailboxCrossProcessMountVerdict(mailbox).ok || !isPeerSessionId(leg.sessionId))
48
+ if (!sessionBoxMountVerdict(mailbox, leg.sessions).ok || !isPeerSessionId(leg.sessionId))
48
49
  return undefined;
49
50
  return {
50
51
  mailbox,
@@ -65,6 +66,7 @@ export function createPeerSessionDrain(opts) {
65
66
  const TERMINAL_DISPOSITIONS = new Set(["committed", "resupply_exhausted", "terminal"]);
66
67
  const isTerminalDisposition = (d) => d !== undefined && TERMINAL_DISPOSITIONS.has(d.kind);
67
68
  const clockOpt = opts.clock !== undefined ? { clock: opts.clock } : {};
69
+ const occupantOpt = opts.occupant !== undefined ? { occupant: opts.occupant } : {};
68
70
  const mintLane = (kind) => {
69
71
  const boxHandle = kind === "session" ? peerSessionBoxHandle(sessionId) : PRINCIPAL_INBOX_HANDLE;
70
72
  return {
@@ -74,7 +76,7 @@ export function createPeerSessionDrain(opts) {
74
76
  ledger: new Map(),
75
77
  ackedUpTo: undefined,
76
78
  disclosedHeld: new Set(),
77
- held: peerHeldQueueFor(scope, sessionId, kind === "session" ? clockOpt : { ...clockOpt, box: boxHandle }),
79
+ held: peerHeldQueueFor(scope, sessionId, kind === "session" ? { ...clockOpt, ...occupantOpt } : { ...clockOpt, box: boxHandle }),
78
80
  };
79
81
  };
80
82
  const lanes = opts.principalInbox === true ? [mintLane("session"), mintLane("principal")] : [mintLane("session")];
@@ -84,11 +86,11 @@ export function createPeerSessionDrain(opts) {
84
86
  let inFlight = Promise.resolve();
85
87
  let noticeRound = 0;
86
88
  let currentRound;
87
- const idleMachine = peerIdleMachineFor(scope, sessionId, clockOpt);
89
+ const idleMachine = peerIdleMachineFor(scope, sessionId, { ...clockOpt, ...occupantOpt });
88
90
  const disclose = (lane, disposition, cause, m, heldNote) => deliverEngineNotice(opts.onNotice, {
89
91
  code: "peer.inbound_disposition",
90
92
  message: `cross-session message seq ${m.seq} in ${lane.label} was ${disposition === "held"
91
- ? `HELD${heldNote !== undefined ? ` (${heldNote})` : lane.kind === "session" ? " (it entered this session's held queue and STAYS IN THE BOX \u2014 the box is that queue's durable seat, so it is not acked until it settles; it is re-judged at every boundary, released or refused with a receipt to the sender, and expires with a receipt under dialogExpiry)" : " (it entered this session's held queue for the principal inbox and STAYS IN THE BOX until it settles; it is re-judged at every boundary. The sender is another principal: no receipt reaches it from here \u2014 the delivery gate's receipt is its record)"}`
93
+ ? `HELD${heldNote !== undefined ? ` (${heldNote})` : lane.kind === "session" ? ` (it entered this session's held queue and STAYS IN THE BOX \u2014 the box is that queue's durable seat, so it is not acked until it settles; it is re-judged at every boundary, released or refused with a receipt to the sender, ${isCrossSessionHoldCause(cause) && peerHeldReceiptStateOf(cause) === "held" ? "and expires with a receipt under dialogExpiry" : "and has no expiry deadline: its cause is this session's own settings or state, not a review"})` : " (it entered this session's held queue for the principal inbox and STAYS IN THE BOX until it settles; it is re-judged at every boundary. The sender is another principal: no receipt reaches it from here \u2014 the delivery gate's receipt is its record)"}`
92
94
  : disposition === "refused"
93
95
  ? "refused by this session's crossSessionInbound setting"
94
96
  : disposition === "resupply_exhausted"
@@ -110,7 +112,7 @@ export function createPeerSessionDrain(opts) {
110
112
  const route = () => ({
111
113
  mailbox,
112
114
  scope,
113
- self: { sessionId, ...(opts.selfName?.() !== undefined ? { name: opts.selfName() } : {}), modeClass: opts.selfModeClass },
115
+ self: { sessionId, ...(opts.selfName?.() !== undefined ? { name: opts.selfName() } : {}), ...occupantOpt, modeClass: opts.selfModeClass },
114
116
  ...(opts.onError !== undefined ? { onError: opts.onError } : {}),
115
117
  });
116
118
  const buildPeerMessagePayload = (lane, m) => {
@@ -146,7 +148,10 @@ export function createPeerSessionDrain(opts) {
146
148
  crossSessionNotice: { kind, text },
147
149
  _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
150
  });
149
- const receiptAddress = (lane, entry) => (lane.kind === "session" ? entry.peerMeta?.fromSession : undefined);
151
+ const receiptAddress = (lane, entry) => {
152
+ const from = lane.kind === "session" ? entry.peerMeta?.fromSession : undefined;
153
+ return from === undefined ? undefined : { sessionId: from, occupant: entry.peerMeta?.fromOccupant };
154
+ };
150
155
  const receipt = (lane) => async (entry, state) => {
151
156
  const to = receiptAddress(lane, entry);
152
157
  if (to === undefined)
@@ -234,18 +239,19 @@ export function createPeerSessionDrain(opts) {
234
239
  for (const lane of lanes)
235
240
  bindHeld(lane, true);
236
241
  idleMachine.target.configure({
237
- notify: (sub, notice) => void routePeerIdleNotice(route(), sub.requester, notice),
242
+ notify: (sub, notice) => void routePeerIdleNotice(route(), { sessionId: sub.requester, occupant: sub.requesterOccupant }, notice),
238
243
  judge: (sub) => judgeMeta(readFacts(), { ...(sub.fromMode !== undefined ? { fromMode: sub.fromMode } : {}), ...(sub.selfSent ? { fromSession: sessionId } : {}) }),
239
244
  heldCount: () => lanes.reduce((n, lane) => n + lane.held.size(), 0),
240
245
  ...(opts.lastTurnText !== undefined ? { lastTurnText: opts.lastTurnText } : {}),
241
246
  });
242
247
  idleMachine.requester.configure({
243
- expired: (o) => void routePeerIdleNotice(route(), sessionId, { kind: "expired", label: o.label }),
248
+ expired: (o) => void routePeerIdleNotice(route(), { sessionId, occupant: opts.occupant }, { kind: "expired", label: o.label }),
244
249
  });
245
- const reconcileHeld = (lane, lease) => {
250
+ const reconcileHeld = async (lane, lease) => {
246
251
  const live = lease.messages.filter((m) => lane.ackedUpTo === undefined || m.seq > lane.ackedUpTo);
247
252
  lane.held.reconcile(new Map(live.map((m) => [m.seq, m.decision])));
248
253
  adoptFinalDecisions(lane, lease);
254
+ await adoptAddressedOccupant(lane, lease);
249
255
  for (const m of live) {
250
256
  const d = lane.ledger.get(m.seq);
251
257
  if (lane.held.has(m.seq)) {
@@ -263,10 +269,70 @@ export function createPeerSessionDrain(opts) {
263
269
  if (!isMailboxDecisionFinal(m.decision))
264
270
  continue;
265
271
  const d = lane.ledger.get(m.seq);
266
- if (d === undefined || d.kind === "held" || d.kind === "invalidated")
272
+ if (d === undefined || d.kind === "held" || d.kind === "invalidated" || d.kind === "addressed_elsewhere")
267
273
  lane.ledger.set(m.seq, { kind: "terminal", why: `held_${m.decision}` });
268
274
  }
269
275
  };
276
+ const confirmations = new WeakMap();
277
+ const holdsSessionNow = (lease) => {
278
+ let answer = confirmations.get(lease);
279
+ if (answer === undefined) {
280
+ answer = (async () => {
281
+ const sessions = opts.sessions;
282
+ if (typeof sessions?.headOf !== "function")
283
+ return false;
284
+ try {
285
+ const head = await sessions.headOf(sessionId);
286
+ return head !== undefined && sameOccupant(head.incarnation, opts.occupant);
287
+ }
288
+ catch (e) {
289
+ opts.onError?.(e, { phase: "degraded", sessionId, classification: "peer-box-occupant" });
290
+ return false;
291
+ }
292
+ })();
293
+ confirmations.set(lease, answer);
294
+ }
295
+ return answer;
296
+ };
297
+ const adoptAddressedOccupant = async (lane, lease) => {
298
+ if (lane.kind !== "session")
299
+ return;
300
+ const elsewhere = lease.messages.filter((m) => {
301
+ if (lane.ackedUpTo !== undefined && m.seq <= lane.ackedUpTo)
302
+ return false;
303
+ const d = lane.ledger.get(m.seq);
304
+ if (d !== undefined && d.kind !== "addressed_elsewhere")
305
+ return false;
306
+ return !sameOccupant(m.peerMeta?.occupant, opts.occupant);
307
+ });
308
+ if (elsewhere.length === 0)
309
+ return;
310
+ const confirmed = await holdsSessionNow(lease);
311
+ for (const m of elsewhere) {
312
+ if (!confirmed) {
313
+ lane.ledger.set(m.seq, { kind: "addressed_elsewhere" });
314
+ continue;
315
+ }
316
+ lane.ledger.set(m.seq, { kind: "terminal", why: "addressed_occupant" });
317
+ discardAddressedElsewhere(m);
318
+ }
319
+ };
320
+ const discardAddressedElsewhere = (m) => {
321
+ const meta = m.peerMeta;
322
+ let frame = { task_id: boxHandle, task_type: "background_agent", status: "event", summary: "cross-session box record", seq: m.seq };
323
+ if (meta?.kind === "engine_frame") {
324
+ const decoded = decodeEngineFrame(m.content);
325
+ if (decoded.ok)
326
+ frame = decoded.payload;
327
+ }
328
+ deliverEngineNotice(opts.onNotice, deliveryDiscardedNotice({ sessionId, occupant: meta?.occupant }, opts.occupant, frame, "box"));
329
+ if (meta?.kind !== "peer_message" || meta.fromRoot !== undefined)
330
+ return;
331
+ const to = receiptAddress(sessionLane, m);
332
+ if (to === undefined)
333
+ return;
334
+ void routePeerDeliveryReceipt(route(), to, "refused", m.seq, meta.occupant !== undefined ? "the receiving engine: that session was deleted and created again before the message was read" : "the receiving engine: the message did not say which session of that id it was for");
335
+ };
270
336
  const wantsCompactionEffects = () => {
271
337
  for (const lane of lanes)
272
338
  for (const d of lane.ledger.values())
@@ -360,6 +426,7 @@ export function createPeerSessionDrain(opts) {
360
426
  const ackSettledPrefix = async (lane, lease) => {
361
427
  const { ledger, boxHandle } = lane;
362
428
  adoptFinalDecisions(lane, lease);
429
+ await adoptAddressedOccupant(lane, lease);
363
430
  const prefix = deriveAckPrefix(lane, lease.messages);
364
431
  if (prefix !== undefined && (lane.ackedUpTo === undefined || prefix > lane.ackedUpTo)) {
365
432
  try {
@@ -422,21 +489,22 @@ export function createPeerSessionDrain(opts) {
422
489
  currentRound.dispose(sessionLane, m.seq, "subscription_unaddressed");
423
490
  return;
424
491
  }
425
- const sub = { requester, ...(m.from !== undefined ? { requesterName: m.from } : {}), ...(meta.fromMode !== undefined ? { fromMode: meta.fromMode } : {}), selfSent: requester.toLowerCase() === sessionId.toLowerCase(), requestedAt: m.sentAt };
492
+ const sub = { requester, ...(meta.fromOccupant !== undefined ? { requesterOccupant: meta.fromOccupant } : {}), ...(m.from !== undefined ? { requesterName: m.from } : {}), ...(meta.fromMode !== undefined ? { fromMode: meta.fromMode } : {}), selfSent: requester.toLowerCase() === sessionId.toLowerCase(), requestedAt: m.sentAt };
493
+ const answerTo = { sessionId: requester, occupant: meta.fromOccupant };
426
494
  const announce = (outcome, live) => deliverEngineNotice(opts.onNotice, {
427
495
  code: "peer.idle_subscription",
428
496
  message: outcome === "recorded" || outcome === "refreshed" ? `${describePeerIdleSubscription(encodePeerAddress(peerSessionBoxHandle(requester)))} (${outcome}; ${live} live)` : `A peer session at ${encodePeerAddress(peerSessionBoxHandle(requester))} asked to be told when this session is next idle and was answered "unavailable": ${outcome === "full" ? "this session's subscription table is full" : `this session's crossSessionInbound setting is "refuse"`}.`,
429
497
  detail: { outcome, fromSession: requester, live, seq: m.seq, box: boxHandle, sessionId, runId },
430
498
  });
431
499
  if (facts.setting.value === "refuse") {
432
- void routePeerIdleNotice(route(), requester, { kind: "unavailable" });
500
+ void routePeerIdleNotice(route(), answerTo, { kind: "unavailable" });
433
501
  announce("refused", idleMachine.target.size());
434
502
  currentRound.dispose(sessionLane, m.seq, "subscription_refused");
435
503
  return;
436
504
  }
437
505
  const outcome = idleMachine.target.subscribe(sub);
438
506
  if (outcome === "full")
439
- void routePeerIdleNotice(route(), requester, { kind: "unavailable" });
507
+ void routePeerIdleNotice(route(), answerTo, { kind: "unavailable" });
440
508
  announce(outcome, idleMachine.target.size());
441
509
  currentRound.dispose(sessionLane, m.seq, `subscription_${outcome}`);
442
510
  };
@@ -560,7 +628,7 @@ export function createPeerSessionDrain(opts) {
560
628
  round.lease(leased.map((c) => c.lane));
561
629
  for (const { lane, lease } of leased) {
562
630
  bindHeld(lane, true);
563
- reconcileHeld(lane, lease);
631
+ await reconcileHeld(lane, lease);
564
632
  await lane.held.rejudge();
565
633
  }
566
634
  try {
@@ -806,25 +874,28 @@ function peerModeClassOf(refs) {
806
874
  return refs.askEffective !== undefined ? foldPermissionModeClass(refs.permissionMode?.(), refs.askEffective) : "unknown";
807
875
  }
808
876
  export function announcePeerLaneMount(deps, leg) {
809
- const verdict = judgePeerLaneMount(deps, leg.sessionId);
877
+ const verdict = judgePeerLaneMount(deps, leg.sessionId, leg.sessions);
810
878
  if (verdict === undefined)
811
879
  return false;
812
880
  if (verdict.ok)
813
881
  return true;
814
882
  deliverEngineNotice(deps.onNotice, {
815
883
  code: "config.peer_lane_unmounted",
816
- message: `Cross-session lane NOT mounted for this run: ${verdict.reason}. ListAgents is not mounted and peer-session addresses refuse with that reason${verdict.code === PEER_SESSION_ID_UNGRAMMATICAL_CODE ? "." : "; wire a mailbox store that declares crossProcessSafe: true (the bundled FileMailboxStore does)."}`,
884
+ message: `Cross-session lane NOT mounted for this run: ${verdict.reason}. ListAgents is not mounted and peer-session addresses refuse with that reason${verdict.code === PEER_SESSION_ID_UNGRAMMATICAL_CODE ? "." : "; wire a mailbox store that declares crossProcessSafe: true (the bundled FileMailboxStore does) over a session store that reads a session's row by id (SessionStore.headOf — the bundled session stores do)."}`,
817
885
  detail: { reason: verdict.reason, code: verdict.code, mailboxWired: deps.mailboxStore !== undefined, sessionId: leg.sessionId, runId: leg.runId },
818
886
  });
819
887
  return false;
820
888
  }
821
889
  export function peerLaneSendMessageSeats(args) {
890
+ const { sessionId, occupant, unread } = args.address;
822
891
  return {
823
892
  peerDirectory: args.peerDirectory,
824
893
  ...(args.peerChannel !== undefined ? { peerChannel: args.peerChannel } : {}),
825
894
  ...(args.listingMounted !== undefined ? { peerListingMounted: args.listingMounted } : {}),
826
895
  peerSelfSession: {
827
- sessionId: args.sessionId,
896
+ sessionId,
897
+ ...(occupant !== undefined ? { occupant } : {}),
898
+ ...(unread === true ? { occupantUnread: true } : {}),
828
899
  scope: args.scope,
829
900
  ...(args.name !== undefined ? { name: args.name } : {}),
830
901
  modeClass: () => peerModeClassOf(args.refs),
@@ -883,13 +954,14 @@ export function bindPeerSessionDrain(harness, opts) {
883
954
  }
884
955
  export function bindPeerLaneDrain(harness, args) {
885
956
  const { deps } = args;
957
+ const { sessionId, occupant } = args.address;
886
958
  let rowName;
887
959
  const lookupRowName = async () => {
888
960
  if (deps.peerDirectory === undefined)
889
961
  return;
890
962
  try {
891
963
  const rows = await listPeerDirectory(deps.peerDirectory, { scope: args.scope });
892
- rowName = rows.find((r) => r.sessionId.toLowerCase() === args.sessionId.toLowerCase())?.name;
964
+ rowName = rows.find((r) => r.sessionId.toLowerCase() === sessionId.toLowerCase())?.name;
893
965
  }
894
966
  catch {
895
967
  rowName = undefined;
@@ -897,7 +969,9 @@ export function bindPeerLaneDrain(harness, args) {
897
969
  };
898
970
  const drain = bindPeerSessionDrain(harness, {
899
971
  mailbox: deps.mailboxStore,
900
- sessionId: args.sessionId,
972
+ sessionId,
973
+ ...(occupant !== undefined ? { occupant } : {}),
974
+ sessions: args.sessions,
901
975
  runId: args.runId,
902
976
  scope: args.scope,
903
977
  ...(terminalsDrainPrincipalInbox(deps) ? { principalInbox: true } : {}),
@@ -197,9 +197,16 @@ export interface SendMessageToolOptions {
197
197
  * `ask.effective`) — read at SEND time, attested on the parked record's typed `peerMeta.fromMode`.
198
198
  * The Runner mount fills it; a direct mount without it sends with no session attestation (the
199
199
  * recipient then judges it as "no class asserted").
200
+ *
201
+ * `occupant` = the occupant this session holds (`SessionMetadata.incarnation`; absent = no token): every record this tool parks
202
+ * names it as `fromOccupant`, so a receipt or an idle notice comes back to this occupant and no later one of the id, and this
203
+ * session's idle machine is the seat of that address. `occupantUnread` = the leg could not read its occupant: its address is
204
+ * nobody's, so nothing can be addressed back to it — a message still goes (naming no `fromOccupant`), an idle subscription is refused.
200
205
  */
201
206
  peerSelfSession?: {
202
207
  sessionId: string;
208
+ occupant?: string;
209
+ occupantUnread?: true;
203
210
  scope?: string;
204
211
  name?: string;
205
212
  modeClass?: () => PermissionModeClass | "unknown";
@@ -6,10 +6,10 @@ import { normalizeAgentName, chosenAgentName, DURABLE_AGENT_HANDLE_RE, DURABLE_A
6
6
  import { announceTranscriptIntegrityGapOnce, canAccessAgentRecord, clearRevivedRowTerminalPayload } from "../core/background-agent-store.js";
7
7
  import { readClampFloor } from "../core/child-clamp-seats.js";
8
8
  import { uuidv7 } from "../internal/harness.js";
9
- import { MAILBOX_TOMBSTONED_RECIPIENT_CODE, mailboxCrossProcessMountVerdict } from "../core/mailbox-store.js";
9
+ import { MAILBOX_TOMBSTONED_RECIPIENT_CODE, sessionBoxMountVerdict } from "../core/mailbox-store.js";
10
10
  import { peerSendVerdictSeverity } from "./cross-session-judge.js";
11
11
  import { listPeerDirectory, parsePeerSessionAddress, peerSessionBoxHandle, peerSessionLane, resolvePeerSessions } from "./peer-directory.js";
12
- import { peerIdleMachineFor } from "./peer-idle.js";
12
+ import { peerIdleMachineOfOwnAddress } from "./peer-idle.js";
13
13
  import { PEER_IDLE_OUTSTANDING_CAP, PEER_IDLE_SUBSCRIPTION_TTL_MS, peerIdleNoticeLabel } from "./peer-notices.js";
14
14
  import { escapeAttributeValue, escapeEnvelopeTag, isObserverTaskId, OBSERVER_SENDMESSAGE_SENDER_REFUSAL, OBSERVER_SENDMESSAGE_TARGET_REFUSAL, } from "./observer.js";
15
15
  import { inlineUntrusted } from "../core/untrusted-text.js";
@@ -94,7 +94,7 @@ export function createSendMessageTool(opts) {
94
94
  return { active: false };
95
95
  if (opts.mailbox === undefined)
96
96
  return { active: false, reason: "a peer-session directory is wired but no mailbox store is (the lane parks messages in the recipient's durable session box)" };
97
- const verdict = mailboxCrossProcessMountVerdict(opts.mailbox);
97
+ const verdict = sessionBoxMountVerdict(opts.mailbox, opts.runner.sessions);
98
98
  return verdict.ok ? { active: true } : { active: false, reason: verdict.reason };
99
99
  })();
100
100
  const baseParameters = Type.Object({
@@ -241,6 +241,7 @@ export function createSendMessageTool(opts) {
241
241
  return { content: `Message not sent: ${text.slice(0, PEER_REFUSAL_TEXT_MAX)}`, details: { error: code, code, to, verdict, ...extra }, isError: true };
242
242
  };
243
243
  const peerSelfSessionId = opts.peerSelfSession?.sessionId ?? directMountSessionId;
244
+ const selfOccupant = opts.peerSelfSession?.occupant;
244
245
  const peerScope = guardScope ?? opts.peerSelfSession?.scope;
245
246
  let ownRowName;
246
247
  const resolvePeerTarget = async () => {
@@ -285,10 +286,12 @@ export function createSendMessageTool(opts) {
285
286
  return admissionRefusal(sendVerdict.reason, peerLabel);
286
287
  const peerMeta = {
287
288
  ...(peerSelfSessionId !== undefined ? { fromSession: peerSelfSessionId } : {}),
289
+ ...(selfOccupant !== undefined ? { fromOccupant: selfOccupant } : {}),
288
290
  ...(modeClass === "bypass" || modeClass === "prompting" ? { fromMode: modeClass } : {}),
289
291
  ...(senderKey !== undefined ? { senderKey } : {}),
290
292
  kind: "peer_message",
291
293
  ...(urgent ? { urgent: true } : {}),
294
+ ...(record.occupant !== null ? { occupant: record.occupant } : {}),
292
295
  };
293
296
  try {
294
297
  seq = await opts.mailbox.append(peerScope, handle, { from: ownRowName ?? opts.peerSelfSession?.name ?? senderLabel, content: storedContent, sentAt: now, hopChain: prospectiveChain, peerMeta });
@@ -306,23 +309,32 @@ export function createSendMessageTool(opts) {
306
309
  if (peerSelfSessionId === undefined) {
307
310
  subscription = { ok: false, code: "peer_send.other", severity: "error", message: "this mount has no session identity, so no idle notice could be addressed back to it — no subscription was made." };
308
311
  }
312
+ else if (opts.peerSelfSession?.occupantUnread === true) {
313
+ subscription = { ok: false, code: "peer_send.other", severity: "error", message: "this session's occupant could not be read, so no idle notice could be addressed back to it — no subscription was made." };
314
+ }
309
315
  else {
310
- const ask = peerIdleMachineFor(peerScope, peerSelfSessionId).requester.request(record.sessionId, peerIdleNoticeLabel(record.name) ?? handle);
311
- if (!ask.ok) {
316
+ const idle = peerIdleMachineOfOwnAddress(peerScope, peerSelfSessionId, selfOccupant !== undefined ? { occupant: selfOccupant } : {});
317
+ const ask = idle?.requester.request(record.sessionId, peerIdleNoticeLabel(record.name) ?? handle);
318
+ if (idle === undefined || ask === undefined) {
319
+ subscription = { ok: false, code: "peer_send.other", severity: "error", message: "this session was deleted and created again after this run started, so no idle notice could be addressed back to it — no subscription was made." };
320
+ }
321
+ else if (!ask.ok) {
312
322
  subscription = { ok: false, code: "peer_send.subscription_cap", severity: peerSendVerdictSeverity("peer_send.subscription_cap"), message: `you already hold ${PEER_IDLE_OUTSTANDING_CAP} outstanding idle subscriptions — no new one was made; wait for a notice or for one to expire.` };
313
323
  }
314
324
  else {
315
325
  const subMeta = {
316
326
  fromSession: peerSelfSessionId,
327
+ ...(selfOccupant !== undefined ? { fromOccupant: selfOccupant } : {}),
317
328
  ...(modeClass === "bypass" || modeClass === "prompting" ? { fromMode: modeClass } : {}),
318
329
  kind: "idle_subscription",
330
+ ...(record.occupant !== null ? { occupant: record.occupant } : {}),
319
331
  };
320
332
  try {
321
333
  subscriptionSeq = await opts.mailbox.append(peerScope, handle, { from: ownRowName ?? opts.peerSelfSession?.name ?? senderLabel, content: `[idle subscription] ${ownRowName ?? opts.peerSelfSession?.name ?? senderLabel} asked to be told once when this session next goes idle`, sentAt: now, hopChain: [], peerMeta: subMeta });
322
334
  subscription = { ok: true, disposition: record.liveness !== "live" ? "parked_offline" : "queued", via: "store" };
323
335
  }
324
336
  catch (e) {
325
- peerIdleMachineFor(peerScope, peerSelfSessionId).requester.settle(record.sessionId, "unavailable");
337
+ idle.requester.settle(record.sessionId, "unavailable");
326
338
  subscription = { ok: false, code: e?.code === MAILBOX_TOMBSTONED_RECIPIENT_CODE ? "peer_send.invalid_target" : "peer_send.other", severity: "error", message: `the session box refused the subscription record (${(thrownText(e)).slice(0, 200)}) — no subscription was made.` };
327
339
  }
328
340
  }
@@ -40,11 +40,13 @@ import { callerPlacementSeats } from "../core/runner/child-tree.js";
40
40
  import { legTaskIdOf } from "../core/leg-identity.js";
41
41
  import { delimitUntrusted, inlineUntrusted } from "../core/untrusted-text.js";
42
42
  import { createSafeNotifier } from "../core/safe-notify.js";
43
- import { boundedRedactedSummary } from "../core/untrusted-egress.js";
43
+ import { boundedRedactedSummary, extensionWords } from "../core/untrusted-egress.js";
44
+ import { readExtensionRequester } from "../core/extension-requester.js";
44
45
  import { uuidv7 } from "../internal/harness.js";
45
46
  import { addWorktree } from "../core/git-worktree-env.js";
46
47
  import { shellQuote } from "../tools/fs/search.js";
47
48
  import { BG_AGENT_REAP_STOP_ERROR, chosenAgentName } from "../core/task-registry.js";
49
+ import { agentOutcomeIsError } from "../core/task-registry-agent.js";
48
50
  import { readDurableOrgAdmission } from "../core/memory-admission.js";
49
51
  import { governanceRetryClass } from "../core/governance-codes.js";
50
52
  import { readSkillGrantCapture } from "../core/skill-grant.js";
@@ -1094,7 +1096,13 @@ function reachableOccupants(registry, scope, root, caller) {
1094
1096
  if (typeof face !== "function")
1095
1097
  return new Map();
1096
1098
  try {
1097
- return new Map(face.call(registry, scope, root, caller).filter((o) => o.reachable).map((o) => [o.id, o.name]));
1099
+ return new Map(face
1100
+ .call(registry, scope, root, caller)
1101
+ .filter((o) => o.reachable)
1102
+ .map((o) => {
1103
+ const requestedBy = readExtensionRequester(o.requestedBy);
1104
+ return [o.id, { name: o.name, ...(requestedBy !== undefined ? { requestedBy } : {}) }];
1105
+ }));
1098
1106
  }
1099
1107
  catch {
1100
1108
  return new Map();
@@ -1102,7 +1110,10 @@ function reachableOccupants(registry, scope, root, caller) {
1102
1110
  }
1103
1111
  function concurrencyOccupants(active, reachable, local) {
1104
1112
  const listed = active.filter((id) => reachable.has(id)).slice(0, REFUSAL_OCCUPANTS_LISTED);
1105
- const parts = listed.map((id) => `task_id ${id} (${JSON.stringify(reachable.get(id))})`);
1113
+ const parts = listed.map((id) => {
1114
+ const o = reachable.get(id);
1115
+ return `task_id ${id} (${JSON.stringify(o.name)}${o.requestedBy !== undefined ? `, started by extension "${extensionWords(o.requestedBy.name, 80)}"` : ""})`;
1116
+ });
1106
1117
  const rest = active.length - listed.length;
1107
1118
  if (rest > 0)
1108
1119
  parts.push(`${rest} ${listed.length > 0 ? "more " : ""}registered`);
@@ -2246,6 +2257,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2246
2257
  ...(ctx.taskId !== undefined ? { parentTaskId: ctx.taskId } : {}),
2247
2258
  ...(ctx.sessionId !== undefined ? { parentSessionId: ctx.sessionId } : {}),
2248
2259
  ...((ctx.rootSessionId ?? ctx.sessionId) !== undefined ? { rootSessionId: ctx.rootSessionId ?? ctx.sessionId } : {}),
2260
+ ...(ctx.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: ctx.rootSessionIncarnation } : {}),
2249
2261
  ...(ctx.placementRoot !== undefined ? { placementRoot: ctx.placementRoot } : {}),
2250
2262
  }),
2251
2263
  ...(ctx.centerArtifactDigest !== undefined ? { parentCenterArtifactDigest: ctx.centerArtifactDigest } : {}),
@@ -2608,6 +2620,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
2608
2620
  ...(sessionScopedBg ? { sessionScoped: true } : {}),
2609
2621
  description: shortDesc,
2610
2622
  agentType: spawnAgentType,
2623
+ ...(extensionSpawn !== undefined ? { requestedBy: extensionSpawn.requestedBy } : {}),
2611
2624
  ...(agentName !== undefined ? { name: agentName } : {}),
2612
2625
  ...(ctx.taskId !== undefined && ctx.taskId !== ctx.sessionId ? { parentTaskId: ctx.taskId } : {}),
2613
2626
  ...(ctx.sessionId !== undefined ? { parentSessionId: ctx.sessionId } : {}),
@@ -3005,6 +3018,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3005
3018
  ].filter(Boolean);
3006
3019
  return {
3007
3020
  content: forkLines.join("\n"),
3021
+ ...(agentOutcomeIsError(forkFace.status) ? { isError: true } : {}),
3008
3022
  details: completedAgentCard(forkChild, {
3009
3023
  subagentType: FORK_SUBAGENT_TYPE,
3010
3024
  error: forkErr,
@@ -3124,6 +3138,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3124
3138
  ...(reviveRow.sessionScoped ? { sessionScoped: true } : {}),
3125
3139
  ...(reviveRow.description !== undefined ? { description: reviveRow.description } : {}),
3126
3140
  agentType: spawnAgentType,
3141
+ ...(reviveRow.requestedBy !== undefined ? { requestedBy: reviveRow.requestedBy } : {}),
3127
3142
  name: reviveRow.name,
3128
3143
  ...(reviveRow.parentTaskId !== undefined ? { parentTaskId: reviveRow.parentTaskId } : {}),
3129
3144
  ...(reviveRow.parentSessionId !== undefined ? { parentSessionId: reviveRow.parentSessionId } : {}),
@@ -3157,6 +3172,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3157
3172
  ...(sessionScopedBg ? { sessionScoped: true } : {}),
3158
3173
  description: shortDesc,
3159
3174
  agentType: spawnAgentType,
3175
+ ...(extensionSpawn !== undefined ? { requestedBy: extensionSpawn.requestedBy } : {}),
3160
3176
  ...(agentName !== undefined ? { name: agentName } : {}),
3161
3177
  ...(ctx.taskId !== undefined && ctx.taskId !== ctx.sessionId ? { parentTaskId: ctx.taskId } : {}),
3162
3178
  ...(ctx.sessionId !== undefined ? { parentSessionId: ctx.sessionId } : {}),
@@ -3989,6 +4005,7 @@ function createSubagentToolNode(opts, depth, excluded, extraToolsBudget) {
3989
4005
  ].filter(Boolean);
3990
4006
  return {
3991
4007
  content: lines.join("\n"),
4008
+ ...(agentOutcomeIsError(childFace.status) ? { isError: true } : {}),
3992
4009
  details: completedAgentCard(child, {
3993
4010
  ...(def !== undefined ? { subagentType: def.name } : {}),
3994
4011
  error: errClass,
@@ -313,6 +313,10 @@ type AllowedToolsSeat = keyof typeof ALLOW_LIST_SEATS;
313
313
  * cannot be received ({@link receiveAnchoredMember}) with `config.invalid_argument`; an anchored path rule whose set declares a
314
314
  * base it cannot be read at — a relative spelling, one of no tree's family — with the code and issue (`unsupported.path_base`) a
315
315
  * deny / ask rule set's declaration meets (`unusableDeclaredBase`, the one judgment).
316
+ *
317
+ * Exported from the package root: a host that takes an allow list in ahead of the run (an admission door) calls this with the seat the
318
+ * list will be handed at, and meets — at the door, in the same words and with the same `code` and `issues` — the refusal the run would
319
+ * answer at its start. It is the one judgment; the host writes no second one.
316
320
  */
317
321
  export declare function screenAllowedToolsValue(value: unknown, seat: AllowedToolsSeat): readonly AllowListEntry[] | undefined;
318
322
  /** The disclosure record for one member, minted from the entries it matched: each sanitized (deployment or model-authored
@@ -136,7 +136,7 @@ export declare function hookAskReasonOf(registration: string | undefined, cause:
136
136
  * inherited station's read of an ancestor's ask): the receipt's own words, under the asker its own members name (the origin
137
137
  * ladder over {@link INHERITED_STATION_FACTS} — a rule it matched, a classifier fallback it replays, else the policy). None when
138
138
  * the ask has no words, or when its engine record says its words are the engine's generic question for the call
139
- * (`genericQuestion`, while the ask's sentence is still that one: a write gate's default question, the plan mode's — the
139
+ * ({@link engineSentenceOf}, while the ask's sentence is still that one: a write gate's default question, the plan mode's — the
140
140
  * call's arguments and the ask's class already say it).
141
141
  */
142
142
  export declare function chainAskReasonsOf(receipt: Extract<PermissionResult, {
@@ -1,4 +1,4 @@
1
- import { attestationOf } from "./engine-attestation.js";
1
+ import { attestationOf, engineSentenceOf } from "./engine-attestation.js";
2
2
  import { isShellFaceToolName } from "./tool-registry.js";
3
3
  import { inlineUntrusted } from "./untrusted-text.js";
4
4
  export const ASK_ORIGINS = Object.freeze(["content_question", "plan_review", "ancestor_marked", "org_unavailable", "org_rule", "rule_store_unavailable", "hook", "ask_rule", "denial_limit_fallback", "shell_gate_tighten", "safety_tighten", "policy"]);
@@ -22,7 +22,7 @@ export function chainAskReasonsOf(receipt, call) {
22
22
  const record = attestationOf(receipt, call);
23
23
  if (record?.receivedAskReasons !== undefined)
24
24
  return record.receivedAskReasons.length > 0 ? record.receivedAskReasons : undefined;
25
- if (message === undefined || message === record?.genericQuestion)
25
+ if (message === undefined || engineSentenceOf(receipt, call)?.generic === true)
26
26
  return undefined;
27
27
  const by = askOriginOf(receipt, { ...INHERITED_STATION_FACTS, call });
28
28
  const words = inlineUntrusted(message, ASK_REASON_WORDS_MAX);
@@ -24,8 +24,10 @@
24
24
  * a live approver reachable for delegated children — is a deployment posture the operator hears through
25
25
  * the sink like every other code; the row only adds the session-stream projection so the person whose
26
26
  * call was refused sees WHY it did not run. `sessionId` is therefore REQUIRED at the mint (the routing
27
- * half of a user row). Dedup unit: per tool call — the gate's obligation (it owns the call); this module
28
- * is pure.
27
+ * half of a user row). On a delegated leg it is the delegation tree's root — the session a person
28
+ * watches; the child's own session has no reader — and `sourceSessionId` / `agentId` say which leg the
29
+ * refused call was (the gate station's notice address, `noticeAddressOf`). Dedup unit: per tool call —
30
+ * the gate's obligation (it owns the call); this module is pure.
29
31
  */
30
32
  import type { EngineNotice } from "./engine-notice.js";
31
33
  import { type ApprovalRemedy, type AssertAllKeysHandled, type HeadlessApproverSeat } from "./ask-origin.js";
@@ -36,8 +38,14 @@ export type AskUnresolvableCause = (typeof ASK_UNRESOLVABLE_CAUSES)[number];
36
38
  export declare function isAskUnresolvableCause(v: unknown): v is AskUnresolvableCause;
37
39
  /** What the gate knows at the deny exit — facts only, no words of the engine's vocabulary composed. */
38
40
  export interface AskUnresolvableFacts {
39
- /** The session whose call was refused — the notice's routing key, required (see module note). */
41
+ /** The session the notice is addressed to — its routing key, required (see module note): the refused leg's own session on a
42
+ * top-level leg, the delegation tree's root on a delegated one (`noticeAddressOf`, leg-identity.ts). */
40
43
  readonly sessionId: string;
44
+ /** Present exactly when the refused call was a delegated leg's: that leg's session (the call's own conversation). */
45
+ readonly sourceSessionId?: string;
46
+ /** The delegated leg's agent id, beside {@link sourceSessionId} (never without it): the id the spawner's card and the leg's
47
+ * events carry. */
48
+ readonly agentId?: string;
41
49
  /** The tool the ask was for (the message quotes it verbatim). */
42
50
  readonly toolName: string;
43
51
  /** The refused call's id — the correlation key to the `tool_end` frame carrying the same deny. */
@@ -86,7 +94,8 @@ export declare function askUnresolvableRemedySeat(cause: AskUnresolvableCause):
86
94
  * an empty session or tool name, or a cause outside the closed set, is refused at the mint with a
87
95
  * `TypeError` rather than shaped into a notice that would route nowhere or say nothing.
88
96
  *
89
- * `detail: { sessionId, toolName, toolCallId, cause, parkLaneExisted, remedy?, remedies? }` — `remedy` rides the causes that say nobody
97
+ * `detail: { sessionId, sourceSessionId?, agentId?, toolName, toolCallId, cause, parkLaneExisted, remedy?, remedies? }` — `sourceSessionId`
98
+ * and `agentId` ride a delegated leg's refusal only (the leg the call was, the notice being addressed to the tree's root); `remedy` rides the causes that say nobody
90
99
  * could be asked ({@link askUnresolvableRemedySeat}: the sentence the refusal's tool text carries) and `remedies` beside it, the same
91
100
  * way out as data ({@link ApprovalRemedy}); `sessionId` is lifted onto the typed key by {@link import("./engine-notice.js").deliverEngineNotice}, the one throat.
92
101
  */
@@ -19,10 +19,17 @@ export function askUnresolvableRemedySeat(cause) {
19
19
  return CAUSE_REMEDY_SEAT[cause];
20
20
  }
21
21
  export function askUnresolvableNotice(facts) {
22
- const { sessionId, toolName, toolCallId, cause, parkLaneExisted, remedy, remedies } = facts;
22
+ const { sessionId, sourceSessionId, agentId, toolName, toolCallId, cause, parkLaneExisted, remedy, remedies } = facts;
23
23
  if (typeof sessionId !== "string" || sessionId.length === 0) {
24
24
  throw new TypeError("delegation.ask_unresolvable: sessionId is required — a user-audience notice with no session routes nowhere");
25
25
  }
26
+ if (sourceSessionId !== undefined && (typeof sourceSessionId !== "string" || sourceSessionId.length === 0)) {
27
+ throw new TypeError("delegation.ask_unresolvable: sourceSessionId, when present, names the delegated leg's session");
28
+ }
29
+ if (agentId !== undefined && (sourceSessionId === undefined || typeof agentId !== "string" || agentId.length === 0)) {
30
+ throw new TypeError("delegation.ask_unresolvable: agentId, when present, is a non-empty id riding beside sourceSessionId");
31
+ }
32
+ const delegated = sourceSessionId !== undefined;
26
33
  if (typeof toolName !== "string" || toolName.length === 0) {
27
34
  throw new TypeError("delegation.ask_unresolvable: toolName is required");
28
35
  }
@@ -48,9 +55,9 @@ export function askUnresolvableNotice(facts) {
48
55
  const park = parkLaneExisted ? "the durable approval park did not take it" : "no durable approval park is armed for this run";
49
56
  return {
50
57
  code: "delegation.ask_unresolvable",
51
- message: `approval for "${toolName}" could not be resolved: ${CAUSE_CLAUSE[cause]} and ${park} — ` +
58
+ message: `approval for "${toolName}"${delegated ? " (a delegated agent's call)" : ""} could not be resolved: ${CAUSE_CLAUSE[cause]} and ${park} — ` +
52
59
  `the call was denied fail-closed and did not run. ${typeof remedy === "string" && remedy.length > 0 ? `To let it run: ${remedy}. ` : ""}To let such approvals wait for a person, run with a checkpoint store and a ` +
53
60
  `durable approval opt-in (or a live approver reachable for delegated children).`,
54
- detail: { sessionId, toolName, toolCallId, cause, parkLaneExisted: parkLaneExisted === true, ...(typeof remedy === "string" && remedy.length > 0 ? { remedy } : {}), ...(remedyList !== undefined ? { remedies: remedyList } : {}) },
61
+ detail: { sessionId, ...(delegated ? { sourceSessionId } : {}), ...(agentId !== undefined ? { agentId } : {}), toolName, toolCallId, cause, parkLaneExisted: parkLaneExisted === true, ...(typeof remedy === "string" && remedy.length > 0 ? { remedy } : {}), ...(remedyList !== undefined ? { remedies: remedyList } : {}) },
55
62
  };
56
63
  }
@@ -579,9 +579,10 @@ export declare function maybeCompact(opts: MaybeCompactOptions): Promise<{
579
579
  * (auto/manual triggers only — never on "forced"). NOT a failure: the caller must not count it
580
580
  * toward the compaction breaker; the next boundary consults the callback again. */
581
581
  blocked?: boolean;
582
- /** MF-18 修①: set (with `compacted:false`) when compaction is DISABLED by settings
583
- * (`enabled:false`) — the request can never be honored this run. Lets the caller resolve a manual
584
- * /compact with the honest `"disabled"` outcome (and trace frame) instead of a structural noop. */
582
+ /** MF-18 修①: set (with `compacted:false`) when this pass is DISABLED by its settings (`enabled:false`
583
+ * — the pass's own gate; a run's lanes resolve it from the seat of the pass they run, `autoCompact` or
584
+ * `manualCompact`). Lets the caller resolve a manual /compact with the honest `"disabled"` outcome (and
585
+ * trace frame) instead of a structural noop. */
585
586
  disabled?: boolean;
586
587
  /** Set (with `compacted:false`) when the pass PASSED the trigger gate
587
588
  * (natural or forced) but found nothing to summarize — no valid cut point / empty history. Was
@@ -755,8 +756,9 @@ export interface CompactSessionRequest {
755
756
  /** This pass's summarization instructions: they REPLACE `compaction.instructions` and the default for this pass (the
756
757
  * `TaskStream.compact` reading); sanitized and capped like every instructions channel. */
757
758
  instructions?: string;
758
- /** The members of `TaskSpec.compaction` a pass reads, as a run would carry them. */
759
- compaction?: Pick<NonNullable<TaskSpec["compaction"]>, "enabled" | "reserveTokens" | "keepRecentTokens" | "instructions" | "clampTolerance">;
759
+ /** The members of `TaskSpec.compaction` a pass reads, as a run would carry them — of the two seats only `manualCompact`
760
+ * (this pass is a requested one; `false` answers `"disabled"`, and absent reads the deployment's twin, else on). */
761
+ compaction?: Pick<NonNullable<TaskSpec["compaction"]>, "manualCompact" | "reserveTokens" | "keepRecentTokens" | "instructions" | "clampTolerance">;
760
762
  /** The independent summary model (`TaskSpec.compactionModel`); absent ⇒ the deployment's `summarize` role (or its tier
761
763
  * default), else the main model. A role-derived model whose key↔URL pairing is broken falls back to the main model,
762
764
  * announced, as on a run. */