@sema-agent/core 7.17.7 → 7.18.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 (163) hide show
  1. package/CHANGELOG.md +140 -13
  2. package/dist/agents/send-message-tool.js +1 -0
  3. package/dist/agents/subagent.d.ts +1 -0
  4. package/dist/agents/subagent.js +5 -0
  5. package/dist/agents/teacher.js +1 -0
  6. package/dist/agents/verify.js +3 -0
  7. package/dist/brain/route-adjudicator.d.ts +18 -0
  8. package/dist/brain/route-adjudicator.js +16 -0
  9. package/dist/core/agent-definition.d.ts +10 -0
  10. package/dist/core/artifact-host.d.ts +41 -4
  11. package/dist/core/artifact-host.js +18 -2
  12. package/dist/core/auto-mode.d.ts +141 -45
  13. package/dist/core/auto-mode.js +109 -3
  14. package/dist/core/checkpoint-store.d.ts +16 -2
  15. package/dist/core/engine-notice.d.ts +47 -1
  16. package/dist/core/engine-notice.js +7 -0
  17. package/dist/core/gate-lanes.js +2 -1
  18. package/dist/core/gate-outcome.d.ts +17 -2
  19. package/dist/core/gate-outcome.js +16 -0
  20. package/dist/core/governance-codes.d.ts +1 -1
  21. package/dist/core/governance-codes.js +8 -0
  22. package/dist/core/hook-seats.d.ts +66 -0
  23. package/dist/core/hook-seats.js +37 -0
  24. package/dist/core/runner/advertised-writable-dirs.d.ts +8 -3
  25. package/dist/core/runner/assemble-result.d.ts +2 -1
  26. package/dist/core/runner/assemble-result.js +1 -1
  27. package/dist/core/runner/classifier-ladder.d.ts +89 -0
  28. package/dist/core/runner/classifier-ladder.js +65 -0
  29. package/dist/core/runner/contracts.d.ts +69 -13
  30. package/dist/core/runner/decide-continuation.d.ts +1 -3
  31. package/dist/core/runner/decide-continuation.js +1 -7
  32. package/dist/core/runner/deferral-census.d.ts +52 -0
  33. package/dist/core/runner/deferral-census.js +44 -0
  34. package/dist/core/runner/derived-route-fallback.d.ts +8 -4
  35. package/dist/core/runner/derived-route-fallback.js +8 -3
  36. package/dist/core/runner/gate-exit.d.ts +12 -0
  37. package/dist/core/runner/gate-exit.js +6 -3
  38. package/dist/core/runner/prepare-artifact.d.ts +10 -2
  39. package/dist/core/runner/prepare-artifact.js +5 -4
  40. package/dist/core/runner/prepare-caps-and-workflow.d.ts +4 -2
  41. package/dist/core/runner/prepare-caps-and-workflow.js +30 -31
  42. package/dist/core/runner/prepare-config-doors.d.ts +1 -1
  43. package/dist/core/runner/prepare-config-doors.js +5 -3
  44. package/dist/core/runner/prepare-defer-classify.d.ts +13 -19
  45. package/dist/core/runner/prepare-defer-classify.js +8 -3
  46. package/dist/core/runner/prepare-gate-stations.d.ts +26 -0
  47. package/dist/core/runner/prepare-gate-stations.js +1 -1
  48. package/dist/core/runner/prepare-hands-readface.d.ts +24 -7
  49. package/dist/core/runner/prepare-hands-readface.js +60 -24
  50. package/dist/core/runner/prepare-inherited-gate.d.ts +17 -4
  51. package/dist/core/runner/prepare-inherited-gate.js +10 -2
  52. package/dist/core/runner/prepare-lsp.d.ts +2 -2
  53. package/dist/core/runner/prepare-lsp.js +1 -1
  54. package/dist/core/runner/prepare-policy-chain.js +2 -0
  55. package/dist/core/runner/prepare-project-context.js +4 -2
  56. package/dist/core/runner/prepare-prompt-inputs.d.ts +4 -2
  57. package/dist/core/runner/prepare-prompt-inputs.js +4 -1
  58. package/dist/core/runner/prepare-run-refs.d.ts +9 -1
  59. package/dist/core/runner/prepare-run-refs.js +3 -2
  60. package/dist/core/runner/prepare-suspend-saga.d.ts +5 -0
  61. package/dist/core/runner/prepare-suspend-saga.js +5 -2
  62. package/dist/core/runner/prepare-task.js +18 -13
  63. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +5 -0
  64. package/dist/core/runner/prepare-tool-disclosure-mount.js +10 -2
  65. package/dist/core/runner/prepare-turn-wiring.d.ts +8 -4
  66. package/dist/core/runner/prepare-turn-wiring.js +3 -2
  67. package/dist/core/runner/prepare-wiring-manifest.d.ts +5 -5
  68. package/dist/core/runner/prepare-wiring-manifest.js +5 -2
  69. package/dist/core/runner/resume-checkpoint-screen.js +7 -0
  70. package/dist/core/runner/run-harness-handlers.js +4 -1
  71. package/dist/core/runner/run-identity-wiring.js +6 -2
  72. package/dist/core/runner/run-leg.d.ts +2 -0
  73. package/dist/core/runner/run-leg.js +35 -41
  74. package/dist/core/runner/run-notification-lane.js +55 -27
  75. package/dist/core/runner/run-settle-and-teardown.js +1 -0
  76. package/dist/core/runner/run-terminal-adoption.js +16 -13
  77. package/dist/core/runner/run-turn-boundary.js +3 -1
  78. package/dist/core/runner/runtask.d.ts +6 -5
  79. package/dist/core/runner/runtask.js +26 -14
  80. package/dist/core/runner/skill-base-dir.d.ts +54 -0
  81. package/dist/core/runner/skill-base-dir.js +42 -0
  82. package/dist/core/runner/synthetic-tools.d.ts +16 -19
  83. package/dist/core/runner/synthetic-tools.js +18 -10
  84. package/dist/core/runner/tool-defer-gate.d.ts +22 -9
  85. package/dist/core/runner/tool-defer-gate.js +15 -5
  86. package/dist/core/runner/tool-disclosure.d.ts +5 -0
  87. package/dist/core/runner/tool-disclosure.js +2 -0
  88. package/dist/core/runner/tool-progress-lane.d.ts +42 -0
  89. package/dist/core/runner/tool-progress-lane.js +61 -0
  90. package/dist/core/runner-deps.d.ts +48 -7
  91. package/dist/core/swappable-deps.d.ts +9 -7
  92. package/dist/core/swappable-deps.js +7 -3
  93. package/dist/core/task-event.d.ts +96 -29
  94. package/dist/core/task-notification.d.ts +142 -16
  95. package/dist/core/task-notification.js +106 -0
  96. package/dist/core/task-result.d.ts +9 -1
  97. package/dist/core/task-spec.d.ts +20 -3
  98. package/dist/core/tighten-task-spec.js +7 -5
  99. package/dist/core/tool-model-gate.d.ts +1 -1
  100. package/dist/core/tool-search-setting.d.ts +78 -0
  101. package/dist/core/tool-search-setting.js +90 -0
  102. package/dist/core/tool-spec.d.ts +8 -0
  103. package/dist/core/types.d.ts +1 -1
  104. package/dist/core/types.js +1 -1
  105. package/dist/core/wiring-manifest.d.ts +46 -0
  106. package/dist/core/wiring-manifest.js +9 -1
  107. package/dist/engine/execution-env/node-execution-env.js +10 -4
  108. package/dist/engine/harness/agent-harness.d.ts +42 -0
  109. package/dist/engine/harness/agent-harness.js +61 -29
  110. package/dist/engine/loop/agent-loop.d.ts +68 -3
  111. package/dist/engine/loop/agent-loop.js +109 -16
  112. package/dist/index.d.ts +10 -5
  113. package/dist/index.js +9 -5
  114. package/dist/internal/harness.d.ts +1 -1
  115. package/dist/orchestration/run-workflow-tool.d.ts +3 -0
  116. package/dist/orchestration/run-workflow-tool.js +6 -1
  117. package/dist/orchestration/workflow-governance.d.ts +7 -1
  118. package/dist/orchestration/workflow-governance.js +9 -5
  119. package/dist/orchestration/workflow-primitives.d.ts +3 -0
  120. package/dist/orchestration/workflow-primitives.js +6 -1
  121. package/dist/orchestration/workflow-types.d.ts +48 -13
  122. package/dist/orchestration/workflow-types.js +1 -1
  123. package/dist/orchestration/workflow.js +45 -17
  124. package/dist/prompt-assembly/epoch.js +2 -0
  125. package/dist/prompt-assembly/packs/sema-default.js +2 -2
  126. package/dist/prompt-assembly/section-usage.d.ts +26 -0
  127. package/dist/prompt-assembly/section-usage.js +10 -0
  128. package/dist/prompt-assembly/types.d.ts +8 -6
  129. package/dist/prompts/default.d.ts +13 -0
  130. package/dist/prompts/default.js +16 -8
  131. package/dist/tools/artifact/artifact-text.d.ts +10 -1
  132. package/dist/tools/artifact/artifact-text.js +6 -3
  133. package/dist/tools/artifact/artifact-tool.d.ts +12 -2
  134. package/dist/tools/artifact/artifact-tool.js +203 -70
  135. package/dist/tools/artifact/conformance.d.ts +56 -0
  136. package/dist/tools/artifact/conformance.js +349 -0
  137. package/dist/tools/artifact/local-stub.js +1 -1
  138. package/dist/tools/artifact/reject-breaker.d.ts +28 -0
  139. package/dist/tools/artifact/reject-breaker.js +42 -0
  140. package/dist/tools/fs/bash-lexer.d.ts +132 -0
  141. package/dist/tools/fs/bash-lexer.js +563 -0
  142. package/dist/tools/fs/bash-program-position.d.ts +142 -0
  143. package/dist/tools/fs/bash-program-position.js +125 -0
  144. package/dist/tools/fs/bash-readonly-classifier.d.ts +54 -16
  145. package/dist/tools/fs/bash-readonly-classifier.js +121 -552
  146. package/dist/tools/fs/containment-face.d.ts +89 -0
  147. package/dist/tools/fs/containment-face.js +81 -0
  148. package/dist/tools/fs/fs-bash.d.ts +46 -1
  149. package/dist/tools/fs/fs-bash.js +158 -22
  150. package/dist/tools/fs/fs-read.d.ts +1 -1
  151. package/dist/tools/fs/fs-search-tools.d.ts +3 -3
  152. package/dist/tools/fs/fs-write.d.ts +4 -3
  153. package/dist/tools/fs/fs-write.js +9 -9
  154. package/dist/tools/fs/index.d.ts +24 -5
  155. package/dist/tools/fs/index.js +18 -6
  156. package/dist/tools/fs/repo-map.d.ts +2 -2
  157. package/dist/tools/fs/safety.d.ts +3 -3
  158. package/dist/tools/fs/safety.js +4 -4
  159. package/package.json +1 -1
  160. package/test/export-surface.snapshot.json +85 -9
  161. package/wire-changes/core@7.17.7.json +49 -0
  162. package/dist/tools/fs/read-face.d.ts +0 -68
  163. package/dist/tools/fs/read-face.js +0 -47
