@sema-agent/core 7.72.0 → 7.73.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 (256) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/dist/agents/inherited-tool-pool.d.ts +26 -1
  3. package/dist/agents/inherited-tool-pool.js +46 -2
  4. package/dist/agents/parked-resume-drive.d.ts +10 -0
  5. package/dist/agents/parked-resume-drive.js +9 -0
  6. package/dist/agents/retain-ledger.d.ts +3 -0
  7. package/dist/agents/send-message-tool.js +1 -0
  8. package/dist/agents/send-user-message-tool.d.ts +12 -0
  9. package/dist/agents/send-user-message-tool.js +67 -0
  10. package/dist/agents/subagent-steps.d.ts +9 -0
  11. package/dist/agents/subagent-steps.js +38 -0
  12. package/dist/agents/subagent.d.ts +2 -0
  13. package/dist/agents/subagent.js +43 -12
  14. package/dist/agents/verify.js +23 -8
  15. package/dist/agents/yield-adoption.js +3 -1
  16. package/dist/brain/anthropic.js +14 -9
  17. package/dist/brain/open-responses.js +4 -5
  18. package/dist/brain/openai.js +30 -23
  19. package/dist/brain/stream-engine.js +159 -151
  20. package/dist/core/actions-digest.d.ts +43 -0
  21. package/dist/core/actions-digest.js +22 -0
  22. package/dist/core/allow-entry.js +3 -3
  23. package/dist/core/auto-mode.d.ts +7 -9
  24. package/dist/core/auto-mode.js +114 -8
  25. package/dist/core/checkpoint-features.d.ts +3 -2
  26. package/dist/core/checkpoint-features.js +1 -1
  27. package/dist/core/checkpoint-rekey.d.ts +1 -1
  28. package/dist/core/checkpoint-rekey.js +6 -1
  29. package/dist/core/checkpoint-requirements.d.ts +23 -3
  30. package/dist/core/checkpoint-requirements.js +5 -1
  31. package/dist/core/checkpoint-row-verdict.js +7 -1
  32. package/dist/core/checkpoint-store.d.ts +24 -2
  33. package/dist/core/checkpoint-store.js +1 -0
  34. package/dist/core/child-clamp-seats.d.ts +15 -0
  35. package/dist/core/child-clamp-seats.js +15 -0
  36. package/dist/core/delegation-frames.d.ts +1 -0
  37. package/dist/core/delegation-frames.js +1 -1
  38. package/dist/core/engine-capabilities.d.ts +5 -1
  39. package/dist/core/engine-capabilities.js +1 -1
  40. package/dist/core/engine-notice.d.ts +30 -22
  41. package/dist/core/engine-version.js +1 -1
  42. package/dist/core/entries-not-applied.d.ts +19 -7
  43. package/dist/core/entries-not-applied.js +33 -1
  44. package/dist/core/governance-codes.d.ts +7 -1
  45. package/dist/core/governance-codes.js +13 -5
  46. package/dist/core/hooks.d.ts +3 -0
  47. package/dist/core/hooks.js +1 -0
  48. package/dist/core/host-instance.d.ts +23 -0
  49. package/dist/core/host-instance.js +69 -0
  50. package/dist/core/instruction-preview.d.ts +63 -0
  51. package/dist/core/instruction-preview.js +406 -0
  52. package/dist/core/leg-budget.d.ts +26 -0
  53. package/dist/core/leg-budget.js +9 -0
  54. package/dist/core/leg-identity.d.ts +51 -1
  55. package/dist/core/leg-identity.js +45 -2
  56. package/dist/core/manager-launch-check.d.ts +48 -0
  57. package/dist/core/manager-launch-check.js +64 -0
  58. package/dist/core/mcp-call-meta.d.ts +2 -2
  59. package/dist/core/mcp-injection-drop.d.ts +20 -10
  60. package/dist/core/mcp-injection-drop.js +9 -3
  61. package/dist/core/mcp-server-spec.d.ts +2 -1
  62. package/dist/core/member-outcome.d.ts +3 -2
  63. package/dist/core/member-outcome.js +1 -1
  64. package/dist/core/memory-engine/deletion-record.d.ts +46 -0
  65. package/dist/core/memory-engine/deletion-record.js +96 -0
  66. package/dist/core/memory-engine/engine.js +24 -16
  67. package/dist/core/memory-engine/file-backend.js +7 -5
  68. package/dist/core/memory-engine/projection-ledger.d.ts +1 -1
  69. package/dist/core/memory-engine/projection-ledger.js +1 -1
  70. package/dist/core/memory-engine/scope-contract.d.ts +18 -13
  71. package/dist/core/memory-engine/scope-contract.js +18 -18
  72. package/dist/core/memory-engine/sync-client.js +26 -6
  73. package/dist/core/memory-engine/sync.d.ts +20 -2
  74. package/dist/core/memory-engine/sync.js +18 -17
  75. package/dist/core/mode-policy.d.ts +21 -6
  76. package/dist/core/mode-policy.js +15 -6
  77. package/dist/core/own-property-receipt.js +11 -4
  78. package/dist/core/parent-spec-seat.d.ts +13 -11
  79. package/dist/core/parent-spec-seat.js +13 -9
  80. package/dist/core/peer-seat.js +3 -3
  81. package/dist/core/peer-task-store.d.ts +365 -0
  82. package/dist/core/peer-task-store.js +682 -0
  83. package/dist/core/permission-rule-consent.js +6 -11
  84. package/dist/core/permission-rule-model.d.ts +27 -0
  85. package/dist/core/permission-rule-model.js +33 -5
  86. package/dist/core/permission-rule-provider.d.ts +35 -33
  87. package/dist/core/permission-rule-provider.js +38 -295
  88. package/dist/core/permission-rule-store.d.ts +181 -8
  89. package/dist/core/permission-rule-store.js +420 -17
  90. package/dist/core/permission-rule-sync.js +15 -1
  91. package/dist/core/project-seat.d.ts +55 -0
  92. package/dist/core/project-seat.js +96 -0
  93. package/dist/core/protocol-http-auth.d.ts +3 -2
  94. package/dist/core/protocol-http-auth.js +26 -18
  95. package/dist/core/remote-env.d.ts +4 -4
  96. package/dist/core/retired-keys.js +1 -0
  97. package/dist/core/rule-offer-read.d.ts +1 -1
  98. package/dist/core/rule-offer-read.js +32 -4
  99. package/dist/core/run-ledger-seat.d.ts +66 -0
  100. package/dist/core/run-ledger-seat.js +70 -0
  101. package/dist/core/run-ledger.d.ts +332 -0
  102. package/dist/core/run-ledger.js +550 -0
  103. package/dist/core/runner/checkpoint-scope.d.ts +13 -3
  104. package/dist/core/runner/checkpoint-scope.js +12 -4
  105. package/dist/core/runner/construction-doors.js +6 -0
  106. package/dist/core/runner/contracts.d.ts +21 -5
  107. package/dist/core/runner/delegation-owner.d.ts +30 -0
  108. package/dist/core/runner/delegation-owner.js +20 -4
  109. package/dist/core/runner/finish-reason-seat.js +4 -2
  110. package/dist/core/runner/leg-frame.js +3 -0
  111. package/dist/core/runner/nested-memory-lane.d.ts +22 -5
  112. package/dist/core/runner/nested-memory-lane.js +91 -30
  113. package/dist/core/runner/person-path-rows.d.ts +21 -16
  114. package/dist/core/runner/person-path-rows.js +80 -15
  115. package/dist/core/runner/prepare-caps-and-workflow.js +98 -88
  116. package/dist/core/runner/prepare-config-doors.d.ts +1 -0
  117. package/dist/core/runner/prepare-config-doors.js +5 -3
  118. package/dist/core/runner/prepare-context-lane.js +1 -0
  119. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  120. package/dist/core/runner/prepare-delegation-surface.js +6 -0
  121. package/dist/core/runner/prepare-execution-env.d.ts +3 -3
  122. package/dist/core/runner/prepare-hands-readface.d.ts +5 -2
  123. package/dist/core/runner/prepare-hands-readface.js +12 -1
  124. package/dist/core/runner/prepare-inherited-gate.d.ts +6 -3
  125. package/dist/core/runner/prepare-inherited-gate.js +13 -5
  126. package/dist/core/runner/prepare-run-refs.d.ts +1 -1
  127. package/dist/core/runner/prepare-run-refs.js +3 -2
  128. package/dist/core/runner/prepare-suspend-saga.d.ts +6 -2
  129. package/dist/core/runner/prepare-suspend-saga.js +4 -2
  130. package/dist/core/runner/prepare-task.js +36 -27
  131. package/dist/core/runner/prepare-turn-wiring.d.ts +4 -3
  132. package/dist/core/runner/prepare-turn-wiring.js +2 -1
  133. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  134. package/dist/core/runner/prepare-wiring-manifest.js +5 -2
  135. package/dist/core/runner/resume-apply.js +11 -5
  136. package/dist/core/runner/resume-review-outcome.d.ts +3 -0
  137. package/dist/core/runner/resume-review-outcome.js +24 -1
  138. package/dist/core/runner/run-harness-handlers.js +3 -0
  139. package/dist/core/runner/run-identity-wiring.js +3 -2
  140. package/dist/core/runner/run-leg.js +3 -0
  141. package/dist/core/runner/run-notification-lane.js +20 -1
  142. package/dist/core/runner/run-settle-and-teardown.js +21 -12
  143. package/dist/core/runner/run-stop-and-final-verify.js +6 -0
  144. package/dist/core/runner/run-telemetry-and-budget-seats.js +1 -1
  145. package/dist/core/runner/runtask.d.ts +6 -2
  146. package/dist/core/runner/runtask.js +21 -9
  147. package/dist/core/runner/shell-env-withheld.d.ts +3 -2
  148. package/dist/core/runner/shell-env-withheld.js +1 -2
  149. package/dist/core/runner/stop-tail-notice.d.ts +10 -2
  150. package/dist/core/runner/stop-tail-notice.js +9 -2
  151. package/dist/core/runner/stream-settle-backstop.d.ts +1 -0
  152. package/dist/core/runner/stream-settle-backstop.js +1 -0
  153. package/dist/core/runner/task-start-doors.js +6 -3
  154. package/dist/core/runner/terminal-account.d.ts +6 -1
  155. package/dist/core/runner/terminal-account.js +16 -1
  156. package/dist/core/runner/unreadable-person-rows.d.ts +2 -1
  157. package/dist/core/runner-deps.d.ts +13 -10
  158. package/dist/core/secret-env.d.ts +53 -37
  159. package/dist/core/secret-env.js +44 -47
  160. package/dist/core/session-checkout.d.ts +3 -0
  161. package/dist/core/session-checkout.js +1 -0
  162. package/dist/core/session-store.d.ts +12 -6
  163. package/dist/core/session-store.js +26 -6
  164. package/dist/core/session.d.ts +31 -8
  165. package/dist/core/store-contracts/checkpoint-store-contract.js +10 -0
  166. package/dist/core/store-contracts/peer-task-store-contract.d.ts +21 -0
  167. package/dist/core/store-contracts/peer-task-store-contract.js +516 -0
  168. package/dist/core/store-contracts/session-store-contract.d.ts +15 -2
  169. package/dist/core/store-contracts/session-store-contract.js +87 -3
  170. package/dist/core/store-contracts/workflow-journal-store-contract.d.ts +19 -1
  171. package/dist/core/store-contracts/workflow-journal-store-contract.js +89 -1
  172. package/dist/core/task-event.d.ts +10 -3
  173. package/dist/core/task-notification.d.ts +96 -10
  174. package/dist/core/task-notification.js +129 -5
  175. package/dist/core/task-registry-shared.d.ts +12 -1
  176. package/dist/core/task-registry-shared.js +3 -1
  177. package/dist/core/task-registry-workflow.d.ts +1 -1
  178. package/dist/core/task-registry-workflow.js +9 -1
  179. package/dist/core/task-registry.d.ts +39 -2
  180. package/dist/core/task-registry.js +76 -12
  181. package/dist/core/task-result.d.ts +13 -0
  182. package/dist/core/task-spec-members.d.ts +3 -1
  183. package/dist/core/task-spec-members.js +11 -3
  184. package/dist/core/task-spec.d.ts +48 -22
  185. package/dist/core/tool-catalog-entries.js +2 -0
  186. package/dist/core/tool-mount-facts.d.ts +1 -1
  187. package/dist/core/tool-mount-facts.js +1 -0
  188. package/dist/core/tool-mount-plan.d.ts +3 -1
  189. package/dist/core/tool-mount-plan.js +6 -0
  190. package/dist/core/tool-mount-static.d.ts +1 -1
  191. package/dist/core/tool-mount-static.js +4 -2
  192. package/dist/core/tool-result-store.d.ts +19 -2
  193. package/dist/core/tool-result-store.js +51 -2
  194. package/dist/core/tool-spec.d.ts +9 -2
  195. package/dist/core/user-attachment.d.ts +5 -1
  196. package/dist/core/user-attachment.js +14 -7
  197. package/dist/core/wiring-manifest.d.ts +26 -20
  198. package/dist/core/wiring-manifest.js +7 -3
  199. package/dist/core/workflow-journal-store.d.ts +53 -10
  200. package/dist/core/workflow-journal-store.js +27 -4
  201. package/dist/core/workflow-run-store-contract.js +16 -0
  202. package/dist/core/workflow-run-store.d.ts +9 -7
  203. package/dist/core/workflow-run-store.js +4 -1
  204. package/dist/engine/execution-env/node-execution-env.js +3 -1
  205. package/dist/engine/harness/types.d.ts +24 -1
  206. package/dist/engine/harness/types.js +10 -0
  207. package/dist/engine/llm/types.d.ts +5 -7
  208. package/dist/engine/lsp/node-lsp-manager.js +2 -1
  209. package/dist/engine/session/import-validate.js +6 -1
  210. package/dist/engine/session/session.d.ts +15 -2
  211. package/dist/engine/session/session.js +34 -4
  212. package/dist/index.d.ts +18 -7
  213. package/dist/index.js +13 -4
  214. package/dist/orchestration/run-workflow-tool.js +40 -32
  215. package/dist/orchestration/workflow-park-adoption.d.ts +51 -12
  216. package/dist/orchestration/workflow-park-adoption.js +47 -12
  217. package/dist/orchestration/workflow-stop.d.ts +128 -0
  218. package/dist/orchestration/workflow-stop.js +156 -0
  219. package/dist/orchestration/workflow.d.ts +30 -6
  220. package/dist/orchestration/workflow.js +117 -55
  221. package/dist/prompts/manager-recipe.d.ts +18 -0
  222. package/dist/prompts/manager-recipe.js +24 -0
  223. package/dist/stores/file/permission-rule-store.d.ts +3 -1
  224. package/dist/stores/file/permission-rule-store.js +0 -1
  225. package/dist/stores/file/workflow-journal-store.d.ts +16 -3
  226. package/dist/stores/file/workflow-journal-store.js +93 -5
  227. package/dist/stores/file/workflow-run-store.d.ts +1 -1
  228. package/dist/tools/fs/file-write-check.js +9 -3
  229. package/dist/tools/fs/index.d.ts +8 -7
  230. package/dist/tools/fs/index.js +4 -4
  231. package/dist/tools/fs/read-deny-home.d.ts +1 -1
  232. package/dist/tools/fs/read-deny-home.js +5 -5
  233. package/dist/tools/fs/read-deny.d.ts +33 -8
  234. package/dist/tools/fs/read-deny.js +114 -25
  235. package/dist/tools/fs/safety.d.ts +4 -1
  236. package/dist/tools/fs/safety.js +4 -2
  237. package/dist/tools/fs/shell-read-check.d.ts +9 -2
  238. package/dist/tools/fs/shell-read-check.js +96 -14
  239. package/dist/tools/fs/shell-read-establish.d.ts +9 -0
  240. package/dist/tools/fs/shell-read-establish.js +21 -11
  241. package/dist/tools/fs/shell-read-judge.d.ts +13 -1
  242. package/dist/tools/fs/shell-read-judge.js +26 -7
  243. package/dist/tools/fs/shell-read-plan.d.ts +5 -0
  244. package/dist/tools/fs/shell-read-write-targets.js +17 -9
  245. package/package.json +2 -2
  246. package/test/export-surface.snapshot.json +131 -1
  247. package/wire-changes/answers/core-stores-sql@7.73.0.json +28 -0
  248. package/wire-changes/answers/core@7.73.0.json +216 -0
  249. package/wire-changes/answers/mods-kernel@7.73.0.json +7 -0
  250. package/wire-changes/answers/primitives@7.73.0.json +12 -0
  251. package/wire-changes/answers/wiki-gate@7.73.0.json +7 -0
  252. package/wire-changes/core-stores-sql@7.73.0.json +326 -0
  253. package/wire-changes/core@7.73.0.json +6480 -0
  254. package/wire-changes/mods-kernel@7.73.0.json +147 -0
  255. package/wire-changes/primitives@7.73.0.json +227 -0
  256. package/wire-changes/wiki-gate@7.73.0.json +145 -0
