@sema-agent/core 7.58.0 → 7.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/CHANGELOG.md +776 -0
  2. package/README.md +6 -4
  3. package/dist/agents/cc-peer-directory.js +8 -8
  4. package/dist/agents/child-model-seat.d.ts +4 -2
  5. package/dist/agents/child-model-seat.js +5 -3
  6. package/dist/agents/peer-directory.d.ts +9 -0
  7. package/dist/agents/peer-directory.js +6 -2
  8. package/dist/agents/send-message-tool.js +21 -12
  9. package/dist/agents/subagent.js +33 -34
  10. package/dist/brain/anthropic.js +161 -45
  11. package/dist/brain/errors.d.ts +9 -3
  12. package/dist/brain/errors.js +7 -1
  13. package/dist/brain/failover.js +2 -1
  14. package/dist/brain/open-responses.js +3 -3
  15. package/dist/brain/openai.js +103 -53
  16. package/dist/brain/provider-dialect.d.ts +11 -0
  17. package/dist/brain/provider-dialect.js +5 -2
  18. package/dist/brain/reasoning-request.js +5 -4
  19. package/dist/brain/reasoning.d.ts +19 -0
  20. package/dist/brain/reasoning.js +17 -2
  21. package/dist/brain/request-route.d.ts +4 -1
  22. package/dist/brain/request-route.js +4 -1
  23. package/dist/brain/route-adjudicator.d.ts +84 -18
  24. package/dist/brain/route-adjudicator.js +87 -21
  25. package/dist/brain/route-conformance.js +1 -1
  26. package/dist/brain/stream-engine.js +84 -49
  27. package/dist/brain/stream-shared.d.ts +30 -0
  28. package/dist/brain/stream-shared.js +34 -1
  29. package/dist/brain/timeout.d.ts +62 -5
  30. package/dist/brain/timeout.js +93 -6
  31. package/dist/core/account-row.d.ts +61 -0
  32. package/dist/core/account-row.js +51 -0
  33. package/dist/core/advisor-verdict.d.ts +2 -1
  34. package/dist/core/advisor-verdict.js +1 -1
  35. package/dist/core/allow-entry.d.ts +18 -6
  36. package/dist/core/allow-entry.js +16 -8
  37. package/dist/core/approval-object.d.ts +29 -15
  38. package/dist/core/approval-object.js +47 -19
  39. package/dist/core/auto-compaction.js +1 -1
  40. package/dist/core/background-agent-store.d.ts +16 -3
  41. package/dist/core/checkpoint-requirements.d.ts +13 -1
  42. package/dist/core/checkpoint-requirements.js +3 -1
  43. package/dist/core/checkpoint-store.d.ts +58 -12
  44. package/dist/core/checkpoint-store.js +18 -6
  45. package/dist/core/child-clamp-seats.d.ts +29 -0
  46. package/dist/core/child-clamp-seats.js +56 -1
  47. package/dist/core/compliance.d.ts +2 -2
  48. package/dist/core/compliance.js +1 -1
  49. package/dist/core/effective-path-target.d.ts +8 -2
  50. package/dist/core/effective-path-target.js +8 -3
  51. package/dist/core/engine-notice.d.ts +98 -8
  52. package/dist/core/engine-notice.js +19 -5
  53. package/dist/core/gate-fold.js +1 -1
  54. package/dist/core/gate-lanes.js +8 -4
  55. package/dist/core/gate-outcome.d.ts +32 -3
  56. package/dist/core/gate-outcome.js +19 -1
  57. package/dist/core/governance-codes.d.ts +9 -1
  58. package/dist/core/governance-codes.js +13 -0
  59. package/dist/core/hooks.d.ts +31 -3
  60. package/dist/core/hooks.js +5 -6
  61. package/dist/core/image-admission.d.ts +6 -5
  62. package/dist/core/image-admission.js +18 -14
  63. package/dist/core/locked-config.d.ts +5 -2
  64. package/dist/core/locked-config.js +2 -1
  65. package/dist/core/mailbox-store.d.ts +45 -1
  66. package/dist/core/mailbox-store.js +53 -9
  67. package/dist/core/mcp-failure.d.ts +114 -18
  68. package/dist/core/mcp-failure.js +63 -5
  69. package/dist/core/mcp-server-link.d.ts +22 -1
  70. package/dist/core/mcp-server-link.js +25 -1
  71. package/dist/core/mcp.d.ts +12 -8
  72. package/dist/core/mcp.js +42 -25
  73. package/dist/core/memory-engine/consolidation-driver.d.ts +2 -4
  74. package/dist/core/memory-engine/consolidation-driver.js +3 -3
  75. package/dist/core/memory-engine/consolidation.d.ts +4 -0
  76. package/dist/core/memory-engine/consolidation.js +1 -0
  77. package/dist/core/memory-engine/delegation-settlement.js +5 -12
  78. package/dist/core/memory-engine/distiller.js +2 -2
  79. package/dist/core/memory-engine/dual-root.d.ts +50 -1
  80. package/dist/core/memory-engine/dual-root.js +44 -1
  81. package/dist/core/memory-engine/engine.d.ts +67 -14
  82. package/dist/core/memory-engine/engine.js +384 -212
  83. package/dist/core/memory-engine/export-bundle.d.ts +23 -0
  84. package/dist/core/memory-engine/export-bundle.js +23 -4
  85. package/dist/core/memory-engine/file-backend.d.ts +128 -55
  86. package/dist/core/memory-engine/file-backend.js +290 -117
  87. package/dist/core/memory-engine/index.d.ts +1 -1
  88. package/dist/core/memory-engine/layout.d.ts +59 -11
  89. package/dist/core/memory-engine/layout.js +190 -40
  90. package/dist/core/memory-engine/memory-backend-contract.d.ts +1 -1
  91. package/dist/core/memory-engine/memory-backend-contract.js +39 -2
  92. package/dist/core/memory-engine/sync-client.d.ts +9 -1
  93. package/dist/core/memory-engine/sync-client.js +31 -8
  94. package/dist/core/memory-engine/sync.d.ts +5 -0
  95. package/dist/core/memory-engine/types.d.ts +6 -0
  96. package/dist/core/mods/classic-events.d.ts +5 -1
  97. package/dist/core/mods/kernel/dispatch.js +2 -1
  98. package/dist/core/mods/kernel/events.d.ts +2 -1
  99. package/dist/core/mods/kernel/events.js +2 -2
  100. package/dist/core/mods/kernel/registration.d.ts +4 -0
  101. package/dist/core/mods/kernel/registration.js +3 -0
  102. package/dist/core/mods/stations.d.ts +31 -10
  103. package/dist/core/mods/stations.js +44 -10
  104. package/dist/core/mods/tool-call.js +1 -1
  105. package/dist/core/parent-spec-seat.d.ts +8 -3
  106. package/dist/core/parent-spec-seat.js +2 -0
  107. package/dist/core/park-selfcheck.js +6 -0
  108. package/dist/core/peer-seat.d.ts +70 -8
  109. package/dist/core/peer-seat.js +143 -11
  110. package/dist/core/permission-rule-consent.js +10 -4
  111. package/dist/core/permission-rule-model.d.ts +16 -0
  112. package/dist/core/permission-rule-model.js +1 -1
  113. package/dist/core/present-plan-tool.d.ts +11 -3
  114. package/dist/core/present-plan-tool.js +2 -2
  115. package/dist/core/resume-startup-cause.js +1 -0
  116. package/dist/core/rewrite-rejudge.d.ts +1 -0
  117. package/dist/core/rewrite-rejudge.js +2 -2
  118. package/dist/core/roles.d.ts +34 -2
  119. package/dist/core/roles.js +43 -4
  120. package/dist/core/runner/announce-once-ledger.d.ts +5 -4
  121. package/dist/core/runner/announce-once-ledger.js +4 -2
  122. package/dist/core/runner/call-hook-stations.js +2 -2
  123. package/dist/core/runner/contracts.d.ts +20 -16
  124. package/dist/core/runner/credential-origin-seat.js +4 -3
  125. package/dist/core/runner/cwd-alignment-probe.d.ts +20 -0
  126. package/dist/core/runner/cwd-alignment-probe.js +21 -0
  127. package/dist/core/runner/decide-continuation.d.ts +2 -2
  128. package/dist/core/runner/gate-exit.d.ts +12 -4
  129. package/dist/core/runner/gate-exit.js +10 -7
  130. package/dist/core/runner/image-removed-seat.d.ts +12 -0
  131. package/dist/core/runner/image-removed-seat.js +19 -0
  132. package/dist/core/runner/inline-image.js +1 -1
  133. package/dist/core/runner/memory-consolidation-driver.js +3 -3
  134. package/dist/core/runner/park-commit.d.ts +1 -1
  135. package/dist/core/runner/park-commit.js +3 -0
  136. package/dist/core/runner/prepare-ask-lane.d.ts +1 -1
  137. package/dist/core/runner/prepare-ask-lane.js +2 -1
  138. package/dist/core/runner/prepare-boundary-parks.js +2 -2
  139. package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -5
  140. package/dist/core/runner/prepare-caps-and-workflow.js +2 -0
  141. package/dist/core/runner/prepare-config-doors.js +2 -0
  142. package/dist/core/runner/prepare-context-lane.js +2 -0
  143. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  144. package/dist/core/runner/prepare-delegation-surface.js +1 -0
  145. package/dist/core/runner/prepare-hands-readface.d.ts +4 -0
  146. package/dist/core/runner/prepare-hands-readface.js +5 -0
  147. package/dist/core/runner/prepare-inherited-gate.d.ts +1 -3
  148. package/dist/core/runner/prepare-inherited-gate.js +14 -27
  149. package/dist/core/runner/prepare-memory.js +10 -17
  150. package/dist/core/runner/prepare-park-ask.d.ts +1 -1
  151. package/dist/core/runner/prepare-park-ask.js +2 -1
  152. package/dist/core/runner/prepare-policy-chain.d.ts +3 -3
  153. package/dist/core/runner/prepare-policy-chain.js +16 -13
  154. package/dist/core/runner/prepare-project-context.d.ts +2 -2
  155. package/dist/core/runner/prepare-project-context.js +2 -2
  156. package/dist/core/runner/prepare-prompt-inputs.d.ts +1 -1
  157. package/dist/core/runner/prepare-prompt-inputs.js +8 -19
  158. package/dist/core/runner/prepare-protocol-tools.js +9 -1
  159. package/dist/core/runner/prepare-run-refs.d.ts +2 -3
  160. package/dist/core/runner/prepare-run-refs.js +4 -1
  161. package/dist/core/runner/prepare-task.js +4 -2
  162. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -1
  163. package/dist/core/runner/prepare-wiring-manifest.js +2 -1
  164. package/dist/core/runner/reply-pricing.d.ts +30 -0
  165. package/dist/core/runner/reply-pricing.js +19 -0
  166. package/dist/core/runner/resume-admission.js +4 -2
  167. package/dist/core/runner/resume-apply.js +6 -1
  168. package/dist/core/runner/resume-policy-outcome.js +5 -5
  169. package/dist/core/runner/role-seat-defaulted.d.ts +44 -0
  170. package/dist/core/runner/role-seat-defaulted.js +40 -0
  171. package/dist/core/runner/run-brain-sinks.js +2 -0
  172. package/dist/core/runner/run-identity-wiring.d.ts +2 -5
  173. package/dist/core/runner/run-identity-wiring.js +5 -4
  174. package/dist/core/runner/run-leg.d.ts +2 -0
  175. package/dist/core/runner/run-leg.js +37 -28
  176. package/dist/core/runner/run-stop-and-final-verify.js +2 -2
  177. package/dist/core/runner/run-terminal-adoption.d.ts +2 -5
  178. package/dist/core/runner/run-terminal-adoption.js +9 -3
  179. package/dist/core/runner/run-turn-boundary.js +77 -70
  180. package/dist/core/runner/runtask.d.ts +1 -1
  181. package/dist/core/runner/runtask.js +2 -2
  182. package/dist/core/runner/side-call-account.d.ts +1 -1
  183. package/dist/core/runner/side-call-account.js +3 -18
  184. package/dist/core/runner/sub-agent-deny-lists.d.ts +24 -0
  185. package/dist/core/runner/sub-agent-deny-lists.js +10 -0
  186. package/dist/core/runner/tool-end-body.js +2 -2
  187. package/dist/core/runner/tool-occurrence.d.ts +1 -1
  188. package/dist/core/runner/tool-occurrence.js +2 -2
  189. package/dist/core/runner/turn-attachments.d.ts +26 -22
  190. package/dist/core/runner/turn-attachments.js +24 -26
  191. package/dist/core/runner-deps.d.ts +1 -1
  192. package/dist/core/secret-env.d.ts +32 -2
  193. package/dist/core/secret-env.js +65 -3
  194. package/dist/core/sensitive-path-policy.js +3 -3
  195. package/dist/core/session-policy-store.d.ts +3 -1
  196. package/dist/core/session-policy-store.js +13 -9
  197. package/dist/core/session-store.d.ts +2 -5
  198. package/dist/core/side-query.d.ts +11 -1
  199. package/dist/core/side-query.js +9 -0
  200. package/dist/core/skill-grant-binding.d.ts +31 -2
  201. package/dist/core/skill-grant-binding.js +31 -1
  202. package/dist/core/skill-grant.d.ts +8 -5
  203. package/dist/core/skill-grant.js +6 -6
  204. package/dist/core/store-contracts/background-agent-store-contract.js +27 -0
  205. package/dist/core/store-contracts/checkpoint-store-contract.js +3 -2
  206. package/dist/core/store-contracts/mailbox-store-contract.js +31 -1
  207. package/dist/core/synthetic-read-verdict.js +2 -1
  208. package/dist/core/task-event.d.ts +32 -8
  209. package/dist/core/task-notification.js +16 -10
  210. package/dist/core/task-registry-agent.js +1 -0
  211. package/dist/core/task-registry-shared.d.ts +5 -0
  212. package/dist/core/task-spec.d.ts +12 -1
  213. package/dist/core/terminal-cause.d.ts +10 -0
  214. package/dist/core/tool-check-reading.d.ts +1 -0
  215. package/dist/core/tool-check-reading.js +3 -3
  216. package/dist/core/tool-policy.d.ts +16 -0
  217. package/dist/core/tool-roster.d.ts +112 -5
  218. package/dist/core/tool-roster.js +42 -1
  219. package/dist/core/tool-spec.d.ts +3 -1
  220. package/dist/core/types.d.ts +2 -2
  221. package/dist/core/types.js +1 -1
  222. package/dist/core/user-attachment.js +1 -1
  223. package/dist/core/wiring-manifest.d.ts +6 -3
  224. package/dist/engine/compaction/compaction.js +29 -3
  225. package/dist/engine/execution-env/node-execution-env.d.ts +4 -3
  226. package/dist/engine/execution-env/node-execution-env.js +9 -12
  227. package/dist/engine/harness/agent-harness.d.ts +25 -2
  228. package/dist/engine/harness/agent-harness.js +41 -12
  229. package/dist/engine/harness/messages.d.ts +3 -1
  230. package/dist/engine/harness/messages.js +3 -2
  231. package/dist/engine/harness/types.d.ts +8 -0
  232. package/dist/engine/llm/rejected-images.d.ts +46 -0
  233. package/dist/engine/llm/rejected-images.js +54 -0
  234. package/dist/engine/llm/tool-turns.d.ts +2 -1
  235. package/dist/engine/llm/types.d.ts +18 -7
  236. package/dist/engine/loop/agent-loop.d.ts +8 -0
  237. package/dist/engine/loop/agent-loop.js +52 -15
  238. package/dist/engine/loop/types.d.ts +3 -1
  239. package/dist/engine/session/path-to-root.d.ts +38 -0
  240. package/dist/engine/session/path-to-root.js +39 -0
  241. package/dist/engine/session/storage-base.js +4 -21
  242. package/dist/index.d.ts +16 -10
  243. package/dist/index.js +11 -7
  244. package/dist/internal/harness-types.d.ts +1 -1
  245. package/dist/internal/harness.d.ts +1 -0
  246. package/dist/internal/llm.d.ts +1 -0
  247. package/dist/orchestration/workflow-observe.d.ts +17 -1
  248. package/dist/orchestration/workflow-observe.js +20 -0
  249. package/dist/orchestration/workflow-types.d.ts +32 -7
  250. package/dist/orchestration/workflow.js +739 -489
  251. package/dist/shell/counting-pass.d.ts +50 -0
  252. package/dist/shell/counting-pass.js +502 -0
  253. package/dist/shell/lex.d.ts +4 -2
  254. package/dist/shell/lex.js +93 -34
  255. package/dist/shell/shell-words.d.ts +1 -1
  256. package/dist/shell/shell-words.js +7 -6
  257. package/dist/stores/file/mailbox-store.js +6 -10
  258. package/dist/tools/fs/fs-bash.d.ts +6 -0
  259. package/dist/tools/fs/fs-bash.js +6 -3
  260. package/dist/tools/fs/index.js +6 -2
  261. package/dist/tools/fs/program-read-model.d.ts +13 -0
  262. package/dist/tools/fs/program-read-model.js +15 -0
  263. package/dist/tools/fs/program-read-model.rows.js +1 -1
  264. package/dist/tools/fs/read-deny.d.ts +13 -10
  265. package/dist/tools/fs/read-deny.js +25 -5
  266. package/dist/tools/fs/read-floor.d.ts +19 -0
  267. package/dist/tools/fs/read-floor.js +23 -0
  268. package/dist/tools/fs/shell-read-check.d.ts +1 -1
  269. package/dist/tools/fs/shell-read-check.js +2 -1
  270. package/dist/tools/fs/shell-read-judge.d.ts +16 -8
  271. package/dist/tools/fs/shell-read-judge.js +10 -6
  272. package/dist/tools/fs/shell-read-plan.d.ts +6 -1
  273. package/dist/tools/fs/shell-read-plan.js +22 -15
  274. package/dist/tools/fs/shell-read-start.js +1 -0
  275. package/dist/tools/fs/shell-reentry-text.d.ts +15 -1
  276. package/dist/tools/fs/shell-reentry-text.js +25 -3
  277. package/dist/tools/monitor.d.ts +4 -0
  278. package/dist/tools/monitor.js +2 -0
  279. package/package.json +3 -2
  280. package/test/export-surface.snapshot.json +87 -1
  281. package/wire-changes/core-stores-sql@7.59.0.json +29 -0
  282. package/wire-changes/core@7.59.0.json +2459 -0
  283. package/wire-changes/mods-kernel@7.59.0.json +29 -0
  284. package/wire-changes/primitives@7.59.0.json +29 -0