@@ -1,4 +1,5 @@
1
1
  import type { ActorAssertion, AssistantMessage, ImageContent, Model, UserMessage } from "../llm/index.js";
2
+ import type { HaltRemainingDirective } from "../loop/types.js";
2
3
  import type { AgentMessage, AgentTool, LoopMalformedToolUseRecovery, LoopThinkingOnlyRecovery, LoopTruncatedOutputRecovery, QueueMode, ThinkingLevel } from "../loop/types.js";
3
4
  import { type EngineSegment } from "../../core/untrusted-text.js";
4
5
  import type { AbortResult, AgentHarnessEvent, AgentHarnessEventResultMap, AgentHarnessOptions, AgentHarnessOwnEvent, AgentHarnessResources, AgentHarnessStreamOptions, ExecutionEnv, PromptTemplate, Skill } from "./types.js";
@@ -24,6 +25,16 @@ export interface HaltConsumption {
24
25
  readonly sources: ReadonlyArray<StopRequestSource>;
25
26
  };
26
27
  }
28
+ /** `prompt()` option: settle the transcript's trailing UNANSWERED tool batch through the loop's own batch pipeline
29
+ * BEFORE the prompt is delivered (a resumed run whose suspended batch still holds unanswered calls). `halt` settles
30
+ * every unanswered call as not-executed instead (the batch-halt form). No unanswered tail ⇒ a no-op. */
31
+ export interface TrailingToolBatchOptions {
32
+ readonly halt?: HaltRemainingDirective;
33
+ }
34
+ /** `prompt()` option: called when the prompt and next-turn queue's messages enter the loop transcript, before
35
+ * their frames are emitted and committed. Not called when a trailing-batch settlement ends the run first — the
36
+ * caller then still owns whatever the prompt was carrying. */
37
+ export type PromptDeliveredCallback = () => void;
27
38
  export interface UserMessageProvenance {
28
39
  /** Exact char length of the engine-prepended prefix on `text` (first-frame reminders etc.).
29
40
  * Sugar for the single segment `[0, chars)` — when `engineSegments` is also supplied, segments win. */
@@ -124,6 +135,14 @@ export declare class AgentHarness<TSkill extends Skill = Skill, TPromptTemplate
124
135
  readonly env: ExecutionEnv;
125
136
  private session;
126
137
  private phase;
138
+ /** Can an engine injection land at a turn boundary RIGHT NOW? A producer choosing a destination
139
+ * BEFORE it commits (the session notification route) needs this as a fact, not as a rejected
140
+ * promise afterwards. Three conjuncts, each a condition a later stage enforces: a turn must EXIST
141
+ * (`steer`/`followUp` throw while idle); the run must not be UNWINDING; it must not be STOPPING
142
+ * (`halt()` / `requestStopAfterTurn()` latch a source and the loop exits at the next boundary) —
143
+ * the phase reads `"turn"` through all of that. Nothing awaits between this read and the injection
144
+ * it gates, so a `true` cannot go stale under its caller. */
145
+ get acceptsInjections(): boolean;
127
146
  /** design/74 R3-A: the one-way clean-stop latch — SET iff this set is non-empty. When set, the boundary consults
128
147
  * answer true so the loop exits CLEANLY (emit `agent_end` + return) WITHOUT an abort/interrupt — the path a
129
148
  * resource-slice suspend needs (an abort would trip the orphan-[INTERRUPTED] reconcile = corrupt resume). It is
@@ -136,6 +155,7 @@ export declare class AgentHarness<TSkill extends Skill = Skill, TPromptTemplate
136
155
  * per turn, so identity carries the generation); the loop's cut-consumption report is accepted for THIS seat only. */
137
156
  private lastPublishedSeat?;
138
157
  private readonly seatCutSources;
158
+ private trailingBatchEndedOn?;
139
159
  private turnCutConsumed?;
140
160
  /** backlog #389 — one-way latch set by {@link abort}. Read by `drainQueuedMessages`: no boundary may
141
161
  * hand a queued frame to the model once the run is unwinding, and — crucially — none may SPLICE one
@@ -208,6 +228,26 @@ export declare class AgentHarness<TSkill extends Skill = Skill, TPromptTemplate
208
228
  * clearing, so they are LEFT STANDING (the durable-park migration reads them AFTER abort()
209
229
  * returns) and the abort-side pass is the belt for an exit that never reached agent_end. */
210
230
  private sweepUndrainedEngineNotes;
231
+ /**
232
+ * How much of a PERSON's input is currently accepted-but-unserved, per lane — the one predicate behind
233
+ * both readers below, so "a person's input is waiting" cannot come to mean two things. Engine-AUTHORED
234
+ * frames are excluded, and the IN-FLIGHT slot counts (a frame spliced out of a queue and never injected
235
+ * is as pending as one that never left it).
236
+ */
237
+ private pendingUserInputsByLane;
238
+ /**
239
+ * Is a PERSON's input waiting for this run's NEXT TURN BOUNDARY? The live read face over
240
+ * {@link pendingUserInputsByLane}, for the producer that must decide whether to YIELD that boundary
241
+ * sooner — the shell's auto-backgrounding leg.
242
+ *
243
+ * THE STEER LANE ONLY: the follow-up lane's contract is delivery at the run's natural
244
+ * would-otherwise-stop seat, which backgrounding a command cannot bring forward.
245
+ * `announceUndrainedUserInputs` still reads both lanes.
246
+ *
247
+ * Synchronous and side-effect-free by contract, the same posture as {@link pendingInjectionCount}:
248
+ * nothing is awaited between the read and the action it gates. An UNWINDING run answers `false`.
249
+ */
250
+ hasPendingUserInput(): boolean;
211
251
  /** backlog #259 — what remains in the steer/follow-up queues AFTER the engine-note sweep is USER
212
252
  * input that was accepted ("queued") and will never be consumed: the run reached agent_end first.
213
253
  * User inputs have no redelivery semantics (unlike engine notes — a steer aimed at a finished run
@@ -320,6 +360,8 @@ export declare class AgentHarness<TSkill extends Skill = Skill, TPromptTemplate
320
360
  * zero-assistant ending still throws (see the executeTurn tail). */
321
361
  prompt(text: string, options?: {
322
362
  images?: ImageContent[];
363
+ settleUnansweredToolCalls?: TrailingToolBatchOptions;
364
+ onDelivered?: PromptDeliveredCallback;
323
365
  } & UserMessageProvenance): Promise<AssistantMessage | undefined>;
324
366
  /** R2-③: an empty/whitespace-only injection with no images carries ZERO information — it
325
367
  * must not mint a user frame (strict endpoints reject empty user content, and an empty follow-up would
@@ -187,6 +187,9 @@ export class AgentHarness {
187
187
  env;
188
188
  session;
189
189
  phase = "idle";
190
+ get acceptsInjections() {
191
+ return this.phase !== "idle" && !this.aborting && !this.stopRequested;
192
+ }
190
193
  stopRequestSources = new Set();
191
194
  get stopRequested() {
192
195
  return this.stopRequestSources.size > 0;
@@ -194,6 +197,7 @@ export class AgentHarness {
194
197
  boundaryStopConsumed;
195
198
  lastPublishedSeat;
196
199
  seatCutSources = new WeakMap();
200
+ trailingBatchEndedOn;
197
201
  turnCutConsumed;
198
202
  aborting = false;
199
203
  drainedPendingInjection = [];
@@ -229,12 +233,20 @@ export class AgentHarness {
229
233
  }
230
234
  }
231
235
  }
232
- announceUndrainedUserInputs() {
236
+ pendingUserInputsByLane() {
233
237
  const inFlight = (lane) => this.drainedPendingInjection.filter((m) => !engineAuthoredInjections.has(m) && drainedFromLane.get(m) === lane).length;
234
- const counts = {
238
+ return {
235
239
  steer: this.steerQueue.filter((m) => !engineAuthoredInjections.has(m)).length + inFlight("steer"),
236
240
  followUp: this.followUpQueue.filter((m) => !engineAuthoredInjections.has(m)).length + inFlight("followUp"),
237
241
  };
242
+ }
243
+ hasPendingUserInput() {
244
+ if (this.aborting)
245
+ return false;
246
+ return this.pendingUserInputsByLane().steer > 0;
247
+ }
248
+ announceUndrainedUserInputs() {
249
+ const counts = this.pendingUserInputsByLane();
238
250
  if ((counts.steer > 0 || counts.followUp > 0) && this.onUndrainedUserInputs) {
239
251
  try {
240
252
  this.onUndrainedUserInputs(counts);
@@ -826,29 +838,7 @@ export class AgentHarness {
826
838
  }
827
839
  async executeTurn(turnState, text, options) {
828
840
  let activeTurnState = turnState;
829
- let messages = [createUserMessage(text, options?.images, options)];
830
- if (this.nextTurnQueue.length > 0) {
831
- const queuedMessages = this.nextTurnQueue.splice(0);
832
- try {
833
- await this.emitQueueUpdate();
834
- }
835
- catch (error) {
836
- this.nextTurnQueue.unshift(...queuedMessages);
837
- throw normalizeHookError(error);
838
- }
839
- for (const m of queuedMessages) {
840
- const payload = engineNotePayloads.get(m);
841
- if (payload !== undefined) {
842
- try {
843
- this.onEngineNoteConsumed?.(payload);
844
- }
845
- catch {
846
- }
847
- }
848
- engineNotePayloads.delete(m);
849
- }
850
- messages = [...queuedMessages, messages[0]];
851
- }
841
+ const userMessage = createUserMessage(text, options?.images, options);
852
842
  const beforeResult = await this.emitHook({
853
843
  type: "before_agent_start",
854
844
  prompt: text,
@@ -856,9 +846,35 @@ export class AgentHarness {
856
846
  systemPrompt: turnState.systemPrompt,
857
847
  resources: turnState.resources,
858
848
  });
859
- if (beforeResult?.messages) {
860
- messages = [...messages, ...beforeResult.messages];
861
- }
849
+ const takePrompts = async () => {
850
+ let messages = [userMessage];
851
+ if (this.nextTurnQueue.length > 0) {
852
+ const queuedMessages = this.nextTurnQueue.splice(0);
853
+ try {
854
+ await this.emitQueueUpdate();
855
+ }
856
+ catch (error) {
857
+ this.nextTurnQueue.unshift(...queuedMessages);
858
+ throw normalizeHookError(error);
859
+ }
860
+ for (const m of queuedMessages) {
861
+ const payload = engineNotePayloads.get(m);
862
+ if (payload !== undefined) {
863
+ try {
864
+ this.onEngineNoteConsumed?.(payload);
865
+ }
866
+ catch {
867
+ }
868
+ }
869
+ engineNotePayloads.delete(m);
870
+ }
871
+ messages = [...queuedMessages, messages[0]];
872
+ }
873
+ if (beforeResult?.messages) {
874
+ messages = [...messages, ...beforeResult.messages];
875
+ }
876
+ return messages;
877
+ };
862
878
  const abortController = new AbortController();
863
879
  const getTurnState = () => activeTurnState;
864
880
  const setTurnState = (nextTurnState) => {
@@ -867,7 +883,20 @@ export class AgentHarness {
867
883
  this.runAbortController = abortController;
868
884
  const runResultPromise = (async () => {
869
885
  try {
870
- return await runAgentLoop(messages, this.createContext(turnState, beforeResult?.systemPrompt), this.createLoopConfig(getTurnState, setTurnState, beforeResult?.systemPrompt), (event) => this.handleAgentEvent(event, abortController.signal), abortController.signal, this.createStreamFn(getTurnState), undefined, this.loopTrace);
886
+ return await runAgentLoop(takePrompts, this.createContext(turnState, beforeResult?.systemPrompt), this.createLoopConfig(getTurnState, setTurnState, beforeResult?.systemPrompt), (event) => this.handleAgentEvent(event, abortController.signal), abortController.signal, this.createStreamFn(getTurnState), undefined, this.loopTrace, {
887
+ ...(options?.settleUnansweredToolCalls !== undefined
888
+ ? {
889
+ settle: {
890
+ ...(options.settleUnansweredToolCalls.halt !== undefined ? { halt: options.settleUnansweredToolCalls.halt } : {}),
891
+ report: (outcome) => {
892
+ if (outcome.aborted)
893
+ this.trailingBatchEndedOn = outcome.assistantMessage;
894
+ },
895
+ },
896
+ }
897
+ : {}),
898
+ ...(options?.onDelivered !== undefined ? { onPromptsDelivered: options.onDelivered } : {}),
899
+ });
871
900
  }
872
901
  catch (error) {
873
902
  try {
@@ -889,6 +918,8 @@ export class AgentHarness {
889
918
  }
890
919
  if (this.stopRequested)
891
920
  return undefined;
921
+ if (this.trailingBatchEndedOn !== undefined)
922
+ return this.trailingBatchEndedOn;
892
923
  throw new AgentHarnessError("invalid_state", "AgentHarness prompt completed without an assistant message");
893
924
  }
894
925
  finally {
@@ -904,6 +935,7 @@ export class AgentHarness {
904
935
  if (this.phase !== "idle") {
905
936
  throw new AgentHarnessError("busy", "AgentHarness is busy");
906
937
  }
938
+ this.trailingBatchEndedOn = undefined;
907
939
  this.stopRequestSources.clear();
908
940
  this.boundaryStopConsumed = undefined;
909
941
  this.turnCutConsumed = undefined;
@@ -1,5 +1,29 @@
1
+ /**
2
+ * First-party agent loop (design/118 ④a — de-vendoring 4/6).
3
+ *
4
+ * Rewritten from the vendored openclaw distillation with the loop's control flow made EXPLICIT as a
5
+ * state machine (the CC query.ts State/transition shape, sema deps injected): every "go around again"
6
+ * is a named {@link LoopContinue} and every exit is a named {@link LoopTerminal}, so tests can assert
7
+ * WHICH path ran (test/loop-transitions.test.ts) instead of inferring it from event order. ④a is
8
+ * behavior-1:1 with the vendored loop — no new recovery chains; those land in ④b as new Continue
9
+ * reasons on this skeleton.
10
+ *
11
+ * Load-bearing invariants carried over verbatim (the VENDORED EDIT provenance comments are kept at
12
+ * their sites as history):
13
+ * - A-1 layer ② abort-before-stream guard (a mid-batch abort must never reach the next provider
14
+ * request) — {@link runSingleTurn} entry guard, Terminal `aborted_before_stream`.
15
+ * - Durable double-execution gate (a deferred parallel tool closure must never run its side effect
16
+ * after a mid-batch suspend/abort) — {@link executePreparedToolCall} entry guard.
17
+ * - D4 post-hook posture (afterToolCall throw must not rewrite a committed side effect into a flat
18
+ * failure) — {@link finalizeExecutedToolCall}.
19
+ * - The TWO queue drain points (1.204 priority wiring基石): steer drains at every turn end
20
+ * (Continue `steer_injected` / mid-work boundary), followUp drains only when the agent would
21
+ * otherwise stop (Continue `follow_up_injected`). Never merge these into one queue.
22
+ * - text_delta.partial reconstruction (upstream cherry-pick 6fcc945702).
23
+ */
24
+ import type { AssistantMessage, ToolResultMessage } from "../llm/index.js";
1
25
  import { type AgentCoreStreamRuntimeDeps } from "./runtime-deps.js";
2
- import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, StreamFn } from "./types.js";
26
+ import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, HaltRemainingDirective, StreamFn } from "./types.js";
3
27
  /** Callback used by synchronous loop runners to publish agent lifecycle events. */
