@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
@@ -1,7 +1,7 @@
1
1
  import { compactionKindOf } from "../task-notification.js";
2
2
  import { mintSystemReminder } from "../reminder-mint.js";
3
3
  import { eventDefaultOn } from "../../prompt-assembly/event-registry.js";
4
- import { compactionFailureCause, compactionFailureReason, compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, manualCompactOutcomeOf, maybeCompact, mintCompactedEvent, nextTrimForceBackoff, recordCompactionAndCheckRapidRefill } from "../auto-compaction.js";
4
+ import { compactionFailureCause, compactionFailureReason, compactionPassReport, compactionCutOf, DEFAULT_COMPACTION_INSTRUCTIONS, manualCompactOutcomeOf, turnCutWhileLegRuns, maybeCompact, measureContext, mintCompactedEvent, nextTrimForceBackoff, recordCompactionAndCheckRapidRefill } from "../auto-compaction.js";
5
5
  import { emitTrace } from "../trace.js";
6
6
  import { compactionEnabled } from "../context-settings.js";
7
7
  import { steeringPreview } from "./steering-preview.js";
@@ -38,7 +38,7 @@ function consumeDelivered(pending, delivered) {
38
38
  }
39
39
  export function createTurnBoundary(input) {
40
40
  const { prepared, stats, rs, deps } = input;
41
- const { spec, queue, loopLatch: { callerStop }, manualCompactRef, todoToolMounted, taskToolsMounted, walltimeMonotonicDeadline, timeout, ident, postToolBatchArmed, batchArgs, compactionBrain, withinTaskCompaction, compactionBreaker, windowSafetyOptions, rapidRefill, drainManualCompact, runnerHooks, runner, display } = deps;
41
+ const { spec, queue, loopLatch: { callerStop }, manualCompactRef, todoToolMounted, taskToolsMounted, walltimeMonotonicDeadline, timeout, ident, postToolBatchArmed, batchArgs, compactionBrain, withinTaskCompaction, compactionBreaker, rapidRefill, drainManualCompact, runnerHooks, runner, display } = deps;
42
42
  let finalVerifySeenAtLastBoundary = 0;
43
43
  let legContinues = true;
44
44
  const boundaryPass = async (event) => {
@@ -514,7 +514,8 @@ export function createTurnBoundary(input) {
514
514
  void prepared.harness.steerFrame(f.seed).catch(() => load.release());
515
515
  }
516
516
  }
517
- return await compactionPass(event.model);
517
+ await compactionPass(event.model);
518
+ return undefined;
518
519
  };
