@sema-agent/core 7.69.0 → 7.69.1

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 (309) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/dist/agents/repair-loop.js +6 -14
  3. package/dist/agents/subagent.js +2 -1
  4. package/dist/agents/verify.d.ts +1 -1
  5. package/dist/agents/verify.js +7 -1
  6. package/dist/brain/reasoning-request.d.ts +7 -0
  7. package/dist/brain/reasoning-request.js +6 -0
  8. package/dist/core/agent-config-dir.d.ts +39 -3
  9. package/dist/core/agent-config-dir.js +67 -11
  10. package/dist/core/allow-entry.d.ts +5 -5
  11. package/dist/core/allow-entry.js +12 -6
  12. package/dist/core/ask-headline.d.ts +2 -2
  13. package/dist/core/ask-origin.d.ts +31 -31
  14. package/dist/core/ask-origin.js +20 -13
  15. package/dist/core/attachment-source.d.ts +1 -1
  16. package/dist/core/attachment-source.js +1 -0
  17. package/dist/core/auto-compaction.d.ts +44 -62
  18. package/dist/core/auto-compaction.js +44 -103
  19. package/dist/core/cache-break-detector.d.ts +23 -11
  20. package/dist/core/cache-break-detector.js +11 -5
  21. package/dist/core/checkpoint-features.d.ts +1 -1
  22. package/dist/core/checkpoint-features.js +1 -1
  23. package/dist/core/checkpoint-requirements.d.ts +19 -1
  24. package/dist/core/checkpoint-requirements.js +6 -0
  25. package/dist/core/checkpoint-row-verdict.js +3 -0
  26. package/dist/core/checkpoint-store.d.ts +13 -2
  27. package/dist/core/child-clamp-seats.d.ts +30 -3
  28. package/dist/core/child-clamp-seats.js +24 -0
  29. package/dist/core/compaction-retired-members.d.ts +12 -0
  30. package/dist/core/compaction-retired-members.js +22 -0
  31. package/dist/core/config-refusal-codes.d.ts +1 -1
  32. package/dist/core/config-refusal-codes.js +2 -0
  33. package/dist/core/context-edit.d.ts +32 -17
  34. package/dist/core/context-edit.js +28 -0
  35. package/dist/core/cron.d.ts +68 -0
  36. package/dist/core/cron.js +259 -0
  37. package/dist/core/engine-attestation.d.ts +16 -0
  38. package/dist/core/engine-attestation.js +2 -0
  39. package/dist/core/engine-capabilities.d.ts +14 -1
  40. package/dist/core/engine-capabilities.js +1 -1
  41. package/dist/core/engine-notice.d.ts +18 -7
  42. package/dist/core/engine-version.js +1 -1
  43. package/dist/core/gate-outcome.d.ts +29 -2
  44. package/dist/core/gate-outcome.js +6 -0
  45. package/dist/core/git-read-only.d.ts +10 -0
  46. package/dist/core/git-read-only.js +1 -0
  47. package/dist/core/git-worktree-env.js +9 -8
  48. package/dist/core/governance-codes.d.ts +9 -2
  49. package/dist/core/governance-codes.js +9 -0
  50. package/dist/core/locked-config.js +7 -3
  51. package/dist/core/lsp.d.ts +3 -0
  52. package/dist/core/lsp.js +3 -2
  53. package/dist/core/memory-engine/engine.d.ts +48 -12
  54. package/dist/core/memory-engine/engine.js +108 -46
  55. package/dist/core/memory-engine/file-backend.d.ts +2 -1
  56. package/dist/core/memory-engine/index-copies.d.ts +47 -0
  57. package/dist/core/memory-engine/index-copies.js +88 -0
  58. package/dist/core/memory-engine/layout.d.ts +20 -3
  59. package/dist/core/memory-engine/layout.js +39 -3
  60. package/dist/core/memory-engine/origin-clearance.d.ts +9 -7
  61. package/dist/core/memory-engine/origin-clearance.js +2 -4
  62. package/dist/core/memory-engine/types.d.ts +16 -3
  63. package/dist/core/mode-policy.d.ts +7 -1
  64. package/dist/core/mode-policy.js +9 -0
  65. package/dist/core/mods/session-compact.js +3 -3
  66. package/dist/core/mods/stations.d.ts +2 -0
  67. package/dist/core/mods/stations.js +2 -1
  68. package/dist/core/path-guard-rows.d.ts +8 -3
  69. package/dist/core/path-guard-rows.js +18 -5
  70. package/dist/core/peer-seat.d.ts +3 -0
  71. package/dist/core/peer-seat.js +3 -0
  72. package/dist/core/permission-rule-model.js +3 -2
  73. package/dist/core/process-identity.d.ts +11 -3
  74. package/dist/core/process-identity.js +26 -16
  75. package/dist/core/runner/assemble-result.d.ts +5 -0
  76. package/dist/core/runner/assemble-result.js +1 -1
  77. package/dist/core/runner/cleared-results-record.d.ts +33 -0
  78. package/dist/core/runner/cleared-results-record.js +56 -0
  79. package/dist/core/runner/compact-session.js +14 -9
  80. package/dist/core/runner/compaction-knobs.d.ts +1 -1
  81. package/dist/core/runner/continuation-gate.js +2 -1
  82. package/dist/core/runner/continues-from.d.ts +1 -1
  83. package/dist/core/runner/continues-from.js +1 -1
  84. package/dist/core/runner/contracts.d.ts +83 -31
  85. package/dist/core/runner/conversation-segment.d.ts +19 -12
  86. package/dist/core/runner/conversation-segment.js +27 -7
  87. package/dist/core/runner/derived-route-fallback.d.ts +2 -12
  88. package/dist/core/runner/derived-route-fallback.js +0 -6
  89. package/dist/core/runner/gate-exit.d.ts +2 -1
  90. package/dist/core/runner/gate-exit.js +4 -2
  91. package/dist/core/runner/git-status-frame.d.ts +2 -2
  92. package/dist/core/runner/git-status-frame.js +2 -1
  93. package/dist/core/runner/initial-run-state.js +1 -1
  94. package/dist/core/runner/leg-caller-places.d.ts +39 -0
  95. package/dist/core/runner/leg-caller-places.js +23 -0
  96. package/dist/core/runner/leg-frame.d.ts +8 -2
  97. package/dist/core/runner/leg-receipt.d.ts +29 -2
  98. package/dist/core/runner/leg-receipt.js +37 -6
  99. package/dist/core/runner/media-removed-seat.d.ts +10 -6
  100. package/dist/core/runner/media-removed-seat.js +6 -3
  101. package/dist/core/runner/messages-omitted-seat.d.ts +2 -1
  102. package/dist/core/runner/messages-omitted-seat.js +15 -5
  103. package/dist/core/runner/person-path-rows.d.ts +25 -7
  104. package/dist/core/runner/person-path-rows.js +16 -2
  105. package/dist/core/runner/prefix-ledger.d.ts +120 -0
  106. package/dist/core/runner/prefix-ledger.js +176 -0
  107. package/dist/core/runner/prepare-advisor.d.ts +2 -0
  108. package/dist/core/runner/prepare-advisor.js +2 -1
  109. package/dist/core/runner/prepare-artifact.d.ts +3 -0
  110. package/dist/core/runner/prepare-artifact.js +2 -2
  111. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  112. package/dist/core/runner/prepare-caps-and-workflow.js +4 -3
  113. package/dist/core/runner/prepare-config-doors.d.ts +9 -8
  114. package/dist/core/runner/prepare-config-doors.js +15 -12
  115. package/dist/core/runner/prepare-context-lane.d.ts +25 -6
  116. package/dist/core/runner/prepare-context-lane.js +82 -27
  117. package/dist/core/runner/prepare-gate-stations.d.ts +1 -2
  118. package/dist/core/runner/prepare-gate-stations.js +2 -4
  119. package/dist/core/runner/prepare-hands-readface.d.ts +18 -5
  120. package/dist/core/runner/prepare-hands-readface.js +41 -22
  121. package/dist/core/runner/prepare-inherited-gate.d.ts +5 -0
  122. package/dist/core/runner/prepare-inherited-gate.js +2 -0
  123. package/dist/core/runner/prepare-memory.d.ts +10 -2
  124. package/dist/core/runner/prepare-memory.js +51 -5
  125. package/dist/core/runner/prepare-policy-chain.d.ts +3 -0
  126. package/dist/core/runner/prepare-policy-chain.js +13 -2
  127. package/dist/core/runner/prepare-prompt-assembly.d.ts +12 -4
  128. package/dist/core/runner/prepare-prompt-assembly.js +10 -4
  129. package/dist/core/runner/prepare-prompt-inputs.d.ts +3 -7
  130. package/dist/core/runner/prepare-prompt-inputs.js +6 -7
  131. package/dist/core/runner/prepare-safety-scan.js +7 -0
  132. package/dist/core/runner/prepare-suspend-saga.d.ts +4 -0
  133. package/dist/core/runner/prepare-suspend-saga.js +3 -2
  134. package/dist/core/runner/prepare-task.js +59 -53
  135. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +5 -11
  136. package/dist/core/runner/prepare-tool-disclosure-mount.js +7 -8
  137. package/dist/core/runner/prepare-turn-wiring.d.ts +16 -25
  138. package/dist/core/runner/prepare-turn-wiring.js +8 -18
  139. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  140. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  141. package/dist/core/runner/prompt-suggestions.d.ts +3 -1
  142. package/dist/core/runner/prompt-suggestions.js +1 -1
  143. package/dist/core/runner/read-block-judge.d.ts +47 -0
  144. package/dist/core/runner/read-block-judge.js +33 -0
  145. package/dist/core/runner/role-resolution-table.d.ts +15 -10
  146. package/dist/core/runner/role-resolution-table.js +4 -5
  147. package/dist/core/runner/rule-store-unreadable-notice.d.ts +7 -4
  148. package/dist/core/runner/rule-store-unreadable-notice.js +4 -3
  149. package/dist/core/runner/run-compaction-machinery.d.ts +0 -10
  150. package/dist/core/runner/run-compaction-machinery.js +3 -39
  151. package/dist/core/runner/run-harness-handlers.js +4 -17
  152. package/dist/core/runner/run-identity-wiring.js +4 -1
  153. package/dist/core/runner/run-leg.js +11 -1
  154. package/dist/core/runner/run-recovery-lanes.d.ts +0 -4
  155. package/dist/core/runner/run-recovery-lanes.js +34 -18
  156. package/dist/core/runner/run-settle-and-teardown.d.ts +1 -3
  157. package/dist/core/runner/run-settle-and-teardown.js +14 -22
  158. package/dist/core/runner/run-telemetry-and-budget-seats.js +0 -1
  159. package/dist/core/runner/run-terminal-adoption.d.ts +11 -30
  160. package/dist/core/runner/run-terminal-adoption.js +5 -88
  161. package/dist/core/runner/run-tool-mount-facts.js +1 -5
  162. package/dist/core/runner/run-turn-boundary.js +56 -26
  163. package/dist/core/runner/runtask.js +7 -7
  164. package/dist/core/runner/session-hash-salt.d.ts +18 -0
  165. package/dist/core/runner/session-hash-salt.js +36 -0
  166. package/dist/core/runner/shell-env-withheld.d.ts +8 -5
  167. package/dist/core/runner/shell-env-withheld.js +3 -3
  168. package/dist/core/runner/side-call-account.d.ts +9 -1
  169. package/dist/core/runner/side-call-account.js +15 -4
  170. package/dist/core/runner/skill-mention.d.ts +12 -0
  171. package/dist/core/runner/skill-mention.js +50 -0
  172. package/dist/core/runner/stream-settle-backstop.js +1 -0
  173. package/dist/core/runner/synthetic-tools.js +2 -2
  174. package/dist/core/runner/tool-table-view.d.ts +5 -9
  175. package/dist/core/runner/tool-table-view.js +23 -21
  176. package/dist/core/runner/write-protection-station.d.ts +5 -2
  177. package/dist/core/runner/write-protection-station.js +1 -1
  178. package/dist/core/runner-deps.d.ts +25 -27
  179. package/dist/core/scheduler.d.ts +13 -3
  180. package/dist/core/scheduler.js +0 -12
  181. package/dist/core/secret-env.d.ts +47 -11
  182. package/dist/core/secret-env.js +65 -4
  183. package/dist/core/sensitive-path-policy.js +4 -0
  184. package/dist/core/session-checkout.js +10 -9
  185. package/dist/core/shell-read-silence.d.ts +2 -1
  186. package/dist/core/shell-run-candidates.d.ts +1 -1
  187. package/dist/core/shell-run-candidates.js +11 -3
  188. package/dist/core/task-event.d.ts +32 -10
  189. package/dist/core/task-intake.d.ts +5 -3
  190. package/dist/core/task-intake.js +6 -2
  191. package/dist/core/task-result.d.ts +39 -0
  192. package/dist/core/task-spec-members.d.ts +3 -0
  193. package/dist/core/task-spec-members.js +2 -2
  194. package/dist/core/task-spec.d.ts +37 -20
  195. package/dist/core/tool-policy.d.ts +30 -18
  196. package/dist/core/tool-policy.js +44 -32
  197. package/dist/core/tool-roster.d.ts +21 -7
  198. package/dist/core/tool-roster.js +34 -6
  199. package/dist/core/tool-spec-members.js +1 -1
  200. package/dist/core/tool-spec.d.ts +27 -0
  201. package/dist/core/tools.js +1 -0
  202. package/dist/core/trace.d.ts +42 -19
  203. package/dist/core/unc-spelling.d.ts +31 -0
  204. package/dist/core/unc-spelling.js +51 -0
  205. package/dist/core/wiring-manifest.d.ts +30 -3
  206. package/dist/core/wiring-manifest.js +10 -0
  207. package/dist/core/workflow-run-store-contract.js +22 -0
  208. package/dist/core/workflow-run-store.d.ts +17 -13
  209. package/dist/core/workflow-run-store.js +1 -1
  210. package/dist/core/write-protect.d.ts +4 -0
  211. package/dist/core/write-protect.js +17 -15
  212. package/dist/engine/compaction/compaction.d.ts +48 -98
  213. package/dist/engine/compaction/compaction.js +136 -216
  214. package/dist/engine/compaction/utils.d.ts +2 -11
  215. package/dist/engine/compaction/utils.js +4 -13
  216. package/dist/engine/execution-env/node-execution-env.js +17 -6
  217. package/dist/engine/harness/agent-harness.d.ts +19 -5
  218. package/dist/engine/harness/agent-harness.js +18 -7
  219. package/dist/engine/harness/types.d.ts +5 -7
  220. package/dist/engine/loop/agent-loop.d.ts +14 -1
  221. package/dist/engine/loop/agent-loop.js +31 -11
  222. package/dist/engine/loop/types.d.ts +8 -2
  223. package/dist/index.d.ts +9 -6
  224. package/dist/index.js +8 -6
  225. package/dist/internal/harness-types.d.ts +1 -1
  226. package/dist/internal/harness.d.ts +1 -1
  227. package/dist/internal/harness.js +1 -1
  228. package/dist/orchestration/run-spec.js +7 -2
  229. package/dist/orchestration/run-workflow-tool.js +5 -3
  230. package/dist/orchestration/workflow-park-adoption.d.ts +66 -8
  231. package/dist/orchestration/workflow-park-adoption.js +195 -45
  232. package/dist/orchestration/workflow-types.d.ts +20 -0
  233. package/dist/orchestration/workflow-types.js +1 -0
  234. package/dist/orchestration/workflow.d.ts +3 -2
  235. package/dist/orchestration/workflow.js +10 -4
  236. package/dist/prompt-assembly/catalog/core-behavior.js +6 -0
  237. package/dist/prompt-assembly/catalog/events.d.ts +8 -0
  238. package/dist/prompt-assembly/catalog/locales/zh-Hans/core-behavior.js +6 -0
  239. package/dist/prompt-assembly/catalog/locales/zh-Hans/mechanism.js +1 -0
  240. package/dist/prompt-assembly/catalog/mechanism.d.ts +8 -0
  241. package/dist/prompt-assembly/catalog/mechanism.js +1 -0
  242. package/dist/prompt-assembly/catalog/schema.d.ts +1 -1
  243. package/dist/prompt-assembly/catalog/schema.js +1 -0
  244. package/dist/prompt-assembly/catalog/sections.js +8 -0
  245. package/dist/prompt-assembly/event-registry.js +1 -0
  246. package/dist/prompt-assembly/select.js +1 -0
  247. package/dist/prompt-assembly/turn-snapshot.d.ts +14 -27
  248. package/dist/prompt-assembly/turn-snapshot.js +6 -18
  249. package/dist/prompt-assembly/types.d.ts +3 -0
  250. package/dist/prompts/default.d.ts +9 -0
  251. package/dist/prompts/default.js +4 -0
  252. package/dist/shell/lex.d.ts +75 -11
  253. package/dist/shell/lex.js +340 -76
  254. package/dist/tools/fs/bash-program-position.js +2 -6
  255. package/dist/tools/fs/bash-readonly-classifier.d.ts +18 -3
  256. package/dist/tools/fs/bash-readonly-classifier.js +19 -9
  257. package/dist/tools/fs/containment-face.d.ts +12 -3
  258. package/dist/tools/fs/containment-face.js +16 -7
  259. package/dist/tools/fs/file-read-check.d.ts +26 -1
  260. package/dist/tools/fs/file-read-check.js +20 -2
  261. package/dist/tools/fs/fs-bash.js +4 -4
  262. package/dist/tools/fs/fs-read.d.ts +3 -0
  263. package/dist/tools/fs/fs-read.js +2 -2
  264. package/dist/tools/fs/fs-search-tools.d.ts +2 -2
  265. package/dist/tools/fs/fs-search-tools.js +4 -4
  266. package/dist/tools/fs/index.js +5 -3
  267. package/dist/tools/fs/pdf.js +12 -4
  268. package/dist/tools/fs/read-deny-home.d.ts +13 -2
  269. package/dist/tools/fs/read-deny-home.js +26 -22
  270. package/dist/tools/fs/read-deny.js +15 -6
  271. package/dist/tools/fs/removal-targets.d.ts +33 -17
  272. package/dist/tools/fs/removal-targets.js +160 -61
  273. package/dist/tools/fs/repo-map.d.ts +1 -1
  274. package/dist/tools/fs/repo-map.js +2 -2
  275. package/dist/tools/fs/safety.d.ts +28 -5
  276. package/dist/tools/fs/safety.js +72 -8
  277. package/dist/tools/fs/shell-read-bindings.d.ts +8 -2
  278. package/dist/tools/fs/shell-read-bindings.js +25 -6
  279. package/dist/tools/fs/shell-read-check.d.ts +3 -0
  280. package/dist/tools/fs/shell-read-check.js +22 -4
  281. package/dist/tools/fs/shell-read-establish.js +73 -43
  282. package/dist/tools/fs/shell-read-judge.d.ts +32 -14
  283. package/dist/tools/fs/shell-read-judge.js +13 -5
  284. package/dist/tools/fs/shell-read-object-path.d.ts +5 -1
  285. package/dist/tools/fs/shell-read-object-path.js +17 -4
  286. package/dist/tools/fs/shell-read-plan.d.ts +8 -2
  287. package/dist/tools/fs/shell-read-plan.js +36 -22
  288. package/dist/tools/fs/shell-read-sourced.js +12 -4
  289. package/dist/tools/fs/shell-read-start.d.ts +4 -2
  290. package/dist/tools/fs/shell-read-start.js +3 -3
  291. package/dist/tools/fs/shell-read-workdir.d.ts +14 -6
  292. package/dist/tools/fs/shell-read-workdir.js +35 -17
  293. package/dist/tools/scheduler-tools.d.ts +7 -17
  294. package/dist/tools/scheduler-tools.js +9 -85
  295. package/dist/tools/worktree.js +5 -4
  296. package/package.json +3 -2
  297. package/test/export-surface.snapshot.json +47 -1
  298. package/wire-changes/core-stores-sql@7.68.6.json +39 -0
  299. package/wire-changes/core-stores-sql@7.69.1.json +39 -0
  300. package/wire-changes/core@7.68.6.json +125 -0
  301. package/wire-changes/core@7.69.1.json +2561 -0
  302. package/wire-changes/mods-kernel@7.68.6.json +39 -0
  303. package/wire-changes/mods-kernel@7.69.1.json +39 -0
  304. package/wire-changes/primitives@7.68.6.json +39 -0
  305. package/wire-changes/primitives@7.69.1.json +39 -0
  306. package/wire-changes/wiki-gate@7.68.6.json +39 -0
  307. package/wire-changes/wiki-gate@7.69.1.json +39 -0
  308. package/dist/core/runner/prompt-hash-salt.d.ts +0 -1
  309. package/dist/core/runner/prompt-hash-salt.js +0 -2