4
28
  export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
5
29
  /** Named reasons the loop goes around again. Assertable in tests via the trace sink. */
@@ -88,8 +112,48 @@ export type LoopStep = {
88
112
  * `next_turn`), then `next_turn`. Don't read the trace as a complete enumeration of concurrent causes.
89
113
  */
90
114
  export type LoopTraceSink = (step: LoopStep) => void;
91
- /** Run a prompt-started loop and emit events through a caller-owned sink. */
92
- export declare function runAgentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn, runtime?: AgentCoreStreamRuntimeDeps, trace?: LoopTraceSink): Promise<AgentMessage[]>;
115
+ /**
116
+ * A request to settle the transcript's trailing UNANSWERED tool batch before the prompts are delivered
117
+ * (a resumed run whose suspended batch still holds calls no tool result answers). The batch is settled
118
+ * as ONE turn of the loop: the live batch pipeline under a turn-scoped interrupt seat, the interrupted-
119
+ * turn settlement when that seat is cut, then the ordinary turn boundary (`prepareNextTurn` + the stop
120
+ * consult). `halt` settles every call as not-executed instead (the batch-halt form). `report` receives
121
+ * the outcome once; `aborted` means the run ENDED before the prompts were delivered (the run signal
122
+ * fired, or the boundary / the interrupt settlement stopped the run).
123
+ */
124
+ export interface TrailingToolBatchSettlement {
125
+ halt?: HaltRemainingDirective;
126
+ report: (outcome: {
127
+ assistantMessage: AssistantMessage;
128
+ settled: number;
129
+ aborted: boolean;
130
+ }) => void;
131
+ }
132
+ /** The caller-facing seams of a prompt run beyond the prompts themselves: an optional trailing-batch
133
+ * settlement, and the moment the prompts enter the loop transcript, before their frames are emitted
134
+ * — delivery accounts precede the carrying messages' commits. */
135
+ export interface RunAgentLoopSeams {
136
+ settle?: TrailingToolBatchSettlement;
137
+ onPromptsDelivered?: () => void;
138
+ }
139
+ /** The last assistant message of `messages` when at least one of its tool calls has no tool result after it. */
140
+ export declare function findUnansweredToolBatch(messages: readonly AgentMessage[]): AssistantMessage | undefined;
141
+ /**
142
+ * Settle the unanswered tool calls of `assistantMessage` (the batch tail a suspended run left open):
143
+ * ONE pipeline with the live turn — the same partition, concurrency cap, preflight gate (a call may
144
+ * suspend again), execution and source-ordered result commit — or, under `halt`, the same not-executed
145
+ * settlement a batch-halt directive applies to never-started siblings. Every unanswered call gets a
146
+ * tool result unless the signal fires mid-batch (the dangling remainder is the suspended batch's own shape).
147
+ */
148
+ export declare function settleUnansweredToolCalls(context: AgentContext, assistantMessage: AssistantMessage, config: AgentLoopConfig, signal: AbortSignal | undefined, emit: AgentEventSink, halt?: HaltRemainingDirective): Promise<ExecutedToolCallBatch>;
149
+ /** Run a prompt-started loop and emit events through a caller-owned sink. `prompts` may be a thunk: it is
150
+ * taken only when the prompts are about to be delivered, so a caller whose prompt assembly CONSUMES queued
151
+ * input (a harness draining its next-turn queue) loses nothing when a trailing-batch settlement ends the run first. */
152
+ export declare function runAgentLoop(prompts: AgentMessage[] | (() => Promise<AgentMessage[]>), context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn, runtime?: AgentCoreStreamRuntimeDeps, trace?: LoopTraceSink, seams?: RunAgentLoopSeams): Promise<AgentMessage[]>;
153
+ type ExecutedToolCallBatch = {
154
+ messages: ToolResultMessage[];
155
+ terminate: boolean;
156
+ };
93
157
  /**
94
158
  * How many tool names an unknown-tool miss spells out. A miss is a NAME problem: seeing a couple of dozen
95
159
  * real names is what lets a model spot the one it meant, while a full listing grows with the deployment
@@ -110,3 +174,4 @@ export declare const TOOL_VALIDATION_REFUSED_CODE = "tool.validation_refused";
110
174
  * reported on the fault seat): a validator is a precondition read, not a network call, so a single
111
175
  * bound serves every tool; a deployment validator that needs longer is a validator doing too much. */
