@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
@@ -0,0 +1,406 @@
1
+ import { InMemorySessionStorage, SessionError, StoredSession } from "../internal/harness.js";
2
+ import { legBudgetSnapshot, resourceTotalOf } from "./leg-budget.js";
3
+ import { createModelFileReader } from "../tools/fs/fs-read.js";
4
+ import { compileReadDeny, inheritSessionReadFileState, readDenyBuiltinConfigOf, resolveContainmentFace, seedReadFileStateFromTranscript } from "../tools/fs/index.js";
5
+ import { whereItsAnsweredPrefixLeads } from "../tools/fs/read-deny-home.js";
6
+ import { resolveKey } from "../tools/fs/safety.js";
7
+ import { unionAddOnly } from "./child-clamp-seats.js";
8
+ import { enterConfigDoor } from "./config-refusal-input.js";
9
+ import { legCallTargetStamp, validatePath } from "./effective-path-target.js";
10
+ import { SeenFileRegistry } from "./existing-target.js";
11
+ import { legTaskIdOf } from "./leg-identity.js";
12
+ import { bindPathRules, createHeadLeads } from "./path-rule-binding.js";
13
+ import { assertStringArraySeat, screenReadDenySeat } from "./read-face-seats.js";
14
+ import { judgeReadFloorKept, readFloorSeat } from "../tools/fs/read-floor.js";
15
+ import { ENV_PURPOSE_UNSUPPORTED, hasDestroy } from "./remote-env.js";
16
+ import { dataRootSpellings } from "./sensitive-path-policy.js";
17
+ import { sessionRootOf } from "./session-checkout.js";
18
+ import { createSyntheticServedReadJudge } from "./synthetic-read-verdict.js";
19
+ import { readEntrySpec } from "./task-start-judge.js";
20
+ import { readMember, thrownText } from "./thrown-value.js";
21
+ import { TOOL_CATALOG_ENTRIES, toolFace } from "./tool-catalog-entries.js";
22
+ import { toolPolicyPathRules } from "./tool-policy.js";
23
+ import { chainPolicyOnLeg } from "./runner/child-tree.js";
24
+ import { createToolOccurrenceTable } from "./runner/tool-occurrence.js";
25
+ import { delegatedTreeOwner, judgedLegOf, judgedOwnerSeat, judgeRowForTree, legRowRefusal, readRootOccupant, readStandsAsJudged, rowNotTheOneJudged } from "./runner/delegation-owner.js";
26
+ import { legCallerPlaces } from "./runner/leg-caller-places.js";
27
+ import { readLegInternals } from "./runner/leg-frame.js";
28
+ import { receiveLeg } from "./runner/leg-receipt.js";
29
+ import { instructionFamilyOf, primeInstructionReading, } from "./runner/nested-memory-lane.js";
30
+ import { seatInstructionLane } from "./runner/prepare-turn-wiring.js";
31
+ import { createPermissionRuleLanes } from "./runner/permission-rule-lanes.js";
32
+ import { pathTablesCompile, personPathRowsOfTask, readRootsOver } from "./runner/person-path-rows.js";
33
+ import { prepareExecutionEnv } from "./runner/prepare-execution-env.js";
34
+ import { readBlockLeg, readBlockOf } from "./runner/read-block-judge.js";
35
+ import { createRollbackStack } from "./runner/rollback-stack.js";
36
+ import { readStateFromTranscript } from "./runner/session-file-state-replay.js";
37
+ import { legReadCarrier, readSeatLeaf } from "./runner/session-read-file-states.js";
38
+ import { createLiveSessionRules, createSessionRulePolicy } from "./runner/session-rule-policy.js";
39
+ import { taskStartDoors } from "./runner/task-start-doors.js";
40
+ import { resolveTaskRootCanonical } from "./runner/task-root-canonical.js";
41
+ import { settleTeardownLeg } from "./runner/teardown-bounded.js";
42
+ import { thrownFailureOf } from "./runner/terminal-account.js";
43
+ import { valveLeaves } from "../agents/tool-filter.js";
44
+ export const EXTERNAL_INCLUDE_POST_APPROVAL_BLOCKS = Object.freeze(["outside_roots", "rule_denied", "approval_required", "admission_unknown"]);
45
+ const NOOP = () => undefined;
46
+ export async function previewInstructionsOf(seats, spec, internals) {
47
+ try {
48
+ const bag = internals !== undefined ? enterConfigDoor("deps", () => readLegInternals(internals, "runTaskStream")) : undefined;
49
+ const request = readEntrySpec(spec, () => seats.deps.models).spec;
50
+ const silentDeps = { ...seats.deps, onNotice: NOOP, onError: NOOP, tracer: undefined };
51
+ const legInternals = {
52
+ ...(enterConfigDoor("deps", () => readRootOccupant(bag, undefined, request.sessionId)) ?? {}),
53
+ receivedPeers: receiveLeg(request, silentDeps),
54
+ };
55
+ const start = taskStartDoors({ request, deps: silentDeps, sessions: seats.sessions, internals: legInternals });
56
+ const projectMemory = instructionFamilyOf(start.spec) === undefined ? "absent" : start.spec.projectMemory === "disabled" ? "disabled" : "on";
57
+ const nestedDecl = start.doors.nestedMemory;
58
+ const rows = rowReader(seats.sessions);
59
+ const existingSession = start.spec.sessionId !== undefined ? await previewSession(seats.sessions, rows, { ...start.spec, sessionId: start.spec.sessionId }, legInternals) : undefined;
60
+ const previewSessionId = start.spec.sessionId ?? "preview-instructions";
61
+ const previewRunId = "preview-instructions";
62
+ const previewTaskId = legTaskIdOf(start.spec, legInternals, previewSessionId);
63
+ const abortController = new AbortController();
64
+ if (start.spec.signal?.aborted)
65
+ abortController.abort();
66
+ const owned = [];
67
+ const rollback = createRollbackStack(NOOP);
68
+ let envPhase;
69
+ try {
70
+ envPhase = await prepareExecutionEnv({
71
+ deps: silentDeps,
72
+ spec: start.spec,
73
+ internals: legInternals,
74
+ resume: undefined,
75
+ placementRootResolved: previewSessionId,
76
+ sessionId: previewSessionId,
77
+ forgetOnThrow: async () => undefined,
78
+ rollback,
79
+ startsEnv: true,
80
+ purpose: "read_changes",
81
+ });
82
+ rollback.commit();
83
+ if (envPhase.ownedEnvSeat.current !== undefined)
84
+ owned.push(envPhase.ownedEnvSeat.current);
85
+ }
86
+ catch (err) {
87
+ await rollback.unwindAll();
88
+ if (readMember(err, "code") !== ENV_PURPOSE_UNSUPPORTED)
89
+ throw err;
90
+ envPhase = undefined;
91
+ }
92
+ try {
93
+ const emptyContext = new StoredSession(new InMemorySessionStorage());
94
+ const previewLeg = {
95
+ harness: { getModel: () => start.doors.model },
96
+ session: { buildContext: () => (existingSession ?? emptyContext).buildContext() },
97
+ sessionId: previewSessionId,
98
+ runId: previewRunId,
99
+ announcedListingsRef: {},
100
+ frameReceipts: { listingSnapshotOwed: false },
101
+ hookIdentity: { taskId: previewTaskId, isDelegatedChild: start.delegation.isDelegatedChild },
102
+ };
103
+ const handsEnabled = envPhase !== undefined && envPhase.handsEnabled;
104
+ assertStringArraySeat(silentDeps.readDenyPatterns, "RunnerDeps.readDenyPatterns", "compiler-owned");
105
+ const readBlock = readBlockOf({ spec: start.spec, resume: undefined });
106
+ const liveReadFace = resolveContainmentFace({
107
+ kind: "read",
108
+ specFace: start.spec.readFace,
109
+ depsFace: silentDeps.readFace,
110
+ readOnlyMount: start.spec.handsReadOnly === true,
111
+ readBlock,
112
+ orgGoverned: silentDeps.permissionRuleStore?.partitions.org === true,
113
+ fullShellReachable: false,
114
+ });
115
+ const readDenyAdditions = unionAddOnly("readDenyPatterns", silentDeps.readDenyPatterns, start.spec.readDenyPatterns);
116
+ const readDenyBuiltinCfg = readDenyBuiltinConfigOf({ tiers: silentDeps.readDenyBuiltinTiers, exclude: silentDeps.readDenyBuiltinExclude });
117
+ if (!handsEnabled) {
118
+ if (readDenyAdditions.length > 0)
119
+ compileReadDeny(readDenyAdditions, "readDenyPatterns", { tiers: [] });
120
+ if (projectMemory !== "on" || nestedDecl === undefined)
121
+ return { ok: true, projectMemory };
122
+ const lane = seatInstructionLane({
123
+ declaration: nestedDecl,
124
+ signal: abortController.signal,
125
+ mark: undefined,
126
+ counts: undefined,
127
+ deps: silentDeps,
128
+ leg: () => previewLeg,
129
+ });
130
+ const instructions = await primeInstructionReading(lane, NOOP);
131
+ return { ok: true, projectMemory, ...(instructions !== undefined ? { instructions } : {}) };
132
+ }
133
+ const executionEnv = envPhase.executionEnv;
134
+ const taskRootFinal = existingSession !== undefined && start.spec.sessionId !== undefined
135
+ ? await sessionRootOf({ env: executionEnv, session: existingSession, sessionId: start.spec.sessionId, baseRoot: envPhase.taskRootInitial, sessions: rows }, `Runner.previewInstructions: session "${start.spec.sessionId}" checkout cannot be resolved`)
136
+ : envPhase.taskRootInitial;
137
+ const { canonical: taskRootCanonical } = await resolveTaskRootCanonical({
138
+ env: executionEnv,
139
+ given: taskRootFinal,
140
+ onNotice: silentDeps.onNotice,
141
+ sessionId: previewSessionId,
142
+ runId: previewRunId,
143
+ });
144
+ assertStringArraySeat(start.spec.additionalDirectories, "TaskSpec.additionalDirectories", "strings");
145
+ assertStringArraySeat(start.spec.additionalReadDirectories, "TaskSpec.additionalReadDirectories", "strings");
146
+ const additionalRootsCanonical = [];
147
+ const additionalReadRootsCanonical = [];
148
+ const declaredAdditionalRoots = [];
149
+ const canonicalizeDirs = async (dirs, sink, declared) => {
150
+ for (const dir of dirs ?? []) {
151
+ if (!dir || !dir.trim())
152
+ continue;
153
+ const c = await executionEnv.canonicalPath(dir);
154
+ if (c.ok) {
155
+ sink.push(c.value);
156
+ declared?.push(Object.freeze({ directory: dir, canonical: c.value }));
157
+ }
158
+ }
159
+ };
160
+ await canonicalizeDirs(start.spec.additionalDirectories, additionalRootsCanonical, declaredAdditionalRoots);
161
+ await canonicalizeDirs(start.spec.additionalReadDirectories, additionalReadRootsCanonical);
162
+ for (const a of [additionalRootsCanonical, additionalReadRootsCanonical])
163
+ a.splice(0, a.length, ...new Set(a));
164
+ const legHome = validatePath(executionEnv.homeDir, { intent: "validate-coordinate" });
165
+ const legAnchors = { root: taskRootCanonical, ...(legHome !== undefined ? { home: legHome } : {}) };
166
+ const callerPlaces = legCallerPlaces({ deps: silentDeps, spec: start.spec, recorded: undefined });
167
+ const onLeg = enterConfigDoor("deps", () => chainPolicyOnLeg({
168
+ leg: legAnchors,
169
+ chainTop: legAnchors,
170
+ placement: undefined,
171
+ chain: (legInternals.inheritedGate?.parentConstraints ?? []).map((c) => c.policy),
172
+ installations: { live: legInternals.inheritedGate?.pathRuleInstallations, seed: undefined },
173
+ rebase: (p) => p,
174
+ }));
175
+ const installedToolPolicy = onLeg.own(start.doors.lockedPreflight.toolPolicy);
176
+ const inheritedPolicies = (legInternals.inheritedGate?.parentConstraints ?? []).flatMap((c, i) => c.policy !== undefined ? [onLeg.chained(c.policy, i)] : []);
177
+ const headLeads = createHeadLeads((part) => whereItsAnsweredPrefixLeads(executionEnv, part));
178
+ let sessionRulePolicy;
179
+ let ownSessionRow;
180
+ if (silentDeps.sessionPolicyStore !== undefined && start.spec.sessionId !== undefined) {
181
+ const key = { sessionId: start.spec.sessionId, ...(start.spec.principal ? { principal: start.spec.principal } : {}) };
182
+ const seed = (await silentDeps.sessionPolicyStore.getRules(key.sessionId, key.principal)) ?? { rev: 0 };
183
+ ownSessionRow = seed;
184
+ sessionRulePolicy = createSessionRulePolicy({ seed, read: createLiveSessionRules(silentDeps.sessionPolicyStore, { ...key, seed }, { onUnreadable: NOOP, onEnforced: (r) => void (ownSessionRow = r) }) }, { env: executionEnv, rootPath: taskRootFinal, toolEffects: new Map(), anchors: legAnchors, onEarlierGrammar: NOOP });
185
+ }
186
+ const personRows = personPathRowsOfTask({
187
+ deps: silentDeps,
188
+ notices: { onUnread: NOOP, onRowsDropped: NOOP },
189
+ principal: start.spec.principal,
190
+ ids: { sessionId: previewSessionId, runId: previewRunId, taskId: previewTaskId },
191
+ root: taskRootFinal,
192
+ rootCanonical: taskRootCanonical,
193
+ leads: headLeads,
194
+ chainTop: legAnchors,
195
+ occurrences: createToolOccurrenceTable(),
196
+ signals: [abortController.signal, ...(start.spec.signal !== undefined ? [start.spec.signal] : [])],
197
+ seatsBeyond: {
198
+ session_rules: () => (ownSessionRow !== undefined ? { rules: ownSessionRow, unread: false } : undefined),
199
+ ancestor_session_rules: () => [],
200
+ skill_grants: () => [],
201
+ },
202
+ });
203
+ await personRows.prime();
204
+ const policyPathRows = toolPolicyPathRules([installedToolPolicy, ...inheritedPolicies], legAnchors);
205
+ const effectivePathDenyRules = policyPathRows.filter((r) => r.faces.length > 0 && r.behavior === "deny" && r.unanchored === undefined);
206
+ const canonicalizePersonDirs = async (dirs) => {
207
+ const out = [];
208
+ for (const d of dirs)
209
+ await canonicalizeDirs([d], out).catch(NOOP);
210
+ return out;
211
+ };
212
+ const compileTables = pathTablesCompile({
213
+ env: executionEnv,
214
+ additions: readDenyAdditions,
215
+ builtin: readDenyBuiltinCfg,
216
+ legRows: effectivePathDenyRules,
217
+ legReadAskRows: [],
218
+ leads: headLeads,
219
+ configRoots: callerPlaces.configRoots.dirs,
220
+ callerHomes: callerPlaces.homes.dirs,
221
+ canonicalize: canonicalizePersonDirs,
222
+ });
223
+ const floorRequired = screenReadDenySeat("readDenyFloorRequired", silentDeps.readDenyFloorRequired) === true;
224
+ const tables = await personRows.attachTables(async (person) => {
225
+ const compiled = await compileTables(person);
226
+ judgeReadFloorKept({ env: executionEnv, table: compiled.readDeny, floor: readFloorSeat(compiled.readDeny)?.(undefined), required: floorRequired, onNotice: NOOP });
227
+ return compiled;
228
+ });
229
+ if (projectMemory !== "on" || nestedDecl === undefined)
230
+ return { ok: true, projectMemory };
231
+ const { personDirectories } = readBlockLeg(readBlock);
232
+ const readRoots = readRootsOver({
233
+ own: () => [...additionalRootsCanonical, ...additionalReadRootsCanonical],
234
+ tables,
235
+ ready: personRows.tablesReady,
236
+ store: () => undefined,
237
+ onHeld: NOOP,
238
+ personDirectories,
239
+ });
240
+ const readFileState = new Map();
241
+ const seenFiles = new SeenFileRegistry();
242
+ if (existingSession !== undefined && start.spec.sessionId !== undefined) {
243
+ const judgeKey = async (path) => {
244
+ const rk = await readRoots.ready().then(() => resolveKey(executionEnv, taskRootCanonical, path, undefined, undefined, readRoots(), undefined, undefined, liveReadFace));
245
+ return rk.ok ? rk.key : undefined;
246
+ };
247
+ const carrier = await legReadCarrier({
248
+ resuming: false,
249
+ spec: start.spec,
250
+ sessionId: start.spec.sessionId,
251
+ seats: seats.readStates,
252
+ leaf: () => readSeatLeaf(existingSession),
253
+ getEntry: (id) => existingSession.getEntry(id),
254
+ });
255
+ if (carrier.from === "seat") {
256
+ await inheritSessionReadFileState(readFileState, carrier.state, judgeKey, seenFiles);
257
+ }
258
+ else if (carrier.from === "transcript") {
259
+ const prior = await existingSession.buildContext().catch(() => undefined);
260
+ const rebuilt = readStateFromTranscript(prior?.messages ?? []);
261
+ for (const rec of rebuilt.records) {
262
+ const rk = await judgeKey(rec.path);
263
+ if (rk === undefined)
264
+ continue;
265
+ if ("content" in rec)
266
+ seedReadFileStateFromTranscript(readFileState, rk, rec.content, rec.at, rec.transmittedByToolCallId);
267
+ else
268
+ readFileState.set(rk, { ...rec.observation, lastReadAt: rec.at });
269
+ }
270
+ }
271
+ }
272
+ const reader = createModelFileReader({
273
+ env: executionEnv,
274
+ state: readFileState,
275
+ rootCanonical: taskRootCanonical,
276
+ additionalRoots: readRoots,
277
+ readDeny: tables.readDeny,
278
+ readFace: liveReadFace,
279
+ });
280
+ const ruleLanes = createPermissionRuleLanes({
281
+ provider: silentDeps.permissionRuleStore,
282
+ localOwnerDeclared: silentDeps.localOwnerRules === true,
283
+ principal: start.spec.principal,
284
+ sessionId: start.spec.sessionId,
285
+ root: taskRootFinal,
286
+ rootCanonical: taskRootCanonical,
287
+ chainTop: legAnchors,
288
+ leads: headLeads,
289
+ liveCwd: () => taskRootCanonical,
290
+ home: executionEnv.homeDir,
291
+ questionToolMounted: false,
292
+ questionToolName: "AskUserQuestion",
293
+ onRevisionDefect: NOOP,
294
+ onDisclosure: NOOP,
295
+ rows: { pin: (id, judged) => personRows.pin(id, judged), forRequest: () => personRows.forRequest() },
296
+ });
297
+ const stampCallTarget = legCallTargetStamp({
298
+ env: executionEnv,
299
+ root: taskRootCanonical,
300
+ cwd: () => undefined,
301
+ judgesPaths: () => installedToolPolicy?.pathRules !== undefined || ruleLanes.personal !== undefined,
302
+ leads: () => headLeads.resolve([...toolPolicyPathRules([installedToolPolicy, ...inheritedPolicies], legAnchors), ...bindPathRules([], legAnchors)]),
303
+ });
304
+ const exemptRoots = Object.freeze(dataRootSpellings(silentDeps.memoryEngineDir));
305
+ const budget = legBudgetSnapshot(resourceTotalOf(start.spec), undefined);
306
+ const servedReadVerdict = createSyntheticServedReadJudge({
307
+ ...(sessionRulePolicy !== undefined ? { denyNarrowingPolicy: sessionRulePolicy } : {}),
308
+ ...(installedToolPolicy !== undefined ? { callerPolicy: installedToolPolicy } : {}),
309
+ inheritedPolicies,
310
+ ...(ruleLanes.personal !== undefined ? { persistedRuleLane: ruleLanes.personal } : {}),
311
+ ...(ruleLanes.org !== undefined ? { orgRuleLane: ruleLanes.org } : {}),
312
+ stampCallTarget,
313
+ signal: abortController.signal,
314
+ }, () => ({ cwd: taskRootCanonical, root: taskRootCanonical, exemptRoots, budget }));
315
+ const readName = TOOL_CATALOG_ENTRIES.find((e) => e.id === "read")?.name;
316
+ const readDecl = readName !== undefined && valveLeaves(start.toolFaceSnapshot.selector)({ name: readName }) ? toolFace("read") : undefined;
317
+ const readContract = readDecl?.contract;
318
+ const readToolFace = readName === undefined || readDecl === undefined || readContract === undefined
319
+ ? undefined
320
+ : {
321
+ names: [readName],
322
+ family: readDecl.family,
323
+ ...(readDecl.pathTarget !== undefined
324
+ ? {
325
+ pathTarget: {
326
+ param: readDecl.pathTarget.param,
327
+ aliases: [...(readDecl.pathTarget.aliases ?? [])],
328
+ access: readDecl.pathTarget.access,
329
+ skillScopeEligible: readDecl.pathTarget.skillScopeEligible === true,
330
+ ...(readDecl.pathTarget.base !== undefined ? { base: readDecl.pathTarget.base } : {}),
331
+ ...(readDecl.pathTarget.absent !== undefined ? { absent: readDecl.pathTarget.absent } : {}),
332
+ },
333
+ }
334
+ : {}),
335
+ capabilityId: readContract.contractId,
336
+ contractId: readContract.contractId,
337
+ shapeDigest: "",
338
+ implementationRevision: readContract.implementationRevision,
339
+ engineMounted: true,
340
+ };
341
+ const lane = seatInstructionLane({
342
+ declaration: nestedDecl,
343
+ signal: abortController.signal,
344
+ mark: undefined,
345
+ counts: undefined,
346
+ deps: silentDeps,
347
+ leg: () => previewLeg,
348
+ env: executionEnv,
349
+ reader,
350
+ judge: servedReadVerdict,
351
+ readFace: () => readToolFace,
352
+ state: readFileState,
353
+ root: taskRootCanonical,
354
+ additionalRoots: declaredAdditionalRoots,
355
+ });
356
+ const instructions = await primeInstructionReading(lane, NOOP);
357
+ return { ok: true, projectMemory, ...(instructions !== undefined ? { instructions } : {}) };
358
+ }
359
+ finally {
360
+ for (const env of owned)
361
+ if (hasDestroy(env))
362
+ await settleTeardownLeg(() => env.destroy(), "ownedEnv.destroy (previewInstructions)", NOOP);
363
+ }
364
+ }
365
+ catch (err) {
366
+ const { code, message, detail } = thrownFailureOf(err, thrownText(err));
367
+ return { ok: false, ...(code !== undefined ? { code } : {}), message, ...(detail !== undefined ? { detail } : {}) };
368
+ }
369
+ }
370
+ function rowReader(sessions) {
371
+ const row = async (sessionId) => {
372
+ const readRow = sessions.readRow;
373
+ if (typeof readRow !== "function") {
374
+ throw Object.assign(new Error("Runner.previewInstructions: the session store has no row read (readRow) — a preview reads a named session without running on it, and never opens it through acquire, which sweeps and records activity"), { code: "config.invalid_session_store" });
375
+ }
376
+ return readRow.call(sessions, sessionId);
377
+ };
378
+ return {
379
+ row,
380
+ async acquire(sessionId) {
381
+ const read = sessionId === undefined ? undefined : await row(sessionId);
382
+ if (sessionId === undefined || read === undefined)
383
+ throw new SessionError("not_found", `Session not found: ${sessionId ?? "(none named)"}`);
384
+ return { session: detachedSession(read), sessionId };
385
+ },
386
+ };
387
+ }
388
+ const detachedSession = (row) => new StoredSession(new InMemorySessionStorage({ metadata: structuredClone(row.metadata), entries: structuredClone(row.entries) }));
389
+ async function previewSession(sessions, rows, spec, internals) {
390
+ const ownerSeat = judgedOwnerSeat(internals);
391
+ const leg = judgedLegOf(spec, internals, ownerSeat === undefined ? undefined : await delegatedTreeOwner(ownerSeat, spec.signal));
392
+ let judged;
393
+ if (leg !== undefined) {
394
+ const verdict = await judgeRowForTree(sessions, { sessionId: spec.sessionId, minted: leg.minted, runsOn: true, writes: false }, { bound: true, owner: leg.owner }, leg.signal);
395
+ if (!verdict.open)
396
+ throw legRowRefusal(spec.sessionId, verdict);
397
+ judged = verdict.head;
398
+ }
399
+ const row = await rows.row(spec.sessionId);
400
+ if (judged !== undefined && !(judged === null && row === undefined) && !readStandsAsJudged(judged, row?.head))
401
+ throw legRowRefusal(spec.sessionId, rowNotTheOneJudged());
402
+ if (row === undefined && spec.requireExistingSession === true) {
403
+ throw Object.assign(new Error(`Runner.previewInstructions: session "${spec.sessionId}" does not exist`), { code: "resume.session_not_found" });
404
+ }
405
+ return row === undefined ? undefined : detachedSession(row);
406
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The leg's budget facts a policy judges every request of the leg under (`ToolCallRequest.budget`) — one reading for a run's prepare and
3
+ * for a preview of that leg (`Runner.previewInstructions`), so a policy that judges the budget judges the preview's reads as the run's.
4
+ */
5
+ import { type ResourceLedger } from "./checkpoint-store.js";
6
+ import type { ToolCallRequest } from "./tool-policy.js";
7
+ /** The resource totals a task configures (`TaskSpec.resourceSuspend`), $ in micro-USD — seeded on the first slice only (later slices
8
+ * read the frozen total off the ledger); `undefined` when the task configures no resource suspend. */
9
+ export declare function resourceTotalOf(spec: {
10
+ readonly resourceSuspend?: {
11
+ readonly totalBudgetUsd?: number;
12
+ readonly totalTokens?: number;
13
+ };
14
+ }): {
15
+ totalBudgetMicroUsd?: number;
16
+ totalTokens?: number;
17
+ } | undefined;
18
+ /** THE leg's budget snapshot, read once per leg from the durable state and frozen onto every request the leg hands a policy. A resumed
19
+ * leg reads its ledger's remaining and spend; a first leg (a preview resumes nothing) its configured total and nothing spent; the count
20
+ * is the durable suspend chain's. Never falsy-test the remaining (`0` = exhausted, not unlimited). */
21
+ export declare function legBudgetSnapshot(resourceTotal: {
22
+ readonly totalBudgetMicroUsd?: number;
23
+ } | undefined, resume: {
24
+ readonly priorLedger?: ResourceLedger;
25
+ readonly priorSuspendCount?: number;
26
+ } | undefined): NonNullable<ToolCallRequest["budget"]>;
@@ -0,0 +1,9 @@
1
+ import { remainingBudgetMicroUsd } from "./checkpoint-store.js";
2
+ export function resourceTotalOf(spec) {
3
+ const r = spec.resourceSuspend;
4
+ return r ? { totalBudgetMicroUsd: r.totalBudgetUsd !== undefined ? Math.round(r.totalBudgetUsd * 1e6) : undefined, totalTokens: r.totalTokens } : undefined;
5
+ }
6
+ export function legBudgetSnapshot(resourceTotal, resume) {
7
+ const priorLedger = resume?.priorLedger;
8
+ return { resourceRemainingMicroUsd: priorLedger ? remainingBudgetMicroUsd(priorLedger) : resourceTotal?.totalBudgetMicroUsd, resourceSpentMicroUsd: priorLedger?.spentMicroUsd ?? 0, suspendCount: resume?.priorSuspendCount ?? 0 };
9
+ }
@@ -39,6 +39,45 @@ export declare function rootAnchorOf(internals: {
39
39
  sessionId: string;
40
40
  occupant?: string;
41
41
  };
42
+ /**
43
+ * The root session id a leg's {@link HookInvocationIdentity} carries — the session the delegation tree's shared task list
44
+ * belongs to (`task_list.partition_is_root_session`): the tree's root anchor (`internals.rootSessionId`) when present, else
45
+ * the leg's own `sessionId` on a top-level leg (`!isDelegatedChild` and not `observerLeg`), else `undefined` (honestly absent
46
+ * when a delegated or observer leg was handed no root anchor — never fabricating a child's own session as the root).
47
+ */
48
+ export declare function hookRootSessionIdOf(internals: {
49
+ readonly rootSessionId?: string | undefined;
50
+ readonly observerLeg?: true | undefined;
51
+ } | undefined, sessionId: string, isDelegatedChild: boolean): string | undefined;
52
+ /**
53
+ * The identity facts a parked row records of its leg (`CheckpointState.legIdentity`, reader word `leg_identity`), so a resume
54
+ * reads them back instead of guessing them from the resuming turn: the task id its host declared (`spec.taskId`, after a member
55
+ * ledger's rebind), the task that spawned it (`internals.parentTaskId`), the delegation tree's root and that root's occupant
56
+ * (`internals.rootSessionId` with the scope its box lives in, `rootSessionScope`, written only together, and the root's occupant
57
+ * `rootSessionIncarnation` beside them) and its explicit spawn name (`internals.explicitAgentName` — never the display name a model
58
+ * chose, `sourceAgentName`). Each member is a non-empty string or absent; a leg with none records no section.
59
+ */
60
+ export interface LegIdentityRecord {
61
+ readonly declaredTaskId?: string;
62
+ readonly parentTaskId?: string;
63
+ readonly rootSessionId?: string;
64
+ readonly rootSessionIncarnation?: string;
65
+ readonly rootSessionScope?: string;
66
+ readonly spawnName?: string;
67
+ }
68
+ /** The leg's {@link LegIdentityRecord} as its park mints it, off the leg's own spec and trusted internals; `undefined` when it has none. */
69
+ export declare function legIdentityRecordOf(declaredTaskId: string | undefined, internals: {
70
+ readonly parentTaskId?: string | undefined;
71
+ readonly rootSessionId?: string | undefined;
72
+ readonly rootSessionIncarnation?: string | undefined;
73
+ readonly rootSessionScope?: string | undefined;
74
+ readonly explicitAgentName?: string | undefined;
75
+ } | undefined): LegIdentityRecord | undefined;
76
+ /** A row's `state.legIdentity` read back: absent ⇒ `undefined` (a row of a leg that had none, or of an earlier release); a record
77
+ * whose every member is a non-empty string, with an occupant and a box scope only beside a root and no other key ⇒ that record (a
78
+ * root recorded without its scope — an earlier mint of this line — is read but restores no root); anything else ⇒
79
+ * `"damaged"` — never read as absent, which would resume the leg under identities its park did not record. */
80
+ export declare function readLegIdentityRecord(raw: unknown): LegIdentityRecord | undefined | "damaged";
42
81
  /** The members of the SYNCHRONOUS-CHILD BLOCK a parked row of an earlier release records beside its identity: the spawning run's session
43
82
  * and task, and the delegation tree's root session with the occupant of its row. One tuple, so the row's member-shape table, the summary
44
83
  * and the row judge (a row holding any of them is a synchronous child's — a leg nobody resumes) name the same four. No release mints
@@ -132,7 +171,8 @@ export interface NoticeRoute {
132
171
  /** The keys the notice carries — spread into its detail as-is. */
133
172
  readonly address: NoticeAddress;
134
173
  /** The session address a notice routed away from the leg's own session is for: on a delegated leg addressed to its tree's
135
- * root, the root's id and the root occupant the tree was born under (absent = unknown). A delivery to it is judged like any
174
+ * root, the root's id, the root occupant the tree was born under (absent = unknown) and the scope the root leg works in (its
175
+ * `rootSessionScope`; absent = not recorded — the scope a notice may name a scope's entries to, `withheldEnvUserNotice`). A delivery to it is judged like any
136
176
  * frame addressed there (`PendingSessionNotifications.discardsStaleNotice`). Never spread into a notice: an occupant token
137
177
  * is an addressing fact, not a word the wire carries. Absent when the notice goes to the leg's own session. */
138
178
  readonly destination?: SessionAddress;
@@ -150,6 +190,7 @@ export interface NoticeRoute {
150
190
  export declare function noticeAddressOf(askSource: AskSourceIdentity, root: {
151
191
  readonly rootSessionId?: string;
152
192
  readonly rootSessionIncarnation?: string;
193
+ readonly rootSessionScope?: string;
153
194
  } | undefined): NoticeRoute;
154
195
  /** A leg's user-face notice seat: where its notices go ({@link NoticeRoute}) and the admission every one is delivered under. */
155
196
  export interface LegNotice {
@@ -160,6 +201,14 @@ export interface LegNotice {
160
201
  * announced record. A delegated leg's is its own session's, not its tree root's. */
161
202
  readonly told: NoticeTold;
162
203
  }
204
+ /**
205
+ * The admission every user-face notice of a leg is delivered under: a notice routed to the tree's root is judged against the
206
+ * root's current occupant, named by the leg it came from and its code — one addressed to an occupant the root no longer holds is
207
+ * not admitted (the judge discards it and announces the discard). A top-level leg's notices, and every notice of a leg prepared
208
+ * outside a Runner, are admitted as they are (no predicate). A notice a delegation lane says on a leg's behalf (a spawn's account,
209
+ * `RunnerSelfSeat.emitNotice` with a route) is admitted by this same reading.
210
+ */
211
+ export declare function legNoticeAdmission(route: NoticeRoute, judge: NoticeDestinationJudge | undefined): ((notice: EngineNotice) => boolean) | undefined;
163
212
  /**
164
213
  * The leg's one notice seat, minted ONCE at prepare beside the ask source (`Prepared.legNotice`): every seat that tells the
165
214
  * person something about this leg — the gate's stations, the shell's withheld-variables line — reads this address and this
@@ -168,4 +217,5 @@ export interface LegNotice {
168
217
  export declare function mintLegNotice(askSource: AskSourceIdentity, root: {
169
218
  readonly rootSessionId?: string;
170
219
  readonly rootSessionIncarnation?: string;
220
+ readonly rootSessionScope?: string;
171
221
  } | undefined, judge: NoticeDestinationJudge | undefined, told: NoticeTold): LegNotice;
@@ -1,3 +1,4 @@
1
+ import { strayMembersOf } from "./own-property-receipt.js";
1
2
  export function agentIdOf(identity) {
2
3
  return identity?.isDelegatedChild === true ? identity.taskId : undefined;
3
4
  }
@@ -9,6 +10,47 @@ export function rootAnchorOf(internals, sessionId, ownOccupant) {
9
10
  const occupant = root !== undefined ? internals?.rootSessionIncarnation : ownOccupant;
10
11
  return { sessionId: root ?? sessionId, ...(occupant !== undefined ? { occupant } : {}) };
11
12
  }
13
+ export function hookRootSessionIdOf(internals, sessionId, isDelegatedChild) {
14
+ if (internals?.rootSessionId !== undefined)
15
+ return internals.rootSessionId;
16
+ if (isDelegatedChild || internals?.observerLeg === true)
17
+ return undefined;
18
+ return sessionId;
19
+ }
20
+ const LEG_IDENTITY_MEMBERS = ["declaredTaskId", "parentTaskId", "rootSessionId", "rootSessionIncarnation", "rootSessionScope", "spawnName"];
21
+ const LEG_IDENTITY_WORDS = { subject: "a parked row's leg identity", unit: "member", moment: "when the row is read" };
22
+ const isFilledString = (v) => typeof v === "string" && v !== "";
23
+ export function legIdentityRecordOf(declaredTaskId, internals) {
24
+ const root = internals?.rootSessionId;
25
+ const scope = internals?.rootSessionScope;
26
+ const record = {};
27
+ if (declaredTaskId !== undefined && declaredTaskId !== "")
28
+ record.declaredTaskId = declaredTaskId;
29
+ if (internals?.parentTaskId !== undefined && internals.parentTaskId !== "")
30
+ record.parentTaskId = internals.parentTaskId;
31
+ if (root !== undefined && root !== "" && scope !== undefined && scope !== "") {
32
+ record.rootSessionId = root;
33
+ record.rootSessionScope = scope;
34
+ if (internals?.rootSessionIncarnation !== undefined && internals.rootSessionIncarnation !== "")
35
+ record.rootSessionIncarnation = internals.rootSessionIncarnation;
36
+ }
37
+ if (internals?.explicitAgentName !== undefined && internals.explicitAgentName !== "")
38
+ record.spawnName = internals.explicitAgentName;
39
+ return Object.keys(record).length > 0 ? record : undefined;
40
+ }
41
+ export function readLegIdentityRecord(raw) {
42
+ if (raw === undefined)
43
+ return undefined;
44
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
45
+ return "damaged";
46
+ const keys = Object.keys(raw);
47
+ if (keys.length === 0 || strayMembersOf(raw, LEG_IDENTITY_WORDS, LEG_IDENTITY_MEMBERS) !== undefined)
48
+ return "damaged";
49
+ if (!keys.every((key) => isFilledString(raw[key])))
50
+ return "damaged";
51
+ const record = raw;
52
+ return (record.rootSessionIncarnation !== undefined || record.rootSessionScope !== undefined) && record.rootSessionId === undefined ? "damaged" : record;
53
+ }
12
54
  export const SYNC_CHILD_BLOCK_MEMBERS = Object.freeze(["parentSessionId", "parentTaskId", "rootSessionId", "rootSessionIncarnation"]);
13
55
  export function mintAskSourceIdentity(leg) {
14
56
  const agentId = agentIdOf({ taskId: leg.taskId, isDelegatedChild: leg.isDelegatedChild });
@@ -44,9 +86,10 @@ export function noticeAddressOf(askSource, root) {
44
86
  return { address: { sessionId: own } };
45
87
  const rootId = root?.rootSessionId;
46
88
  const address = { sessionId: rootId ?? own, sourceSessionId: own, ...(askSource.agentId !== undefined ? { agentId: askSource.agentId } : {}) };
47
- return rootId !== undefined && rootId !== own ? { address, destination: { sessionId: rootId, occupant: root?.rootSessionIncarnation } } : { address };
89
+ const scope = root?.rootSessionScope;
90
+ return rootId !== undefined && rootId !== own ? { address, destination: { sessionId: rootId, occupant: root?.rootSessionIncarnation, ...(scope !== undefined ? { scope } : {}) } } : { address };
48
91
  }
49
- function legNoticeAdmission(route, judge) {
92
+ export function legNoticeAdmission(route, judge) {
50
93
  const { address, destination } = route;
51
94
  if (destination === undefined || judge === undefined)
52
95
  return undefined;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * THE LAUNCH CHECK of a run that directs workers and reports to a person (a run that declares a member ledger,
3
+ * `TaskSpec.runLedger`): before it spends anything, read whether the leg has what such a run needs, item by item, and say so —
4
+ * refuse when it cannot do the job at all, narrow (and say how) when it can do part of it, never start a manager that can only
5
+ * repeat its workers' words without saying that it can.
6
+ *
7
+ * A pure function over facts the leg's prepare reads; each item `ok`, `missing`, or `unknown` (the fact could not be read here —
8
+ * never shown as missing, and never a reason to narrow or refuse).
9
+ */
10
+ /** The items, in the order they are read. */
11
+ export declare const MANAGER_LAUNCH_ITEMS: readonly ["background_delegation", "report_tool", "read_hands", "worker_transcript", "isolated_checks", "worker_write_approval", "task_list"];
12
+ export type ManagerLaunchItem = (typeof MANAGER_LAUNCH_ITEMS)[number];
13
+ export type ManagerLaunchState = "ok" | "missing" | "unknown";
14
+ /** `task.manager_launch_narrowed`: the run starts without some of what its job needs (the check's sentence). */
15
+ export declare function managerLaunchNarrowedNotice(c: ManagerLaunchCheck, ids: Record<string, string | undefined>): {
16
+ code: "task.manager_launch_narrowed";
17
+ message: string;
18
+ detail: Record<string, unknown>;
19
+ };
20
+ export interface ManagerLaunchCheck {
21
+ /** `ready`: nothing missing; `narrowed`: something missing that the run can do without (said in `items`); `refused`. */
22
+ readonly verdict: "ready" | "narrowed" | "refused";
23
+ readonly items: ReadonlyArray<{
24
+ readonly item: ManagerLaunchItem;
25
+ readonly state: ManagerLaunchState;
26
+ readonly means?: string;
27
+ }>;
28
+ }
29
+ /** The facts the check reads — each `undefined` when the leg cannot read it. */
30
+ export type ManagerLaunchFacts = Readonly<Record<ManagerLaunchItem, boolean | undefined>>;
31
+ /** The check over its facts — see the module head. */
32
+ export declare function managerLaunchCheck(facts: ManagerLaunchFacts): ManagerLaunchCheck;
33
+ /** What a prepared leg reads for the check: the names on its roster, whether its delegation lane launches in the background and
34
+ * its results come back on a lane, whether a person or a park can take its workers' asks, and whether it is one-shot. */
35
+ export interface ManagerLaunchLegReading {
36
+ readonly names: ReadonlySet<string>;
37
+ readonly backgroundAgents: boolean | undefined;
38
+ readonly completionLane: boolean;
39
+ readonly approver: boolean;
40
+ readonly parkStore: boolean;
41
+ readonly oneShot: boolean;
42
+ }
43
+ /** The check's facts off a prepared leg's reading. A worker's writes have an approval route when the leg has an approver to hand
44
+ * down; they have none when there is no approver, no park store and the run is one-shot (nobody can be asked — the measured
45
+ * `delegation.ask_unresolvable`); every other case is not read here (`unknown`). */
46
+ export declare function managerLaunchFactsOf(r: ManagerLaunchLegReading): ManagerLaunchFacts;
47
+ /** The check as one sentence (the notice's message, the refusal's): what is missing and what that means. */
48
+ export declare function managerLaunchCheckSentence(c: ManagerLaunchCheck): string;