519
520
  const compactInPlace = async (model, request) => {
520
521
  let outcome = "mooted";
@@ -523,14 +524,22 @@ export function createTurnBoundary(input) {
523
524
  await compactionPass(model, request.call);
524
525
  return outcome;
525
526
  };
526
- const compactionPass = async (model, call) => {
527
- if (manualCompactRef.requested && !compactionEnabled("manualCompact", spec.compaction, legContextOverlayOption(prepared, runner).contextOverlay)) {
527
+ const reportUsage = async (contextUsage) => {
528
+ const sections = contextUsageSections(prepared.promptManifest.sections);
529
+ queue.push({ type: "context_usage", ...contextUsage, ...(sections !== undefined ? { sections } : {}), ...ident() });
530
+ const measured = measureSession(prepared.modBus, prepared.sessionMeasure, contextUsage, prepared.hookIdentity, prepared.abortController.signal);
531
+ if (measured !== undefined)
532
+ await measured;
533
+ };
534
+ const compactionPass = async (model, call, turnStart) => {
535
+ if (turnStart === undefined && manualCompactRef.requested && !compactionEnabled("manualCompact", spec.compaction, legContextOverlayOption(prepared, runner).contextOverlay)) {
528
536
  emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.disabled", version: 1, taskId: rs.telemetry.taskId, ts: Date.now() }));
529
537
  queue.push({ type: "compaction_outcome", outcome: "disabled", trigger: "manual", ...requesterOf(manualCompactRef.waiters), ...ident() });
530
538
  drainManualCompact("disabled");
531
539
  }
532
- const forceManual = manualCompactRef.requested;
533
- if ((!withinTaskCompaction() && !forceManual) ||
540
+ const forceManual = turnStart === undefined && manualCompactRef.requested;
541
+ const automaticOn = turnStart?.owed === "leg-start" ? compactionEnabled("autoCompact", spec.compaction, legContextOverlayOption(prepared, runner).contextOverlay) : withinTaskCompaction();
542
+ if ((!automaticOn && !forceManual) ||
534
543
  prepared.abortController.signal.aborted ||
535
544
  callerStop.signal.aborted ||
536
545
  prepared.pausedRef.current !== undefined) {
@@ -539,9 +548,12 @@ export function createTurnBoundary(input) {
539
548
  queue.push({ type: "compaction_outcome", outcome: "mooted", trigger: "manual", reason: "task_ending", ...requesterOf(manualCompactRef.waiters), ...ident() });
540
549
  drainManualCompact("mooted");
541
550
  }
542
- legContinues &&= !prepared.abortController.signal.aborted && prepared.pausedRef.current === undefined;
543
- return undefined;
551
+ if (turnStart === undefined)
552
+ legContinues &&= !prepared.abortController.signal.aborted && prepared.pausedRef.current === undefined;
553
+ return false;
544
554
  }
555
+ if (turnStart?.signal?.aborted === true)
556
+ return false;
545
557
  if (compactionBreaker.failures >= MAX_CONSECUTIVE_COMPACTION_FAILURES) {
546
558
  if (forceManual) {
547
559
  emitTrace(rs.telemetry.tracer, () => ({
@@ -555,7 +567,7 @@ export function createTurnBoundary(input) {
555
567
  queue.push({ type: "compaction_outcome", outcome: "failed", trigger: "manual", reason: "compaction circuit breaker open (3 consecutive failures this task) — manual request drained without an attempt", ...requesterOf(manualCompactRef.waiters), ...ident() });
556
568
  drainManualCompact("failed");
557
569
  }
558
- return undefined;
570
+ return false;
559
571
  }
560
572
  const claimedManual = forceManual
561
573
  ? (() => {
@@ -580,16 +592,38 @@ export function createTurnBoundary(input) {
580
592
  w.resolve(outcome);
581
593
  };
582
594
  const claimedCancelSignals = claimedManual?.waiters.flatMap((w) => (w.signal !== undefined ? [w.signal] : [])) ?? [];
583
- const manualCancelSignal = claimedCancelSignals.length === 0 ? callerStop.signal : AbortSignal.any([callerStop.signal, ...claimedCancelSignals]);
584
- const compactionPassSignal = AbortSignal.any([prepared.abortController.signal, manualCancelSignal]);
585
- const trimPressureArmed = prepared.trimPressureRef.droppedMessages;
595
+ const withdrawals = [...claimedCancelSignals, ...(turnStart?.signal !== undefined ? [turnCutWhileLegRuns(turnStart.signal, prepared.abortController.signal)] : [])];
596
+ const manualCancelSignal = withdrawals.length === 0 ? callerStop.signal : AbortSignal.any([callerStop.signal, ...withdrawals]);
597
+ const compactionPassSignal = AbortSignal.any([prepared.abortController.signal, manualCancelSignal, ...(turnStart?.signal !== undefined ? [turnStart.signal] : [])]);
598
+ const trimPressureArmed = turnStart === undefined && prepared.trimPressureRef.droppedMessages;
586
599
  if (trimPressureArmed)
587
600
  prepared.trimPressureRef.droppedMessages = false;
588
601
  const trimPressure = trimPressureArmed && !rs.counters.trimForceBackoff && withinTaskCompaction();
602
+ if (turnStart === undefined && !forceManual && !trimPressure) {
603
+ prepared.microCompact.turnStartCompactionRef.owed = "boundary";
604
+ try {
605
+ const ctx = await prepared.session.buildContext();
606
+ const overlay = legContextOverlayOption(prepared, runner).contextOverlay;
607
+ const measured = measureContext({
608
+ messages: ctx.messages,
609
+ model,
610
+ ...(overlay !== undefined ? { contextOverlay: overlay } : {}),
611
+ settings: legCompactionSettings(spec, overlay, "autoCompact"),
612
+ ...(prepared.promptOverheadTokens !== undefined ? { overheadTokens: prepared.promptOverheadTokens } : {}),
613
+ });
614
+ if (measured.contextUsage !== undefined)
615
+ await reportUsage(measured.contextUsage);
616
+ }
617
+ catch (err) {
618
+ runnerHooks.onError?.(err, { phase: "degraded", sessionId: prepared.sessionId, classification: "context-measurement" });
619
+ }
620
+ return false;
621
+ }
589
622
  const passTrigger = trimPressure ? "forced" : forceManual ? "manual" : "auto";
590
623
  let manualOutcome = "failed";
591
624
  const manualInstructions = claimedManual?.instructions;
592
625
  const passReport = compactionPassReport(queue, ident);
626
+ let landed = false;
593
627
  try {
594
628
  const comp = await prepared.compactStation.compact({
595
629
  session: prepared.session,
@@ -598,8 +632,7 @@ export function createTurnBoundary(input) {
598
632
  ...centerAdoptionOption(prepared),
599
633
  model,
600
634
  ...legContextOverlayOption(prepared, runner),
601
- compactionModel: prepared.compModel,
602
- ...forkContextOption(prepared, false),
635
+ ...(turnStart !== undefined ? { forkContext: turnStart.fork } : forkContextOption(prepared, false)),
603
636
  brain: compactionBrain,
604
637
  getApiKeyAndHeaders: spec.getApiKeyAndHeaders,
605
638
  thinking: prepared.thinking,
@@ -617,7 +650,6 @@ export function createTurnBoundary(input) {
617
650
  ...(prepared.onCompactionApplied ? { onApplied: prepared.onCompactionApplied } : {}),
618
651
  ...seamCCompactionOptions(runner, prepared),
619
652
  ...compactionRestateOptions(prepared, instructionEchoTo(queue, ident, rs.attach)),
620
- ...windowSafetyOptions(model),
621
653
  ...compactionHookOptions(runner, prepared, passTrigger, compactionPassSignal),
622
654
  onStarted: passReport.onStarted,
623
655
  }, maybeCompact, { ...(manualInstructions !== undefined ? { instructions: manualInstructions } : {}), ...(call !== undefined ? { call } : {}) });
@@ -634,13 +666,8 @@ export function createTurnBoundary(input) {
634
666
  compactionBreaker.failures = 0;
635
667
  }
636
668
  rs.counters.trimForceBackoff = nextTrimForceBackoff(rs.counters.trimForceBackoff, comp, trimPressure);
637
- if (comp.contextUsage) {
638
- const sections = contextUsageSections(prepared.promptManifest.sections);
639
- queue.push({ type: "context_usage", ...comp.contextUsage, ...(sections !== undefined ? { sections } : {}), ...ident() });
640
- const measured = measureSession(prepared.modBus, prepared.sessionMeasure, comp.contextUsage, prepared.hookIdentity, prepared.abortController.signal);
641
- if (measured !== undefined)
642
- await measured;
643
- }
669
+ if (comp.contextUsage && turnStart === undefined)
670
+ await reportUsage(comp.contextUsage);
644
671
  if (comp.unevaluableWindow) {
645
672
  discloseUnevaluableWindow(comp.unevaluableWindow, prepared, rs.telemetry.tracer, rs.telemetry.taskId, runnerHooks.onError);
646
673
  }
@@ -676,6 +703,7 @@ export function createTurnBoundary(input) {
676
703
  }
677
704
  recordCompactionReuse(runner, prepared, comp);
678
705
  if (comp.compacted) {
706
+ landed = true;
679
707
  queue.push({ ...mintCompactedEvent(comp, passTrigger, ident()), ...requester });
680
708
  rs.counters.compactionPasses += 1;
681
709
  rs.counters.compactionKind = compactionKindOf(passTrigger);
@@ -700,12 +728,13 @@ export function createTurnBoundary(input) {
700
728
  }
701
729
  }
702
730
  catch (err) {
703
- if (isCompactionManualCancel(err)) {
731
+ const cut = compactionCutOf(err);
732
+ if (cut === "cancelled") {
704
733
  emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.mooted", version: 1, taskId: rs.telemetry.taskId, reason: "cancelled", ts: Date.now() }));
705
734
  queue.push({ type: "compaction_outcome", outcome: "mooted", trigger: passTrigger, reason: "cancelled", ...passReport.end, ...requester, ...ident() });
706
735
  manualOutcome = "mooted";
707
736
  }
708
- else if (!prepared.abortController.signal.aborted) {
737
+ else if (cut === "failed") {
709
738
  compactionBreaker.failures += 1;
710
739
  runnerHooks.onError?.(err, { phase: "compaction", sessionId: prepared.sessionId });
711
740
  const failReason = compactionFailureReason(err), failCause = compactionFailureCause(err);
@@ -730,8 +759,9 @@ export function createTurnBoundary(input) {
730
759
  }
731
760
  if (forceManual)
732
761
  resolveClaimedWaiters(manualOutcome);
733
- return undefined;
762
+ return landed;
734
763
  };
764
+ prepared.microCompact.turnStartCompactionRef.current = async (owed, signal, fork) => await compactionPass(prepared.harness.getModel(), undefined, { owed, ...(signal !== undefined ? { signal } : {}), fork });
735
765
  const onTurnBoundary = async (event) => {
736
766
  legContinues = true;
737
767
  try {
@@ -533,9 +533,9 @@ export class Runner {
533
533
  runnerHooks: { onError: (e, info) => this.deps.onError?.(e, info), onNotice: this.deps.onNotice },
534
534
  },
535
535
  });
536
- const { compactionBrain, withinTaskCompaction, compactionBreaker, windowSafetyOptions } = runCompactionMachinery({ spec, prepared, rs, stats, noteUnevaluablePriceTable, runner: this.depsSeat });
536
+ const { compactionBrain, withinTaskCompaction, compactionBreaker } = runCompactionMachinery({ spec, prepared, rs, stats, noteUnevaluablePriceTable, runner: this.depsSeat });
537
537
  runStopAndFinalVerify({ spec, prepared, queue, rs, stats, ident, walltimeMonotonicDeadline, deliveryObligations, runner: this.depsSeat });
538
- runRecoveryLanes({ spec, prepared, queue, rs, ident, compactionBrain, compactionBreaker, windowSafetyOptions, callerStop: loopLatch.callerStop, runner: this.depsSeat });
538
+ runRecoveryLanes({ spec, prepared, queue, rs, ident, compactionBrain, compactionBreaker, callerStop: loopLatch.callerStop, runner: this.depsSeat });
539
539
  const rapidRefill = createRapidRefillState();
540
540
  const drainManualCompact = (outcome) => {
541
541
  manualCompactRef.requested = false;
@@ -548,7 +548,7 @@ export class Runner {
548
548
  spec, queue, loopLatch, manualCompactRef, todoToolMounted, taskToolsMounted,
549
549
  walltimeMonotonicDeadline,
550
550
  timeout, ident, postToolBatchArmed, batchArgs, compactionBrain, withinTaskCompaction,
551
- compactionBreaker, windowSafetyOptions, rapidRefill, drainManualCompact, display,
551
+ compactionBreaker, rapidRefill, drainManualCompact, display,
552
552
  runnerHooks: { onError: this.deps.onError },
553
553
  runner: this.depsSeat,
554
554
  },
@@ -559,11 +559,11 @@ export class Runner {
559
559
  announceWorkspaceMove, withBrainSinks, flushGitMirror, loopLatch, notificationLane, unsubscribeTaskNotifications, unsubGitRetry, unsubBoundary, unsub,
560
560
  runner: this.depsSeat,
561
561
  next: ({ final, threw, abortedLive, userInterruptedLive, strandedHumanAnswers }) => runTerminalAdoption({
562
- spec, queue, prepared, rs, stats, ident, emitCommitted, startedToolCallIds, toolLabels, timeout, compactionBrain, compactionBreaker, windowSafetyOptions,
563
- undrainedUserAtEnd, userInputLostAtEnd, final, threw, abortedLive, userInterruptedLive, callerStop: loopLatch.callerStop, runner: this.depsSeat, sessions: this.sessions,
564
- next: ({ threw, comp, answerSettled, owedUserInput }) => runSettleAndTeardown({
562
+ queue, prepared, rs, stats, ident, emitCommitted, startedToolCallIds, toolLabels, timeout,
563
+ undrainedUserAtEnd, userInputLostAtEnd, final, threw, abortedLive, userInterruptedLive, runner: this.depsSeat, sessions: this.sessions,
564
+ next: ({ threw, answerSettled, owedUserInput }) => runSettleAndTeardown({
565
565
  spec, queue, prepared, resume, internals, rs, stats, ident, loopLatch, timeout, ownCommittedTailRef, legWrites,
566
- emitDelegationLifecycle, taskIdRef, manualCompactRef, drainManualCompact, final, threw, abortedLive, userInterruptedLive, answerSettled, strandedHumanAnswers, reasoningResolution, comp, deliveryObligations, compactionBreaker, owedUserInput,
566
+ emitDelegationLifecycle, taskIdRef, manualCompactRef, drainManualCompact, final, threw, abortedLive, userInterruptedLive, answerSettled, strandedHumanAnswers, reasoningResolution, deliveryObligations, compactionBreaker, owedUserInput,
567
567
  setResult, onSuggestions, onSuspend, runner: this.depsSeat, sessions: this.sessions, display,
568
568
  }),
569
569
  }),
@@ -0,0 +1,18 @@
1
+ import type { SessionTreeEntry } from "../../internal/harness-types.js";
2
+ import type { PromptHashScope } from "../trace.js";
3
+ export declare const PROMPT_HASH_SALT_CUSTOM_TYPE = "engine:prompt-hash-salt";
4
+ export interface PromptHashSalt {
5
+ readonly salt: Uint8Array;
6
+ /** How far the digests taken under the salt compare: across the session, or within this leg only (the store could not keep it). */
7
+ readonly scope: PromptHashScope;
8
+ }
9
+ /** The salt the session's branch holds, newest first; undefined when none is readable. */
10
+ export declare function storedPromptHashSalt(branch: ReadonlyArray<SessionTreeEntry>): Uint8Array | undefined;
11
+ /**
12
+ * Resolve the session's salt: the stored one, else a fresh one written to the session. `onFailure` hears a read or write that
13
+ * failed (the result is then a fresh key for this leg only); it must be loud — the host's digests stop comparing across runs.
14
+ */
15
+ export declare function resolvePromptHashSalt(session: {
16
+ getBranch(): Promise<ReadonlyArray<SessionTreeEntry>>;
17
+ appendCustomEntry(customType: string, data?: unknown): Promise<string>;
18
+ }, onFailure: (error: unknown, step: "read" | "write") => void): Promise<PromptHashSalt>;
@@ -0,0 +1,36 @@
1
+ import { randomBytes } from "node:crypto";
2
+ export const PROMPT_HASH_SALT_CUSTOM_TYPE = "engine:prompt-hash-salt";
3
+ const SALT_SHAPE = /^[0-9a-f]{32}$/;
4
+ export function storedPromptHashSalt(branch) {
5
+ for (let i = branch.length - 1; i >= 0; i--) {
6
+ const e = branch[i];
7
+ if (e.type !== "custom" || e.customType !== PROMPT_HASH_SALT_CUSTOM_TYPE)
8
+ continue;
9
+ const v = e.data?.salt;
10
+ if (typeof v === "string" && SALT_SHAPE.test(v))
11
+ return Uint8Array.from(Buffer.from(v, "hex"));
12
+ }
13
+ return undefined;
14
+ }
15
+ export async function resolvePromptHashSalt(session, onFailure) {
16
+ let branch;
17
+ try {
18
+ branch = await session.getBranch();
19
+ }
20
+ catch (error) {
21
+ onFailure(error, "read");
22
+ return { salt: Uint8Array.from(randomBytes(16)), scope: "leg" };
23
+ }
24
+ const stored = storedPromptHashSalt(branch);
25
+ if (stored !== undefined)
26
+ return { salt: stored, scope: "session" };
27
+ const salt = Uint8Array.from(randomBytes(16));
28
+ try {
29
+ await session.appendCustomEntry(PROMPT_HASH_SALT_CUSTOM_TYPE, { salt: Buffer.from(salt).toString("hex") });
30
+ return { salt, scope: "session" };
31
+ }
32
+ catch (error) {
33
+ onFailure(error, "write");
34
+ return { salt, scope: "leg" };
35
+ }
36
+ }
@@ -14,9 +14,10 @@
14
14
  * leg's to its own session, a delegated leg's to the delegation tree's root, naming the leg whose shell it is about. The answer
15
15
  * is read at each such call because it can grow during a run — a credential the engine takes in when it first routes a
16
16
  * model, dials a peer or builds a seat is withheld from the next child — and a call follows at least one model request.
17
- * Told once per SESSION per answer — each leg's own session, so a delegated child tells it once for its shell: the digest
18
- * rides the session's announced record (`advisories`), and a run-time record write is parked for the leg's flush like every
19
- * other run-time arm of that record.
17
+ * Told once per SESSION per sentence — each leg's own session, so a delegated child tells it once for its shell: the digest of the
18
+ * sentence as minted (so a sentence that reads differently, e.g. a notice that now names the leg's own entry, is told again) rides the
19
+ * session's announced record (`advisories`), and a run-time record write is parked for the leg's flush like every other run-time arm
20
+ * of that record.
20
21
  *
21
22
  * An answer of `"unknown"` is told as unknown, never as silence. A value that is neither a list of findings nor
22
23
  * `"unknown"` (or a read that throws) is a wiring fault: it is announced to the operator under the existing
@@ -25,6 +26,7 @@
25
26
  * The same seat relays the environment's one other disclosure about what its shell gets (`relayLateDeclaration`, below).
26
27
  */
27
28
  import { type EngineNotice } from "../engine-notice.js";
29
+ import { type PeerEntriesTaken } from "../secret-env.js";
28
30
  import type { ExecutionEnv } from "../../internal/harness.js";
29
31
  import type { Prepared } from "./contracts.js";
30
32
  export type WithheldShellEnvSeatInput = Pick<Prepared, "runId" | "sessionId" | "legNotice" | "toolRosterDeltas" | "announcedListingsRef" | "frameReceipts"> & {
@@ -32,8 +34,9 @@ export type WithheldShellEnvSeatInput = Pick<Prepared, "runId" | "sessionId" | "
32
34
  readonly env: Pick<ExecutionEnv, "withheldEnv" | "lateDeclarationNotice">;
33
35
  };
34
36
  };
35
- /** The seat, per run. `onToolStart` and `onToolEnd` never throw: a diagnostic may not be what fails a call. */
36
- export declare function createWithheldShellEnvSeat(prepared: WithheldShellEnvSeatInput, onNotice: ((notice: EngineNotice) => void) | undefined): {
37
+ /** The seat, per run. `onToolStart` and `onToolEnd` never throw: a diagnostic may not be what fails a call. `peerEntries` = the (variable,
38
+ * entry) pairs the leg's receipt took in (leg-receipt.ts `LegReceipt.peerEntries`): the only entries its notice names, each for its variable. */
39
+ export declare function createWithheldShellEnvSeat(prepared: WithheldShellEnvSeatInput, onNotice: ((notice: EngineNotice) => void) | undefined, peerEntries: PeerEntriesTaken | undefined): {
37
40
  onToolStart(toolName: string): void;
38
41
  onToolEnd(): void;
39
42
  };
@@ -40,7 +40,7 @@ function relayLateDeclaration(prepared, onNotice) {
40
40
  }
41
41
  };
42
42
  }
43
- export function createWithheldShellEnvSeat(prepared, onNotice) {
43
+ export function createWithheldShellEnvSeat(prepared, onNotice, peerEntries) {
44
44
  let shapeFaultTold = false;
45
45
  const relay = relayLateDeclaration(prepared, onNotice);
46
46
  return {
@@ -60,11 +60,11 @@ export function createWithheldShellEnvSeat(prepared, onNotice) {
60
60
  });
61
61
  return;
62
62
  }
63
- const notice = withheldEnvUserNotice(answer, { ...prepared.legNotice.route.address, runId: prepared.runId });
63
+ const notice = withheldEnvUserNotice(answer, { ...prepared.legNotice.route.address, runId: prepared.runId }, peerEntries);
64
64
  if (notice === undefined)
65
65
  return;
66
66
  const d = notice.detail;
67
- const digest = announceDigest(notice.code, `${d.state}\n${[...(d.names ?? [])].sort().join("\n")}\n\n${[...(d.ownCredentials ?? [])].sort().join("\n")}${d.sourceSessionId !== undefined ? `\n\n${d.sourceSessionId}` : ""}`);
67
+ const digest = announceDigest(notice.code, `${notice.message}${d.sourceSessionId !== undefined ? `\n\n${d.sourceSessionId}` : ""}`);
68
68
  tellOncePerSession(prepared, digest, () => deliverEngineNotice(onNotice, notice, prepared.legNotice.admission));
69
69
  },
70
70
  };
@@ -5,7 +5,7 @@
5
5
  * (every lane folds into the total — it is the budget coordinate and the reported figure); it is total over the lanes by its
6
6
  * fence, so another lane is a row here, not a second accounting function.
7
7
  */
8
- import type { AssistantMessageDiagnostic, Model, Usage } from "../../internal/llm.js";
8
+ import type { AssistantMessage, AssistantMessageDiagnostic, Model, Usage } from "../../internal/llm.js";
9
9
  import type { FastModeCall } from "../../brain/fast-mode.js";
10
10
  import type { ServedReading } from "../../brain/model-lane.js";
11
11
  import type { ModelPricing } from "../pricing.js";
@@ -97,6 +97,13 @@ export interface SideCallCall {
97
97
  * lane is left out of the cache-hit rate; the cache members fold through the one cache account (`./cache-hit-account.ts`).
98
98
  */
99
99
  export declare function recordSideCallUsage(stats: Stats, usage: Usage | undefined, lane: SideCallLane, call: SideCallCall): void;
100
+ type SideCallRowTelemetry = {
101
+ readonly tracer: TaskSpec["tracer"];
102
+ readonly taskId: string;
103
+ };
104
+ /** The prompt-suggestion pass's row: its reply priced by the same function as the booked lanes, emitted by the builder above,
105
+ * and booked nowhere (the pass's spend is the result's separate `stats.suggestions` line). */
106
+ export declare function emitSuggestionsRow(telemetry: SideCallRowTelemetry, reply: AssistantMessage, model: Model, pricing: RunnerDeps["pricing"]): void;
100
107
  /**
101
108
  * The accounted brain of a DERIVED LEG — a model call made beside the main loop on the leg's behalf (the compaction summary,
102
109
  * the advisor consultation): every reply is booked through `book` exactly once, under `lane`, and the call runs behind a
@@ -121,3 +128,4 @@ export declare function derivedLegBrain(brainOf: () => Brain, lane: SideCallLane
121
128
  /** The leg's door: `recordSideCallUsage` bound to the leg's `stats` and account, reading what the reply itself says — its
122
129
  * marks, and its bills (`billsOf`: every hop the model lane left behind, then the reply, each at its own model). */
123
130
  export declare function sideCallBookOf(stats: Stats, account: SideCallAccount): SideCallBook;
131
+ export {};
@@ -3,6 +3,7 @@ import { emitTrace } from "../trace.js";
3
3
  import { billsOf, priceReply } from "./reply-pricing.js";
4
4
  import { bookCacheOperands, cacheTraceMembersOf } from "./cache-hit-account.js";
5
5
  import { cacheFamilyOf } from "./usage-accounting.js";
6
+ import { readingOfUsage } from "./prefix-ledger.js";
6
7
  export const SIDE_CALL_LANE_TOTAL = {
7
8
  compaction: "compactionMicroUsd",
8
9
  classifier: "sideCallMicroUsd",
@@ -60,13 +61,23 @@ export function recordSideCallUsage(stats, usage, lane, call) {
60
61
  stats.costMicroUsd += costMicroUsd;
61
62
  const total = SIDE_CALL_LANE_TOTAL[lane];
62
63
  stats[total] = (stats[total] ?? 0) + costMicroUsd;
63
- emitTrace(account.telemetry.tracer, () => ({
64
- kind: "brain.call", version: 1, taskId: account.telemetry.taskId, model: modelId, lane, provider: served.provider,
65
- promptTokens: uncachedInputTokens, totalInputTokens, completionTokens: usage.output || 0,
64
+ emitSideCallRow(account.telemetry, lane, usage, { modelId, provider: served.provider, uncachedInputTokens, totalInputTokens, ...(priced ? { costMicroUsd } : {}), ...(call.stopReason !== undefined ? { stopReason: call.stopReason } : {}) });
65
+ }
66
+ function emitSideCallRow(telemetry, lane, usage, priced) {
67
+ const request = readingOfUsage(usage);
68
+ emitTrace(telemetry.tracer, () => ({
69
+ kind: "brain.call", version: 1, taskId: telemetry.taskId, model: priced.modelId, lane, provider: priced.provider,
70
+ promptTokens: priced.uncachedInputTokens, totalInputTokens: priced.totalInputTokens, completionTokens: usage.output || 0,
66
71
  ...cacheTraceMembersOf(usage),
67
- latencyMs: 0, ...(priced ? { costMicroUsd } : {}), ...(call.stopReason !== undefined ? { stopReason: call.stopReason } : {}), ts: Date.now(),
72
+ latencyMs: 0, ...(priced.costMicroUsd !== undefined ? { costMicroUsd: priced.costMicroUsd } : {}), ...(priced.stopReason !== undefined ? { stopReason: priced.stopReason } : {}),
73
+ ...(request !== undefined ? { request } : {}),
74
+ ts: Date.now(),
68
75
  }));
69
76
  }
77
+ export function emitSuggestionsRow(telemetry, reply, model, pricing) {
78
+ const priced = priceReply(reply.usage, model, pricing, false);
79
+ emitSideCallRow(telemetry, "suggestions", reply.usage, { modelId: priced.modelId, provider: priced.served.provider, uncachedInputTokens: priced.uncachedInputTokens, totalInputTokens: priced.totalInputTokens, ...(priced.priced ? { costMicroUsd: priced.costMicroUsd } : {}), ...(typeof reply.stopReason === "string" ? { stopReason: reply.stopReason } : {}) });
80
+ }
70
81
  export function derivedLegBrain(brainOf, lane, book, fastModeOf) {
71
82
  const shielded = (fn) => runWithStatusSink(() => { }, fn);
72
83
  const withFastMode = (o) => {
@@ -0,0 +1,12 @@
1
+ import type { EngineText } from "../../prompt-assembly/engine-text.js";
2
+ /**
3
+ * The listed skills `text` names as `/<name>`, each once, in the order the text first names it (the module header gives the
4
+ * reading). `listed` is the leg's announced skill names; a name outside it is never a mention.
5
+ */
6
+ export declare function skillMentionsIn(text: string, listed: ReadonlySet<string>): string[];
7
+ /**
8
+ * The frame body for the named skills, in the run's engine text reading: one sentence per skill, joined by a line break, as
9
+ * many whole sentences as fit the kind's ceiling (`maxBytes` of the `skill_mention` registry row) in the order given.
10
+ * `undefined` when nothing is named or not one sentence fits.
11
+ */
12
+ export declare function renderSkillMentionFrame(names: readonly string[], say: EngineText): string | undefined;
@@ -0,0 +1,50 @@
1
+ import { eventMaxBytes } from "../../prompt-assembly/event-registry.js";
2
+ import { SKILL_TOOL_NAME } from "./synthetic-tools.js";
3
+ const MENTION_TOKEN = /\/[a-zA-Z][a-zA-Z0-9.:_-]*/g;
4
+ const MENTION_EDGE = /^[\s\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3000-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2014\u2026\u2018\u2019\u201c\u201d]$/u;
5
+ function isEdge(cp) {
6
+ return cp === undefined || MENTION_EDGE.test(cp);
7
+ }
8
+ function codePointBefore(text, at) {
9
+ if (at <= 0)
10
+ return undefined;
11
+ return Array.from(text.slice(Math.max(0, at - 2), at)).pop();
12
+ }
13
+ function codePointAt(text, at) {
14
+ const cp = text.codePointAt(at);
15
+ return cp === undefined ? undefined : String.fromCodePoint(cp);
16
+ }
17
+ export function skillMentionsIn(text, listed) {
18
+ if (listed.size === 0 || !text.includes("/"))
19
+ return [];
20
+ const named = [];
21
+ const seen = new Set();
22
+ for (const m of text.matchAll(MENTION_TOKEN)) {
23
+ const start = m.index;
24
+ let end = start + m[0].length;
25
+ while (text[end - 1] === ".")
26
+ end--;
27
+ if (!isEdge(codePointBefore(text, start)) || !isEdge(codePointAt(text, end)))
28
+ continue;
29
+ const name = text.slice(start + 1, end);
30
+ if (!listed.has(name) || seen.has(name))
31
+ continue;
32
+ seen.add(name);
33
+ named.push(name);
34
+ }
35
+ return named;
36
+ }
37
+ export function renderSkillMentionFrame(names, say) {
38
+ const ceiling = eventMaxBytes("skill_mention");
39
+ const lines = [];
40
+ let bytes = 0;
41
+ for (const name of names) {
42
+ const line = say("core/event.skill-mention", { name, tool: SKILL_TOOL_NAME });
43
+ const cost = Buffer.byteLength(line, "utf8") + (lines.length > 0 ? 1 : 0);
44
+ if (bytes + cost > ceiling)
45
+ continue;
46
+ lines.push(line);
47
+ bytes += cost;
48
+ }
49
+ return lines.length > 0 ? lines.join("\n") : undefined;
50
+ }
@@ -85,6 +85,7 @@ export function streamSettleBackstop(input) {
85
85
  const observed = taskIdRef.editedFiles?.();
86
86
  return observed !== undefined && observed.length > 0 ? { editedFiles: observed } : {};
87
87
  })(),
88
+ ...(taskIdRef.readFloorUnkept?.current === true ? { readDenyFloor: { kept: false } } : {}),
88
89
  ...(() => {
89
90
  const hinted = readMember(err, "retryAfterMs");
90
91
  return code === "memory.admission_required" && typeof hinted === "number" && Number.isFinite(hinted) && hinted > 0
@@ -162,8 +162,8 @@ export function createSkillTool(skills, grants) {
162
162
  `A skill is a packaged set of instructions the user or project has set up for a particular kind of task (deploy steps, a review checklist, a repo-specific workflow). ` +
163
163
  `Available skills appear in a system-reminder listing with one-line descriptions. ` +
164
164
  `When the task at hand is one a listed skill covers, call this tool first — the skill's instructions load into the turn for you to follow in place of your default approach. ` +
165
- `Users may also ask for one by name; that's a request to invoke it.\n\n` +
166
- `- \`skill\`: exact name from the listing. Directory-scoped skills are listed with a path prefix (\`apps/web:deploy\`); when both scoped and unscoped variants of a name exist, pick the one whose directory contains the files you're working on (most specific wins; unscoped otherwise).\n` +
165
+ `Users may also ask for one by name (\`/<name>\`, or "slash command"); that's a request to invoke it.\n\n` +
166
+ `- \`skill\`: exact name from the listing, no leading slash. Directory-scoped skills are listed with a path prefix (\`apps/web:deploy\`); when both scoped and unscoped variants of a name exist, pick the one whose directory contains the files you're working on (most specific wins; unscoped otherwise).\n` +
167
167
  `- \`args\`: optional arguments to pass through.\n\n` +
168
168
  `Only names from the listing (or one the user explicitly asked for by name) are valid — never guess or invent a skill name. ` +
169
169
  `Do not invoke a skill that is already running. ` +
@@ -19,11 +19,10 @@
19
19
  import type { Context, StreamFn } from "../../internal/llm.js";
20
20
  import type { TurnPromptSnapshot } from "../../prompt-assembly/turn-snapshot.js";
21
21
  import type { LegVerdicts } from "../../agents/tool-filter.js";
22
- import { type ToolFingerprintInput } from "../cache-break-detector.js";
23
22
  import { type ToolRoster } from "../tool-roster.js";
24
23
  import { type ToolPolicy } from "../tool-policy.js";
25
- /** The faces the view reads, the roster whose face the gate stamps on a call of a tool, and the leg's prefix seats (the
26
- * cache-break fingerprint and the turn snapshot name the tools ACTUALLY sent). */
24
+ /** The faces the view reads, the roster whose face the gate stamps on a call of a tool, and the leg's turn snapshot (it
25
+ * names the tools ACTUALLY sent). */
27
26
  export interface ToolTableViewFaces {
28
27
  readonly policy: Pick<ToolPolicy, "wholeToolRefusals"> | undefined;
29
28
  /** The stored rules — the person's rows and the org's, one read of the store for both. */
@@ -35,12 +34,6 @@ export interface ToolTableViewFaces {
35
34
  * is met by the gate at its call, which the run records (`TaskResult.verdictRefused`); hidden, the leg would end with no outcome and no
36
35
  * trace of why. */
37
36
  readonly verdicts: Pick<LegVerdicts, "has">;
38
- readonly fpRef: {
39
- current?: {
40
- systemPrompt: string;
41
- tools: ToolFingerprintInput[];
42
- };
43
- };
44
37
  readonly turnSnapshotRef: {
45
38
  current?: TurnPromptSnapshot;
46
39
  };
@@ -49,6 +42,9 @@ export interface ToolTableView {
49
42
  /** The request `context` as the model is shown it: its tools block without the tools the faces refuse whole (the same
50
43
  * object when none is) — over one read of every face. */
51
44
  request(context: Context, signal?: AbortSignal): Promise<Context>;
45
+ /** The same view of `context`, from the same reading, with nothing moved: the leg's prefix seats and {@link shows} keep
46
+ * what the last request showed (a rendering of a request that may never be sent). */
47
+ render(context: Context, signal?: AbortSignal): Promise<Context>;
52
48
  /** Whether the last request showed the tool (before any request: every tool) — the search space of a lane that answers the
53
49
  * model about tools between requests (ToolSearch: a tool the model is not shown is no tool it can find). */
54
50
  shows(toolName: string): boolean;
@@ -7,40 +7,42 @@ export function createToolTableView(faces) {
7
7
  return undefined;
8
8
  let refused = () => false;
9
9
  let hidOne = false;
10
+ const judge = async (tools, signal) => {
11
+ const refuses = await read(signal);
12
+ const answers = new Map();
13
+ const judged = (toolName) => {
14
+ const known = answers.get(toolName);
15
+ if (known !== undefined)
16
+ return known;
17
+ const answer = !faces.verdicts.has(toolName) && refuses({ toolName, ...callFaceSeat(toolCallFaceOf(faces.roster.current, toolName)) });
18
+ answers.set(toolName, answer);
19
+ return answer;
20
+ };
21
+ return { shown: tools.filter((t) => !judged(t.name)), judged };
22
+ };
10
23
  return {
24
+ async render(context, signal) {
25
+ const tools = context.tools;
26
+ if (tools === undefined || tools.length === 0)
27
+ return context;
28
+ const { shown } = await judge(tools, signal);
29
+ return shown.length < tools.length ? { ...context, tools: shown } : context;
30
+ },
11
31
  async request(context, signal) {
12
32
  const tools = context.tools;
13
33
  if (tools === undefined || tools.length === 0)
14
34
  return context;
15
- const refuses = await read(signal);
16
- const answers = new Map();
17
- const judged = (toolName) => {
18
- const known = answers.get(toolName);
19
- if (known !== undefined)
20
- return known;
21
- const answer = !faces.verdicts.has(toolName) && refuses({ toolName, ...callFaceSeat(toolCallFaceOf(faces.roster.current, toolName)) });
22
- answers.set(toolName, answer);
23
- return answer;
24
- };
35
+ const { shown, judged } = await judge(tools, signal);
25
36
  refused = judged;
26
- const shown = tools.filter((t) => !judged(t.name));
27
37
  const hides = shown.length < tools.length;
28
- if (hides || hidOne) {
29
- const inputs = toolsToFingerprintInputs(shown);
30
- const fingerprint = faces.fpRef.current;
31
- if (fingerprint !== undefined && !sameNames(fingerprint.tools, shown))
32
- fingerprint.tools = inputs;
33
- faces.turnSnapshotRef.current?.refreshTools(inputs, "view");
34
- }
38
+ if (hides || hidOne)
39
+ faces.turnSnapshotRef.current?.refreshTools(toolsToFingerprintInputs(shown), "view");
35
40
  hidOne = hides;
36
41
  return hides ? { ...context, tools: shown } : context;
37
42
  },
38
43
  shows: (toolName) => !refused(toolName),
39
44
  };
40
45
  }
41
- function sameNames(a, b) {
42
- return a.length === b.length && a.every((t, i) => t.name === b[i].name);
43
- }
44
46
  export function streamShowingView(seat, stream) {
45
47
  return (model, context, options) => {
46
48
  const view = seat.current;
@@ -53,8 +53,11 @@ export interface LegWriteGuard {
53
53
  export declare function legWriteProtectionTable(deps: Pick<RunnerDeps, "writeProtectedPaths">, spec: Pick<TaskSpec, "writeProtectedAdditions">): ReturnType<typeof unionAddOnly<"writeProtectedAdditions">>;
54
54
  export declare function mountWriteProtection(input: {
55
55
  /** borrowed-readonly — the deployment seats: the table (`writeProtectedPaths`; absent ⇒ the default
56
- * table, `[]` ⇒ opted out), the configuration root the host declared (`agentConfigDir`) and the operator sink. */
57
- deps: Pick<RunnerDeps, "writeProtectedPaths" | "agentConfigDir" | "onNotice">;
56
+ * table, `[]` ⇒ opted out) and the operator sink. */
57
+ deps: Pick<RunnerDeps, "writeProtectedPaths" | "onNotice">;
58
+ /** borrowed-readonly — the leg's configuration roots (`leg-caller-places.ts`, the leg's one mint: the deployment's root, the
59
+ * task's, a resumed row's) — the `.sema` rows are also placed below each. */
60
+ configRoots: readonly string[];
58
61
  /** borrowed-readonly — the leg's one exempt root and the chain's guarded write rows ({@link LegWriteGuard}). */
59
62
  guard: LegWriteGuard;
60
63
  /** borrowed-readonly — the request's own rows (already judged at the task layer's door). */
@@ -13,7 +13,7 @@ export function mountWriteProtection(input) {
13
13
  ...(input.guard.exemptFiles !== undefined ? { exemptFiles: input.guard.exemptFiles } : {}),
14
14
  ...(input.guard.rows !== undefined ? { guardRows: input.guard.rows } : {}),
15
15
  ...(input.guard.checkout !== undefined ? { checkoutOf: input.guard.checkout } : {}),
16
- ...(input.deps.agentConfigDir !== undefined ? { agentConfigDir: input.deps.agentConfigDir } : {}),
16
+ ...(input.configRoots.length > 0 ? { declaredAgentConfigDirs: input.configRoots } : {}),
17
17
  ...(input.env !== undefined ? { env: input.env } : {}),
18
18
  rootPath: input.rootPath,
19
19
  onViewAbsent: (absence) => {