112
176
  export declare const TOOL_INPUT_VALIDATION_TIMEOUT_MS = 10000;
177
+ export {};
@@ -20,20 +20,110 @@ function resolveAssistantMessageUpdate(event, currentMessage) {
20
20
  }
21
21
  return currentMessage;
22
22
  }
23
- export async function runAgentLoop(prompts, context, config, emit, signal, streamFn, runtime, trace) {
24
- const newMessages = [...prompts];
25
- const currentContext = {
26
- ...context,
27
- messages: [...context.messages, ...prompts],
28
- };
23
+ export function findUnansweredToolBatch(messages) {
24
+ for (let i = messages.length - 1; i >= 0; i--) {
25
+ const m = messages[i];
26
+ if (m.role !== "assistant")
27
+ continue;
28
+ return unansweredToolCallsOf(m, messages.slice(i + 1)).length > 0 ? m : undefined;
29
+ }
30
+ return undefined;
31
+ }
32
+ function unansweredToolCallsOf(assistantMessage, after) {
33
+ const answered = new Set(after.filter((m) => m.role === "toolResult").map((m) => m.toolCallId));
34
+ const seen = new Set();
35
+ const unanswered = [];
36
+ for (const c of assistantMessage.content) {
37
+ if (c.type !== "toolCall" || answered.has(c.id) || seen.has(c.id))
38
+ continue;
39
+ seen.add(c.id);
40
+ unanswered.push(c);
41
+ }
42
+ return unanswered;
43
+ }
44
+ export async function settleUnansweredToolCalls(context, assistantMessage, config, signal, emit, halt) {
45
+ const at = context.messages.lastIndexOf(assistantMessage);
46
+ const toolCalls = unansweredToolCallsOf(assistantMessage, at >= 0 ? context.messages.slice(at + 1) : context.messages);
47
+ if (toolCalls.length === 0)
48
+ return { messages: [], terminate: false };
49
+ if (halt !== undefined) {
50
+ const messages = [];
51
+ for (const toolCall of toolCalls) {
52
+ if (signal?.aborted)
53
+ break;
54
+ messages.push((await settleHaltedToolCall(toolCall, halt, emit)).message);
55
+ }
56
+ return { messages, terminate: true };
57
+ }
58
+ return config.toolExecution === "sequential"
59
+ ? executeToolCallsSequential(context, assistantMessage, toolCalls, config, signal, emit)
60
+ : executeToolCallsPartitioned(context, assistantMessage, toolCalls, config, signal, emit);
61
+ }
62
+ export async function runAgentLoop(prompts, context, config, emit, signal, streamFn, runtime, trace, seams) {
63
+ const state = await createLoopState({ ...context, messages: [...context.messages] }, config, []);
29
64
  await emit({ type: "agent_start" });
30
65
  await emit({ type: "turn_start" });
31
- for (const prompt of prompts) {
66
+ if (seams?.settle !== undefined && (await settleTrailingBatchTurn(state, signal, emit, seams.settle)) === "ended") {
67
+ return state.newMessages;
68
+ }
69
+ const delivered = typeof prompts === "function" ? await prompts() : prompts;
70
+ if (delivered.length > 0)
71
+ state.hasMoreToolCalls = true;
72
+ state.context.messages.push(...delivered);
73
+ state.newMessages.push(...delivered);
74
+ seams?.onPromptsDelivered?.();
75
+ for (const prompt of delivered) {
32
76
  await emit({ type: "message_start", message: prompt });
33
77
  await emit({ type: "message_end", message: prompt });
34
78
  }
35
- await runLoop(currentContext, newMessages, config, signal, emit, streamFn, runtime, trace);
36
- return newMessages;
79
+ await runLoop(state, signal, emit, streamFn, runtime, trace);
80
+ return state.newMessages;
81
+ }
82
+ async function settleTrailingBatchTurn(state, signal, emit, settle) {
83
+ const tail = findUnansweredToolBatch(state.context.messages);
84
+ if (tail === undefined)
85
+ return "continue";
86
+ const turnController = new AbortController();
87
+ const onRunAbort = () => turnController.abort();
88
+ if (signal !== undefined) {
89
+ if (signal.aborted)
90
+ turnController.abort();
91
+ else
92
+ signal.addEventListener("abort", onRunAbort, { once: true });
93
+ }
94
+ state.config.publishTurnInterruptSeat?.(turnController);
95
+ let batch;
96
+ try {
97
+ batch = await settleUnansweredToolCalls(state.context, tail, state.config, turnController.signal, emit, settle.halt);
98
+ }
99
+ finally {
100
+ state.config.publishTurnInterruptSeat?.(undefined);
101
+ signal?.removeEventListener("abort", onRunAbort);
102
+ }
103
+ state.context.messages.push(...batch.messages);
104
+ state.newMessages.push(...batch.messages);
105
+ let ended = signal?.aborted === true;
106
+ let terminalEmitted = false;
107
+ if (!ended && turnController.signal.aborted) {
108
+ state.config.noteTurnCutConsumed?.(turnController);
109
+ const pendingBeforeSettlement = state.pendingMessages;
110
+ const outcome = await settleInterruptedTurn(state, tail, new StreamToolExecutor(state.context, state.config, turnController.signal, emit), batch.messages, signal, emit);
111
+ ended = outcome.kind === "terminal";
112
+ if (!ended)
113
+ state.pendingMessages.unshift(...pendingBeforeSettlement);
114
+ terminalEmitted = ended;
115
+ }
116
+ else if (!ended) {
117
+ const boundary = { message: tail, toolResults: batch.messages, context: state.context, newMessages: state.newMessages };
118
+ adoptNextTurnSnapshot(state, await state.config.prepareNextTurn?.(boundary));
119
+ ended = (await state.config.shouldStopAfterTurn?.(boundary)) === true || signal?.aborted === true;
120
+ if (!ended)
121
+ state.pendingMessages.push(...((await state.config.getSteeringMessages?.()) || []));
122
+ }
123
+ settle.report({ assistantMessage: tail, settled: batch.messages.length, aborted: ended });
124
+ if (ended && !terminalEmitted)
125
+ await emit({ type: "agent_end", messages: state.newMessages });
126
+ return ended ? "ended" : "continue";
37
127
  }
38
128
  const PROMPT_TOO_LONG_RE = /context.{0,3}length|context_length|context window (?:limit|exceeded)|reached its context window|prompt is too long|too many tokens|maximum context|exceeds? .{0,30}(?:context|token)|input is too long|\b413\b/i;
39
129
  function isBlankFailureContent(message) {
@@ -140,21 +230,23 @@ function createContinueNudge() {
140
230
  timestamp: Date.now(),
141
231
  };
142
232
  }
143
- async function runLoop(initialContext, newMessages, initialConfig, signal, emit, streamFn, runtime, trace) {
144
- const state = {
145
- context: initialContext,
146
- config: initialConfig,
233
+ async function createLoopState(context, config, newMessages) {
234
+ return {
235
+ context,
236
+ config,
147
237
  newMessages,
148
238
  firstTurn: true,
149
- pendingMessages: (await initialConfig.getSteeringMessages?.()) || [],
239
+ pendingMessages: (await config.getSteeringMessages?.()) || [],
150
240
  hasMoreToolCalls: true,
151
241
  truncatedOutputContinues: 0,
152
- staticReasoningCutRecoveries: initialContext.messages.filter((m) => m.role === "assistant" && m.staticReasoningCut === true).length,
242
+ staticReasoningCutRecoveries: context.messages.filter((m) => m.role === "assistant" && m.staticReasoningCut === true).length,
153
243
  degenerateContinues: 0,
154
244
  malformedToolUseRetries: 0,
155
245
  thinkingOnlyRetries: 0,
156
246
  midstreamPartialContinues: 0,
157
247
  };
248
+ }
249
+ async function runLoop(state, signal, emit, streamFn, runtime, trace) {
158
250
  while (true) {
159
251
  if (!state.hasMoreToolCalls && state.pendingMessages.length === 0) {
160
252
  const followUpMessages = (await state.config.getFollowUpMessages?.()) || [];
@@ -489,7 +581,8 @@ async function settleInterruptedTurn(state, message, executor, committedResults,
489
581
  const toolResults = [...committedResults];
490
582
  toolResults.push(...(await harvestExecutorOnErrorFinal(executor, state, message, signal, emit)));
491
583
  const turnCalls = message.content.filter((c) => c.type === "toolCall");
492
- const answered = new Set(toolResults.map((r) => r.toolCallId));
584
+ const priorResults = state.context.messages.slice(state.context.messages.lastIndexOf(message) + 1).filter((m) => m.role === "toolResult");
585
+ const answered = new Set([...priorResults, ...toolResults].map((r) => r.toolCallId));
493
586
  for (const call of turnCalls) {
494
587
  if (answered.has(call.id))
495
588
  continue;
package/dist/index.d.ts CHANGED
@@ -15,15 +15,18 @@ export { SESSION_LOG_DIGEST_SCHEME, sessionEntryDigest, sessionLogDigest, sessio
15
15
  export type { ResumeTaskConfig } from "./core/runner/runtask.js";
16
16
  export { defineTool } from "./core/tools.js";
17
17
  export { SKILL_TOOL_NAME } from "./core/runner/synthetic-tools.js";
18
+ export { TOOL_SEARCH_POLICIES, TOOL_SEARCH_DEFAULT_THRESHOLD_PERCENT, TOOL_SEARCH_INVALID_CODE, type ToolSearchSetting, type ToolSearchPolicy, } from "./core/tool-search-setting.js";
19
+ export type { ToolDisclosureSnapshot } from "./core/runner/deferral-census.js";
18
20
  export { createSkillsFromDirectory, type SkillsDirectoryOptions, type SkillsDirectoryWarning, type SkillsDirectoryWarningCode, } from "./core/skills-directory.js";
19
21
  export { REPORT_FINDINGS_TOOL_NAME, type ReportedFinding } from "./core/runner/synthetic-tools.js";
20
22
  export { formatToolError, formatZodValidationError, formatValidationPath, truncateError, errorClassOf } from "./core/tool-errors.js";
21
23
  export type { WorkerErrorClass } from "./core/tool-errors.js";
22
24
  export { createWebFetchTool, webFetchToolSpec, htmlToText, type WebFetchConfig, createWebSearchTool, type WebSearchConfig, createSearxngSearchBackend, probeSearchBackend, type SearxngBackendOptions, createWebFetchSummarizer, WEBFETCH_SUMMARY_MAX_CONTENT, WEBFETCH_SUMMARY_GUIDELINES, } from "./tools/web.js";
23
25
  export { createTodoWriteTool } from "./tools/todo.js";
24
- export { ARTIFACT_ACTIONS, ARTIFACT_PLANES, ARTIFACT_PUBLISH_CONTEXTS, ARTIFACT_LIST_SCOPES, ARTIFACT_PLANE_CONTENT_ORIGIN, ARTIFACT_ACTION_HOST_METHOD, ARTIFACT_HOST_FAILURE_CODES, ARTIFACT_FAILURE_RESULT_CODE, ARTIFACT_HOST_ERROR_CODE, ARTIFACT_CARD, readArtifactHostCapabilities, type ArtifactAction, type ArtifactPlane, type ArtifactPublishContext, type ArtifactListScope, type ArtifactHostFailureCode, type ArtifactResultCode, type ArtifactHost, type ArtifactHostCapabilities, type ArtifactHostCapabilitiesVerdict, type ArtifactCallContext, type ArtifactFileContent, type ArtifactPublishRequest, type ArtifactPublishOutcome, type ArtifactConflictSnapshot, type ArtifactListOutcome, type ArtifactReadOutcome, type ArtifactFilesOutcome, type ArtifactFileOutcome, type ArtifactRef, type ArtifactListRow, } from "./core/artifact-host.js";
26
+ export { ARTIFACT_ACTIONS, ARTIFACT_PLANES, ARTIFACT_COMMIT_CERTAINTIES, ARTIFACT_COMMIT_THROW_OUTCOME, ARTIFACT_PUBLISH_CONTEXTS, ARTIFACT_LIST_SCOPES, ARTIFACT_PLANE_CONTENT_ORIGIN, ARTIFACT_ACTION_HOST_METHOD, ARTIFACT_ACTION_CONCURRENCY_SAFE, ARTIFACT_HOST_FAILURE_CODES, ARTIFACT_FAILURE_RESULT_CODE, ARTIFACT_HOST_ERROR_CODE, ARTIFACT_CARD, readArtifactHostCapabilities, type ArtifactAction, type ArtifactPlane, type ArtifactCommitCertainty, type ArtifactPublishContext, type ArtifactListScope, type ArtifactHostFailureCode, type ArtifactResultCode, type ArtifactHost, type ArtifactHostCapabilities, type ArtifactHostCapabilitiesVerdict, type ArtifactCallContext, type ArtifactFileContent, type ArtifactPublishRequest, type ArtifactPublishOutcome, type ArtifactConflictSnapshot, type ArtifactListOutcome, type ArtifactReadOutcome, type ArtifactFilesOutcome, type ArtifactFileOutcome, type ArtifactRef, type ArtifactListRow, } from "./core/artifact-host.js";
25
27
  export { createArtifactTool, artifactAttemptId, normalizePublishedPath, mediaTypeOf, type ArtifactToolOptions, type ArtifactLocalRead } from "./tools/artifact/artifact-tool.js";
26
28
  export { localArtifactStub, LocalArtifactStub, EVAL_STUB_URL_PREFIX, LOCAL_STUB_MAX_FILE_BYTES, LOCAL_STUB_MAX_TOTAL_BYTES, type LocalArtifactStubOptions } from "./tools/artifact/local-stub.js";
29
+ export { ARTIFACT_CONFORMANCE_VECTORS, artifactConformanceVectors, runArtifactConformance, type ArtifactConformanceHooks, type ArtifactConformanceOptions, type ArtifactConformanceStatus, type ArtifactConformanceVector, type ArtifactConformanceResult, type ArtifactConformanceReport, } from "./tools/artifact/conformance.js";
27
30
  export { createTaskListTools, createMemoryTaskListStore, assertJsonMetadata, type TaskListItem, type TaskListStore } from "./tools/task-list.js";
28
31
  export { assembleCodeTools, type CodeToolsConfig, CODE_ROLE } from "./scenarios/full-body.js";
29
32
  export { TOOL_MODEL_GATE_CLASSES, isModelGatedForClass, type ToolModelGateRule } from "./core/tool-model-gate.js";
@@ -101,7 +104,7 @@ export { bashReversibilityProbe, bashReadBoundaryProbe, BASH_READONLY_DEFAULT_AL
101
104
  export { classifyCompoundReadonlyDetailed, formatOutOfRootReadApprovalOption, type BashReadonlyRootBoundary, type CompoundReadonlyVerdict, } from "./tools/fs/index.js";
102
105
  export { resolveBashTimeoutCaps } from "./tools/fs/index.js";
103
106
  export { READ_FACE_DEFAULT_DENY_ENTRIES, READ_FACE_BUILTIN_DENY_TABLE, READ_DENY_BUILTIN_TIERS, READ_DENY_DEFAULT_TIERS, resolveReadDenyBuiltins, compileReadDeny, type ReadDenyEntry, type ReadDenyMatcher, type NormalizedReadDenyEntry, type ReadDenyBuiltinTier, type ReadDenyBuiltinRow, type ReadDenyBuiltinConfig, } from "./tools/fs/index.js";
104
- export { deploymentReadFaceClampNotice, resolveReadFace, type ReadFace, type ReadFaceInputs } from "./tools/fs/index.js";
107
+ export { deploymentFaceClampNotice, resolveContainmentFace, type ContainmentFace, type ContainmentFaceInputs, type ContainmentFaceKind, type ContainmentFaceLayer, } from "./tools/fs/index.js";
105
108
  export { WRITE_PROTECTED_DEFAULT_TABLE, resolveWriteProtectedTable, compileWriteProtection, type WriteProtectedEntry, type WriteProtectedRow, type WriteProtectedKind, type WriteProtectedHit, type WriteProtectionMatcher, } from "./core/write-protect.js";
106
109
  export { InMemoryToolResultStore, OFFLOAD_TOOL_NAME, DEFAULT_TOOL_RESULT_THRESHOLD_CHARS, assertSafeToolResultRef, buildToolResultRef, toolResultContentSegment, MAX_MINTED_TOOL_RESULT_REF_CHARS, type ToolResultProvenance, assertToolResultProvenanceMatch, normalizeToolResultProvenance, toolResultProvenanceOf, ToolResultRefConflictError, TOOL_RESULT_REF_CONFLICT_CODE, type ToolResultStore, type ToolResultSlice, type ToolResultDeletionReport, } from "./core/tool-result-store.js";
107
110
  export { InMemoryCheckpointStore, CheckpointError, mintCheckpointId, mintCheckpointToken, checkpointVersionOf, CURRENT_CHECKPOINT_VERSION, MAX_SUPPORTED_CHECKPOINT_VERSION, ORG_ADMISSION_CHECKPOINT_VERSION, F012_CHECKPOINT_VERSION, REAL_APPROVAL_CHECKPOINT_VERSION, RESOURCE_CHECKPOINT_VERSION, TOKEN_CHECKPOINT_VERSION, debitLedger, remainingBudgetMicroUsd, remainingTokens, winnerFromOutcome, validatePendingSteer, readPendingSteerQueue, appendPendingSteer, MAX_PENDING_STEER_CHARS, MAX_PENDING_STEER_ENTRIES, PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES, PENDING_STEER_FROZEN_FIELDS, ACTOR_ASSERTION_FROZEN_FIELDS, MAX_ACTOR_FIELD_CHARS, MAX_STEER_INPUT_ID_CHARS, type ActorAssertion, type PendingSteerEntry, type PendingSteerInput, riskSeverity, buildRiskDescriptor, summarizeCheckpoint, type RiskDescriptor, type ProbeCause, type ProbeCauseOperands, type CheckpointStore, type CheckpointSummary, type Checkpoint, type CheckpointToken, type CheckpointGate, type CheckpointState, type SerializedCheckpointState, type CheckpointFaultMode, type PendingAction, type ResumeOutcome, type ResolvedOutcome, type ReopenReason, type ResolveExpectation, type TerminalClaimIntent, type TerminalClaimOutcome, type SafetyAxis, type RealApprovalGateBit, type ResourceLedger, type ResourceLimitReason, type PlatformLimitReason, type CheckpointRow, realApprovalOrgFact, resolveCheckpointStore, checkpointStoreExecutionUndeclared, } from "./core/checkpoint-store.js";
@@ -143,7 +146,7 @@ export { parkedToolIdentity } from "./core/tool-roster.js";
143
146
  export { type ToolCallIdentity } from "./core/fs-write-gate-policy.js";
144
147
  export { type RuleFaceView, catalogRuleFaceView } from "./core/permission-rules.js";
145
148
  export { DURABLE_HISTORY_NAMES } from "./engine/compaction/utils.js";
146
- export { describeStaticWiring, deriveWiringManifest, deriveAskEffective, resolveDeclaredDurability, resolveSubagentTranscriptTier, type SubagentTranscriptTier, resolveAskSeamForm, resolveQuestionSeam, countElicitOptIns, AUTO_MODE_ARM_REASONS, type AutoModeArmReason, type AutoModeArmFact, type WiringManifest, type WiringManifestMcpEntry, type WiringFacts, type WiringLegKind, type AskSeamForm, type AskEffective, type QuestionChannelState, type SeamProvenance, type ParkLaneReason, type ManifestDurability, type StaticWiringDeps, type StaticWiringSpec, } from "./core/wiring-manifest.js";
149
+ export { describeStaticWiring, deriveWiringManifest, deriveAskEffective, resolveDeclaredDurability, resolveSubagentTranscriptTier, type SubagentTranscriptTier, resolveAskSeamForm, resolveQuestionSeam, countElicitOptIns, AUTO_MODE_ARM_REASONS, type AutoModeArmReason, type AutoModeArmFact, type WiringManifest, type WiringManifestMcpEntry, LSP_LANES, type LspLane, type WiringFacts, type WiringLegKind, type AskSeamForm, type AskEffective, type QuestionChannelState, type SeamProvenance, type ParkLaneReason, type ManifestDurability, type StaticWiringDeps, type StaticWiringSpec, } from "./core/wiring-manifest.js";
147
150
  export { probeParkRoundTrip, durableParkGapOf, durableParkGapFor, PARK_SELFCHECK_SCOPE_PREFIX, type ParkSelfCheckResult, type ParkProbeFinding, type ParkProbeFindingCode, } from "./core/park-selfcheck.js";
148
151
  export { type StoreDurability } from "./core/checkpoint-store.js";
149
152
  export { type StoreFidelity } from "./core/checkpoint-store.js";
@@ -174,7 +177,7 @@ export { AUTO_MODE_DENY_SOURCES, isAutoModeDenySource, type AutoModeDenySource }
174
177
  export { SETTLEMENT_KINDS, type SettlementKind, isSettlementKind, type Settlement, SETTLEMENT_IS_REFUSAL, DENIED_BY_VALUES, type DeniedBy, isDeniedBy, DENIED_BY_MAY_VETO, CLASSIFIER_DENY_CAUSES, type ClassifierDenyCause, isClassifierDenyCause, DENIED_BY_MAY_CARRY_CAUSE, type GateDisposition, type GateOutcome, screenGateOutcome } from "./core/gate-outcome.js";
175
178
  export { type AskCarry } from "./core/hooks.js";
176
179
  export { SWAPPABLE_DEP_SEATS, SWAP_SEAT_NOTICE, isSwappableDepSeat, screenSwappableDeps, type SwappableDepSeat, type SwappableDeps } from "./core/swappable-deps.js";
177
- export { parseAutoModeResponse, createAutoModeDecider, AUTO_MODE_UNAVAILABLE_CAUSES, isAutoModeUnavailableCause, classifierUnavailableDenyMessage, CLASSIFIER_PARSE_FAILURE_DENY_MESSAGE, type AutoModeUnavailableCause, type AutoModeVerdict, type AutoModeDecider, type AutoModeDeciderOptions, type AutoModeClassified, type AutoModeClassifyFn, type AutoModeClassifyInput, createAutoModeDenialTracker, denialLimitFallbackMessage, denialLimitSentence, unarmedWindow, type AutoModeDenialTracker, type AutoModeDenialLimitOptions, type DenialLimitCounts, type DenialLimitFallbackFace, type UnarmedDenialLimitFallback, type DenialLimitFallback, type DenialLimitVerdict, } from "./core/auto-mode.js";
180
+ export { parseAutoModeResponse, createAutoModeDecider, AUTO_MODE_UNAVAILABLE_CAUSES, isAutoModeUnavailableCause, classifierUnavailableDenyMessage, CLASSIFIER_PARSE_FAILURE_DENY_MESSAGE, type AutoModeUnavailableCause, AUTO_MODE_CLASSIFIER_FALLBACKS, isAutoModeClassifierFallback, AUTO_MODE_FALLBACK_CAUSES, isAutoModeFallbackCause, type AutoModeClassifierFallback, type AutoModeFallbackCause, type AutoModeClassifierRound, type AutoModeLadderRung, type AutoModeVerdict, type AutoModeDecider, type AutoModeDeciderOptions, type AutoModeClassified, type AutoModeClassifyFn, type AutoModeClassifyInput, createAutoModeDenialTracker, denialLimitFallbackMessage, denialLimitSentence, unarmedWindow, type AutoModeDenialTracker, type AutoModeDenialLimitOptions, type DenialLimitCounts, type DenialLimitFallbackFace, type UnarmedDenialLimitFallback, type DenialLimitFallback, type DenialLimitVerdict, } from "./core/auto-mode.js";
178
181
  export { AUTO_MODE_DENIAL_LIMIT_DEFAULTS, AUTO_MODE_DENIAL_AUTO_DENY_DEFAULT_MS, AUTO_MODE_CLASSIFIER_MAX_TOKENS } from "./core/auto-mode-defaults.js";
179
182
  export { buildAutoModePrompt, renderAutoModeWindow, renderAutoModeAction, AUTO_MODE_DEFAULTS_SENTINEL, type AutoModeRules, type BuildAutoModePromptOptions, type AutoModeWindowOptions, } from "./core/auto-mode-prompt.js";
180
183
  export { AUTO_MODE_BASE_PROMPT, AUTO_MODE_PERMISSIONS_EXTERNAL } from "./core/auto-mode-prompt-assets.js";
@@ -212,6 +215,7 @@ export { adoptFilePermissionRuleStore, type AdoptFileRuleStoreResult } from "./s
212
215
  export { AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootAdoptionFile, ROOT_ADOPTION_FILE, type AdoptionErrorCode, type AdoptionSource, type AdoptionReport, type AdoptionReceipt, type AdoptionLegReport, type AffectedDeploymentConfig, type RootAdoptionFile, } from "./stores/file/adoption/marker.js";
213
216
  export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, type AdoptionStatus, type AdoptLocalDataRootOptions, type AdoptLocalDataRootResult, type AdoptionCarriageLeg, type AdoptionCarriageLegContext, type AdoptionConfigWitnessReceipt, } from "./stores/file/adoption/adopt.js";
214
217
  export { formatHookFeedback, runToolGate, createHookEnvCapabilities, createPreToolUseConstraintPolicy, type PersistedRuleHit, type PersistedRuleHitRule, type PersistedRuleUnreadable, type PersistedRuleCoverage, type PersistedRuleAnswer, normalizePersistedRuleHit, type Hooks, type HookToolContext, type HookInvocationIdentity, type UserPromptSubmitContext, type PostToolBatchContext, type HookEnvCapabilities, type HookToolOutput, type PreToolUseResult, type PostToolUseResult, type UserPromptSubmitResult, type HookToolFailure, type PostToolUseFailureResult, type PostToolBatchCall, type PostToolBatchResult, type PreCompactContext, type PreCompactResult, type PostCompactContext, type StopFailureContext, type PermissionDeniedPayload, } from "./core/hooks.js";
218
+ export { HOOK_FAMILIES, HOOKS_INVALID_CODE, type HookFamily, type WiringManifestHookEntry } from "./core/hook-seats.js";
215
219
  export { InMemoryMemoryStore, composeMemoryBlock, composeLayeredMemoryBlock, normalizeMemorySpec, type NormalizedMemorySpec, type MemorySpecInput, supportsConsolidation, supportsPeriodicConsolidation, firstSentence, expandLexicalTerms, lexicalSearchMatch, type Embedder, classifyPromotable, enforcePromotableWriteGate, guardedMemoryStore, MemoryGateError, detectSecret, enforceSecretWriteGate, enforceStructuredNoteSecretGate, type UtilityGate, type MemoryStore, type MemoryVectorMode, type ScoredMemory, type MemoryNoteHeader, type MemoryNoteRecord, type MemoryNoteType, type StructuredNoteInput, } from "./core/memory.js";
216
220
  export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, type MemoryBackendContractHooks, buildMemoryInstruction, writableRootOf, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_ORIGIN_CAUSES, committedOriginOf, originEquals, consolidationExposedFrontmatter, ambiguousOriginRepresentation, type OriginClearanceRow, type OriginClearanceEvent, type OriginClearanceShadow, committedDistilledOf, distilledEquals, type MemoryEntryDistilled, type MemoryEntryDistilledInput, CONSOLIDATION_DEFAULTS, ConsolidationRefusedError, MEMORY_SEARCH_SUPERSEDED_TAG, consolidationTypeEligible, deriveSupersededSet, memorySupersededNote, readIntentCredentials, supersessionFuseCeiling, memoryConsolidationRecommendedNotice, memoryConsolidationCommittedNotice, memoryConsolidationConflictNotice, memoryConsolidationIncompleteNotice, memoryConsolidationRefusedNotice, memoryConsolidationWithheldNotice, type ConsolidationGateRead, type ConsolidationGateRow, type ConsolidationIntent, type ConsolidationIntentCredentialRow, type ConsolidationLeaseSeat, type ConsolidationProductProposal, type ConsolidationProposal, type MemoryConsolidationOptions, type ConsolidationCommitReceipt, type ConsolidationReconcileReport, type ConsolidationResolveReceipt, type ConsolidationPlanSummary, type ConsolidationPlanFoldEvidence, type SessionMemoryStatus, DISTILLER_DEFAULT_MAX_INPUTS_PER_PRODUCT, LLM_DISTILLER_CONTRACT, LLM_DISTILLER_CONTRACT_DL2, LLM_DISTILLER_CONTRACT_DL3, LLM_DISTILLER_CONTRACTS, MEMORY_DISTILLER_CONTRACT_V1, contractGroupingDiff, driveConsolidationToFixpoint, isAliasModelId, llmPlanDistiller, mintExposurePartitionedPlan, mintLlmConsolidationPlan, MEMORY_DISTILLER_PURITY_CONTRACT_V1, detectCleanArmVerbatimLeak, type CleanArmLeakFinding, type CleanArmLeakVerdict, type MemoryDistillerPurityContract, openAiCompatChatSeat, parseJsonAnswer, planParseRepairs, sanitizeLlmGroups, scheduleUnderFuse, type ConsolidationDistillFn, type ConsolidationDriveCycleRow, type ConsolidationDriveEngine, type ConsolidationDriveResult, type ConsolidationFoldState, type DistillerCandidate, type DistillerChatAnswer, type DistillerChatFn, type DistillerChatRequest, type FuseSchedule, type LlmConsolidationPlan, type LlmConsolidationPlanArm, type LlmConsolidationPlanProduct, type LlmDistillerContract, type MintLlmConsolidationPlanResult, type PlanParseRepairs, type SanitizedLlmGroups, CONSOLIDATION_DRIVER_PLANS_DIR, CONSOLIDATION_DRIVER_RUNS_FILE, CONSOLIDATION_RUN_STOP_REASONS, archiveDistillerPlan, readConsolidationDriverRun, runMemoryConsolidationDriver, type ConsolidationDriverEngine, type ConsolidationDriverRunRow, type ConsolidationRunReceipt, type ConsolidationRunStopReason, type RunMemoryConsolidationOptions, isInstructionEntry, type MemoryEntryOrigin, type MemoryOriginCause, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, MEMORY_READONLY_NOTICE, MEMORY_CAPTURE_OPTOUT_NOTICE, memoryCaptureOptedOutNotice, memoryCaptureOptOutUnpersistedNotice, SESSION_CAPTURE_OPTOUT_DIR, markSessionCaptureOptOut, readSessionCaptureOptOut, listSessionCaptureOptOut, fileSessionCaptureRecordStore, type SessionCaptureOptOutRecord, type SessionCaptureOptOutMarkOutcome, type SessionCaptureRecordStore, readV2HeaderHints, type V2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, type ControlPlaneRebuildReceipt, type StrictControlPlaneLedger, type ChallengeAssignment, type ChallengeEvent, type ChallengedHistoryRow, type LineagePendingTxn, type LineagePromotion, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_INDEX_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, type MemorySearchDetails, type MemorySearchHit, type CleanMemorySearchHit, type ExposedMemorySearchHit, MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, memoryExposureIndexRow, type MemoryGetDetails, type MemoryIndexDetails, type MemoryIndexRow, type CleanMemoryIndexRow, type ExposedMemoryIndexRow, STUB_ARCHIVED_LINE, DEFAULT_MAX_MEMORY_FILES, DEFAULT_MAX_ENTRY_DEPTH, DEFAULT_HARVEST_DEADLINE_MS, DEFAULT_HARVEST_FILE_BUDGET, MASS_DELETION_FUSE_RATIO, scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE, renderAnnouncements, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, type MemoryAnnouncement, type ScanFinding, type MemoryEngineOptions, type MemoryInjection, type EntryProvenanceAccount, type TransferEvidence, type CommittedBinding, type CommittedEntrySnapshot, type CommittedScopeSnapshots, type EntryCustodyReport, erasureSelectHash, type EraseMemoryEntriesInput, type ErasureSelect, type ErasedBinding, type MemoryErasureAttestation, computeMemoryBundleHash, type MemoryExportBundle, type MemoryImportReport, type MemoryExportSnapshot, type MemoryBundleImportPlan, type BundleChallengeRow, type BundleLineageRow, type BundlePollutedSession, type MemoryBackend, type MemoryEntry, type MemoryEntryFrontmatter, type MemoryEntryHeader, type MemoryScopeEnumeration, type ScoredMemoryEntry, type NotePatch, type PatchReport, type MaterializedFile, type MemorySessionHandle, type HarvestReport, type HarvestRejection, type HarvestRejectionCode, type ParsedEntryFile, type ScannedEntryFile, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, type ParsedScopeKey, migrateScope, type MigrateScopeReport, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, type RemoteMemoryFile, type RemoteMemoryBaseline, type RemoteMaterialization, type RemoteHarvestResult, type InboundEntryFinding, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, type MemorySyncCursor, type MemorySyncConflict, type MemorySyncPlan, type RecallSource, syncMemoryScope, type MemorySyncTransport, type MemorySyncRequestBody, type MemorySyncResponseBody, type MemorySyncClientConflict, type SyncMemoryScopeOptions, type MemorySyncClientResult, } from "./core/memory-engine/index.js";
217
221
  export { SHARED_MEMORY_READ_CAP_BYTES, SHARED_MEMORY_LIST_PAGE_SIZE, SharedMemoryStoreError, type SharedMemoryStoreProvider, type SharedMemoryStoreReader, type SharedMemoryPagedList, type SharedMemoryStoreInfo, type SharedMemoryDocumentEntry, type SharedMemorySnapshot, type SharedMemoryRequestContext, type MemoryListDetails, type MemoryReadDetails, } from "./core/shared-memory/types.js";
@@ -222,7 +226,7 @@ export { runMemoryConsolidation, CONSOLIDATION_SYSTEM_PROMPT, DEFAULT_CONSOLIDAT
222
226
  export { consolidateScope, advanceCursorAfterInline, type ConsolidateScopeDeps, type ConsolidateScopeOptions, } from "./core/consolidate-scope.js";
223
227
  export { resolveMemoryConsolidationDriver, type MemoryConsolidationDriverDeps, } from "./core/runner/memory-consolidation-driver.js";
224
228
  export { DEFAULT_COMPACTION_INSTRUCTIONS } from "./core/auto-compaction.js";
225
- export { DEFAULT_SYSTEM_PROMPT, CODE_AGENT_PROMPT, SUBAGENT_PROMPT, CODE_SYSTEM_PROMPT, MEMORY_GUIDANCE, MEMORY_SAFETY, MEMORY_HYGIENE, NO_PERSISTENT_MEMORY_NOTICE, OUTPUT_EFFICIENCY, CYBER_RISK, HARNESS_SECTION_ANCHOR, URL_SAFETY, SUMMARIZE_TOOL_RESULTS, EXECUTION_ENVIRONMENT, EXECUTION_ENVIRONMENT_OPEN_READS, harnessContext, buildEnvironmentContext, buildGitSnapshot, buildScratchpadSection, GIT_STATUS_MAX_CHARS, formatLocalDate, type EnvironmentFacts, defaultPromptProvider, composeSystemPrompt, composeConstitution, constitutionBlocks, type PromptBlock, analyzePromptCacheFriendliness, assertPromptCacheFriendly, type PromptProvider, type StablePromptContext, type PromptCacheReport, type PromptTextDeclaration, } from "./prompts/default.js";
229
+ export { DEFAULT_SYSTEM_PROMPT, CODE_AGENT_PROMPT, SUBAGENT_PROMPT, CODE_SYSTEM_PROMPT, MEMORY_GUIDANCE, MEMORY_SAFETY, MEMORY_HYGIENE, NO_PERSISTENT_MEMORY_NOTICE, OUTPUT_EFFICIENCY, CYBER_RISK, HARNESS_SECTION_ANCHOR, URL_SAFETY, SUMMARIZE_TOOL_RESULTS, EXECUTION_ENVIRONMENT, EXECUTION_ENVIRONMENT_OPEN_READS, executionEnvironmentBlockFor, harnessContext, buildEnvironmentContext, buildGitSnapshot, buildScratchpadSection, GIT_STATUS_MAX_CHARS, formatLocalDate, type EnvironmentFacts, defaultPromptProvider, composeSystemPrompt, composeConstitution, constitutionBlocks, type PromptBlock, analyzePromptCacheFriendliness, assertPromptCacheFriendly, type PromptProvider, type StablePromptContext, type PromptCacheReport, type PromptTextDeclaration, } from "./prompts/default.js";
226
230
  export { SUPERVISOR_PROMPT, ORCHESTRATION_GUIDANCE, ORCHESTRATION_AWARENESS, GOAL_COMPLETION_GUIDANCE } from "./prompts/supervisor.js";
227
231
  export { compose, validatePack } from "./prompt-assembly/composer.js";
228
232
  export { SEMA_DEFAULT_PACK } from "./prompt-assembly/packs/sema-default.js";
@@ -233,6 +237,7 @@ export { buildTurnPromptSnapshot, loweringRecordFor, LOWERING_VERSION, PREFIX_IN
233
237
  export { CenterPromptSource, FilePromptArtifactStore, FilePromptSourceStateStore, MemoryPromptArtifactStore, MemoryPromptSourceStateStore, type PromptArtifactSource, type PromptArtifactStore, type PromptSourceState, type PromptSourceStateStore, } from "./prompt-assembly/artifact-store.js";
234
238
  export { stripEngineMetadata } from "./internal/llm.js";
235
239
  export { EVENT_PROMPT_REGISTRY, eventDefaultOn, type CompiledEventPrompt, type EventDedupe, type EventDefaultPolicy } from "./prompt-assembly/event-registry.js";
240
+ export { contextUsageSections, type ContextUsageSection } from "./prompt-assembly/section-usage.js";
236
241
  export type { CompiledSection, ComposedPrompt, PackSectionDeclaration, PromptCacheClass, PromptCarrier, PromptMutability, PromptOwner, PromptPack, PromptRenderCadence, PromptRuntimeFacts, PromptSlot, PromptTrust, SectionRenderInputs, } from "./prompt-assembly/types.js";
237
242
  export { type ReasoningIntensity, type ReasoningResolution, type ResolvedReasoning, type ReasoningFormat, DEFAULT_EFFORT_LEVELS, REASONING_BUDGET_SHARE, isThinkingLevel, rankOf, resolveEffort, reasoningEffortLevelsOf, resolveBinary, reasoningBudgetShare, resolveReasoning, thinkingOffExpressible, declaredOffSpelling, type OffCapabilityModel, resolveReasoningProfile, type ReasoningTier, type ReasoningProfileFlags, } from "./brain/reasoning.js";
238
243
  export { DESIGN_REVIEW_PROMPTS, CODE_REVIEW_PROMPT, SCENARIO_REGISTRY, runScenario, type ScenarioId, type CodeReviewMode, type ScenarioProfile, type RunScenarioOptions, type RunScenarioResult, } from "./scenarios/scenario-registry.js";