@@ -8,6 +8,11 @@
8
8
  * definitions a delegation or workflow tool of the roster was made with are read off the very entries the leg mounts;
9
9
  * - `agents` — the list read once, each per-task definition copied whole ({@link snapshotDefinitionLists}) or refused on its own.
10
10
  *
11
+ * And first, before anything of the spec, the declarations the Runner itself holds ({@link receiveHeldDeclarations}): before a leg
12
+ * starts, every declaration its Runner holds has passed its receipt — whether or not the leg mounts the tool that would use it. The
13
+ * MCP servers and A2A peers whose credential references the receipt takes in are the leg's own: the person told why its shell lacks a
14
+ * variable is given the names of the entries this receipt took in for that very variable, never another leg's ({@link LegReceipt.peerEntries}).
15
+ *
11
16
  * The leg holds every reference this receipt names ({@link legDeclarations}, the one keeper reading `heldDeclarationsOf`) from the call
12
17
  * until its stream settles, and every door of its prepare judges this same receipt: what a leg holds, what it mounts and what it dials
13
18
  * are one read. A refusal is kept and raised by the door that judges it, where it would have been raised. A prepare entered without
@@ -16,19 +21,41 @@
16
21
  import type { AgentDefinition, RunnerDeps, TaskSpec } from "../types.js";