@@ -93,6 +93,36 @@ export interface TurnCapFacts {
93
93
  outputTokens: number | undefined;
94
94
  capTokens: number | undefined;
95
95
  }
96
+ /**
97
+ * The door's reading of a stream frame's members, one reading for every lane's frame decoder: a member the
98
+ * lane reads is taken only in the shape the wire defines — an object (non-null, non-array), an array, a string (`word`),
99
+ * a count. `null` and absent state nothing (`undefined`, not recorded). Any other value is a member in no shape: it reads
100
+ * as `undefined` — never coerced, never dereferenced — and the reader records it (`outOfShape`), so the lane says the loss
101
+ * where that member's loss is already said. A lane keeps one reader per outlet (the frame, the call stream, the usage), so
102
+ * one outlet's record never speaks for another's.
103
+ */
104
+ export interface MemberReader {
105
+ object(v: unknown): Record<string, unknown> | undefined;
106
+ array(v: unknown): readonly unknown[] | undefined;
107
+ word(v: unknown): string | undefined;
108
+ count(v: unknown): number | undefined;
109
+ /** Did a member this reader read hold a value in no shape? */
110
+ readonly outOfShape: boolean;
111
+ }
112
+ export declare function memberReader(): MemberReader;
113
+ /** The word a seat reads when something arrived there in no word shape — the echo seat's placeholder: an ending in no
114
+ * word, a late frame the door could not read. */
115
+ export declare const NO_WORD = "?";
116
+ /** The stream's ending seat as both wires read it (`finish_reason`, `stop_reason`), before AND after the end, by one rule:
117
+ * a falsy value states no ending (as it always read); a string is the provider's word; any other value (a number, `true`,
118
+ * an object) is an ending in no word the engine reads — {@link NO_WORD}. */
119
+ export declare function endingWordOf(raw: unknown): string | null;
120
+ /** Did the ending seat hold a non-word ({@link endingWordOf}'s third answer) — not a provider that spelled `?`? */
121
+ export declare function endingInNoWord(raw: unknown): boolean;
122
+ /** The one sentence a turn's dropped frames are stated in (the `bad_frame` note), for the three lanes: `data:` frames that
123
+ * were not valid JSON, or that held members in no shape the stream defines ({@link MemberReader}) — counted together, the
124
+ * first one's bytes as the sample. */
125
+ export declare function droppedFramesNote(count: number, sample: string | undefined): string;
96
126
  /**
97
127
  * The structured account of a turn that FAILED for its dropped tool calls (`AssistantMessage.modelOutputInvalid`) —
98
128
  * the lane calls it on the arm whose message is the dropped-calls sentence. `cause` is `truncated` when any call's
@@ -48,7 +48,40 @@ export function truncationCauseClause(facts) {
48
48
  }
49
49
  return terminalFrameSeen ? "" : "; the stream ended before its stop frame — the connection closed mid-response";
50
50
  }
51
- const countOf = (v) => (typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : undefined);
51
+ const isCount = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
52
+ const countOf = (v) => (isCount(v) ? v : undefined);
53
+ export function memberReader() {
54
+ let outOfShape = false;
55
+ const take = (v, inShape) => {
56
+ if (v === null || v === undefined)
57
+ return undefined;
58
+ if (inShape(v))
59
+ return v;
60
+ outOfShape = true;
61
+ return undefined;
62
+ };
63
+ return {
64
+ object: (v) => take(v, (x) => typeof x === "object" && !Array.isArray(x)),
65
+ array: (v) => take(v, Array.isArray),
66
+ word: (v) => take(v, (x) => typeof x === "string"),
67
+ count: (v) => take(v, isCount),
68
+ get outOfShape() {
69
+ return outOfShape;
70
+ },
71
+ };
72
+ }
73
+ export const NO_WORD = "?";
74
+ export function endingWordOf(raw) {
75
+ if (!raw)
76
+ return null;
77
+ return typeof raw === "string" ? raw : NO_WORD;
78
+ }
79
+ export function endingInNoWord(raw) {
80
+ return endingWordOf(raw) === NO_WORD && raw !== NO_WORD;
81
+ }
82
+ export function droppedFramesNote(count, sample) {
83
+ return `\n[note: ${count} provider stream frame(s) were not valid JSON or not in the stream's frame shape; what could not be read was dropped — the streamed output may be missing content (first sample: ${JSON.stringify(sample)})]`;
84
+ }
52
85
  export function modelOutputInvalidOf(drops, cap) {
53
86
  if (drops.truncated > 0) {
54
87
  const outputTokens = countOf(cap.outputTokens);
@@ -47,7 +47,8 @@ export declare function resolveStallTimeoutMs(value: number | undefined, knob: s
47
47
  * prefill BEFORE writing headers is silent here for minutes and healthy; the 30s "connect" clock
48
48
  * this replaces cut that prefill and re-sent the same body ten times. 300s is the reference
49
49
  * implementation's window for a non-first-party route; the window grows with the request body
50
- * ({@link firstByteWindow}) and the one retry is widened ({@link FIRST_BYTE_RETRY_WINDOW_FACTOR}).
50
+ * up to {@link FIRST_BYTE_WINDOW_CAP_MS} ({@link firstByteWindow}) and the one retry is widened
51
+ * ({@link FIRST_BYTE_RETRY_WINDOW_FACTOR}).
51
52
  * - first-token 600s: bounds the headers→first-delta wait, NOT the model's thought (the first
52
53
  * THINKING delta already counts as the first token, design/17 O5), so a slow reasoner is safe. A
53
54
  * minutes-scale bound is FALSE for a self-hosted server working through a long prefill AFTER
@@ -86,8 +87,17 @@ export declare const RETIRED_TIMEOUT_KNOBS: {
86
87
  export declare function refuseRetiredTimeoutKnobs(holder: object | undefined, level: keyof typeof RETIRED_TIMEOUT_KNOBS, where: string): void;
87
88
  /** The first-byte window grows with the request body: one second per this many bytes, rounded up (the
88
89
  * reference implementation's allowance) — a large context on a slow uplink is still UPLOADING when a
89
- * fixed window would call the gateway silent. */
90
+ * fixed window would call the gateway silent. The growth stops at {@link FIRST_BYTE_WINDOW_CAP_MS}. */
90
91
  export declare const FIRST_BYTE_UPLOAD_BYTES_PER_SECOND = 32768;