@@ -7,6 +7,7 @@
7
7
  * pre-CAS.
8
8
  */
9
9
  import { type Checkpoint, type PendingSteerEntry, type ResumeOutcome } from "../checkpoint-store.js";
10
+ import type { PermissionMode } from "../types.js";
10
11
  export interface ResumeReviewOutcomeInput {
11
12
  /** borrowed-readonly — the pending row (the lane is keyed on the STORED gate kind). */
12
13
  cp: Checkpoint;
@@ -16,6 +17,8 @@ export interface ResumeReviewOutcomeInput {
16
17
  outcomeGate: ResumeOutcome["gate"];
17
18
  /** borrowed-readonly — the validated wake message, carried into the wake twin. */
18
19
  wakeMessage: Omit<PendingSteerEntry, "seq"> | undefined;
20
+ /** borrowed-readonly — the resume config's mode as its door read it: a plan approval's mode may not contradict it. */
21
+ configPermissionMode: PermissionMode | undefined;
19
22
  }
20
23
  export interface ResumeReviewOutcomeResult {
21
24
  /** The review lane's plain twin (a plan_review / needs_review row), else undefined. */
@@ -2,8 +2,9 @@ import { CheckpointError } from "../checkpoint-store.js";
2
2
  import { isGateKind, PAUSE_REGISTRY, resumeGateMatches } from "../pause-registry.js";
3
3
  import { sanitizeUntrustedText, sentinelTagRefusal } from "../untrusted-text.js";
4
4
  import { assertOutcomeText, captureHostDecision, describeSuppliedValue, refuseSuppliedKeys, SUPPLIED_RECORD_KEY } from "./decide-continuation.js";
5
+ import { isPermissionMode, PERMISSION_MODES } from "../ask-origin.js";
5
6
  export function resumeReviewOutcome(input) {
6
- const { cp, outcome, outcomeGate, wakeMessage } = input;
7
+ const { cp, outcome, outcomeGate, wakeMessage, configPermissionMode } = input;
7
8
  const gateMatch = isGateKind(cp.gate.kind) && resumeGateMatches(cp.gate.kind, outcomeGate);
8
9
  if (!gateMatch) {
9
10
  throw new CheckpointError("checkpoint.gate_mismatch", `resume outcome (gate "${describeSuppliedValue(outcomeGate)}") does not match checkpoint gate "${cp.gate.kind}" — resume serves ${Object.entries(PAUSE_REGISTRY)
@@ -17,6 +18,7 @@ export function resumeReviewOutcome(input) {
17
18
  const decision = decide.decision;
18
19
  const editedPlan = decide.editedPlan;
19
20
  const reason = decide.reason;
21
+ const permissionMode = decide.permissionMode;
20
22
  if (decision !== "approve" && decision !== "edit" && decision !== "reject") {
21
23
  throw new CheckpointError("checkpoint.invalid_outcome", `resume decision "${describeSuppliedValue(decision)}" is outside the plan_review domain — a plan review is exactly "approve", "edit" or "reject"; refusing pre-CAS, the checkpoint stays pending`);
22
24
  }
@@ -24,11 +26,15 @@ export function resumeReviewOutcome(input) {
24
26
  const hostDecision = captureHostDecision(cp, decide.hostDecision, "plan_review", { word: decision, allows: decision !== "reject" });
25
27
  assertOutcomeText(editedPlan, "editedPlan");
26
28
  assertOutcomeText(reason, "reason");
29
+ const modeRefusal = planApprovalModeRefusal(permissionMode, decision, configPermissionMode);
30
+ if (modeRefusal !== undefined)
31
+ throw new CheckpointError("checkpoint.invalid_outcome", `${modeRefusal}; refusing pre-CAS, the checkpoint stays pending`);
27
32
  plainReviewOutcome = {
28
33
  gate: "plan_review",
29
34
  decision,
30
35
  ...(editedPlan !== undefined ? { editedPlan } : {}),
31
36
  ...(reason !== undefined ? { reason } : {}),
37
+ ...(permissionMode !== undefined ? { permissionMode: permissionMode } : {}),
32
38
  hostDecision,
33
39
  };
34
40
  }
@@ -71,6 +77,10 @@ export function resumeReviewOutcome(input) {
71
77
  if (winner.reason !== undefined && winner.reason !== plainReviewOutcome.reason) {
72
78
  throw new CheckpointError("checkpoint.reopen_revote", "an env_failed reopen replays the ALREADY-RECORDED review decision — refusing a re-vote whose reviewer note differs from the recorded one");
73
79
  }
80
+ const replayedMode = plainReviewOutcome.gate === "plan_review" ? plainReviewOutcome.permissionMode : undefined;
81
+ if (winner.permissionMode !== undefined && winner.permissionMode !== replayedMode) {
82
+ throw new CheckpointError("checkpoint.reopen_revote", `an env_failed reopen replays the ALREADY-RECORDED review decision — refusing a re-vote whose approved mode ("${describeSuppliedValue(replayedMode)}") differs from the recorded one ("${winner.permissionMode}")`);
83
+ }
74
84
  }
75
85
  }
76
86
  let plainParkOutcome;
@@ -89,3 +99,16 @@ export function resumeReviewOutcome(input) {
89
99
  }
90
100
  return { plainReviewOutcome, plainParkOutcome };
91
101
  }
102
+ function planApprovalModeRefusal(mode, decision, configMode) {
103
+ if (mode === undefined)
104
+ return undefined;
105
+ if (!isPermissionMode(mode))
106
+ return `plan_review permissionMode "${describeSuppliedValue(mode)}" is not one of ${PERMISSION_MODES.map((w) => JSON.stringify(w)).join(", ")}`;
107
+ if (mode === "plan")
108
+ return 'plan_review permissionMode "plan" would keep an approved plan open — name the mode the plan runs under, or leave it out';
109
+ if (decision === "reject")
110
+ return "plan_review permissionMode names the mode an approved plan runs under, and a reject approves none — leave it out";
111
+ if (configMode !== undefined && configMode !== "plan" && configMode !== mode)
112
+ return `plan_review permissionMode "${mode}" contradicts the resume config's permissionMode "${configMode}" — name the mode once`;
113
+ return undefined;
114
+ }
@@ -67,6 +67,9 @@ export function createHarnessHandlers(input) {
67
67
  else if (ev.type === "thinking_delta" && ev.delta) {
68
68
  pushContent({ type: "reasoning_delta", delta: ev.delta, ...ident() });
69
69
  }
70
+ else if (ev.type === "thinking_end" && typeof ev.content === "string" && ev.content.length !== 0) {
71
+ pushContent({ type: "reasoning_end", content: ev.content, ...ident() });
72
+ }
70
73
  if (callsModel && rs.budget.streamCancel && !rs.limits.budgetHit && (ev.type === "text_delta" || ev.type === "thinking_delta") && ev.delta) {
71
74
  rs.budget.callOutputChars += ev.delta.length;
72
75
  if (rs.budget.callOutputChars - rs.budget.lastStreamBudgetCheck >= 256) {
@@ -5,7 +5,7 @@ import { createSnapshotFrameSeat } from "../snapshot-frame-seat.js";
5
5
  import { emitsChildRowFrames, taskStartedFrame } from "../delegation-frames.js";
6
6
  import { recordFrameReceipt, toolResultReceiptKey } from "../frame-settlement.js";
7
7
  import { createReceivingChain } from "../mods/session-receive.js";
8
- import { discloseDroppedPending, isSystemInjectionPriority, parkAtSeat, renderTaskNotificationXml, sessionAddressOf, taskNotificationDedupKey, taskNotificationFrame, taskNotificationNoteOptions } from "../task-notification.js";
8
+ import { discloseDroppedPending, isSystemInjectionPriority, isTerminalTaskNotification, parkAtSeat, renderTaskNotificationXml, sessionAddressOf, taskNotificationDedupKey, taskNotificationFrame, taskNotificationNoteOptions } from "../task-notification.js";
9
9
  import { buildAppliedHumanInputEvent } from "../human-input-projection.js";
10
10
  import { announceAcceptance, nextHumanInputSeq } from "./steer-admission.js";
11
11
  import { deliverDelegationLifecycle, deliverEngineNotice, parentLegIds, parkedInputIdsOf, undrainedUserInputNotices } from "../types.js";
@@ -55,7 +55,7 @@ export function runIdentityWiring(input) {
55
55
  deliverDelegationLifecycle(runner.deps.onDelegationLifecycle, event, delegationLifecycleNotifier, "runtask.onDelegationLifecycle", runner.deps.onNotice);
56
56
  };
57
57
  if (emitsChildRowFrames(prepared.hookIdentity) && (resume === undefined || resume.opensCycle === true)) {
58
- const started = taskStartedFrame({ taskId: runSourceTaskId, sessionId: prepared.sessionId, model: prepared.model.id, identity: prepared.hookIdentity }, internals, ident());
58
+ const started = taskStartedFrame({ taskId: runSourceTaskId, sessionId: prepared.sessionId, model: prepared.model.id, identity: prepared.hookIdentity, startedAt: prepared.legStartedAt }, internals, ident());
59
59
  queue.push(started);
60
60
  forwardSafely(internals, started);
61
61
  emitDelegationLifecycle({ phase: "spawn", identity: prepared.hookIdentity });
@@ -154,6 +154,7 @@ export function runIdentityWiring(input) {
154
154
  for (const payload of discloseDroppedPending(pendingIdle, prepared.taskReadHandleOf, () => prepared.listBackgroundTasks({ settled: true }))) {
155
155
  const parkedPriority = pendingIdle.priorities?.get(payload);
156
156
  deliveredAtTurnOpen.add(taskNotificationDedupKey(payload));
157
+ prepared.runLedgerBook?.observeFrame(payload, isTerminalTaskNotification(payload));
157
158
  queue.push({ ...taskNotificationFrame(payload, parkedPriority), ...ident() });
158
159
  const handOver = (shown) => {
159
160
  void prepared.harness.nextTurn(renderTaskNotificationXml(shown), taskNotificationNoteOptions(payload, parkedPriority)).catch(() => {
@@ -959,6 +959,7 @@ async function resolvePendingCall(runner, prepared, resume, emit, emitCommitted,
959
959
  const args = structuredClone(executedArgs);
960
960
  screened?.admit();
961
961
  onExecuteStart?.(pendingAction.toolCallId);
962
+ prepared.runLedgerBook?.callResumed(pendingAction.toolCallId);
962
963
  occurrences.release(pendingAction.toolCallId);
963
964
  prepared.suspendProgressRef.executedApproved = true;
964
965
  const finalize = (executed) => prepared.harness.finalizeToolCall({ type: "toolCall", id: pendingAction.toolCallId, name: spelledName, arguments: executedArgs }, executedArgs, executed);
@@ -973,12 +974,14 @@ async function resolvePendingCall(runner, prepared, resume, emit, emitCommitted,
973
974
  const failed = await finalize({ result: { content: [{ type: "text", text: execError }], details: marks ?? {} }, isError: true });
974
975
  const failedText = failed.result.content.flatMap((c) => (c.type === "text" ? [c.text] : [])).join("\n");
975
976
  await settleEnd(true, { content: failedText, ...(marks !== undefined ? { details: marks } : {}) });
977
+ prepared.runLedgerBook?.callEnded(pendingAction.toolCallId);
976
978
  const eid = await appendAdmittedRow(prepared.admitRows, prepared.session, resultRow(failedText, true));
977
979
  emitCommitted(eid, "toolResult", pendingAction.toolCallId);
978
980
  return;
979
981
  }
980
982
  const ran = await finalize({ result: res, isError: res.isError === true });
981
983
  await settleEnd(ran.isError, ran.result);
984
+ prepared.runLedgerBook?.callEnded(pendingAction.toolCallId);
982
985
  onResolvedToolSuccess?.(pendingAction.toolName, ran.isError ? undefined : ran.result.details);
983
986
  const eid = await appendAdmittedRow(prepared.admitRows, prepared.session, {
984
987
  role: "toolResult",
@@ -3,6 +3,9 @@ import { boundInputHashOf } from "../canonical-json.js";
3
3
  import { readPendingSteerQueue } from "../checkpoint-store.js";
4
4
  import { scopeKeyOf } from "../isolation-scope.js";
5
5
  import { wakeOpening } from "../run-origin.js";
6
+ import { runLedgerBookFor } from "../run-ledger.js";
7
+ import { bindRunLedgerBook } from "../run-ledger-seat.js";
8
+ import { rootAnchorOf } from "../leg-identity.js";
6
9
  import { bindDeliveryObligations, createLiveNotificationLane, DeliveryObligations, DurableAppendObligations, injectionLaneOf, isDelegatedAgentTerminal, isTerminalTaskNotification, renderTaskNotificationXml, routeOrParkNotification, sessionAddressOf, SystemInjectionQueue, taskNotificationDedupKey, taskNotificationFrame, taskNotificationNoteOptions } from "../task-notification.js";
7
10
  import { settleConsumedFrame, settleUndeliveredFrame } from "../frame-settlement.js";
8
11
  import { createReceivingChain } from "../mods/session-receive.js";
@@ -85,6 +88,7 @@ async function runNotificationLaneAs(input, obligations) {
85
88
  };
86
89
  const receiving = createReceivingChain(() => prepared.receiveSeat);
87
90
  const unsubscribeTaskNotifications = taskNotificationQueue.subscribe((item) => {
91
+ runLedgerBook?.observeFrame(item.payload, isTerminalTaskNotification(item.payload));
88
92
  queue.push({ ...taskNotificationFrame(item.payload, item.priority), ...notificationIdent() });
89
93
  receiving.pass(item.payload, {
90
94
  handOver: (shown) => handOver(item, shown),
@@ -124,7 +128,13 @@ async function runNotificationLaneAs(input, obligations) {
124
128
  });
125
129
  const takeOnThisLane = laneSeat.take;
126
130
  const takeAsDestination = laneSeat.takeAsDestination;
131
+ const refusePeerTaskFrame = (notification) => {
132
+ runner.deps.onError?.(new Error(`peer_task notification ${notification.task_id} refused: no peer-task producer is active on this lane in this engine release`), { phase: "degraded", sessionId: notificationAddress?.sessionId ?? "", classification: "peer-task-frame-refused" });
133
+ return Promise.resolve("refused");
134
+ };
127
135
  const injectTaskNotification = (notification, opts) => {
136
+ if (notification.task_type === "peer_task")
137
+ return refusePeerTaskFrame(notification);
128
138
  const priority = opts?.priority ?? "later";
129
139
  return new Promise((resolve) => {
130
140
  const own = takeOnThisLane(notification, priority, resolve);
@@ -140,14 +150,20 @@ async function runNotificationLaneAs(input, obligations) {
140
150
  const peerInboundChainRef = internals?.peerInboundChainRef ?? createPeerInboundChainRef();
141
151
  const modelCatalog = runner.deps.models;
142
152
  const deliveryObligations = new DeliveryObligations();
153
+ const runLedgerBook = runLedgerBookFor(spec, resume !== undefined ? { section: resume.cp.state.runLedger } : undefined, internals?.rowTaskId);
154
+ if (taskIdRef !== undefined && runLedgerBook?.taskId !== undefined)
155
+ taskIdRef.current = runLedgerBook.taskId;
143
156
  const laneSink = (notification, opts) => {
157
+ if (notification.task_type === "peer_task")
158
+ return refusePeerTaskFrame(notification);
144
159
  try {
145
160
  upstreamTaskNotification?.(notification, opts);
146
161
  }
147
162
  catch {
148
163
  }
164
+ const terminal = isTerminalTaskNotification(notification);
149
165
  const outcome = injectTaskNotification(notification, opts);
150
- if (isTerminalTaskNotification(notification))
166
+ if (terminal)
151
167
  deliveryObligations.discharge(notification);
152
168
  return outcome;
153
169
  };
@@ -162,8 +178,11 @@ async function runNotificationLaneAs(input, obligations) {
162
178
  sessionReadStates,
163
179
  sessionModeSeats, sessionFastModeSeats, sessionPromptSeats, sessionMcpPools,
164
180
  onTaskNotification: laneSink,
181
+ runLedgerBook,
165
182
  }, self, taskIdRef, holdSessionLock, legWrites, (destination, delivery) => pendingSessionNotifications.discardsStaleNotice(destination, delivery), promptSubmitRef, runEnd);
166
183
  settlementSeat = prepared.frameSettlement;
184
+ if (runLedgerBook !== undefined)
185
+ bindRunLedgerBook(runLedgerBook, prepared, rootAnchorOf(internals, prepared.sessionId, prepared.sessionIncarnation).occupant);
167
186
  try {
168
187
  pendingSessionNotifications.admit(sessionAddressOf(prepared), prepared.sessionBox);
169
188
  const settling = pendingSessionNotifications.settleBoxDebts(sessionAddressOf(prepared), prepared.abortController.signal);
@@ -15,6 +15,8 @@ import { emitTrace } from "../trace.js";
15
15
  import { deliverEngineNotice, parentLegIds, settleOwedUserInput } from "../types.js";
16
16
  import { assembleResult } from "./assemble-result.js";
17
17
  import { discloseUnconsumedEndings, haltConsumed } from "./halt-attribution.js";
18
+ import { runLedgerIdentityOf } from "../run-ledger.js";
19
+ import { reapTaskAgentsBeforeLastWord } from "../run-ledger-seat.js";
18
20
  import { forwardSafely } from "./forward-sink.js";
19
21
  import { completedPastLimitNotice, limitCrossedOf, TIMER_LATENESS_REPORT_MS } from "./clock-and-limits.js";
20
22
  import { verdictRefusedNotice } from "./verdict-refusal.js";
@@ -37,6 +39,10 @@ export async function runSettleAndTeardown(input) {
37
39
  const { spec, queue, prepared, resume, internals, rs, stats, ident, loopLatch, timeout, ownCommittedTailRef, legWrites, emitDelegationLifecycle, taskIdRef, manualCompactRef, drainManualCompact, final, threw, abortedLive, userInterruptedLive, answerSettled, strandedHumanAnswers, reasoningResolution, deliveryObligations, compactionBreaker, owedUserInput, setResult, onSuggestions, onSuspend, runner, sessions, display } = input;
38
40
  const bound = settleBound(), writeOwedSessionRecords = legEndRecords(prepared, rs, runner, bound);
39
41
  let rowAnswer;
42
+ const runEndNow = () => prepared.pausedRef.current !== undefined
43
+ ? undefined
44
+ : runEndCauseOf({ ceiling: oneShotEndingBook(spec.oneShot, deliveryObligations)?.stoppedWaitingAtCeiling === true, abortedLive, userInterrupted: userInterruptedLive, userHalted: haltConsumed(prepared.harness.haltConsumption()), walltime: timeout.fired, turns: rs.limits.turnsExceeded, spendStopped: rs.limits.budgetHit !== undefined });
45
+ const stopSourceNow = () => abortedLive && !answerSettled && !timeout.fired && !rs.limits.turnsExceeded && rs.limits.budgetHit === undefined && prepared.pausedRef.current === undefined ? "user" : "parent";
40
46
  try {
41
47
  const shown = display?.settled();
42
48
  if (shown !== undefined)
@@ -137,7 +143,7 @@ export async function runSettleAndTeardown(input) {
137
143
  if (abortedLive && answerSettled && result.terminal.kind === "completed") {
138
144
  const origin = runEndCauseOf({ ceiling: false, abortedLive, userInterrupted: userInterruptedLive, userHalted: false, walltime: timeout.fired, turns: rs.limits.turnsExceeded, spendStopped: rs.limits.budgetHit !== undefined });
139
145
  const waitedFor = stopTailWaitedFor(waitStoppedAtCeiling ? undefined : endingBook, endingReach);
140
- deliverEngineNotice(runner.deps.onNotice, interruptUnconsumedNotice(waitedFor, origin, { sessionId: prepared.sessionId, runId: rs.telemetry.runId, ...legNoticeTaskId(prepared) }));
146
+ deliverEngineNotice(runner.deps.onNotice, interruptUnconsumedNotice(waitedFor, origin, { sessionId: prepared.sessionId, runId: rs.telemetry.runId, ...legNoticeTaskId(prepared) }, result.limitCrossed?.axis));
141
147
  }
142
148
  if (result.limitCrossed !== undefined && result.terminal.kind === "completed")
143
149
  deliverEngineNotice(runner.deps.onNotice, completedPastLimitNotice(result.limitCrossed, { sessionId: prepared.sessionId, runId: rs.telemetry.runId, ...legNoticeTaskId(prepared) }));
@@ -262,6 +268,18 @@ export async function runSettleAndTeardown(input) {
262
268
  }));
263
269
  if (prepared.pausedRef.current !== undefined)
264
270
  await yieldParkedLegBackground(prepared, runner);
271
+ if (prepared.runLedgerBook === undefined) {
272
+ const kept = runLedgerIdentityOf(spec, resume !== undefined ? { section: resume.cp.state.runLedger } : undefined, undefined);
273
+ if (kept !== undefined && "notKept" in kept)
274
+ result.runLedgerNotKept = kept.notKept;
275
+ }
276
+ if (prepared.runLedgerBook !== undefined) {
277
+ if (result.terminal.kind !== "paused")
278
+ await reapTaskAgentsBeforeLastWord(prepared.registryAccess, stopSourceNow(), runEndNow());
279
+ const ledger = prepared.runLedgerBook.snapshot(result.terminal.kind === "paused" ? { kind: "park" } : { kind: "run_end" });
280
+ result.runLedger = ledger;
281
+ await settleTeardownLeg(async () => void (await prepared.session.appendRunLedger?.(ledger)), "session.appendRunLedger (settle leg)", (e) => runner.deps.onError?.(e, { phase: "config", sessionId: prepared.sessionId }));
282
+ }
265
283
  await writeOwedSessionRecords();
266
284
  result.continuesFrom = await settledContinuesFrom({
267
285
  closed: legWrites.close(), bound,
@@ -305,20 +323,11 @@ export async function runSettleAndTeardown(input) {
305
323
  finally {
306
324
  settleOwedUserInput(owedUserInput, !prepared.suspendProgressRef.executedApproved, { taskId: prepared.taskId, sessionId: prepared.sessionId, runId: prepared.runId, parent: parentLegIds(internals) }, runner.deps.onNotice);
307
325
  await writeOwedSessionRecords();
308
- const runEnd = prepared.pausedRef.current !== undefined
309
- ? undefined
310
- : runEndCauseOf({ ceiling: oneShotEndingBook(spec.oneShot, deliveryObligations)?.stoppedWaitingAtCeiling === true, abortedLive, userInterrupted: userInterruptedLive, userHalted: haltConsumed(prepared.harness.haltConsumption()), walltime: timeout.fired, turns: rs.limits.turnsExceeded, spendStopped: rs.limits.budgetHit !== undefined });
326
+ const runEnd = runEndNow();
311
327
  const envGoing = envDestroyedAtTeardown(prepared, resume?.cp.state.workspaceHandle !== undefined && rowKeepsWhatItsRetryNeeds(rowAnswer));
312
328
  const ownedEnvDying = envGoing !== undefined && isIsolated(envGoing);
313
329
  await settleTeardownLeg(() => defaultTaskRegistry.settleKilledForOwner({ ...prepared.registryAccess, sessionId: prepared.sessionId }, {
314
- source: abortedLive &&
315
- !answerSettled &&
316
- !timeout.fired &&
317
- !rs.limits.turnsExceeded &&
318
- rs.limits.budgetHit === undefined &&
319
- prepared.pausedRef.current === undefined
320
- ? "user"
321
- : "parent",
330
+ source: stopSourceNow(),
322
331
  skipSessionScoped: true,
323
332
  envDying: ownedEnvDying,
324
333
  retainProcesses: spec.retainBackgroundProcesses === true,
@@ -6,6 +6,7 @@ import { classicEventBase, legEventsOf } from "../mods/stations.js";
6
6
  import { judgeStopFamily, stopFamilyBlockText, stopFamilyContextText, stopFamilyWord, teammateStopPass } from "../mods/teammate-stations.js";
7
7
  import { heldInProgress } from "../../tools/task-list.js";
8
8
  import { steeringPreview } from "./steering-preview.js";
9
+ import { ceilingTurnNote, stopTailWaitedFor } from "./stop-tail-notice.js";
9
10
  import { taskAxisCrossed } from "./clock-and-limits.js";
10
11
  import { oneShotEndingBook, oneShotWaitCeilingOf } from "../task-notification.js";
11
12
  import { FINAL_VERIFICATION_MARK } from "./clock-and-limits.js";
@@ -40,6 +41,7 @@ export function runStopAndFinalVerify(input) {
40
41
  const owed = oneShotEndingBook(spec.oneShot, deliveryObligations);
41
42
  if (stopArmed || teammateArmed || finalVerificationOn || owed !== undefined) {
42
43
  let consecutiveBlocks = 0;
44
+ let ceilingTurnGiven = false;
43
45
  const ending = () => prepared.abortController.signal.aborted || prepared.pausedRef.current !== undefined || prepared.batchHaltRef.current !== undefined || taskAxisCrossed(rs.limits, walltimeMonotonicDeadline);
44
46
  prepared.harness.setStopGate(async () => {
45
47
  if (ending())
@@ -48,6 +50,10 @@ export function runStopAndFinalVerify(input) {
48
50
  const waitEnd = pushedBack.length === 0 ? await owed?.waitOut(AbortSignal.any([prepared.abortController.signal, callerStop.signal]), () => !ending() && prepared.harness.pendingInjectionCount() === 0, (wake) => prepared.harness.subscribe((e) => void (e.type === "queue_update" && wake())), oneShotWaitCeilingOf(spec.limits)) : undefined;
49
51
  if (waitEnd === "signal")
50
52
  prepared.harness.consumeStopAtEnding();
53
+ if (waitEnd === "ceiling" && prepared.runLedgerBook !== undefined && !ceilingTurnGiven && owed !== undefined) {
54
+ ceilingTurnGiven = true;
55
+ return [{ role: "user", engineMinted: true, content: ceilingTurnNote(stopTailWaitedFor(owed, { read: { ...prepared.registryAccess, sessionId: prepared.sessionId }, owner: prepared.registryAccess }), oneShotWaitCeilingOf(spec.limits)), timestamp: Date.now() }];
56
+ }
51
57
  return pushedBack;
52
58
  });
53
59
  async function pushBack() {
@@ -70,7 +70,7 @@ export function runTelemetryAndBudgetSeats(input) {
70
70
  taskIdRef.current = rs.telemetry.taskId;
71
71
  taskIdRef.sessionId = prepared.sessionId;
72
72
  }
73
- rs.telemetry.taskStart = Date.now();
73
+ rs.telemetry.taskStart = prepared.legStartedAt;
74
74
  rs.telemetry.taskStartMonotonic = performance.now();
75
75
  const discloseNoteTaskRunFailure = (err) => {
76
76
  try {
@@ -1,3 +1,4 @@
1
+ import { type NoticeRoute } from "../leg-identity.js";
1
2
  import type { Model } from "../../internal/llm.js";
2
3
  import { type CheckpointToken, type ResumeOutcome } from "../checkpoint-store.js";
3
4
  import { type TaskOutcome } from "../task-outcome.js";
@@ -13,6 +14,7 @@ export type { ResumeTaskConfig } from "./contracts.js";
13
14
  import { type ResumeConfigQuestion, type ResumeConfigVerdict } from "../resume-config-judge.js";
14
15
  import { type TaskStartVerdict } from "../task-start-judge.js";
15
16
  import type { SessionChanges, SessionChangesRequest } from "../session-changes.js";
17
+ import { type InstructionPreviewResult } from "../instruction-preview.js";
16
18
  import type { CompactSessionRequest, CompactSessionResult } from "../auto-compaction.js";
17
19
  import type { RewindFilesRequest, RewindFilesResult } from "../file-history-store.js";
18
20
  import type { RewindConversationRequest, RewindConversationResult } from "../rewind-conversation.js";
@@ -87,7 +89,7 @@ export declare class Runner implements RunnerSelfSeat {
87
89
  * into private deps. */
88
90
  emitTaskOutcome(outcome: TaskOutcome): void;
89
91
  /** Announce a composition's own fact on `RunnerDeps.onNotice` (read at the call: `swapDeps` replaces the deps): {@link RunnerSelfSeat.emitNotice}. */
90
- emitNotice(notice: EngineNotice): void;
92
+ emitNotice(notice: EngineNotice, route?: NoticeRoute): void;
91
93
  /** Whether a child this Runner runs can be placed in another tree: {@link RunnerSelfSeat.canRerootChild}. */
92
94
  canRerootChild(): boolean;
93
95
  /** A completion addressed to a tree's root, through this Runner's route: {@link RunnerSelfSeat.sessionCompletionLane}. */
@@ -162,6 +164,8 @@ export declare class Runner implements RunnerSelfSeat {
162
164
  rewindFiles(request: RewindFilesRequest): Promise<RewindFilesResult>;
163
165
  /** What changed in a session's files, read outside any run — the contract is {@link readSessionChanges}'s (no lock: a leg running on the session does not refuse it; no gate, no frame, no write). */
164
166
  readSessionChanges(request: SessionChangesRequest): Promise<SessionChanges>;
167
+ /** Pre-run instruction-file manifest preview via the lane's single first-load reading (zero model calls, session/read-state writes, or notices; coded refusal on bad specs). */
168
+ previewInstructions(spec: TaskSpec, internals?: RunInternals): Promise<InstructionPreviewResult>;
165
169
  /** The out-of-run manual compaction, no run and no user turn — the contract is {@link compactIdleSession}'s (the one pass every lane runs; refused while a leg of this Runner holds or awaits the session's lock, or a write issued to it has not settled, and while the session is parked at a pending checkpoint). */
166
170
  compactSession(request: CompactSessionRequest): Promise<CompactSessionResult>;
167
171
  /** The out-of-run conversation rewind, no model call and no run — the contract is {@link rewindSessionConversation}'s (the landing a run's `resumeAt` + `resumeAtMode: "before"` makes; refused while a leg of this Runner holds or awaits the session's lock, or a write issued to it has not settled, and while the session is parked at a pending checkpoint; `dryRun` judges the same and writes nothing). */
@@ -335,6 +339,6 @@ export declare class Runner implements RunnerSelfSeat {
335
339
  */
336
340
  private resumeHandoff;
337
341
  }
338
- /** Convenience: one-shot run with explicit deps (creates a throwaway Runner). */
342
+ /** Convenience: one-shot run with explicit deps (creates a throwaway Runner; delivers a construction refusal as a failed TaskResult rather than throwing synchronously). */
339
343
  export declare function runTask(spec: TaskSpec, deps: RunnerDeps): Promise<TaskResult>;
340
344
  export type { TaskEvent, TaskStream };
@@ -1,7 +1,7 @@
1
1
  import { classicEventBase, legEventsOf, legNoticeTaskId } from "../mods/stations.js";
2
2
  import { openMessageDisplay } from "../mods/message-display.js";
3
- import { legTaskIdOf } from "../leg-identity.js";
4
- import { restoreRowTaskId } from "./checkpoint-scope.js";
3
+ import { legNoticeAdmission, legTaskIdOf } from "../leg-identity.js";
4
+ import { restoreRowIdentity, resumedDeclaredTaskId } from "./checkpoint-scope.js";
5
5
  import { checkpointClaimRevOf, checkpointRevOf } from "../checkpoint-generation.js";
6
6
  import { judgedOwnerSeat, readRootOccupant } from "./delegation-owner.js";
7
7
  import { raceSettlementAgainstSignal } from "./abort-race.js";
@@ -59,7 +59,7 @@ import { resumePreflight } from "./resume-preflight.js";
59
59
  import { resumeClaim } from "./resume-claim.js";
60
60
  import { voidVerifierPause } from "./void-verifier-pause.js";
61
61
  import { LocalClaims } from "./local-claims.js";
62
- import { streamSettleBackstop } from "./stream-settle-backstop.js";
62
+ import { failedPreRunResult, streamSettleBackstop } from "./stream-settle-backstop.js";
63
63
  import { streamReap } from "./stream-reap.js";
64
64
  import { streamSteerVerb } from "./stream-steer-verb.js";
65
65
  import { bindAuthoredSteer } from "../input-author.js";
@@ -90,6 +90,7 @@ import { deploymentCanRerootChild } from "./child-tree.js";
90
90
  import { rewindSessionFiles } from "./rewind-files.js";
91
91
  import { rewindOutcomeOf } from "./rewind-outcome.js";
92
92
  import { readSessionChanges } from "./read-session-changes.js";
93
+ import { previewInstructionsOf } from "../instruction-preview.js";
93
94
  import { compactIdleSession } from "./compact-session.js";
94
95
  import { rewindSessionConversation } from "./rewind-conversation.js";
95
96
  import { egressThrownText } from "../untrusted-egress.js";
@@ -171,8 +172,8 @@ export class Runner {
171
172
  emitTaskOutcome(outcome) {
172
173
  emitTaskOutcome(this.deps, outcome);
173
174
  }
174
- emitNotice(notice) {
175
- deliverEngineNotice(this.deps.onNotice, notice);
175
+ emitNotice(notice, route) {
176
+ deliverEngineNotice(this.deps.onNotice, notice, route !== undefined ? legNoticeAdmission(route, (destination, delivery) => this.pendingSessionNotifications.discardsStaleNotice(destination, delivery)) : undefined);
176
177
  }
177
178
  canRerootChild() { return deploymentCanRerootChild(this.deps); }
178
179
  sessionCompletionLane(root, unkept) { return this.pendingSessionNotifications.completionLaneOf(root, unkept); }
@@ -294,6 +295,7 @@ export class Runner {
294
295
  }
295
296
  rewindFiles(request) { return rewindSessionFiles({ deps: this.deps, sessions: this.sessions, readStates: this.sessionReadStates, ...this.verbLockSeats }, request); }
296
297
  readSessionChanges(request) { return readSessionChanges({ deps: this.deps, sessions: this.sessions }, request); }
298
+ previewInstructions(spec, internals) { return previewInstructionsOf({ deps: this.deps, sessions: this.sessions, readStates: this.sessionReadStates }, spec, internals); }
297
299
  compactSession(request) { return compactIdleSession({ deps: this.deps, liveModels: () => this.deps.models, sessions: this.sessions, ...this.verbLockSeats }, request); }
298
300
  rewindConversation(request) { return rewindSessionConversation({ deps: this.deps, sessions: this.sessions, ...this.verbLockSeats }, request); }
299
301
  forgetMcpFailure(request) { return forgetSessionMcpFailure(this.sessionMcpPools, request, this.deps.peerSeat); }
@@ -305,6 +307,8 @@ export class Runner {
305
307
  throw new TypeError("runTaskStream: `resume` must be a ResumeRun carrying `outcome` — got a value without one. " +
306
308
  "(Note the parameter order: runTaskStream(spec, resume?, internals?) — internals is the THIRD parameter.)");
307
309
  }
310
+ if (resume !== undefined)
311
+ internals = restoreRowIdentity(internals, resume.cp.state);
308
312
  const entry = readEntrySpec(spec, () => this.deps.models);
309
313
  spec = entry.spec;
310
314
  const entryActor = entry.actor;
@@ -341,7 +345,7 @@ export class Runner {
341
345
  };
342
346
  const runStartedAt = Date.now();
343
347
  const rewind = rewindOutcomeOf(spec);
344
- const taskIdRef = { current: legTaskIdOf(spec, restoreRowTaskId(internals, resume?.cp.state.rowTaskId), undefined), sessionId: spec.sessionId, intake: { committed: false }, ...(judgedOwnerSeat(internals) !== undefined ? { rowVerified: false } : {}), ...(rewind !== undefined ? { rewind } : {}) };
348
+ const taskIdRef = { current: legTaskIdOf(spec, internals, undefined), sessionId: spec.sessionId, intake: { committed: false }, ...(judgedOwnerSeat(internals) !== undefined ? { rowVerified: false } : {}), ...(rewind !== undefined ? { rewind } : {}) };
345
349
  let held = resumeHold === undefined ? undefined : { sessionId: resumeHold.sessionId, taken: Promise.resolve() };
346
350
  let releaseLock = resumeHold?.release;
347
351
  const holdSessionLock = (sessionId) => {
@@ -641,7 +645,7 @@ export class Runner {
641
645
  async resumeLadder(token, outcome, admitted) {
642
646
  const { config, internals, store, cp, outcomeGate, resumeSignal, wakeMessage, chainRefusal, rootLayerUnrestated } = admitted;
643
647
  const readGeneration = checkpointRevOf(cp);
644
- const { plainReviewOutcome, plainParkOutcome } = resumeReviewOutcome({ cp, outcome, outcomeGate, wakeMessage });
648
+ const { plainReviewOutcome, plainParkOutcome } = resumeReviewOutcome({ cp, outcome, outcomeGate, wakeMessage, configPermissionMode: config.permissionMode });
645
649
  const { plainPolicyOutcome: capturedPolicyOutcome, redeemedAnswer } = resumePolicyOutcome({ cp, outcome, config, runner: this.depsSeat });
646
650
  const { resumeInternals, chainRung } = resumeCheckpointScreen({ cp, resumeSignal, internals, tools: config.tools, runner: this.depsSeat, chainRefusal });
647
651
  const { recheckGovernanceWindow } = resumeInternalsAndConfig({ cp, config, internals, outcomeGate, runner: this.depsSeat, resumeSignal, chainRefused: chainRung !== undefined });
@@ -687,11 +691,13 @@ export class Runner {
687
691
  const answerFace = plainPolicyOutcome !== undefined && redeemedAnswer !== undefined
688
692
  ? answerFaceForRedeemedCall(redeemedAnswer, plainPolicyOutcome.boundCallId, config.onQuestion ?? this.deps.onQuestion, boundInputHashOf(cp.pendingAction.args?.questions))
689
693
  : undefined;
694
+ const declaredTaskId = resumedDeclaredTaskId(config, cp.state);
690
695
  const spec = {
691
696
  ...config,
692
697
  ...((config.principal || undefined) === undefined && (cp.principal || undefined) !== undefined ? { principal: cp.principal } : {}),
693
698
  ...((config.isolationScope || undefined) === undefined && (cp.isolationScope || undefined) !== undefined ? { isolationScope: cp.isolationScope } : {}),
694
699
  ...(config.durableApproval === undefined && cp.durableApproval === false ? { durableApproval: cp.durableApproval } : {}),
700
+ ...(declaredTaskId !== undefined ? { taskId: declaredTaskId } : {}),
695
701
  objective: "",
696
702
  sessionId: cp.sessionId,
697
703
  requireExistingSession: true,
@@ -724,6 +730,12 @@ async function sessionLockUnlessAborted(taken, signal, row) {
724
730
  void taken.then((release) => release(), () => { });
725
731
  throw new CheckpointError("checkpoint.resume_aborted", resumeCancelledSentence("while it waited for the session to be free", row));
726
732
  }
727
- export function runTask(spec, deps) {
728
- return new Runner(deps).runTask(spec);
733
+ export async function runTask(spec, deps) {
734
+ try {
735
+ const runner = enterConfigDoor("deps", () => new Runner(deps));
736
+ return runner.runTask(spec);
737
+ }
738
+ catch (err) {
739
+ return failedPreRunResult(err, spec);
740
+ }
729
741
  }
@@ -35,9 +35,10 @@ export type WithheldShellEnvSeatInput = Pick<Prepared, "runId" | "sessionId" | "
35
35
  };
36
36
  };
37
37
  /** The seat, per run. `onToolStart` and `onToolEnd` never throw: a diagnostic may not be what fails a call. `peerEntries` = the (variable,
38
- * entry) pairs the leg's receipt took in (leg-receipt.ts `LegReceipt.peerEntries`), and `isolationScope` = the leg's isolation scope
38
+ * entry) pairs the leg's receipt took in (leg-receipt.ts `LegReceipt.peerEntries`) and `isolationScope` = the leg's isolation scope
39
39
  * (isolation-scope.ts `legIdentityOf`): the entries its notice names, each for its variable, are those pairs and the ones the host declared
40
- * to every leg or — on a top-level leg, whose notice its own session reads — to that scope (secret-env.ts `declarePeerHeldEnv`). */
40
+ * to every leg or to the scope of the session the notice is delivered to — read off the leg's one notice route (`Prepared.legNotice`:
41
+ * a delegated leg's root address carries its scope), by the notice's own reading (secret-env.ts `withheldEnvUserNotice`). */
41
42
  export declare function createWithheldShellEnvSeat(prepared: WithheldShellEnvSeatInput, onNotice: ((notice: EngineNotice) => void) | undefined, peerEntries: PeerEntriesTaken | undefined, isolationScope?: string): {
42
43
  onToolStart(toolName: string): void;
43
44
  onToolEnd(): void;
@@ -43,7 +43,6 @@ function relayLateDeclaration(prepared, onNotice) {
43
43
  export function createWithheldShellEnvSeat(prepared, onNotice, peerEntries, isolationScope) {
44
44
  let shapeFaultTold = false;
45
45
  const relay = relayLateDeclaration(prepared, onNotice);
46
- const readerScope = prepared.legNotice.route.address.sourceSessionId === undefined ? isolationScope : undefined;
47
46
  return {
48
47
  onToolEnd: relay,
49
48
  onToolStart(toolName) {
@@ -61,7 +60,7 @@ export function createWithheldShellEnvSeat(prepared, onNotice, peerEntries, isol
61
60
  });
62
61
  return;
63
62
  }
64
- const notice = withheldEnvUserNotice(answer, { ...prepared.legNotice.route.address, runId: prepared.runId }, peerEntries, readerScope);
63
+ const notice = withheldEnvUserNotice(answer, { ...prepared.legNotice.route.address, runId: prepared.runId }, peerEntries, isolationScope, prepared.legNotice.route.destination?.scope);
65
64
  if (notice === undefined)
66
65
  return;
67
66
  const d = notice.detail;
@@ -36,8 +36,16 @@ export declare function stopTailWaitedFor(owed: Pick<DeliveryObligations, "pendi
36
36
  read: TaskAccess;
37
37
  owner: TaskAccess;
38
38
  }, registry?: Pick<TaskRegistry, "runEndReading">): readonly StopTailWaitedTask[];
39
- /** `task.interrupt_unconsumed`, for a stop that landed after the answer settled. `origin` names the axis that stopped the run. */
40
- export declare function interruptUnconsumedNotice(waitedFor: readonly StopTailWaitedTask[], origin: string, ids: Record<string, string>): EngineNotice;
39
+ /** `task.interrupt_unconsumed`, for a stop that landed after the answer settled. `origin` names the axis that stopped the run;
40
+ * `crossedAxis` the axis the result's `limitCrossed` records when it records one (a budget, walltime or turn stop at the tail is a
41
+ * ceiling the run ended past) — the sentence then names that record instead of saying none exists. */
42
+ export declare function interruptUnconsumedNotice(waitedFor: readonly StopTailWaitedTask[], origin: string, ids: Record<string, string>, crossedAxis?: string): EngineNotice;
43
+ /**
44
+ * The engine note a run with a member ledger reads when its one-shot wait reached its ceiling (`TaskSpec.runLedger`): one more turn,
45
+ * told which tasks it is leaving behind and what the run's end does to each, so the gap goes into its report to the person. Same
46
+ * reading as {@link waitCeilingReachedNotice} (read before the run-end sweep).
47
+ */
48
+ export declare function ceilingTurnNote(waitedFor: readonly StopTailWaitedTask[], ceilingMs: number): string;
41
49
  /**
42
50
  * `task.wait_ceiling_reached`, for a one-shot ending whose wait reached its ceiling (`limits.oneShotWaitCeilingMs`, `ceilingMs` the
43
51
  * value it waited under) with background tasks it started still owed: no stop arrived — the wait gave up. `waitedFor` is the same
@@ -27,8 +27,10 @@ function fatesSaid(waitedFor) {
27
27
  .join("; ");
28
28
  }
29
29
  const counted = (n) => `${n} background task${n === 1 ? "" : "s"}`;
30
- export function interruptUnconsumedNotice(waitedFor, origin, ids) {
31
- const tail = "the answer stands as the result, the run ends completed, and no interruption marker or limit code records the stop.";
30
+ export function interruptUnconsumedNotice(waitedFor, origin, ids, crossedAxis) {
31
+ const tail = crossedAxis !== undefined
32
+ ? `the answer stands as the result and the run ends completed; no interruption marker records the stop, and the result records the ${crossedAxis} limit it ended past.`
33
+ : "the answer stands as the result, the run ends completed, and no interruption marker or limit code records the stop.";
32
34
  if (waitedFor.length === 0) {
33
35
  return { code: "task.interrupt_unconsumed", message: `a stop arrived after the run had already given its answer: nothing was cut or stopped by it — ${tail}`, detail: { ...ids, origin, waitedFor: [] } };
34
36
  }
@@ -39,6 +41,11 @@ export function interruptUnconsumedNotice(waitedFor, origin, ids) {
39
41
  detail: { ...ids, origin, waitedFor: waitedFor.map((t) => ({ ...t })) },
40
42
  };
41
43
  }
44
+ export function ceilingTurnNote(waitedFor, ceilingMs) {
45
+ const left = waitedFor.length > 0 ? ` ${counted(waitedFor.length)} you started ${waitedFor.length === 1 ? "has" : "have"} not finished (${fatesSaid(waitedFor)}).` : "";
46
+ return (`[Engine note] The wait for the work you dispatched reached its ceiling (${ceilingMs} ms), so this run ends after this turn.${left} ` +
47
+ "Nothing from them reaches your result. Tell the person what is missing — call SendUserMessage with the gap and what it means for your conclusions — then end.");
48
+ }
42
49
  export function waitCeilingReachedNotice(waitedFor, ceilingMs, ids) {
43
50
  return {
44
51
  code: "task.wait_ceiling_reached",
@@ -1,3 +1,4 @@
1
+ export { failedPreRunResult } from "./terminal-account.js";
1
2
  import type { CheckpointToken } from "../checkpoint-store.js";
2
3
  import type { PushQueue } from "../push-queue.js";
3
4
  import type { SessionStore } from "../session.js";
@@ -1,4 +1,5 @@
1
1
  import { thrownFailureOf } from "./terminal-account.js";
2
+ export { failedPreRunResult } from "./terminal-account.js";
2
3
  import { compensateUnstarted, reopenReasonOf, resumeAgainMayCure, rowKeepsWhatItsRetryNeeds, unstartedFailureOf, unstartedRowSentence } from "../resume-startup-cause.js";
3
4
  import { resumeDecisionWasNegative } from "./decide-continuation.js";
4
5
  import { drainForwardedFramesBeforeDone, forwardsSubagentEvents } from "./prepare-run-refs.js";
@@ -21,7 +21,8 @@ import { enterConfigDoor, LIVE_OVER_ROW, resolveSeatValue } from "../config-refu
21
21
  import { envOfAssembly, workspaceOfAssembly } from "./prepare-execution-env.js";
22
22
  import { compileReadDeny, readDenyBuiltinConfigOf } from "../../tools/fs/read-deny.js";
23
23
  import { readDenyFloorRefusal } from "../../tools/fs/read-floor.js";
24
- import { unionAddOnly } from "../child-clamp-seats.js";
24
+ import { unionAddOnly, withOwnLegHands } from "../child-clamp-seats.js";
25
+ import { assertRunLedgerDeclaration } from "../run-ledger.js";
25
26
  import { prepareSafetyScan } from "./prepare-safety-scan.js";
26
27
  import { boundOwnToolLists, boundToolListsJudgment, judgeHostToolCeiling, ownListsWhereOf, readToolSelector, refuseNonListToolCeiling } from "./sub-agent-deny-lists.js";
27
28
  import { legRetiredNameView, selectorLayerUnderView } from "../tool-name-aliases.js";
@@ -64,13 +65,16 @@ export function taskStartDoors(input) {
64
65
  const languageDeclared = enterConfigDoor("taskConfig", () => screenLanguageSeat(spec.language));
65
66
  const allowedTools = enterConfigDoor("taskConfig", () => screenAllowedToolsValue(spec.allowedTools, "TaskSpec.allowedTools"));
66
67
  const userAttachmentsSeat = enterConfigDoor("taskConfig", () => screenUserAttachments(spec.userAttachments, { resumeLeg: resume !== undefined }));
68
+ const delegation = effectiveDelegationFacts(internals, resume?.seed.isDelegatedChild);
67
69
  const declaredModeAtDoor = (() => {
68
- const requested = modeRequestAfterResume(permissionModeSeat, recordedModeSeed(resume?.seed.inheritedGate), resume?.outcome);
69
70
  const live = internals?.inheritedGate?.permissionModeCeiling;
70
71
  const ceiling = live !== undefined ? (live.observed ?? live.current) : internals?.inheritedGate?.permissionMode;
72
+ const requested = modeRequestAfterResume(permissionModeSeat, recordedModeSeed(resume?.seed.inheritedGate), resume?.outcome, delegation.isDelegatedChild && ceiling === undefined ? true : undefined);
71
73
  return ceiling === undefined ? (requested ?? "default") : clampPermissionMode(requested, ceiling).effective;
72
74
  })();
73
75
  spec = withModeSeats(spec, declaredModeAtDoor);
76
+ enterConfigDoor("taskConfig", () => assertRunLedgerDeclaration(spec.runLedger));
77
+ spec = enterConfigDoor("taskConfig", () => withOwnLegHands(spec));
74
78
  const planFile = spec.planFile;
75
79
  enterConfigDoor("taskConfig", () => checkedPlanFileShape(planFile));
76
80
  const scanned = spec;
@@ -80,7 +84,6 @@ export function taskStartDoors(input) {
80
84
  const { toolFaceLists } = doors;
81
85
  const ownListsRecord = resolveSeatValue(internals?.ownToolLists, () => resume?.seed.ownToolLists, LIVE_OVER_ROW);
82
86
  const ownToolLists = enterConfigDoor(ownListsRecord.input, () => boundOwnToolLists(ownListsRecord.value, toolFaceLists));
83
- const delegation = effectiveDelegationFacts(internals, resume?.seed.isDelegatedChild);
84
87
  const approvalParkNotResumable = approvalParkNotResumableOf({ engineLaneLeg: engineLaneLegOf(internals), parkLaneHeld: internals?.parkLaneHeld === true, hostDeclaredNotResumable: doors.hostApprovalParksNotResumable });
85
88
  const notResumableSays = notResumableSaysOf(approvalParkNotResumable, doors.hostApprovalParksNotResumable);
86
89
  const overlay = enterConfigDoor("deps", () => contextOverlayFor(deps.contextSettings, doors.resolvedRole.modelRef, deps));
@@ -8,7 +8,7 @@
8
8
  import { type AssistantMessage, type ModelOutputInvalid } from "../../internal/llm.js";
9
9
  import type { LoopTerminalReason } from "../../internal/harness-types.js";
10
10
  import { type RequestRoute } from "../../brain/request-route.js";
11
- import type { TerminalCause } from "../types.js";
11
+ import type { TaskResult, TerminalCause } from "../types.js";
12
12
  import { type TerminalFailureDetail } from "../terminal-cause.js";
13
13
  type ProviderRejected = Extract<TerminalFailureDetail, {
14
14
  kind: "provider_rejected";
@@ -56,6 +56,11 @@ export declare function thrownFailureOf(err: unknown, text: string): {
56
56
  message: string;
57
57
  detail?: TerminalFailureDetail;
58
58
  };
59
+ /** A `failed` TaskResult for a throw that occurred before a Runner leg could start (e.g. the one-shot `runTask(spec, deps)`
60
+ * when `new Runner(deps)` refuses deployment deps): carries the same coded terminal account (`thrownFailureOf`),
61
+ * intake (`{ committed: false }`), unsettled continuation, and zero/usageMissing stats as the stream settle backstop,
62
+ * without invoking any throwing getter on `spec`. */
63
+ export declare function failedPreRunResult(err: unknown, spec: unknown): TaskResult;
59
64
  /** The completion's one account, read off the final message: it ended on a provider word the brain does not read (the
60
65
  * turn was kept and the run announced the word — stated in the echo shape the brain carried it in), or its answer stopped
61
66
  * arriving before the provider ended it and what arrived was kept. A cut stream has no ending word, so the two never meet. */