17
22
  import type { PeerDeclarations } from "../peer-seat.js";
18
23
  import { type Received, type ReceivedPeerDeclarations } from "../locked-config.js";
24
+ import { type PeerEntriesTaken } from "../secret-env.js";
19
25
  import { snapshotCallerRoster } from "./caller-roster.js";
26
+ /**
27
+ * Declarations held before a leg receives them as part of its spec, each through the receipt that reads it where it is used, so what
28
+ * their MCP servers' and A2A peers' credential references name is taken in (locked-config.ts `snapshotDeclaredEntry`) before a child is
29
+ * spawned: agent definitions (`agents`) through the definition receipt ({@link snapshotDefinitionLists} — the delegation tool's and the
30
+ * workflow tool's), and a workflow governance baseline (`workflowGovernanceBaseline`) through the baseline's
31
+ * ({@link receiveGovernanceBaseline} — the workflow tool's). Called first by every leg's receipt ({@link receiveLeg}) with what the Runner
32
+ * holds of its own (`RunnerDeps.agents`, `RunnerDeps.workflowGovernanceBaseline`), and by `runSpec` with its task's definitions before
33
+ * its preflight.
34
+ *
35
+ * Nothing is refused here and this never throws: a declaration its receipt refuses is refused where it is received to be used (the
36
+ * delegation tool's assembly, the workflow tool's mount, the leg's door), exactly as before; here what the receipt read before its
37
+ * refusal stands, and every other one is received on its own. Every leg receives them again, as they stand at its receipt: there is no
38
+ * memo, so a declaration the host edits or adds after an earlier leg is taken in by the next leg's receipt.
39
+ */
40
+ export declare function receiveHeldDeclarations(held: {
41
+ readonly agents?: unknown;
42
+ readonly workflowGovernanceBaseline?: unknown;
43
+ }): void;
20
44
  /** What a leg received of its spec at the call (see the module note). */