92
+ /**
93
+ * The most the upload allowance may grow a first-byte window to: 599 s, the reference implementation's
94
+ * default (its request timeout, 600 s, less one second). Without it the window grew with the body without
95
+ * bound — a 40 MB request (a context full of screenshots) armed 300 s + 1 280 s, so a gateway that never
96
+ * answered was given up on after ~26 minutes. The cap bounds the ALLOWANCE only: a knob (or its widened
97
+ * retry) already at or above it is the window as set and gains no allowance — a deployment that chose a
98
+ * longer wait is never shortened behind its back.
99
+ */
100
+ export declare const FIRST_BYTE_WINDOW_CAP_MS = 599000;
91
101
  /** A first-byte stall is re-sent at most this many times by default ({@link BrainTimeoutConfig.firstByteRetries}),
92
102
  * out of its OWN budget rather than `maxRetries` (the reference implementation: "normally one retry, not the
93
103
  * session budget"); the shared ladder counts transport failures, and this is not one. */
@@ -106,7 +116,9 @@ export declare function resolveWatchdogMs(configured: number | undefined, adviso
106
116
  export interface FirstByteWindow {
107
117
  /** The knob's value for THIS attempt (the configured value, widened on the retry). */
108
118
  knobMs: number;
109
- /** The upload allowance added for the request body, ms (0 for an empty body). */
119
+ /** The upload allowance granted for the request body, ms: one second per
120
+ * {@link FIRST_BYTE_UPLOAD_BYTES_PER_SECOND} bytes, granted up to {@link FIRST_BYTE_WINDOW_CAP_MS} and no
121
+ * further (0 for an empty body, and for a knob already at the cap). */
110
122
  allowanceMs: number;
111
123
  /** What is actually armed: `knobMs + allowanceMs`, capped at {@link MAX_TIMER_DELAY_MS}. `0` = off. */
112
124
  windowMs: number;
@@ -127,8 +139,9 @@ export interface BrainTimeoutConfig {
127
139
  /**
128
140
  * `fetch()` call → response headers, ms: the window a gateway has to START answering (until 7.33.0 a
129
141
  * knob named `connectTimeoutMs` bounded this wait; it is gone — the connect clock is the transport's). Absent ⇒
130
- * {@link STALL_FIRST_BYTE_MS}; the armed window grows with the request body ({@link firstByteWindow});
131
- * a stall earns ONE retry at a widened window ({@link firstByteRetries}), then fails naming this knob.
142
+ * {@link STALL_FIRST_BYTE_MS}; the armed window grows with the request body up to
143
+ * {@link FIRST_BYTE_WINDOW_CAP_MS} ({@link firstByteWindow}); a value at or above that cap is the window
144
+ * as set. A stall earns ONE retry at a widened window ({@link firstByteRetries}), then fails naming this knob.
132
145
  * Fires as a `stall` (this process cancelled its own request), never as a transport fault. `0` ⇒ off.
133
146
  */
134
147
  firstByteTimeoutMs?: number;
@@ -157,16 +170,60 @@ export interface BrainTimeoutConfig {
157
170
  */
158
171
  idleTimeoutMs?: number;
159
172
  }
173
+ /** How often the wall clock is read while a wait is judged for a host suspend (the reference
174
+ * implementation's sampling period). */
175
+ export declare const SUSPEND_SAMPLE_MS = 1000;
176
+ /** A gap between two samples longer than this is time this process did not run — the host slept, or the
177
+ * process was stopped — and is counted as slept, whole (the reference implementation's threshold). A
178
+ * shorter gap is a busy event loop, not a suspend. */
179
+ export declare const SUSPEND_GAP_MS = 5000;
180
+ /**
181
+ * The ONE host-suspend judgment every model-call wait reads — the response headers, the first token, the
182
+ * silence between deltas. A host that sleeps (a laptop lid closed over lunch) stops every timer; on waking,
183
+ * the connection the wait was on is usually gone, and a timer clock that did not count the sleep would
184
+ * leave the wait to run out its whole window on it. So while a wait is armed the wall clock is read every
185
+ * {@link SUSPEND_SAMPLE_MS}: the sampler is SCHEDULED on the timer clock, so a gap between two readings
186
+ * longer than {@link SUSPEND_GAP_MS} is time the timers did not run, and it is counted as slept. The armed
187
+ * wait ends — `onSuspend(sleptMs)`, once — at the first sample where the sleep it has seen exceeds half its
188
+ * window; a deadline calls {@link SuspendWatch.check} before it judges, so a deadline that runs before the
189
+ * next sample names the same suspend.
190
+ *
191
+ * The wall clock alone, not a monotonic reading beside it: a monotonic clock that counts sleep (the host's
192
+ * choice, not the engine's) cannot see a suspend at all, while a gap between samples scheduled on the timer
193
+ * clock is visible whichever way the host counts. A forward step of the wall clock reads as a suspend and
194
+ * costs one reconnect; a backward step is not counted.
195
+ */
196
+ export interface SuspendWatch {
197
+ /** Judge a new wait of `windowMs` from now — the sleep seen before this call is not its sleep. Replaces any
198
+ * armed wait; `0` (a watchdog that is off) judges nothing. */
199
+ arm(windowMs: number, onSuspend: (sleptMs: number) => void): void;
200
+ /** The armed wait ended (headers, the first token, the attempt). */
201
+ disarm(): void;
202
+ /** Read the clock now: `true` when this reading ended the armed wait as a suspend (its `onSuspend` ran). */
203
+ check(): boolean;
204
+ /** Stop for good (the attempt is over). */
205
+ dispose(): void;
206
+ }
207
+ export declare function watchSuspend(): SuspendWatch;
160
208
  /**
161
209
  * A per-attempt abort controller that fires at the first-byte deadline while still forwarding an
162
210
  * outer (task) abort. The returned `signal` governs the **whole** request including the streamed body
163
211
  * — so once headers arrive, call `clearTimer()` (NOT `dispose()`) to stop the deadline while keeping
164
212
  * the outer-abort link alive for the body read; call `dispose()` only when the request is fully done
165
213
  * or being discarded.
214
+ *
215
+ * The header wait is also judged for a host suspend ({@link SuspendWatch}, armed with the same window):
216
+ * a suspend aborts the signal like the deadline does, and is told apart by {@link suspendedMs} rather than
217
+ * {@link timedOut}. The same watch is handed on (`suspend`) for the waits after the headers; `dispose()`
218
+ * ends it.
166
219
  */
167
220
  export declare function createAttemptController(firstByteWindowMs: number | undefined, outerSignal: AbortSignal | undefined): {
168
221
  signal: AbortSignal;
169
222
  timedOut: () => boolean;
223
+ /** How long the host was suspended across the header wait, when that is what ended it; else undefined. */
224
+ suspendedMs: () => number | undefined;
225
+ /** The attempt's suspend judgment, for the waits after the headers (first token, idle). */
226
+ suspend: SuspendWatch;
170
227
  clearTimer: () => void;
171
228
  /** Abort this attempt's signal. The signal handed to `doFetch` is how an injected fetch wrapper
172
229
  * learns it may release its transport, so an attempt being ABANDONED (its error body cut short by
@@ -34,6 +34,7 @@ export function refuseRetiredTimeoutKnobs(holder, level, where) {
34
34
  }
35
35
  }
36
36
  export const FIRST_BYTE_UPLOAD_BYTES_PER_SECOND = 32_768;
37
+ export const FIRST_BYTE_WINDOW_CAP_MS = 599_000;
37
38
  export const FIRST_BYTE_RETRY_BUDGET = 1;
38
39
  export function resolveFirstByteRetries(value) {
39
40
  if (value === undefined)
@@ -53,7 +54,8 @@ export function firstByteWindow(knobMs, bodyBytes, retryIndex) {
53
54
  if (knobMs === undefined || knobMs <= 0)
54
55
  return { knobMs: 0, allowanceMs: 0, windowMs: 0 };
55
56
  const widened = knobMs * FIRST_BYTE_RETRY_WINDOW_FACTOR ** Math.max(0, retryIndex);
56
- const allowanceMs = Math.ceil(Math.max(0, bodyBytes) / FIRST_BYTE_UPLOAD_BYTES_PER_SECOND) * 1000;
57
+ const uploadMs = Math.ceil(Math.max(0, bodyBytes) / FIRST_BYTE_UPLOAD_BYTES_PER_SECOND) * 1000;
58
+ const allowanceMs = Math.min(uploadMs, Math.max(0, FIRST_BYTE_WINDOW_CAP_MS - widened));
57
59
  return { knobMs: widened, allowanceMs, windowMs: Math.min(widened + allowanceMs, MAX_TIMER_DELAY_MS) };
58
60
  }
59
61
  export function firstByteLaneKnobMs(knobMs) {
@@ -62,6 +64,76 @@ export function firstByteLaneKnobMs(knobMs) {
62
64
  total += firstByteWindow(knobMs, 0, retryIndex).knobMs;
63
65
  return total;
64
66
  }
67
+ export const SUSPEND_SAMPLE_MS = 1_000;
68
+ export const SUSPEND_GAP_MS = 5_000;
69
+ export function watchSuspend() {
70
+ let readAt = 0;
71
+ let sleptMs = 0;
72
+ let wait;
73
+ let timer;
74
+ let disposed = false;
75
+ const read = () => {
76
+ const now = Date.now();
77
+ const gap = now - readAt;
78
+ readAt = now;
79
+ if (gap > SUSPEND_GAP_MS)
80
+ sleptMs += gap;
81
+ };
82
+ const stopSampling = () => {
83
+ if (timer !== undefined)
84
+ clearTimeout(timer);
85
+ timer = undefined;
86
+ };
87
+ const check = () => {
88
+ if (wait === undefined)
89
+ return false;
90
+ read();
91
+ const slept = sleptMs - wait.sleptAtArm;
92
+ if (!(slept > wait.windowMs / 2))
93
+ return false;
94
+ const { onSuspend } = wait;
95
+ wait = undefined;
96
+ stopSampling();
97
+ onSuspend(slept);
98
+ return true;
99
+ };
100
+ const sample = () => {
101
+ timer = setTimeout(() => {
102
+ timer = undefined;
103
+ if (!check() && wait !== undefined)
104
+ sample();
105
+ }, SUSPEND_SAMPLE_MS);
106
+ timer.unref?.();
107
+ };
108
+ return {
109
+ arm(windowMs, onSuspend) {
110
+ if (disposed)
111
+ return;
112
+ if (timer !== undefined)
113
+ read();
114
+ else
115
+ readAt = Date.now();
116
+ if (!(windowMs > 0)) {
117
+ wait = undefined;
118
+ stopSampling();
119
+ return;
120
+ }
121
+ wait = { windowMs, sleptAtArm: sleptMs, onSuspend };
122
+ if (timer === undefined)
123
+ sample();
124
+ },
125
+ disarm() {
126
+ wait = undefined;
127
+ stopSampling();
128
+ },
129
+ check,
130
+ dispose() {
131
+ disposed = true;
132
+ wait = undefined;
133
+ stopSampling();
134
+ },
135
+ };
136
+ }
65
137
  export function createAttemptController(firstByteWindowMs, outerSignal) {
66
138
  const ac = new AbortController();
67
139
  let timedOut = false;
@@ -73,24 +145,39 @@ export function createAttemptController(firstByteWindowMs, outerSignal) {
73
145
  outerSignal.addEventListener("abort", onAbort, { once: true });
74
146
  }
75
147
  let timer;
148
+ let suspendedMs;
149
+ const suspend = watchSuspend();
150
+ const clearTimer = () => {
151
+ if (timer)
152
+ clearTimeout(timer);
153
+ timer = undefined;
154
+ suspend.disarm();
155
+ };
76
156
  if (firstByteWindowMs && firstByteWindowMs > 0) {
157
+ suspend.arm(firstByteWindowMs, (slept) => {
158
+ suspendedMs = slept;
159
+ clearTimer();
160
+ ac.abort();
161
+ });
77
162
  timer = setTimeout(() => {
163
+ timer = undefined;
164
+ if (suspend.check())
165
+ return;
166
+ suspend.disarm();
78
167
  timedOut = true;
79
168
  ac.abort();
80
169
  }, firstByteWindowMs);
81
170
  }
82
- const clearTimer = () => {
83
- if (timer)
84
- clearTimeout(timer);
85
- timer = undefined;
86
- };
87
171
  return {
88
172
  signal: ac.signal,
89
173
  timedOut: () => timedOut,
174
+ suspendedMs: () => suspendedMs,
175
+ suspend,
90
176
  clearTimer,
91
177
  abort: () => ac.abort(),
92
178
  dispose: () => {
93
179
  clearTimer();
180
+ suspend.dispose();
94
181
  if (outerSignal)
95
182
  outerSignal.removeEventListener("abort", onAbort);
96
183
  },
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The engine's account LINE and its one reading. A host that keeps a session's spend (a result frame's total, a `/cost`
3
+ * view, a server's session aggregate) keeps the engine-priced lines it is handed — one per finished run, one per side query — and
4
+ * reads them back through {@link foldAccount}; no host re-sums, re-prices, or decides for itself what an unpriced line means.
5
+ *
6
+ * What the engine owns: the pricing (`priceReply`, the arithmetic every run lane already uses) and the line's shape. What it
7
+ * does not own: where lines are kept — persistence is the host's, so "a resumed session includes its history" is the fold of
8
+ * the history lines the host supplies plus this run's line.
9
+ */
10
+ import type { TaskResult } from "./task-result.js";
11
+ /** Who caused a line of the account: a run (the user's turns and everything the run's own agent caused — its compaction,
12
+ * classifier, mods, advisor and delegated sub-agents are INSIDE the run's line) or a side query (`Runner.sideQuery`, the one-shot
13
+ * utility call that belongs to no run). A closed set: the fold's `byOrigin` is total over it by its type. */
14
+ export declare const ACCOUNT_ORIGINS: readonly ["run", "side_query"];
15
+ export type AccountOrigin = (typeof ACCOUNT_ORIGINS)[number];
16
+ /** One priced line. `costMicroUsd` is integer micro-USD and ABSENT when any spend in the line was unpriced — unknown, never a
17
+ * fabricated 0 (the run's `stats.costMicroUsd` law); `usageMissing` marks figures that are a lower bound because a reply
18
+ * reported no usage. */
19
+ export interface AccountRow {
20
+ origin: AccountOrigin;
21
+ tokens: number;
22
+ costMicroUsd?: number;
23
+ usageMissing?: true;
24
+ }
25
+ /**
26
+ * The line a finished run contributes: its own usage plus its delegated sub-agents' (`stats.nested`) — the fully reconciled
27
+ * spend of the run. Unknown stays unknown: a run whose own or delegated spend was unpriced yields a line without a cost.
28
+ *
29
+ * The line is exactly what the result's `stats` says, so it is exact for a run that did not durably resume and that no
30
+ * background delegate outlived. `stats` itself is not one interval across a durable resume chain — a leg's own usage is per leg
31
+ * (a `resource_limit` chain's folds the earlier slices in), its delegated usage is cumulative over the chain, and an unknown
32
+ * mark does not survive the chain or the delegation rollup — so the lines of ONE chain are not additive, and spend a background
33
+ * delegate books after the result settled is in no line. Spend the engine books after the result — the prompt-suggestion pass,
34
+ * memory consolidation — is on its own face. The reading that has none of these gaps is an account the engine keeps, minted where
35
+ * each interval is known.
36
+ */
37
+ export declare function accountRowOfResult(result: {
38
+ readonly stats: Pick<TaskResult["stats"], "tokens" | "costMicroUsd" | "usageMissing" | "nested">;
39
+ }): AccountRow;
40
+ /** A fold of lines: how many, their tokens, their cost (absent as soon as any one line's cost is unknown), and whether any
41
+ * figure is a lower bound. An empty fold is a known zero. */
42
+ export interface AccountTotal {
43
+ rows: number;
44
+ tokens: number;
45
+ costMicroUsd?: number;
46
+ usageMissing?: true;
47
+ }
48
+ /** The session's account: the total over every line, and the same fold per origin. */
49
+ export interface SessionAccount extends AccountTotal {
50
+ byOrigin: Record<AccountOrigin, AccountTotal>;
51
+ }
52
+ /**
53
+ * THE reading of a session's account: fold the lines a host holds — history lines it persisted, this run's line, side-query lines —
54
+ * into one total and one total per origin. A line whose cost is unknown makes every total that contains it unknown (cost
55
+ * absent), because a sum that skipped it would present a lower bound as the whole. A malformed line (origin outside the closed set,
56
+ * a negative or non-finite number, a cost spelled as anything but an absent key) is refused loudly rather than summed.
57
+ *
58
+ * Which total a field shows is the host's mapping, stated once so the hosts agree: a run result frame's `total_cost_usd` is
59
+ * `byOrigin.run` (the run lines, history included, side queries not in it); a session's cumulative figure is the whole fold.
60
+ */
61
+ export declare function foldAccount(rows: Iterable<AccountRow>): SessionAccount;
@@ -0,0 +1,51 @@
1
+ export const ACCOUNT_ORIGINS = Object.freeze(["run", "side_query"]);
2
+ export function accountRowOfResult(result) {
3
+ const { tokens, costMicroUsd, usageMissing, nested } = result.stats;
4
+ const known = costMicroUsd !== undefined && (nested === undefined || nested.costMicroUsd !== undefined);
5
+ return {
6
+ origin: "run",
7
+ tokens: tokens + (nested?.tokens ?? 0),
8
+ ...(known ? { costMicroUsd: costMicroUsd + (nested?.costMicroUsd ?? 0) } : {}),
9
+ ...(usageMissing === true ? { usageMissing: true } : {}),
10
+ };
11
+ }
12
+ function addRow(total, row) {
13
+ total.rows += 1;
14
+ total.tokens += row.tokens;
15
+ total.costMicroUsd = total.costMicroUsd === undefined || row.costMicroUsd === undefined ? undefined : total.costMicroUsd + row.costMicroUsd;
16
+ if (row.usageMissing === true)
17
+ total.usageMissing = true;
18
+ }
19
+ function settled(total) {
20
+ const { costMicroUsd, ...rest } = total;
21
+ return { ...rest, ...(costMicroUsd !== undefined ? { costMicroUsd } : {}) };
22
+ }
23
+ function checkedRow(row, index) {
24
+ const bad = (why) => {
25
+ throw new TypeError(`foldAccount: row ${index} ${why}`);
26
+ };
27
+ if (typeof row !== "object" || row === null)
28
+ return bad("is not an object");
29
+ const { origin, tokens, costMicroUsd, usageMissing } = row;
30
+ if (!ACCOUNT_ORIGINS.includes(origin))
31
+ bad(`has origin ${JSON.stringify(origin)}, outside ${JSON.stringify(ACCOUNT_ORIGINS)}`);
32
+ if (typeof tokens !== "number" || !Number.isFinite(tokens) || tokens < 0)
33
+ bad("has tokens that are not a finite non-negative number");
34
+ if (costMicroUsd !== undefined && (typeof costMicroUsd !== "number" || !Number.isInteger(costMicroUsd) || costMicroUsd < 0))
35
+ bad("has costMicroUsd that is not a non-negative integer of micro-USD (an unknown cost is an absent key; a USD figure is not micro-USD)");
36
+ if (usageMissing !== undefined && usageMissing !== true)
37
+ bad("has usageMissing other than true (an absent key is the only other reading)");
38
+ return { origin: origin, tokens: tokens, ...(costMicroUsd !== undefined ? { costMicroUsd: costMicroUsd } : {}), ...(usageMissing === true ? { usageMissing: true } : {}) };
39
+ }
40
+ export function foldAccount(rows) {
41
+ const empty = () => ({ rows: 0, tokens: 0, costMicroUsd: 0 });
42
+ const byOrigin = { run: empty(), side_query: empty() };
43
+ const all = empty();
44
+ let index = 0;
45
+ for (const raw of rows) {
46
+ const row = checkedRow(raw, index++);
47
+ addRow(byOrigin[row.origin], row);
48
+ addRow(all, row);
49
+ }
50
+ return { ...settled(all), byOrigin: { run: settled(byOrigin.run), side_query: settled(byOrigin.side_query) } };
51
+ }
@@ -6,6 +6,7 @@
6
6
  * The closed sets the answers are spelled in live beside them.
7
7
  */
8
8
  import type { SessionTreeEntry } from "../internal/harness-types.js";
9
+ import type { AssistantMessage } from "../internal/llm.js";
9
10
  import { type BrainErrorCode } from "../brain/errors.js";
10
11
  import type { AssertAllKeysHandled } from "./ask-origin.js";
11
12
  import type { EngineNotice, Model, ModelRef, RunnerDeps } from "./types.js";
@@ -86,7 +87,7 @@ export type HoldCausesCoverEveryBrainCode = AssertAllKeysHandled<Exclude<BrainEr
86
87
  /** What a failed advisor request said about itself — the fields the hold reads and the card carries. */
87
88
  export interface AdvisorFailure {
88
89
  readonly code?: BrainErrorCode;
89
- readonly errorKind?: "input_too_long" | "degenerate" | "length_empty";
90
+ readonly errorKind?: AssistantMessage["errorKind"];
90
91
  readonly inputTooLongRuledOut?: true;
91
92
  }
92
93
  /** Whether this failure switches the advisor off for the conversation ({@link ADVISOR_HOLD_CAUSES}). */
@@ -62,7 +62,7 @@ export function advisorFailureHolds(f) {
62
62
  const row = ADVISOR_HOLD_CAUSES[f.code];
63
63
  return row === "hold" || (row === "hold_unless_window" && f.errorKind !== "input_too_long" && f.inputTooLongRuledOut === true);
64
64
  }
65
- const ERROR_KINDS = new Set(["input_too_long", "degenerate", "length_empty"]);
65
+ const ERROR_KINDS = new Set(["input_too_long", "degenerate", "length_empty", "image_unprocessable"]);
66
66
  export function advisorHoldOf(entries) {
67
67
  for (let i = entries.length - 1; i >= 0; i--) {
68
68
  const e = entries[i];
@@ -123,13 +123,23 @@ export declare const AUTO_STRIPPED_PROGRAMS: readonly ["python", "python3", "pyt
123
123
  * Does auto mode strip this allow entry for this call (see the module doc)? Read for every rule-shaped member — a list
124
124
  * entry, and a person's stored row through {@link autoStrippedRule}; a hook's allow is not an entry and is never stripped.
125
125
  * A stripped entry takes no part in the match (the reference removes it before matching), so it neither clears nor is
126
- * disclosed.
126
+ * disclosed. `allShell`: the leg declared `TaskSpec.classifyAllShell` — every shell command rule stands down, whatever it
127
+ * names, and no entry of any kind clears a call that answers to the shell (the reference suspends every shell allow rule
128
+ * under that setting without reading its content; a path rule a shell-face tool's declared target reaches is one here).
127
129
  */
128
- export declare function autoStripped(compiled: CompiledAllowEntry, call: ToolCallRequest | undefined): boolean;
129
- /** {@link autoStripped} over a person's stored ALLOW row, read as its list twin ({@link entryOfRow}): a row is stripped exactly when
130
+ export declare function autoStripped(compiled: CompiledAllowEntry, call: ToolCallRequest | undefined, allShell: boolean): boolean;
131
+ /** THE strip as every allow member reads it, per call: only in `auto`, and then {@link autoStripped} under the leg's
132
+ * `classifyAllShell` declaration. The one place the mode is compared for the strip. */
133
+ export declare function strippedInAuto(compiled: CompiledAllowEntry, call: ToolCallRequest | undefined, mode: PermissionMode | undefined, allShell: boolean): boolean;
134
+ /** {@link strippedInAuto} over a person's stored ALLOW row, read as its list twin ({@link entryOfRow}): a row is stripped exactly when
130
135
  * the entry spelling the same rule is (a deny / ask row never is; a row no grammar reads has no twin and is not stripped here — the
131
136
  * lane reads no allow it cannot parse). */
132
- export declare function autoStrippedRule(rule: PersistedRule, call: ToolCallRequest): boolean;
137
+ export declare function autoStrippedRule(rule: PersistedRule, call: ToolCallRequest, mode: PermissionMode | undefined, allShell: boolean): boolean;
138
+ /** Does the leg's spec declare that every shell entry is the classifier's in `auto` — the one reading of
139
+ * `TaskSpec.classifyAllShell` (its value is screened at the door: present ⇒ a boolean). */
140
+ export declare function classifiesAllShell(spec: {
141
+ readonly classifyAllShell?: boolean;
142
+ }): boolean;
133
143
  /** One row a list matcher reads. */
134
144
  export interface AllowEntryRow {
135
145
  readonly behavior: "allow" | "deny";
@@ -138,12 +148,14 @@ export interface AllowEntryRow {
138
148
  }
139
149
  /** The facts a list's content row is judged under: the leg's root and session (which rows apply), the live working
140
150
  * directory (where a command's `cd` lands), and the ANCHORS of the list's path rows — the leg the list was installed
141
- * on (its root and environment home): a path row of a list never moves with a `cd`. */
151
+ * on (its root and environment home): a path row of a list never moves with a `cd`. `classifyAllShell`: the leg's
152
+ * declaration ({@link classifiesAllShell}) the auto strip reads ({@link strippedInAuto}); absent ⇒ the leg declared nothing. */
142
153
  export interface AllowEntryJudgeContext {
143
154
  readonly root: string | undefined;
144
155
  readonly sessionId: string | undefined;
145
156
  readonly liveCwd: () => string | undefined;
146
157
  readonly anchors: PathRuleBases;
158
+ readonly classifyAllShell?: boolean;
147
159
  }
148
160
  /** For a list whose allow rows admitted no call ({@link judgeAllowEntries}): the first segment of the call's command no command
149
161
  * row covers under `posture` — the word a refusal names; `undefined` when the call carries no command or no single segment is
@@ -165,7 +177,7 @@ export declare function uncoveredCommandSegment(rows: readonly AllowEntryRow[],
165
177
  */
166
178
  export declare function judgeAllowEntries<R extends AllowEntryRow>(rows: readonly R[], req: ToolCallRequest, behavior: "allow" | "deny", ctx: AllowEntryJudgeContext, posture?: AdmissionPosture): readonly R[] | undefined;
167
179
  /** The allow rows of a list, as the allow layer reads them in `mode`: the strip applied BEFORE the match (in `auto`). */
168
- export declare function allowingRows<R extends AllowEntryRow>(rows: readonly R[], req: ToolCallRequest, mode: PermissionMode | undefined): readonly R[];
180
+ export declare function allowingRows<R extends AllowEntryRow>(rows: readonly R[], req: ToolCallRequest, mode: PermissionMode | undefined, allShell: boolean): readonly R[];
169
181
  /** The two sources {@link AllowEntryTable} holds (a skill's list is the skill table's). */
170
182
  export type AllowEntrySource = "request" | "deployment";
171
183
  /** What spoke for a call: the entries it stands on, as the list spells them, and — for entries of the list the run received —
@@ -127,30 +127,35 @@ function shellRuleContent(rule) {
127
127
  const body = "reject" in split ? rule.command : (split.segments[split.segments.length - 1] ?? rule.command).trim();
128
128
  return rule.match === "prefix" ? `${body}:*` : rule.match === "wildcard" ? `${body} *` : body;
129
129
  }
130
- export function autoStripped(compiled, call) {
130
+ export function autoStripped(compiled, call, allShell) {
131
131
  switch (compiled.kind) {
132
132
  case "shell":
133
133
  return true;
134
134
  case "tool":
135
+ case "covering":
135
136
  return call !== undefined && answersTo(call, isShellFaceToolName);
136
137
  case "command":
138
+ if (allShell)
139
+ return true;
137
140
  return compiled.rule.match === "pattern" ? commandPatternMayRun(compiled.rule.command, AUTO_STRIPPED_PROGRAMS) : shellContentStripped(shellRuleContent(compiled.rule));
138
- case "covering":
139
141
  case "path":
140
142
  case "name":
141
143
  case "domain":
142
- return false;
144
+ return allShell && call !== undefined && answersTo(call, isShellFaceToolName);
143
145
  default: {
144
146
  const exhaustive = compiled;
145
147
  return exhaustive;
146
148
  }
147
149
  }
148
150
  }
149
- export function autoStrippedRule(rule, call) {
151
+ export function strippedInAuto(compiled, call, mode, allShell) {
152
+ return mode === "auto" && autoStripped(compiled, call, allShell);
153
+ }
154
+ export function autoStrippedRule(rule, call, mode, allShell) {
150
155
  if (rule.behavior !== "allow")
151
156
  return false;
152
157
  const entry = entryOfRow(rule);
153
- return entry !== undefined && autoStripped(entry, call);
158
+ return entry !== undefined && strippedInAuto(entry, call, mode, allShell);
154
159
  }
155
160
  function entryOfRow(rule) {
156
161
  if (rule.match === "tool")
@@ -158,6 +163,9 @@ function entryOfRow(rule) {
158
163
  const grammar = ruleToolGrammarOf(rule.tool);
159
164
  return grammar === undefined ? undefined : { kind: grammar, rule };
160
165
  }
166
+ export function classifiesAllShell(spec) {
167
+ return spec.classifyAllShell === true;
168
+ }
161
169
  const NO_LEADS = new Map();
162
170
  function nameRowReaches(compiled, req) {
163
171
  if (compiled.kind === "tool" || compiled.kind === "shell")
@@ -234,8 +242,8 @@ export function judgeAllowEntries(rows, req, behavior, ctx, posture = "grant") {
234
242
  }
235
243
  return undefined;
236
244
  }
237
- export function allowingRows(rows, req, mode) {
238
- return mode === "auto" ? rows.filter((r) => !autoStripped(r.compiled, req)) : rows;
245
+ export function allowingRows(rows, req, mode, allShell) {
246
+ return rows.filter((r) => !strippedInAuto(r.compiled, req, mode, allShell));
239
247
  }
240
248
  export class AllowEntryTable {
241
249
  held = [];
@@ -270,7 +278,7 @@ export class AllowEntryTable {
270
278
  lane(ctx) {
271
279
  return {
272
280
  allowing: (req, mode) => {
273
- const hit = judgeAllowEntries(allowingRows(this.held, req, mode), req, "allow", ctx);
281
+ const hit = judgeAllowEntries(allowingRows(this.held, req, mode, ctx.classifyAllShell === true), req, "allow", ctx);
274
282
  if (hit === undefined)
275
283
  return undefined;
276
284
  const entries = hit.map((r) => r.entry);