21
45
  export interface LegReceipt extends ReceivedPeerDeclarations {
22
46
  /** The tool roster's one snapshot, or the refusal it met (raised as prepare's first refusal). */
23
47
  readonly roster: Received<ReturnType<typeof snapshotCallerRoster>>;
24
48
  /** `TaskSpec.agents`: absent when the task carries none; else the list read once, each definition copied whole or refused on its own. */
25
49
  readonly agents?: Received<readonly Received<AgentDefinition>[]>;
50
+ /** The entries whose credential references this receipt took in, per variable they name, as a sentence names each entry (`MCP server "acme"`):
51
+ * the (variable, entry) pairs the leg's person is told an entry of by name (secret-env.ts {@link peerEntriesTakenIn}). */
52
+ readonly peerEntries: PeerEntriesTaken;
26
53
  }
27
54
  /** Take a leg's receipt of `spec` (see the module note). Never throws for a spec that is an object. */
28
- export declare function receiveLeg(spec: TaskSpec, deps: Pick<RunnerDeps, "lockedConfig">): LegReceipt;
55
+ export declare function receiveLeg(spec: TaskSpec, deps: Pick<RunnerDeps, "lockedConfig" | "agents" | "workflowGovernanceBaseline">): LegReceipt;
29
56
  /** Prepare's receipt — the one the Runner took at the call, or (prepare outside a Runner) one taken now by {@link receiveLeg} — and its
30
57
  * roster snapshot, the snapshot's refusal raised here, as prepare's first. */
31
- export declare function receiptAtPrepare(taken: LegReceipt | undefined, spec: TaskSpec, deps: Pick<RunnerDeps, "lockedConfig">): {
58
+ export declare function receiptAtPrepare(taken: LegReceipt | undefined, spec: TaskSpec, deps: Pick<RunnerDeps, "lockedConfig" | "agents" | "workflowGovernanceBaseline">): {
32
59
  readonly receipt: LegReceipt;
33
60
  readonly callerRoster: ReturnType<typeof snapshotCallerRoster>;
34
61
  };
@@ -1,14 +1,45 @@
1
1
  import { readCallerSpec } from "../task-spec-members.js";
2
2
  import { receivePeerDeclarations, receivedDeclarations, received, receiving } from "../locked-config.js";
3
3
  import { heldDeclarationsOf, snapshotDefinitionLists } from "../../agents/agent-definition.js";
4
+ import { receiveGovernanceBaseline } from "../../orchestration/governance-baseline-validity.js";
5
+ import { peerEntriesTakenIn } from "../secret-env.js";
4
6
  import { snapshotCallerRoster } from "./caller-roster.js";
7
+ const guarded = (read) => {
8
+ try {
9
+ return read();
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ };
15
+ function receiveHeld(read, receipt) {
16
+ const held = guarded(read);
17
+ if ((typeof held === "object" || typeof held === "function") && held !== null)
18
+ guarded(() => receipt(held));
19
+ }
20
+ export function receiveHeldDeclarations(held) {
21
+ const definitions = guarded(() => {
22
+ const listed = held.agents;
23
+ return Array.isArray(listed) ? listed : undefined;
24
+ });
25
+ if (definitions !== undefined) {
26
+ const count = guarded(() => definitions.length);
27
+ for (let i = 0; typeof count === "number" && i < count; i++)
28
+ receiveHeld(() => definitions[i], (definition) => snapshotDefinitionLists(definition));
29
+ }
30
+ receiveHeld(() => held.workflowGovernanceBaseline, (baseline) => receiveGovernanceBaseline(baseline));
31
+ }
5
32
  export function receiveLeg(spec, deps) {
6
- const taken = readCallerSpec(spec).spec;
7
- const peers = receivePeerDeclarations(taken, deps);
8
- const roster = receiving(() => snapshotCallerRoster(taken));
9
- const listed = taken.agents;
10
- const agents = listed === undefined ? undefined : receiving(() => listed.map((definition) => receiving(() => snapshotDefinitionLists(definition))));
11
- return { ...peers, roster, ...(agents !== undefined ? { agents } : {}) };
33
+ const { value, entries } = peerEntriesTakenIn(() => {
34
+ receiveHeldDeclarations(deps);
35
+ const taken = readCallerSpec(spec).spec;
36
+ const peers = receivePeerDeclarations(taken, deps);
37
+ const roster = receiving(() => snapshotCallerRoster(taken));
38
+ const listed = taken.agents;
39
+ const agents = listed === undefined ? undefined : receiving(() => listed.map((definition) => receiving(() => snapshotDefinitionLists(definition))));
40
+ return { ...peers, roster, ...(agents !== undefined ? { agents } : {}) };
41
+ });
42
+ return { ...value, peerEntries: entries };
12
43
  }
13
44
  export function receiptAtPrepare(taken, spec, deps) {
14
45
  const receipt = taken ?? receiveLeg(spec, deps);
@@ -23,24 +23,28 @@ import type { Prepared } from "./contracts.js";
23
23
  import type { NoticeSeatInput } from "./notice-seat-input.js";
24
24
  /** The session's announced record and the leg's receipt ledger (the parked write). */
25
25
  export type MediaBudgetRecord = Pick<Prepared, "announcedListingsRef" | "frameReceipts">;
26
- /** The provider-refusal account: one notice per refusal, once per run. */
27
- export declare function createProviderRefusalSeat(ids: NoticeSeatInput): (removals: readonly RejectedImageRemoval[]) => void;
26
+ /** The provider-refusal account: one notice per refusal, once per run. A refusal met for the first time is the request that
27
+ * re-sends the turn without those images — a rewrite of what the refused request carried: `onNewlyRemoved` is told (before
28
+ * that request leaves). */
29
+ export declare function createProviderRefusalSeat(ids: NoticeSeatInput, onNewlyRemoved?: () => void): (removals: readonly RejectedImageRemoval[]) => void;
28
30
  /**
29
31
  * The run's account of a tool whose input schema a provider refused (`context.tool_schema_removed`, user): the loop re-sent
30
32
  * the turn with that tool's parameters taken out of what the model sees (`engine/llm/rejected-images.ts`), and every later
31
33
  * request built from a transcript the refusal's record stands in sends it so. ONCE PER REFUSAL (`refusalAt`): the loop
32
- * re-sends once per refusal, and a refusal recorded before the run began is never re-sent, so never announced again.
34
+ * re-sends once per refusal, and a refusal recorded before the run began is never re-sent, so never announced again. The
35
+ * re-send's tool table is not the refused request's: `onNewlyRemoved` is told once per refusal, before the re-send leaves.
33
36
  */
34
37
  export declare function createToolSchemaRemovedSeat(onNotice: ((notice: EngineNotice) => void) | undefined, ids: {
35
38
  sessionId: string;
36
39
  runId: string;
37
- }): (refusal: {
40
+ }, onNewlyRemoved?: () => void): (refusal: {
38
41
  tool: string;
39
42
  refusalAt: number;
40
43
  }) => void;
41
44
  /** The request budget's account of one request view the trim cut: its trace frame, then — of the blocks it left out, those
42
- * the session was not yet told of — one notice. */
45
+ * the session was not yet told of — one notice. Those blocks are the newly cut ones (the trim takes the oldest first, so
46
+ * each sat in an earlier message the previous request carried whole): `onNewlyRemoved` is told, before the view leaves. */
43
47
  export declare function createMediaBudgetSeat(ids: NoticeSeatInput, record: MediaBudgetRecord, trace: {
44
48
  readonly tracer: TracerHook | undefined;
45
49
  readonly taskId: string;
46
- }): (trim: RequestMediaTrim, limits: RequestMediaLimits) => void;
50
+ }, onNewlyRemoved?: () => void): (trim: RequestMediaTrim, limits: RequestMediaLimits) => void;
@@ -17,23 +17,25 @@ function announceMediaRemoved(ids, reason, images, documents) {
17
17
  `The session still holds the original; to show the model ${it} again, read the file again or send ${it} again. Said once per image or document per conversation.`;
18
18
  deliverEngineNotice(ids.onNotice, { code: MEDIA_REMOVED, message, detail: { reason, images, documents, sessionId: ids.sessionId, runId: ids.runId } });
19
19
  }
20
- export function createProviderRefusalSeat(ids) {
20
+ export function createProviderRefusalSeat(ids, onNewlyRemoved) {
21
21
  const announced = new Set();
22
22
  return (removals) => {
23
23
  for (const { refusalAt, images } of removals) {
24
24
  if (announced.has(refusalAt))
25
25
  continue;
26
26
  announced.add(refusalAt);
27
+ onNewlyRemoved?.();
27
28
  announceMediaRemoved(ids, "rejected_by_provider", images, 0);
28
29
  }
29
30
  };
30
31
  }
31
- export function createToolSchemaRemovedSeat(onNotice, ids) {
32
+ export function createToolSchemaRemovedSeat(onNotice, ids, onNewlyRemoved) {
32
33
  const announced = new Set();
33
34
  return ({ tool, refusalAt }) => {
34
35
  if (announced.has(refusalAt))
35
36
  return;
36
37
  announced.add(refusalAt);
38
+ onNewlyRemoved?.();
37
39
  const name = inlineUntrusted(tool, 160);
38
40
  deliverEngineNotice(onNotice, {
39
41
  code: "context.tool_schema_removed",
@@ -44,7 +46,7 @@ export function createToolSchemaRemovedSeat(onNotice, ids) {
44
46
  });
45
47
  };
46
48
  }
47
- export function createMediaBudgetSeat(ids, record, trace) {
49
+ export function createMediaBudgetSeat(ids, record, trace, onNewlyRemoved) {
48
50
  const lookedAt = new WeakSet();
49
51
  return ({ removed, removedBase64Chars, items, base64Chars }, { maxItems, budgetBase64Chars }) => {
50
52
  const cutImages = removed.filter((r) => r.type === "image").length;
@@ -81,6 +83,7 @@ export function createMediaBudgetSeat(ids, record, trace) {
81
83
  }
82
84
  if (fresh.size === 0)
83
85
  return;
86
+ onNewlyRemoved?.();
84
87
  announceMediaRemoved(ids, "media_budget", images, documents);
85
88
  record.announcedListingsRef.advisories = withAnnounceDigests(record.announcedListingsRef.advisories, [...fresh]);
86
89
  record.frameReceipts.listingSnapshotOwed = true;
@@ -1,2 +1,3 @@
1
+ import type { InTurnCompactionVerdict } from "./contracts.js";
1
2
  import type { NoticeSeatInput } from "./notice-seat-input.js";
2
- export declare function createMessagesOmittedSeat(ids: NoticeSeatInput): (omitted: number) => void;
3
+ export declare function createMessagesOmittedSeat(ids: NoticeSeatInput): (omitted: number, compaction?: InTurnCompactionVerdict) => void;
@@ -1,7 +1,17 @@
1
1
  import { deliverEngineNotice } from "../engine-notice.js";
2
+ const ACCOUNT = {
3
+ landed: { why: "Compaction ran but did not bring this conversation under what the model can read in one request", out: "The newest messages alone are too large: start a new conversation, or send less at once (large tool results, attachments)." },
4
+ noop: { why: "Compaction found nothing older to summarize, and this conversation does not fit what the model can read in one request", out: "The newest messages alone are too large: start a new conversation, or send less at once (large tool results, attachments)." },
5
+ failed: { why: "Compaction failed (its summary did not land), and this conversation does not fit what the model can read in one request", out: "Compact the conversation again, or start a new conversation." },
6
+ paused: { why: "Compaction is paused after failing several times in a row, and this conversation does not fit what the model can read in one request", out: "Compact the conversation by hand, or start a new conversation." },
7
+ off: { why: "Automatic compaction is off for this run, and this conversation does not fit what the model can read in one request", out: "Compact the conversation by hand, or turn automatic compaction on." },
8
+ suppressed: { why: "Compaction ran recently and freed too little to run again yet, and this conversation does not fit what the model can read in one request", out: "It runs again once the conversation grows further; compact it by hand to run it now." },
9
+ cut: { why: "Compaction was stopped, and this conversation does not fit what the model can read in one request", out: "Compact the conversation, or start a new conversation." },
10
+ unknown: { why: "This conversation no longer fits what the model can read in one request, and compaction did not make it fit", out: "Compact the conversation, or start a new conversation." },
11
+ };
2
12
  export function createMessagesOmittedSeat(ids) {
3
13
  let inStretch = false;
4
- return (omitted) => {
14
+ return (omitted, compaction) => {
5
15
  if (omitted <= 0) {
6
16
  inStretch = false;
7
17
  return;
@@ -10,12 +20,12 @@ export function createMessagesOmittedSeat(ids) {
10
20
  return;
11
21
  inStretch = true;
12
22
  const what = omitted === 1 ? "1 earlier message was" : `${omitted} earlier messages were`;
23
+ const { why, out } = ACCOUNT[compaction ?? "unknown"];
13
24
  deliverEngineNotice(ids.onNotice, {
14
25
  code: "context.messages_omitted",
15
- message: `This conversation no longer fits what the model can read in one request, and compaction did not make it fit, so ${what} ` +
16
- `left out of what the model sees (the oldest go first; the model is told that earlier messages were omitted). The session ` +
17
- `still holds every message. Said once until a request fits again.`,
18
- detail: { omitted, sessionId: ids.sessionId, runId: ids.runId },
26
+ message: `${why}, so ${what} left out of what the model sees (the oldest go first; the model is told that earlier messages were ` +
27
+ `omitted). The session still holds every message. ${out} Said once until a request fits again.`,
28
+ detail: { omitted, ...(compaction !== undefined ? { compaction } : {}), sessionId: ids.sessionId, runId: ids.runId },
19
29
  });
20
30
  };
21
31
  }
@@ -179,19 +179,25 @@ export interface PersonPathRowsConfig {
179
179
  export declare function createPersonPathRows(cfg: PersonPathRowsConfig): PersonPathRows;
180
180
  /** The compile of a run's path tables over the leg's own rows beside one set of the person's: every row also judged where
181
181
  * its head leads in this environment; the home-anchored and rooted rows placed at their homes and where they lead (the
182
- * host's declared configuration root among them); the write face over the same rows with the read table's home views;
183
- * the person's read directories canonicalized by `canonicalize` (the leg's admission of a declared read root). */
182
+ * leg's declared configuration roots and its caller's homes among them); the write face over the same rows with the read
183
+ * table's home views; the person's read directories canonicalized by `canonicalize` (the leg's admission of a declared read root). */
184
184
  export declare function pathTablesCompile(seats: {
185
185
  readonly env: ExecutionEnv;
186
186
  readonly additions: readonly ReadDenyEntry[];
187
187
  readonly builtin: ReadDenyBuiltinConfig;
188
188
  readonly legRows: readonly PathRuleDenyRow[];
189
189
  readonly leads: HeadLeads;
190
- readonly configRoot: string | undefined;
190
+ readonly configRoots: readonly string[];
191
+ readonly callerHomes: readonly string[];
191
192
  readonly canonicalize: (dirs: readonly string[]) => Promise<readonly string[]>;
192
193
  }): (person: PersonTableRows) => Promise<PathTables>;
194
+ /** Whether a leg's read roots take the person's read directories: `honored` (the person's `Read(//dir/**)` allow rows widen the
195
+ * roots), or `set_aside` (a leg that refuses reads outside its declared directories — `TaskSpec.blockReadsOutsideRoots` —
196
+ * reads its own roots alone, whatever the person's rows say). */
197
+ export type PersonDirectories = "honored" | "set_aside";
193
198
  /** The read face's root set over the leg's own roots (`own`, read per judgment) and the person's read directories — a
194
- * call's own (`forCall`) or the run's latest. A person's directory that admits any part of the local artifact store
199
+ * call's own (`forCall`) or the run's latest, both through one composition (`personDirectories` is read there, so neither
200
+ * reading can take a directory the other sets aside). A person's directory that admits any part of the local artifact store
195
201
  * (`store`, once known) is no read root: the store rule an in-flight grant meets; `onHeld` hears each such directory once. */
196
202
  export declare function readRootsOver(seats: {
197
203
  readonly own: () => readonly string[];
@@ -199,6 +205,7 @@ export declare function readRootsOver(seats: {
199
205
  readonly ready: PersonPathRows["tablesReady"];
200
206
  readonly store: () => string | undefined;
201
207
  readonly onHeld: (dir: string, store: string) => void;
208
+ readonly personDirectories: PersonDirectories;
202
209
  }): ReadRootsSeat;
203
210
  /** The deny seats a shell read boundary carries for one compiled table pair, through the ONE adapter every face mounting a
204
211
  * deny table uses (`readDenySeat`: zero entries is no judge), resolved once per table. */
@@ -211,9 +218,10 @@ export declare function denySeatsOf(t: PathTables): {
211
218
  readonly write: WriteDenySeat;
212
219
  };
213
220
  /**
214
- * The leg's read stations as ONE gate input, each judgment on its call's pinned read of the person's rules: a station is
215
- * a call's first consumer of the person's rows (it sits in the fold, ahead of the rule lanes), so it takes the call's
216
- * read before it judges — the read every later consumer of the call is handed — and judges with that read's tables. A
221
+ * The leg's read stations as ONE gate input, each judgment on its call's pinned read of the person's rules: the station in
222
+ * the fold judges ahead of the rule lanes, so it takes the call's read before it judges — the read every later consumer of
223
+ * the call is handed — and judges with that read's tables (a judgment of the same call ahead of the fold, where an inherited
224
+ * station settles an ancestor's question, takes no read: {@link onNewestRead}). A
217
225
  * judgment that is no call of the leg (no id, or one the leg does not hold) takes no read and judges with the run's
218
226
  * newest tables once they are ready, as every reader that is no call does; a judged call the station finds nothing to
219
227
  * read in is vouched for, as it would have been. (A partition of those rows that could not be read reaches the station on
@@ -223,6 +231,16 @@ export declare function onPinnedRead(rows: PersonPathRows, stations: ReadonlyArr
223
231
  readonly check: ShellReadCheck;
224
232
  readonly tools: ReadonlySet<string>;
225
233
  }>): ShellReadCheck | undefined;
234
+ /**
235
+ * One read station judged ahead of the gate's fold — where an inherited station settles an ancestor's question about a call
236
+ * before the call reaches the station's own seat: the run's newest tables, once they are ready, and no read taken (a call's
237
+ * pinned read belongs to the bytes its fold judges, and the bytes judged here may still be rewritten before that). A
238
+ * judgment the station finds nothing to read in is vouched for.
239
+ */
240
+ export declare function onNewestRead(rows: PersonPathRows, station: {
241
+ readonly check: ShellReadCheck;
242
+ readonly tools: ReadonlySet<string>;
243
+ }): ShellReadCheck;
226
244
  /** A tool that holds the run's tables, run once the tables it reads are compiled (or the call is cancelled) — the tool
227
245
  * reads its call's own (`seatForCall`) at the start of its execution; a call no gate consumer pinned reads the run's
228
246
  * newest. The wait is bounded ({@link PATH_TABLES_READY_BOUND_MS}). */
@@ -329,13 +329,14 @@ export function pathTablesCompile(seats) {
329
329
  return async (person) => {
330
330
  const rows = [...seats.legRows, ...person.denyRows];
331
331
  const led = rowsWhereTheyLead(rows, await seats.leads.resolve(rows));
332
- const placed = await placeReadDenyAtHome(seats.env, (homes, linked) => compileReadDeny(seats.additions, "readDenyPatterns", seats.builtin, led, homes, linked), undefined, undefined, seats.configRoot);
332
+ const placed = await placeReadDenyAtHome(seats.env, (homes, linked) => compileReadDeny(seats.additions, "readDenyPatterns", seats.builtin, led, homes, linked), undefined, undefined, { configRoots: seats.configRoots, callerHomes: seats.callerHomes });
333
333
  return { readDeny: placed.matcher, writeDeny: carryHomeViews(compileWriteDeny(led), placed.matcher.homeViews), readDirectories: [...new Set(await seats.canonicalize(person.readDirectories))], ruleRows: rows };
334
334
  };
335
335
  }
336
336
  export function readRootsOver(seats) {
337
337
  const said = new Set();
338
- const rootsOf = (personDirs) => {
338
+ const rootsOf = (rowDirs) => {
339
+ const personDirs = seats.personDirectories === "set_aside" ? [] : rowDirs;
339
340
  const own = seats.own();
340
341
  const store = seats.store();
341
342
  const held = store === undefined ? [] : personDirs.filter((k) => !own.includes(k) && rootAdmittingArtifactStore(store, [k]) !== undefined);
@@ -375,6 +376,19 @@ export function onPinnedRead(rows, stations) {
375
376
  unanswered: (call, cause) => check.unanswered(call, cause),
376
377
  };
377
378
  }
379
+ export function onNewestRead(rows, station) {
380
+ const { check } = station;
381
+ if (!rows.holdsPersonRows)
382
+ return check;
383
+ return {
384
+ judge(call, args, cwd, signal, callOpts) {
385
+ if (readStationMemberOf(call, station.tools) === undefined)
386
+ return check.judge(call, args, cwd, signal, callOpts);
387
+ return rows.tablesReady(undefined, signal).then(() => check.judge(call, args, cwd, signal, callOpts) ?? VOUCHED);
388
+ },
389
+ unanswered: (call, cause) => check.unanswered(call, cause),
390
+ };
391
+ }
378
392
  export function afterCallTables(rows, tool) {
379
393
  return {
380
394
  ...tool,
@@ -0,0 +1,120 @@
1
+ import type { Context, Model, SimpleStreamOptions } from "../../internal/llm.js";
2
+ import type { PrefixChangeCause } from "../cache-break-detector.js";
3
+ import type { Brain } from "../model-seat.js";
4
+ /** Where in the canonical rendering a position falls. */
5
+ export type PrefixRegion = "params" | "system" | "tools" | "messages";
6
+ /** The first position at which a request stops repeating the previous main request of its model. */
7
+ export interface PrefixDivergence {
8
+ /** Where the request stops repeating, in the canonical rendering (UTF-16 units, not provider tokens): in `params` / `system` /
9
+ * `tools` the first differing unit (it can fall inside a character); in `messages` the start of the first changed message. */
10
+ readonly at: number;
11
+ /** The previous main request's length in the same rendering. */
12
+ readonly of: number;
13
+ readonly region: PrefixRegion;
14
+ /** `messages` only: the index of the first message that differs (or that the request no longer carries). */
15
+ readonly message?: number;
16
+ }
17
+ /** What one request is, as the ledger read it. */
18
+ export interface RequestPrefixReading {
19
+ /** sha256 of the request head (controls + system + tools), salted with the session's hash salt, first 16 hex digits. */
20
+ readonly head: string;
21
+ /** The number of messages the request carries. */
22
+ readonly messages: number;
23
+ /** The request's length in the canonical rendering. */
24
+ readonly chars: number;
25
+ /** `extends` — a byte extension of the previous main request of the same model; `no-baseline` — this process holds none
26
+ * (never saw one, or a declared history rewrite voided it); else where it stops repeating it. */
27
+ readonly prefix: "extends" | "no-baseline" | PrefixDivergence;
28
+ }
29
+ /**
30
+ * A main request that does not extend the previous one, with what was declared since. `at` / `of` are absent exactly when this
31
+ * process holds no earlier main request of this model for the session (a reloaded engine, a switch to a model not served here, a
32
+ * baseline a declared history rewrite voided): the leg start's comparison against the stored anchor found the change; `segments` names it.
33
+ */
34
+ export interface PrefixChange {
35
+ readonly at?: number;
36
+ readonly of?: number;
37
+ readonly region: PrefixRegion;
38
+ readonly message?: number;
39
+ /** The head segments the leg start's anchor comparison found moved (prompt block ids, `tools`); present only then. */
40
+ readonly segments?: readonly string[];
41
+ /** Every word declared since the previous main request (empty: nothing was). */
42
+ readonly causes: readonly PrefixChangeCause[];
43
+ /** A declared word covers the region that changed ({@link REGION_CAUSES}). */
44
+ readonly declared: boolean;
45
+ }
46
+ /** The declaration words that can account for a change in each region. */
47
+ export declare const REGION_CAUSES: Readonly<Record<PrefixRegion, readonly PrefixChangeCause[]>>;
48
+ interface Rendered {
49
+ head: string;
50
+ /** Where the system and tool regions start inside `head` (params starts at 0). */
51
+ systemAt: number;
52
+ toolsAt: number;
53
+ digests: string[];
54
+ lengths: number[];
55
+ chars: number;
56
+ }
57
+ /** The canonical rendering of a request (see the module header). */
58
+ export declare function renderRequest(context: Context, options: SimpleStreamOptions | undefined): Rendered;
59
+ /** Where `now` stops repeating `prev`, or undefined when it extends it. */
60
+ export declare function divergenceOf(prev: Rendered, now: Rendered): PrefixDivergence | undefined;
61
+ /** The session's ledger. */
62
+ export interface SessionPrefixLedger {
63
+ /** A word the main line declared before its next request (the turn snapshot's declarations; the leg start's opening, with
64
+ * the head segments its anchor comparison found moved). */
65
+ declare(cause: PrefixChangeCause, segments?: readonly string[]): void;
66
+ /**
67
+ * Read one request. `main` requests become the model's new baseline and, when they do not extend the previous one, come
68
+ * back with the change; a side request is read against the baseline and leaves it as it was.
69
+ */
70
+ observe(input: {
71
+ model: Pick<Model, "provider" | "id">;
72
+ context: Context;
73
+ options?: SimpleStreamOptions;
74
+ main: boolean;
75
+ salt: Uint8Array;
76
+ }): {
77
+ reading: RequestPrefixReading;
78
+ change?: PrefixChange;
79
+ };
80
+ }
81
+ /** The reading of the request whose reply carried `usage`, when that request went through an observing brain. */
82
+ export declare function readingOfUsage(usage: object | undefined): RequestPrefixReading | undefined;
83
+ /** Read one request before it goes out; undefined = nothing to read (the leg's ledger is not seated, detection is off). */
84
+ export type RequestObserver = (model: Model, context: Context, options: SimpleStreamOptions | undefined) => RequestPrefixReading | undefined;
85
+ /**
86
+ * A brain whose every request is read by `observe` before it goes out, and whose every reply carries that reading
87
+ * ({@link readingOfUsage}). Both arms obey the same law; the reply is returned unchanged.
88
+ */
89
+ export declare function observingBrain(brain: Brain, observe: RequestObserver): Brain;
90
+ /**
91
+ * The leg's publication seat for prefix changes: armed at prepare, before any request goes out; the run's stream subscribes
92
+ * once it exists (changes published before then are buffered, bounded, and flushed in order) and drops its sink when the leg
93
+ * ends (a late change buffers, unread).
94
+ */
95
+ export declare class PrefixChangeSeat {
96
+ #private;
97
+ /** How many changes this leg published (the task-end low-hit summary stays silent once one was). */
98
+ get published(): number;
99
+ emit(change: PrefixChange): void;
100
+ subscribe(sink: (change: PrefixChange) => void): void;
101
+ unsubscribe(): void;
102
+ }
103
+ /** A leg's request observers over its session's ledger. */
104
+ export interface LegPrefixObservers {
105
+ readonly ledger: SessionPrefixLedger;
106
+ /** The main line's changes, as {@link observeMain} reads them. */
107
+ readonly changes: PrefixChangeSeat;
108
+ /** Reads a main-line request (it becomes the model's baseline; a change is published on {@link changes}). */
109
+ readonly observeMain: RequestObserver;
110
+ /** Reads a side request against the main line (the baseline stays as it was). */
111
+ readonly observeSide: RequestObserver;
112
+ /** Seat the session's hash salt (resolved with the prompt assembly); a request read before it is seated reads nothing. */
113
+ seatSalt(salt: Uint8Array): void;
114
+ }
115
+ /** The observers of one leg of `session`; with `detection` false (`RunnerDeps.cacheBreakDetection === false`) they read nothing. */
116
+ export declare function legPrefixObservers(session: object, detection: boolean): LegPrefixObservers;
117
+ /** The ledger of `session` (one per session object). */
118
+ export declare function sessionPrefixLedgerOf(session: object): SessionPrefixLedger;
119
+ export declare function createSessionPrefixLedger(): SessionPrefixLedger;
120
+ export {};
@@ -0,0 +1,176 @@
1
+ import { createHash } from "node:crypto";
2
+ import { ZERO_USAGE } from "../../brain/errors.js";
3
+ import { projectToolSchema } from "../../brain/tool-schema-projection.js";
4
+ export const REGION_CAUSES = Object.freeze({
5
+ params: ["request_policy", "model_namespace", "leg_start_inputs"],
6
+ system: ["compaction", "leg_start_inputs"],
7
+ tools: ["tool_table", "leg_start_inputs"],
8
+ messages: ["history_rewrite", "tool_result_clear", "compaction"],
9
+ });
10
+ const HISTORY_REWRITES = REGION_CAUSES.messages;
11
+ const SEP = "\n<|m|>";
12
+ function messageText(m) {
13
+ if (m.role === "toolResult")
14
+ return JSON.stringify([m.role, m.toolCallId, m.toolName, m.content, m.isError]);
15
+ return JSON.stringify([m.role, m.content]);
16
+ }
17
+ export function renderRequest(context, options) {
18
+ const params = `<|params|>${JSON.stringify({ reasoning: options?.reasoning ?? null })}\n`;
19
+ const system = `<|system|>${context.systemPrompt ?? ""}\n`;
20
+ const tools = `<|tools|>${JSON.stringify((context.tools ?? []).map((t) => [t.name, t.description, projectToolSchema(t.parameters)]))}`;
21
+ const head = params + system + tools;
22
+ const digests = [];
23
+ const lengths = [];
24
+ let chars = head.length;
25
+ for (const m of context.messages) {
26
+ const text = SEP + messageText(m);
27
+ digests.push(createHash("sha256").update(text).digest("hex").slice(0, 32));
28
+ lengths.push(text.length);
29
+ chars += text.length;
30
+ }
31
+ return { head, systemAt: params.length, toolsAt: params.length + system.length, digests, lengths, chars };
32
+ }
33
+ function lcp(a, b) {
34
+ const n = Math.min(a.length, b.length);
35
+ let i = 0;
36
+ while (i < n && a.charCodeAt(i) === b.charCodeAt(i))
37
+ i++;
38
+ return i;
39
+ }
40
+ export function divergenceOf(prev, now) {
41
+ if (now.head !== prev.head) {
42
+ const at = lcp(prev.head, now.head);
43
+ const region = at < prev.systemAt ? "params" : at < prev.toolsAt ? "system" : "tools";
44
+ return { at, of: prev.chars, region };
45
+ }
46
+ let at = prev.head.length;
47
+ for (let k = 0; k < prev.digests.length; k++) {
48
+ if (now.digests[k] !== prev.digests[k])
49
+ return { at, of: prev.chars, region: "messages", message: k };
50
+ at += prev.lengths[k];
51
+ }
52
+ return undefined;
53
+ }
54
+ const READINGS = new WeakMap();
55
+ export function readingOfUsage(usage) {
56
+ return usage === undefined ? undefined : READINGS.get(usage);
57
+ }
58
+ export function observingBrain(brain, observe) {
59
+ const tag = (msg, reading) => {
60
+ if (reading !== undefined && msg.usage !== undefined && msg.usage !== ZERO_USAGE)
61
+ READINGS.set(msg.usage, reading);
62
+ return msg;
63
+ };
64
+ return {
65
+ stream: async (model, context, options) => {
66
+ const reading = observe(model, context, options);
67
+ const inner = await Promise.resolve(brain.stream(model, context, options));
68
+ const tagged = inner.result().then((msg) => tag(msg, reading));
69
+ tagged.catch(() => { });
70
+ return { [Symbol.asyncIterator]: () => inner[Symbol.asyncIterator](), result: () => tagged };
71
+ },
72
+ complete: async (model, context, options) => {
73
+ const reading = observe(model, context, options);
74
+ const msg = brain.complete !== undefined ? await brain.complete(model, context, options) : await (await Promise.resolve(brain.stream(model, context, options))).result();
75
+ return tag(msg, reading);
76
+ },
77
+ ...(brain.adjudicateRoute !== undefined ? { adjudicateRoute: (model, auth) => brain.adjudicateRoute?.(model, auth) } : {}),
78
+ };
79
+ }
80
+ export class PrefixChangeSeat {
81
+ #pending = [];
82
+ #sink;
83
+ #published = 0;
84
+ get published() {
85
+ return this.#published;
86
+ }
87
+ emit(change) {
88
+ this.#published++;
89
+ if (this.#sink !== undefined)
90
+ this.#sink(change);
91
+ else {
92
+ this.#pending.push(change);
93
+ if (this.#pending.length > 64)
94
+ this.#pending.shift();
95
+ }
96
+ }
97
+ subscribe(sink) {
98
+ this.#sink = sink;
99
+ const pending = this.#pending;
100
+ this.#pending = [];
101
+ for (const c of pending)
102
+ sink(c);
103
+ }
104
+ unsubscribe() {
105
+ this.#sink = undefined;
106
+ }
107
+ }
108
+ export function legPrefixObservers(session, detection) {
109
+ const ledger = sessionPrefixLedgerOf(session);
110
+ const changes = new PrefixChangeSeat();
111
+ let salt;
112
+ const observer = (main) => (model, context, options) => {
113
+ if (!detection || salt === undefined)
114
+ return undefined;
115
+ const r = ledger.observe({ model, context, options, main, salt });
116
+ if (r.change !== undefined)
117
+ changes.emit(r.change);
118
+ return r.reading;
119
+ };
120
+ return {
121
+ ledger,
122
+ changes,
123
+ observeMain: observer(true),
124
+ observeSide: observer(false),
125
+ seatSalt: (s) => void (salt = s),
126
+ };
127
+ }
128
+ const LEDGERS = new WeakMap();
129
+ export function sessionPrefixLedgerOf(session) {
130
+ let ledger = LEDGERS.get(session);
131
+ if (ledger === undefined)
132
+ LEDGERS.set(session, (ledger = createSessionPrefixLedger()));
133
+ return ledger;
134
+ }
135
+ export function createSessionPrefixLedger() {
136
+ const lastMain = new Map();
137
+ let pending = [];
138
+ let segments;
139
+ return {
140
+ declare(cause, moved) {
141
+ if (!pending.includes(cause))
142
+ pending.push(cause);
143
+ if (moved !== undefined && moved.length > 0)
144
+ segments = moved;
145
+ },
146
+ observe({ model, context, options, main, salt }) {
147
+ const now = renderRequest(context, options);
148
+ const key = `${model.provider}:${model.id}`;
149
+ const prev = lastMain.get(key);
150
+ const div = prev === undefined ? undefined : divergenceOf(prev, now);
151
+ const reading = {
152
+ head: createHash("sha256").update(salt).update(now.head).digest("hex").slice(0, 16),
153
+ messages: context.messages.length,
154
+ chars: now.chars,
155
+ prefix: prev === undefined ? "no-baseline" : (div ?? "extends"),
156
+ };
157
+ if (!main)
158
+ return { reading };
159
+ const causes = pending;
160
+ const moved = segments;
161
+ pending = [];
162
+ segments = undefined;
163
+ if (causes.some((c) => HISTORY_REWRITES.includes(c)))
164
+ lastMain.clear();
165
+ lastMain.set(key, now);
166
+ const covered = (region) => causes.some((c) => REGION_CAUSES[region].includes(c));
167
+ if (div !== undefined)
168
+ return { reading, change: { ...div, ...(moved !== undefined ? { segments: moved } : {}), causes, declared: covered(div.region) } };
169
+ if (prev === undefined && moved !== undefined) {
170
+ const region = moved.every((s) => s === "tools") ? "tools" : "system";
171
+ return { reading, change: { region, segments: moved, causes, declared: covered(region) } };
172
+ }
173
+ return { reading };
174
+ },
175
+ };
176
+ }