@sema-agent/core 5.65.0 → 7.0.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 (165) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/agents/subagent.d.ts +2 -2
  3. package/dist/agents/subagent.js +11 -0
  4. package/dist/agents/verify.d.ts +1 -1
  5. package/dist/brain/anthropic.js +1 -1
  6. package/dist/brain/errors.d.ts +29 -0
  7. package/dist/brain/errors.js +20 -0
  8. package/dist/brain/open-responses.js +2 -2
  9. package/dist/brain/route-adjudicator.d.ts +8 -1
  10. package/dist/brain/route-adjudicator.js +1 -0
  11. package/dist/brain/status-sink.js +12 -1
  12. package/dist/brain/stream-engine.js +17 -6
  13. package/dist/core/auto-compaction.d.ts +26 -0
  14. package/dist/core/auto-compaction.js +7 -2
  15. package/dist/core/auto-mode-arming.d.ts +138 -0
  16. package/dist/core/auto-mode-arming.js +181 -0
  17. package/dist/core/auto-mode-defaults.d.ts +13 -0
  18. package/dist/core/auto-mode-defaults.js +5 -0
  19. package/dist/core/auto-mode-prompt.d.ts +14 -3
  20. package/dist/core/auto-mode-prompt.js +10 -7
  21. package/dist/core/auto-mode-rebuild.d.ts +75 -0
  22. package/dist/core/auto-mode-rebuild.js +41 -0
  23. package/dist/core/auto-mode.d.ts +15 -0
  24. package/dist/core/auto-mode.js +4 -2
  25. package/dist/core/checkpoint-store.d.ts +18 -0
  26. package/dist/core/context-edit.d.ts +47 -5
  27. package/dist/core/context-guard.d.ts +1 -1
  28. package/dist/core/file-history-retention.d.ts +106 -0
  29. package/dist/core/file-history-retention.js +36 -0
  30. package/dist/core/file-history-store.d.ts +768 -0
  31. package/dist/core/file-history-store.js +880 -0
  32. package/dist/core/governance-codes.d.ts +13 -3
  33. package/dist/core/governance-codes.js +15 -0
  34. package/dist/core/hooks.d.ts +39 -7
  35. package/dist/core/hooks.js +38 -21
  36. package/dist/core/lsp.d.ts +2 -2
  37. package/dist/core/mcp.d.ts +29 -7
  38. package/dist/core/memory-engine/consolidation-driver.d.ts +11 -0
  39. package/dist/core/memory-engine/consolidation-driver.js +71 -4
  40. package/dist/core/memory-engine/consolidation.d.ts +25 -2
  41. package/dist/core/memory-engine/consolidation.js +4 -1
  42. package/dist/core/memory-engine/distiller.d.ts +84 -1
  43. package/dist/core/memory-engine/distiller.js +68 -0
  44. package/dist/core/memory-engine/dual-root.js +3 -0
  45. package/dist/core/memory-engine/engine.d.ts +328 -15
  46. package/dist/core/memory-engine/engine.js +355 -29
  47. package/dist/core/memory-engine/file-backend.d.ts +30 -0
  48. package/dist/core/memory-engine/file-backend.js +14 -13
  49. package/dist/core/memory-engine/frontmatter.d.ts +22 -1
  50. package/dist/core/memory-engine/frontmatter.js +3 -0
  51. package/dist/core/memory-engine/header-hints.d.ts +5 -0
  52. package/dist/core/memory-engine/index.d.ts +5 -4
  53. package/dist/core/memory-engine/index.js +5 -4
  54. package/dist/core/memory-engine/layout.d.ts +88 -2
  55. package/dist/core/memory-engine/layout.js +112 -3
  56. package/dist/core/memory-engine/provenance-wording.d.ts +7 -0
  57. package/dist/core/memory-engine/provenance-wording.js +3 -0
  58. package/dist/core/memory-engine/tools.d.ts +89 -8
  59. package/dist/core/memory-engine/tools.js +263 -22
  60. package/dist/core/memory-engine/types.d.ts +64 -1
  61. package/dist/core/memory-recall.d.ts +6 -0
  62. package/dist/core/memory.d.ts +27 -1
  63. package/dist/core/memory.js +16 -2
  64. package/dist/core/permission-rule-consent.d.ts +62 -2
  65. package/dist/core/permission-rule-consent.js +105 -14
  66. package/dist/core/permission-rule-model.d.ts +118 -16
  67. package/dist/core/permission-rule-model.js +57 -9
  68. package/dist/core/permission-rule-session.d.ts +124 -0
  69. package/dist/core/permission-rule-session.js +121 -0
  70. package/dist/core/permission-rule-store.d.ts +65 -2
  71. package/dist/core/permission-rule-store.js +75 -16
  72. package/dist/core/permission-rule-sync.d.ts +9 -0
  73. package/dist/core/permission-rule-sync.js +52 -19
  74. package/dist/core/retention-policy.d.ts +9 -0
  75. package/dist/core/retention-policy.js +5 -2
  76. package/dist/core/retention.d.ts +13 -2
  77. package/dist/core/runner/assemble-result.d.ts +19 -1
  78. package/dist/core/runner/assemble-result.js +17 -2
  79. package/dist/core/runner/compaction-call-options.d.ts +93 -0
  80. package/dist/core/runner/compaction-call-options.js +3 -0
  81. package/dist/core/runner/memory-capture-optout.d.ts +80 -0
  82. package/dist/core/runner/memory-capture-optout.js +53 -0
  83. package/dist/core/runner/prepare-config-doors.d.ts +5 -0
  84. package/dist/core/runner/prepare-config-doors.js +16 -0
  85. package/dist/core/runner/prepare-hands-readface.d.ts +110 -5
  86. package/dist/core/runner/prepare-hands-readface.js +99 -7
  87. package/dist/core/runner/prepare-memory.d.ts +88 -0
  88. package/dist/core/runner/prepare-memory.js +305 -24
  89. package/dist/core/runner/prepare-task.d.ts +141 -1
  90. package/dist/core/runner/prepare-task.js +478 -81
  91. package/dist/core/runner/runtask.d.ts +9 -20
  92. package/dist/core/runner/runtask.js +133 -96
  93. package/dist/core/runner/session-file-state-replay.d.ts +18 -10
  94. package/dist/core/runner/session-file-state-replay.js +52 -1
  95. package/dist/core/runner/tool-disclosure.js +2 -1
  96. package/dist/core/runner/turn-attachments.d.ts +22 -12
  97. package/dist/core/session-store.d.ts +1 -1
  98. package/dist/core/session-store.js +6 -1
  99. package/dist/core/session.d.ts +34 -1
  100. package/dist/core/store-contracts/file-history-store-contract.d.ts +3 -0
  101. package/dist/core/store-contracts/file-history-store-contract.js +720 -0
  102. package/dist/core/store-contracts/permission-rule-sync-contract.js +15 -1
  103. package/dist/core/task-registry-shared.js +11 -1
  104. package/dist/core/tool-errors.js +1 -0
  105. package/dist/core/tool-policy.d.ts +172 -1
  106. package/dist/core/tool-policy.js +32 -1
  107. package/dist/core/tool-result-store.js +2 -1
  108. package/dist/core/trace.d.ts +31 -2
  109. package/dist/core/types.d.ts +795 -89
  110. package/dist/core/types.js +4 -3
  111. package/dist/core/untrusted-text.d.ts +1 -1
  112. package/dist/core/untrusted-text.js +8 -0
  113. package/dist/core/workflow-run-store-contract.js +6 -2
  114. package/dist/core/workflow-run-store.d.ts +4 -1
  115. package/dist/engine/compaction/compaction.d.ts +88 -10
  116. package/dist/engine/compaction/compaction.js +109 -30
  117. package/dist/engine/execution-env/node-execution-env.d.ts +9 -1
  118. package/dist/engine/execution-env/node-execution-env.js +28 -0
  119. package/dist/engine/harness/agent-harness.d.ts +52 -1
  120. package/dist/engine/harness/agent-harness.js +36 -1
  121. package/dist/engine/harness/types.d.ts +26 -1
  122. package/dist/engine/llm/types.d.ts +50 -4
  123. package/dist/engine/loop/agent-loop.d.ts +5 -1
  124. package/dist/engine/loop/agent-loop.js +25 -0
  125. package/dist/engine/loop/types.d.ts +19 -0
  126. package/dist/engine/lsp/node-lsp-manager.d.ts +1 -1
  127. package/dist/engine/session/session.js +1 -1
  128. package/dist/index.d.ts +20 -9
  129. package/dist/index.js +16 -7
  130. package/dist/orchestration/run-workflow-tool.d.ts +20 -2
  131. package/dist/orchestration/run-workflow-tool.js +22 -3
  132. package/dist/orchestration/workflow-governance.d.ts +59 -1
  133. package/dist/orchestration/workflow-governance.js +61 -8
  134. package/dist/orchestration/workflow-meta.d.ts +4 -2
  135. package/dist/orchestration/workflow-primitives.js +56 -13
  136. package/dist/orchestration/workflow-types.d.ts +78 -2
  137. package/dist/orchestration/workflow.d.ts +20 -0
  138. package/dist/orchestration/workflow.js +163 -14
  139. package/dist/prompt-assembly/event-registry.js +1 -1
  140. package/dist/prompts/default.d.ts +7 -7
  141. package/dist/stores/file/file-history-store.d.ts +368 -0
  142. package/dist/stores/file/file-history-store.js +1248 -0
  143. package/dist/stores/file/index.d.ts +22 -13
  144. package/dist/stores/file/index.js +4 -4
  145. package/dist/stores/file/permission-rule-store.d.ts +11 -0
  146. package/dist/stores/file/permission-rule-store.js +23 -9
  147. package/dist/stores/file/strategy-store.d.ts +3 -3
  148. package/dist/tools/fs/bash-readonly-classifier.d.ts +87 -3
  149. package/dist/tools/fs/bash-readonly-classifier.js +106 -4
  150. package/dist/tools/fs/fs-bash.js +9 -5
  151. package/dist/tools/fs/fs-shared.d.ts +52 -1
  152. package/dist/tools/fs/fs-shared.js +14 -0
  153. package/dist/tools/fs/fs-write.d.ts +5 -5
  154. package/dist/tools/fs/fs-write.js +71 -14
  155. package/dist/tools/fs/index.d.ts +6 -1
  156. package/dist/tools/fs/index.js +1 -1
  157. package/dist/tools/web.js +2 -1
  158. package/package.json +5 -1
  159. package/test/export-surface.snapshot.json +169 -23
  160. package/dist/core/file-snapshot-store.d.ts +0 -165
  161. package/dist/core/file-snapshot-store.js +0 -259
  162. package/dist/core/store-contracts/file-snapshot-store-contract.d.ts +0 -13
  163. package/dist/core/store-contracts/file-snapshot-store-contract.js +0 -134
  164. package/dist/stores/file/file-snapshot-store.d.ts +0 -58
  165. package/dist/stores/file/file-snapshot-store.js +0 -353
@@ -264,9 +264,12 @@ export declare class AgentHarness<TSkill extends Skill = Skill, TPromptTemplate
264
264
  private handleAgentEvent;
265
265
  private emitRunFailure;
266
266
  private executeTurn;
267
+ /** Returns the run's final assistant message — or `undefined` on exactly one arm (#504): a bare
268
+ * user halt ({@link halt}) stopped the run before any assistant output existed. Every other
269
+ * zero-assistant ending still throws (see the executeTurn tail). */
267
270
  prompt(text: string, options?: {
268
271
  images?: ImageContent[];
269
- } & UserMessageProvenance): Promise<AssistantMessage>;
272
+ } & UserMessageProvenance): Promise<AssistantMessage | undefined>;
270
273
  /** R2-③: an empty/whitespace-only injection with no images carries ZERO information — it
271
274
  * must not mint a user frame (strict endpoints reject empty user content, and an empty follow-up would
272
275
  * pointlessly extend the run by one turn). No-op, not a throw: injection callers are fire-and-
@@ -315,6 +318,54 @@ export declare class AgentHarness<TSkill extends Skill = Skill, TPromptTemplate
315
318
  * turn — later immediates join the same boundary batch).
316
319
  */
317
320
  interruptTurn(frame: AgentMessage): boolean;
321
+ /**
322
+ * design/373 (#504) — the BARE user interrupt, the CC Esc form: CUT the in-flight turn (when one
323
+ * is in flight) and STOP the run at that manufactured boundary — no new model turn starts, the
324
+ * run collects to a clean, resumable ending (never the orphan-[INTERRUPTED] run-abort reconcile).
325
+ * The run-model equivalent of "the session stays alive waiting for the user's next input".
326
+ *
327
+ * Two halves, one call:
328
+ * - STOP — the one-way `requestStopAfterTurn` latch, now consulted at BOTH boundary faces
329
+ * (post-turn `shouldStopAfterTurn` and #504's pre-turn `shouldHaltBeforeTurn`), so the loop
330
+ * ends at whichever boundary comes first and never starts another provider request;
331
+ * - CUT — the design/373 S1 turn seat, aborted WITHOUT the frame-consumption guard: unlike
332
+ * {@link interruptTurn} (an accelerator FOR a queued immediate frame, guarded so it can never
333
+ * cut the delivery it exists to speed up), a bare halt is not delivering anything — there is
334
+ * no frame whose consumption could make the cut self-defeating, so the seat's own liveness is
335
+ * the only guard. The cut settles exactly as every S1 cut does: finished tool calls keep
336
+ * their REAL results, never-started ones settle as paired interrupted results, the
337
+ * CC-verbatim interruption marker lands.
338
+ *
339
+ * Returns `{ turnCut, accepted }` — `turnCut` `true` iff THIS call aborted a live turn seat (an
340
+ * in-flight provider stream / tool batch will settle as interrupted; the completion-race arm is
341
+ * honest: a turn whose work already finished when the abort landed ends normally and the run
342
+ * still stops at its boundary). `false` = nothing was in flight (between turns / boundary
343
+ * housekeeping / a boundary already being manufactured) — the stop half alone answers, at the
344
+ * imminent boundary. `accepted` (#504 codex r3) is the ATOMIC ownership bit: `true` iff this
345
+ * call latched the stop on a run whose harness-channel abort had NOT already fired — captured
346
+ * BEFORE the seat abort dispatches, so a re-entrant abort fired by the cut's own listeners can
347
+ * never rewrite the answer. The unwinding arm answers `{ turnCut:false, accepted:false }`: an
348
+ * abort-owned ending is never this verb's claim (the runner's attribution seat keys on it).
349
+ *
350
+ * Guards, in order (the interruptTurn discipline, minus the frame guard):
351
+ * - idle ⇒ typed refusal (the steer posture — misuse must be loud; the runner's birth-window
352
+ * poll owns the not-yet-started arm);
353
+ * - an unwinding run (`abort()` latched) owns its ending — never contest it, and never latch a
354
+ * stale stop onto a harness a later `prompt()` would inherit... (the latch is per-prompt
355
+ * reset, but the honest answer while unwinding is still "nothing for this verb to do");
356
+ * - stop latch, THEN seat: latch-before-abort ordering is load-bearing — the cut's settlement
357
+ * consults the latch at its own boundary, so the stop is provably in place when the forced
358
+ * boundary arrives (the enqueue-then-abort discipline, one lane over).
359
+ *
360
+ * Queued injection frames are deliberately NOT touched (CC 2.1.223 `control_request:"interrupt"`
361
+ * keeps the queue and answers `still_queued` — see {@link abort}'s recorded ruling): whatever
362
+ * the queues hold settles by the run's ordinary terminal contract for accepted-but-undelivered
363
+ * input (durable park when a suspend seat exists, else the loud undrained accounts).
364
+ */
365
+ halt(): {
366
+ turnCut: boolean;
367
+ accepted: boolean;
368
+ };
318
369
  /**
319
370
  * design/373 §3.3 (the final-commit-point double check) — how many queued injection frames a
320
371
  * boundary drain could deliver RIGHT NOW: both lanes, minus frames the current state refuses to
@@ -1,4 +1,4 @@
1
- import { snapshotActorAssertion, stripEngineMetadata } from "../llm/index.js";
1
+ import { createAssistantMessageEventStream, snapshotActorAssertion, stripEngineMetadata } from "../llm/index.js";
2
2
  import { runAgentLoop } from "../loop/agent-loop.js";
3
3
  import { resolveAgentCoreStreamFn } from "../loop/runtime-deps.js";
4
4
  import { normalizeEngineSegments } from "../../core/untrusted-text.js";
@@ -456,6 +456,25 @@ export class AgentHarness {
456
456
  headers: mergeHeaders(dropAuthCarriers(turnState.streamOptions.headers), auth?.headers),
457
457
  };
458
458
  const requestOptions = await this.emitBeforeProviderRequest(model, turnState.sessionId, snapshotOptions);
459
+ if (streamOptions?.signal?.aborted) {
460
+ const out = createAssistantMessageEventStream();
461
+ out.push({
462
+ type: "error",
463
+ reason: "aborted",
464
+ error: {
465
+ role: "assistant",
466
+ content: [{ type: "text", text: "" }],
467
+ api: model.api,
468
+ provider: model.provider,
469
+ model: model.id,
470
+ stopReason: "aborted",
471
+ timestamp: Date.now(),
472
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
473
+ usageMissing: true,
474
+ },
475
+ });
476
+ return out;
477
+ }
459
478
  return resolveAgentCoreStreamFn(this.runtime)(model, context, {
460
479
  ...(auth?.apiKey !== undefined ? { apiKey: auth.apiKey } : {}),
461
480
  cacheRetention: requestOptions.cacheRetention,
@@ -564,6 +583,7 @@ export class AgentHarness {
564
583
  : {}),
565
584
  convertToLlm: (messages) => stripEngineMetadata(convertToLlm(messages)),
566
585
  shouldStopAfterTurn: () => this._stopAfterTurn,
586
+ shouldHaltBeforeTurn: () => this._stopAfterTurn,
567
587
  transformContext: async (messages, signal) => {
568
588
  const result = await this.emitHook({ type: "context", messages: [...messages], ...(signal !== undefined ? { signal } : {}) });
569
589
  if (result?.adoptSessionRebuild !== true) {
@@ -820,6 +840,8 @@ export class AgentHarness {
820
840
  return mergeTruncatedOutputChain(newMessages, i);
821
841
  }
822
842
  }
843
+ if (this._stopAfterTurn)
844
+ return undefined;
823
845
  throw new AgentHarnessError("invalid_state", "AgentHarness prompt completed without an assistant message");
824
846
  }
825
847
  finally {
@@ -955,6 +977,19 @@ export class AgentHarness {
955
977
  seat.abort();
956
978
  return true;
957
979
  }
980
+ halt() {
981
+ if (this.phase === "idle") {
982
+ throw new AgentHarnessError("invalid_state", "Cannot halt while idle");
983
+ }
984
+ if (this.aborting)
985
+ return { turnCut: false, accepted: false };
986
+ this._stopAfterTurn = true;
987
+ const seat = this.turnInterruptSeat;
988
+ if (seat === undefined || seat.signal.aborted)
989
+ return { turnCut: false, accepted: true };
990
+ seat.abort();
991
+ return { turnCut: true, accepted: true };
992
+ }
958
993
  pendingInjectionCount() {
959
994
  if (this.aborting)
960
995
  return 0;
@@ -259,6 +259,17 @@ export interface FileInfo {
259
259
  size: number;
260
260
  /** Modification time as milliseconds since Unix epoch. */
261
261
  mtimeMs: number;
262
+ /**
263
+ * design/381 DV-8 — OPTIONAL POSIX permission bits of the addressed object (`mode & 0o7777`,
264
+ * symlinks not followed, like every other field here). Present only when the backend can express
265
+ * them: an env whose filesystem has no POSIX permission model, or a transport that does not carry
266
+ * them, OMITS the field rather than inventing a plausible number — a fabricated `0o644` is
267
+ * indistinguishable from a real one, and the rewind history would then "preserve" a mode the file
268
+ * never had. Absent ⇒ a consumer has nothing to preserve and says so
269
+ * ({@link import("../../core/file-history-store.js").FileHistoryRestoreResult.modeNotPreserved}),
270
+ * which is the honest degraded form.
271
+ */
272
+ mode?: number;
262
273
  }
263
274
  /** Options for {@link Shell.exec}. */
264
275
  export interface ExecutionEnvExecOptions {
@@ -360,6 +371,20 @@ export interface FileSystem {
360
371
  appendFile(path: string, content: string | Uint8Array, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;
361
372
  /** Return metadata for the addressed path without following symlinks. */
362
373
  fileInfo(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo, FileError>>;
374
+ /**
375
+ * design/381 DV-8 — OPTIONAL companion of {@link FileInfo.mode}: set the addressed object's POSIX
376
+ * permission bits (`mode & 0o7777`), symlinks NOT followed (an env whose backend can only chmod
377
+ * through a link omits this method rather than following one — a restore must never re-permission
378
+ * a file it was pointed at by a link it did not verify).
379
+ *
380
+ * Optional in the same sense as {@link readLink}/{@link writeFileGuarded}: an env whose filesystem
381
+ * has no permission model, or whose transport cannot carry one, leaves this `undefined`. The
382
+ * caller then reports the mode as NOT preserved rather than silently dropping it — the whole point
383
+ * of the pair being optional is that "we could not keep the executable bit" is a fact somebody has
384
+ * to be able to read. An env that CAN express modes but is asked for one it cannot apply answers a
385
+ * typed {@link FileError}; the caller treats that exactly like absence (disclosed, never fatal).
386
+ */
387
+ setFileMode?(path: string, mode: number, abortSignal?: AbortSignal): Promise<Result<void, FileError>>;
363
388
  /** List direct children of a directory without following symlinks. */
364
389
  listDir(path: string, abortSignal?: AbortSignal): Promise<Result<FileInfo[], FileError>>;
365
390
  /** Return the canonical path for an existing path, resolving symlinks where supported. */
@@ -825,7 +850,7 @@ export interface SessionStorage<TMetadata extends SessionMetadata = SessionMetad
825
850
  * `windowTokens` arms a DEFENSIVE re-clamp of the compaction summary's retained invoked-skills
826
851
  * area against the CURRENT model's window (the area was budgeted at compaction time against the
827
852
  * model active THEN; a later, smaller-window model must not inherit an area that alone overflows
828
- * its window). `charsPerToken` is the structural coefficient for that clamp (default 4). Absent ⇒
853
+ * its window). `charsPerToken` is the structural coefficient for that clamp (default 3 since design/374 slice 4). Absent ⇒
829
854
  * legacy behavior, byte-identical context.
830
855
  */
831
856
  export interface BuildContextOptions {
@@ -387,6 +387,49 @@ export interface AssistantMessage {
387
387
  model: string;
388
388
  responseModel?: string;
389
389
  responseId?: string;
390
+ /**
391
+ * The provider's own REQUEST identifier for the attempt this message reports on, lifted from the
392
+ * response headers (`request-id` / `x-request-id`) and admitted only in a conservative identifier
393
+ * shape. It is the handle a provider's support channel asks for, and it is the ONLY field on an
394
+ * error message that can be correlated with the upstream's own records.
395
+ *
396
+ * IN-SCOPE / PRESENCE: stamped by the streaming engine on the terminal ERROR shell of a provider
397
+ * failure ({@link isApiErrorMessage}), and only when the failing attempt's response actually
398
+ * carried a readable header — a connect failure, a DNS refusal, or a provider that states no such
399
+ * header leaves it ABSENT. Absence is a fact ("no id was stated"), never a default; a consumer must
400
+ * not read it as "no request was made". Distinct from {@link responseId}, which is the provider's
401
+ * identifier for a RESPONSE BODY on the success path. Additive/optional throughout.
402
+ */
403
+ requestId?: string;
404
+ /**
405
+ * This assistant message WRAPS A PROVIDER FAILURE — the turn ended because the transport or the
406
+ * provider failed, not because the model or this engine decided something. Set from the brain
407
+ * error's minter-declared provider-boundary mark, so a DEPLOYMENT-side refusal that never reached
408
+ * the wire (a credential-pairing refusal, an inexpressible request) is deliberately NOT marked:
409
+ * the two need different operator responses and had no machine-readable difference before this seat
410
+ * (both arrive as `stopReason:"error"` with a `[code]` prefix, and `invalid_request` is minted by
411
+ * both). CC-anchored spelling (`isApiErrorMessage`).
412
+ *
413
+ * PRESENCE: `true` only on an errored message the engine minted for a provider/transport failure.
414
+ * ABSENT on success, on an aborted turn (a cancel is not a provider fault), on the circuit
415
+ * breaker's local fast-fail, and on the in-band terminal-output causes (`stream_torn` / `refusal` /
416
+ * `length_empty`), which are model-output problems rather than API failures. A consumer must not
417
+ * infer the negative from absence on messages minted by a custom Brain that does not stamp it.
418
+ */
419
+ isApiErrorMessage?: true;
420
+ /**
421
+ * The HTTP status of the failing provider response, when there WAS one. Only meaningful together
422
+ * with {@link isApiErrorMessage}.
423
+ *
424
+ * PRESENCE: present only when the provider answered with an error STATUS (the terminal HTTP throw).
425
+ * ABSENT — deliberately, not zeroed — for every failure that had no HTTP error status of its own: a
426
+ * connect failure or DNS refusal (no response at all), a connect/first-token/idle stall, a
427
+ * mid-stream tear (the response's own status was a success and reporting it here would name a
428
+ * status that failed nothing), and an in-band SSE error frame (delivered inside a 200). Same
429
+ * three-state discipline CC states for its own `api_error_status`; absence must never be rendered
430
+ * as `0`.
431
+ */
432
+ apiErrorStatus?: number;
390
433
  diagnostics?: AssistantMessageDiagnostic[];
391
434
  usage: Usage;
392
435
  /** TB 尸检 T1-5: the provider never delivered a usage frame for this message (e.g. a
@@ -788,10 +831,13 @@ export interface Model<TApi extends Api = Api> {
788
831
  * trimToBudget), cut-point accounting, the prompt-overhead term, and the summarization input guard.
789
832
  * API-agnostic model property (NOT a wire knob), hence top-level and not `compat`.
790
833
  *
791
- * Default **4** (byte-compatible with the historical chars/4 heuristic; CC 198's legacy-family
792
- * value claude-3.x / opus·sonnet-4-x / haiku-4-5). Newer families tokenize denser (CC 198 uses
793
- * **3** for the sonnet-5/fable-5 class). CJK-heavy deployments should consider **2–3**: chars/4
794
- * underestimates Chinese by 60–75%, which lets the defenses pass over-window requests.
834
+ * Default **3** (design/374 slice 4, 2026-08-28; it was 4 before). CC's coefficient is a
835
+ * two-branch function `Z6.has(family) ? 4 : 3` whose table holds only the OLDER families
836
+ * (claude-3.x / opus-4-0·4-1·4-5·4-6 / sonnet-4-0·4-5·4-6 / haiku-4-5) **3 is the default
837
+ * branch**, 4 is the whitelist hit, and CC's own opus-5/sonnet-5 generation is outside the table.
838
+ * Declare **4** explicitly for a model of that older generation. CJK-heavy deployments should
839
+ * consider **2**: even chars/3 underestimates Chinese, and an underestimate is what lets the
840
+ * defenses pass an over-window request.
795
841
  */
796
842
  charsPerToken?: number;
797
843
  maxTokens: number;
@@ -31,7 +31,11 @@ export type LoopTerminalReason =
31
31
  | "aborted_before_stream"
32
32
  /** The assistant message itself ended with stopReason "error" or "aborted". */
33
33
  | "assistant_error"
34
- /** `shouldStopAfterTurn` requested a clean stop at the turn boundary (mod #16 one-shot). */
34
+ /** A clean stop was requested at a turn boundary (mod #16 one-shot): `shouldStopAfterTurn`
35
+ * answered true after a turn, or — #504's pre-turn half — `shouldHaltBeforeTurn` refused to
36
+ * start the next one. One reason for both consult points: the fact reported is the same (the
37
+ * loop ended cleanly at a manufactured boundary, no reconcile owed), and which consult caught
38
+ * it is timing, not semantics. */
35
39
  | "stop_requested"
36
40
  /** RB-206 (CC 220 counterpart @400176-400230, `Bxs` @397652-397674 buckets it
37
41
  * with budget_exhausted/api_error/model_error/turn_setup_failed, explicitly NOT `"completed"`): every
@@ -195,8 +195,16 @@ async function runSingleTurn(state, signal, emit, streamFn, runtime, trace) {
195
195
  await emit({ type: "agent_end", messages: state.newMessages });
196
196
  return { kind: "terminal", reason: "aborted_before_stream" };
197
197
  }
198
+ if (state.config.shouldHaltBeforeTurn?.() === true) {
199
+ await emit({ type: "agent_end", messages: state.newMessages });
200
+ return { kind: "terminal", reason: "stop_requested" };
201
+ }
198
202
  if (!state.firstTurn) {
199
203
  await emit({ type: "turn_start" });
204
+ if (state.config.shouldHaltBeforeTurn?.() === true) {
205
+ await emit({ type: "agent_end", messages: state.newMessages });
206
+ return { kind: "terminal", reason: "stop_requested" };
207
+ }
200
208
  }
201
209
  else {
202
210
  state.firstTurn = false;
@@ -580,6 +588,23 @@ async function streamAssistantResponse(context, config, signal, emit, streamFn,
580
588
  const resolvedApiKey = (config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;
581
589
  const perCallMaxTokens = config.maxTokensPerCall?.();
582
590
  const perCallStallTimeouts = config.stallTimeoutsPerCall?.();
591
+ if (signal?.aborted) {
592
+ const abortedBeforeDispatch = {
593
+ role: "assistant",
594
+ content: [{ type: "text", text: "" }],
595
+ api: config.model.api,
596
+ provider: config.model.provider,
597
+ model: config.model.id,
598
+ stopReason: "aborted",
599
+ timestamp: Date.now(),
600
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
601
+ usageMissing: true,
602
+ };
603
+ context.messages.push(abortedBeforeDispatch);
604
+ await emit({ type: "message_start", message: { ...abortedBeforeDispatch } });
605
+ await emit({ type: "message_end", message: abortedBeforeDispatch });
606
+ return abortedBeforeDispatch;
607
+ }
583
608
  const response = await streamFunction(config.model, llmContext, {
584
609
  ...config,
585
610
  ...(perCallMaxTokens !== undefined ? { maxTokens: perCallMaxTokens, maxTokensDynamic: true } : {}),
@@ -411,6 +411,25 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
411
411
  * Contract: must not throw or reject. Throwing interrupts the low-level agent loop without producing a normal event sequence.
412
412
  */
413
413
  shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
414
+ /**
415
+ * design/373 (#504) — the PRE-turn half of the clean-stop latch, consulted at the top of every
416
+ * turn BEFORE any provider work (and before `turn_start` for non-first turns). `true` ⇒ the loop
417
+ * emits `agent_end` and exits at this manufactured boundary instead of starting a new model turn
418
+ * (terminal reason `"stop_requested"`, the same clean stop the post-turn consult reports).
419
+ *
420
+ * It exists because `shouldStopAfterTurn`'s consult sits at the END of a turn: a stop requested
421
+ * while the loop is between its boundary consult and the next provider request (the drain-point
422
+ * awaits, the stop gate's await, the follow-up drain) used to buy one full extra model turn
423
+ * before being honored. The bare user-halt verb ("cut + stop", the CC Esc form) promises that no
424
+ * new model turn starts once the halt is accepted, so the latch must guard the turn that has NOT
425
+ * started — a context-carrying callback about the finished turn cannot.
426
+ *
427
+ * Contract: SYNCHRONOUS and side-effect-free (the `pendingInjectionCount` discipline). Frames
428
+ * already drained into the refused turn's pending batch are NOT injected (no message events); the
429
+ * host's in-flight accounting (`#389`) reports them through its own terminal account. Absent ⇒
430
+ * the pre-#504 behavior (only the post-turn consult stops the loop).
431
+ */
432
+ shouldHaltBeforeTurn?: () => boolean;
414
433
  /**
415
434
  * Called after `turn_end` and before the loop decides whether another provider request should start.
416
435
  * Return replacement context/model/thinking state to affect the next turn in this run.
@@ -124,7 +124,7 @@ export declare function languageFor(filePath: string): string | undefined;
124
124
  export { MAX_LSP_FILE_BYTES } from "../../core/lsp.js";
125
125
  /**
126
126
  * RB-232: the local default {@link LspReadText}, hardened with a stat-first precondition (CC
127
- * 2.1.220 validateInput does the same before ever reading — "Path is not a file", pretty220.js ~474700).
127
+ * 2.1.220 validateInput does the same before ever reading — "Path is not a file", (pretty220.js:474700, historical; not relocated in 250 — see cc-250 anchors)).
128
128
  * The stat check is the LOAD-BEARING part, do not "simplify" it away: a plain `readFile` on a FIFO/socket
129
129
  * blocks forever on the FIRST read and PINS a libuv threadpool thread (default pool = 4) for the process
130
130
  * lifetime — measured: `readFile(fifo, { signal })` with an abort fired at 2s was still unsettled at 10s,
@@ -2,7 +2,7 @@ import { asAgentMessage, createCompactionSummaryMessage, createCustomMessage, }
2
2
  import { SessionError, isValidModelChange, normalizeAnnouncedListing, normalizeCompactionStateCarrier, normalizeGitAnnouncement, normalizeReminderMark, normalizeWorkspaceState } from "../harness/types.js";
3
3
  import { normalizePromptEpoch } from "../../prompt-assembly/epoch.js";
4
4
  import { budgetInvokedSkillsRetention, readElidedMessages, readRetainedInvokedSkills, readUnsummarizedMessages, renderInvokedSkillsRetention, } from "../compaction/utils.js";
5
- const RETENTION_CLAMP_DEFAULT_CHARS_PER_TOKEN = 4;
5
+ const RETENTION_CLAMP_DEFAULT_CHARS_PER_TOKEN = 3;
6
6
  const RETENTION_CLAMP_WINDOW_FRACTION = 0.5;
7
7
  export function buildSessionContext(pathEntries, opts) {
8
8
  let thinkingLevel = "off";
package/dist/index.d.ts CHANGED
@@ -99,10 +99,18 @@ export { InMemoryCheckpointStore, CheckpointError, mintCheckpointId, mintCheckpo
99
99
  export { InMemoryUsageWindowStore, GLOBAL_USAGE_KEY, EMPTY_USAGE_WINDOW_RECORD, chargeUsageRecord, readUsageRecord, usageRetryAfterMs, resolveUsageWindows, type UsageWindow, type UsageWindowStore, type UsageWindowReading, type UsageWindowRecord, type UsageSlot, type UsageBucketRow, } from "./core/usage-window-store.js";
100
100
  export { FileUsageWindowStore } from "./stores/file/usage-window-store.js";
101
101
  export { ENV_LIFETIME_SUSPEND_MARGIN_MS, USAGE_WINDOW_REAP_MARGIN_MS } from "./core/runner/prepare-task.js";
102
- export { InMemoryFileSnapshotStore, DEFAULT_SNAPSHOT_BOUNDS } from "./core/file-snapshot-store.js";
103
- export { captureManifest, applyManifest } from "./core/file-snapshot-store.js";
104
- export type { FileSnapshotStore, FileSnapshotResult, FileSnapshotError, FileSnapshotBounds } from "./core/file-snapshot-store.js";
105
- export { FileStorageBackend, FileSessionRepo, FileCheckpointStore, FileMemoryStore, FileToolResultStore, FileSessionPolicyStore, FileFileSnapshotStore, FileStrategyStore, FileWorkflowJournalStore, MAX_JOURNAL_RESULT_BYTES, oversizeJournalResult, resolveDataRoot, sanitizeScope, sanitizePathComponent, createFileConsolidationLock, atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog, FileStoreLockError, type FileStoreLockErrorCode, type FileStorageBackendOptions, type FileStorageCorruptReadInfo, type FileStrategyStoreOptions, type FileSessionRepoOptions, type FileFileSnapshotStoreOptions, type FileCheckpointStoreOptions, } from "./stores/file/index.js";
102
+ export { InMemoryFileHistoryStore, boundaryPublishVerdict } from "./core/file-history-store.js";
103
+ export { captureFileBackupViaEnv, applyFileRestoreViaEnv } from "./core/file-history-store.js";
104
+ export { modeProvenDifferent as fileHistoryModeProvenDifferent } from "./core/file-history-store.js";
105
+ export { previewFileDelta as fileHistoryPreviewFileDelta, countRestoreLineDiff, FILE_HISTORY_DIFF_LINE_BUDGET } from "./core/file-history-store.js";
106
+ export { worldStillMatchesMint } from "./core/file-history-store.js";
107
+ export { trackKeyOf as fileHistoryTrackKeyOf, resolveTrackKey as fileHistoryResolveTrackKey } from "./core/file-history-store.js";
108
+ export { describeTrackKey as fileHistoryDescribeTrackKey, trackKeyFamilyOf as fileHistoryKeyFamilyOf, fileHistoryExportDigest, validateFileHistoryExport } from "./core/file-history-store.js";
109
+ export type { FileHistoryStore, FileHistoryResult, FileHistoryTrackResult, FileHistoryError, FileHistoryKeyFamily, FileHistoryTrackKeyDescriptor, FileHistoryRestoreResult, FileHistoryDiffStats, FileHistoryExport, FileBackupCapture, FileRestoreTarget, FileRestoreApplyOptions, FileRestoreApplyOutcome, FileHistoryTrackKeyResolution } from "./core/file-history-store.js";
110
+ export type { InMemoryFileHistoryStoreOptions } from "./core/file-history-store.js";
111
+ export { DEFAULT_FILE_HISTORY_BOUNDARY_KEEP, resolveFileHistoryRetention, fileHistoryBoundariesToKeep } from "./core/file-history-retention.js";
112
+ export type { FileHistoryRetentionPolicy } from "./core/file-history-retention.js";
113
+ export { FileStorageBackend, FileSessionRepo, FileCheckpointStore, FileMemoryStore, FileToolResultStore, FileSessionPolicyStore, FileStrategyStore, FileFileHistoryStore, FileWorkflowJournalStore, MAX_JOURNAL_RESULT_BYTES, oversizeJournalResult, resolveDataRoot, sanitizeScope, sanitizePathComponent, createFileConsolidationLock, atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog, FileStoreLockError, type FileStoreLockErrorCode, type FileStorageBackendOptions, type FileStorageCorruptReadInfo, type FileStrategyStoreOptions, type FileFileHistoryStoreOptions, type FileSessionRepoOptions, type FileCheckpointStoreOptions, } from "./stores/file/index.js";
106
114
  export { CacheBreakDetector, type CacheBreakFinding, type ToolFingerprintInput } from "./core/cache-break-detector.js";
107
115
  export { maybeCompact, type MaybeCompactOptions, type CompactionWindowSafetyInfo } from "./core/auto-compaction.js";
108
116
  export { brainToRuntime } from "./core/runtime.js";
@@ -110,7 +118,7 @@ export { createSensitivePathPolicy, RECOMMENDED_SENSITIVE_PATTERNS } from "./cor
110
118
  export { createFsWriteGatePolicy, type FsWriteGatePolicyOptions } from "./core/fs-write-gate-policy.js";
111
119
  export { RETIRED_TOOL_NAMES } from "./core/tool-name-aliases.js";
112
120
  export { DEFAULT_SUBAGENT_TOOL_NAME } from "./agents/subagent.js";
113
- export { renderTaskNotificationXml, taskNotificationDedupKey, isDelegatedAgentTerminal, isTerminalTaskNotification, SystemInjectionQueue, type TaskNotificationPayload, type TaskNotificationStatus, type ExternalNotificationInput, type SystemInjection, type SystemInjectionPriority, } from "./core/task-notification.js";
121
+ export { renderTaskNotificationXml, taskNotificationDedupKey, isDelegatedAgentTerminal, isTerminalTaskNotification, SystemInjectionQueue, type TaskNotificationPayload, type TaskNotificationStatus, type ExternalNotificationInput, type SystemInjection, type SystemInjectionPriority, SYSTEM_INJECTION_PRIORITIES, isSystemInjectionPriority, } from "./core/task-notification.js";
114
122
  export { describeStaticWiring, deriveWiringManifest, deriveAskEffective, resolveDeclaredDurability, resolveSubagentTranscriptTier, type SubagentTranscriptTier, resolveAskSeamForm, resolveQuestionSeam, countElicitOptIns, type WiringManifest, 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";
115
123
  export { probeParkRoundTrip, durableParkGapOf, durableParkGapFor, PARK_SELFCHECK_SCOPE_PREFIX, type ParkSelfCheckResult, type ParkProbeFinding, type ParkProbeFindingCode, } from "./core/park-selfcheck.js";
116
124
  export { type StoreDurability } from "./core/checkpoint-store.js";
@@ -140,6 +148,8 @@ export { createAllowDenyPolicy, createApprovalPolicy, COARSE_SHELL_TOOLS, create
140
148
  export { parseAutoModeResponse, createAutoModeDecider, type AutoModeVerdict, type AutoModeDecider, type AutoModeDeciderOptions, type AutoModeClassifyFn, type AutoModeClassifyInput, } from "./core/auto-mode.js";
141
149
  export { buildAutoModePrompt, renderAutoModeWindow, renderAutoModeAction, AUTO_MODE_DEFAULTS_SENTINEL, type AutoModeRules, type BuildAutoModePromptOptions, type AutoModeWindowOptions, } from "./core/auto-mode-prompt.js";
142
150
  export { AUTO_MODE_BASE_PROMPT, AUTO_MODE_PERMISSIONS_EXTERNAL } from "./core/auto-mode-prompt-assets.js";
151
+ export { AUTO_MODE_ARMING_RECIPE_VERSION, autoModeArmingRecipeOf, sanitizeAutoModeArmingRecipe, foldAutoModeArming, type AutoModeArmingRecipe, type AutoModeArmingFace, type AutoModeArmingFold, type AutoModeRebuildRefusal, } from "./core/auto-mode-arming.js";
152
+ export { rebuildAutoModeDecider, type AutoModeClassifierCompletion, type AutoModeRebuildOptions, type AutoModeRebuildResult, } from "./core/auto-mode-rebuild.js";
143
153
  export { createPermissionRulePolicy, validatePermissionRules, parsePermissionRule, wildcardMatch, isNamespacedCoveringRuleName, namespacedRuleNameCovers, type PermissionRule, type ParsedPermissionRule, type PermissionRuleIssue, type PermissionRuleCaps, type PermissionRulePolicyOptions, } from "./core/permission-rules.js";
144
154
  /**
145
155
  * design/179 — persisted ALLOW rules: the standing form of approvals a person already gave.
@@ -157,8 +167,9 @@ export { createPermissionRulePolicy, validatePermissionRules, parsePermissionRul
157
167
  * allowed and widening is not.
158
168
  */
159
169
  export { parseAllowRuleText, formatAllowRuleText, ruleAdmitsCommand, findAdmittingRule, suggestRulesForCommand, scopeCoversCwd, pathWithinRoot, isRuleLive, renderUntrustedCommandText, BARE_INTERPRETER_NAMES, MAX_RULE_TEXT_CHARS, type PersistedAllowRule, type RuleTombstone, type RuleScope, type RuleDot, type RuleAdd, type RuleAddOrigin, type RuleOffer, type SegmentRuleSuggestion, type SegmentCoverage, type RuleReject, type RuleRejectCode, type ParsedAllowRule, type PersistedRuleTool, type PersistedRuleMatch, } from "./core/permission-rule-model.js";
160
- export { removePersistedRule, applyTombstones, sameScope, InMemoryPermissionRuleStore, EMPTY_RULE_STORE, type PermissionRuleStore, type PermissionRuleStoreProvider, type StoredAllowRules, type RemoveResult, type PutResult, joinRuleStates, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, sameRuleOwner, type RuleSyncState, type RuleSyncFrontier, type RuleSyncDrop, type RuleSyncLandingReport, type RuleOwner, type QuarantinedRuleAdd, PERMISSION_RULE_WRITER, writerOf, foldDelta, addDotsOf, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, type PermissionRuleWriter, type WritablePermissionRuleStore, type RuleWriteDelta, type RuleAddDelta, type RuleDeleteDelta, type RuleSyncJoinDelta, type RawRuleSyncState, type RedemptionAuthorization, } from "./core/permission-rule-store.js";
170
+ export { removePersistedRule, applyTombstones, sameScope, isValidConsentScope, isValidDurableScope, InMemoryPermissionRuleStore, EMPTY_RULE_STORE, type PermissionRuleStore, type PermissionRuleStoreProvider, type StoredAllowRules, type RemoveResult, type PutResult, joinRuleStates, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, sameRuleOwner, type RuleSyncState, type RuleSyncFrontier, type RuleSyncDrop, type RuleSyncLandingReport, type RuleOwner, type QuarantinedRuleAdd, PERMISSION_RULE_WRITER, writerOf, foldDelta, addDotsOf, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, assertWriteDeltaScopeDurable, type PermissionRuleWriter, type WritablePermissionRuleStore, type RuleWriteDelta, type RuleAddDelta, type RuleDeleteDelta, type RuleSyncJoinDelta, type RawRuleSyncState, type RedemptionAuthorization, } from "./core/permission-rule-store.js";
161
171
  export { syncPermissionRules, parseRuleSyncResponse, PERMISSION_RULE_SYNC_PATH, LOCAL_OWNER_UNSYNCABLE_CODE, type PermissionRuleSyncTransport, type PermissionRuleSyncResult, type RuleSyncRequestBody, type RuleSyncResponseBody, } from "./core/permission-rule-sync.js";
172
+ export { InMemorySessionRuleOverlay, type SessionRuleOverlay, type SessionRuleOverlayAdd, type SessionRuleOverlayApplyResult, } from "./core/permission-rule-session.js";
162
173
  export { createOrgRuleOverlay, orgRuleVerdictFor, effectivePermissionRules, orgRuleStatePersistenceOf, ORG_UNAVAILABLE_DECISION_REASON, ORG_RULE_DECISION_REASON, ORG_ADJUDICATION_TIMEOUT_MS, type OrgPermissionRule, type OrgRuleSnapshot, type OrgRuleSnapshotProvider, type OrgRuleStatePersistence, type PersistedOrgRuleState, type OrgRuleOverlay, type OrgOverlayResolution, type OrgOverlayStatus, type EffectivePermissionRule, } from "./core/permission-rule-org.js";
163
174
  export { RULE_SYNC_DROP_CODES, type RuleSyncDropReason, type RuleQuarantineReason } from "./core/governance-codes.js";
164
175
  export { prepareCardApproval, confirmRuleApproval, type ConfirmResult, type ConfirmRefusalReason, precheckEditedRuleText, type EditedRuleTextPrecheck, redeemRuleTicket, redeemRuleBatch, prepareCcImport, prepareStarterBatch, mintRuleTicket, STARTER_RULES, InMemoryRuleApprovalRecordStore, ruleOffersOfRecord, type RuleTicket, type RuleCandidate, type RuleApprovalKind, type RuleApprovalRecord, type RuleApprovalRecordStore, type RuleOffer2, type StaleRuleApprovalRecord, type RuleConsentDeps, type RedeemResult, type RedeemedBatchMember, type CcImportLayer, type ImportedSettingsLayer, type ImportPreview, } from "./core/permission-rule-consent.js";
@@ -168,7 +179,7 @@ export { AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootA
168
179
  export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, type AdoptionStatus, type AdoptLocalDataRootOptions, type AdoptLocalDataRootResult, type AdoptionCarriageLeg, type AdoptionCarriageLegContext, type AdoptionConfigWitnessReceipt, } from "./stores/file/adoption/adopt.js";
169
180
  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, type PermissionDeniedSource, } from "./core/hooks.js";
170
181
  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";
171
- export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, type MemoryBackendContractHooks, buildMemoryInstruction, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_ORIGIN_CAUSES, committedOriginOf, originEquals, 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, 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, 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, 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, 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_ENGINE_TOOL_NAMES, type MemorySearchDetails, type MemorySearchHit, type CleanMemorySearchHit, type ExposedMemorySearchHit, MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, memoryExposureIndexRow, type MemoryGetDetails, 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";
182
+ export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, type MemoryBackendContractHooks, buildMemoryInstruction, 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, 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";
172
183
  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";
173
184
  export { sharedMemoryStoreContract, type SharedMemoryFixture, type SharedMemoryStoreContractHooks, } from "./core/shared-memory/contract.js";
174
185
  export { termSet, jaccardDistance, cosineDistance } from "./core/memory-vector.js";
@@ -219,7 +230,7 @@ export { type ContractAssertionRunner } from "./core/store-contracts/contract-ha
219
230
  export { checkpointStoreContract } from "./core/store-contracts/checkpoint-store-contract.js";
220
231
  export { sessionRepoContract } from "./core/store-contracts/session-repo-contract.js";
221
232
  export { toolResultStoreContract } from "./core/store-contracts/tool-result-store-contract.js";
222
- export { fileSnapshotStoreContract } from "./core/store-contracts/file-snapshot-store-contract.js";
233
+ export { fileHistoryStoreContract } from "./core/store-contracts/file-history-store-contract.js";
223
234
  export { permissionRuleSyncContract, type PermissionRuleSyncContractHooks } from "./core/store-contracts/permission-rule-sync-contract.js";
224
235
  export { MAILBOX_CONTRACT_SCOPE, mailboxStoreContract, mailboxAckOwnershipContract, mailboxBundledOnlyContract, mailboxTombstonedRecipientContract, type MailboxTombstonedRecipientContractHooks, } from "./core/store-contracts/mailbox-store-contract.js";
225
236
  export { BACKGROUND_AGENT_CONTRACT_SCOPE, backgroundAgentStoreContract, backgroundAgentStoreScopesContract, } from "./core/store-contracts/background-agent-store-contract.js";
@@ -263,7 +274,7 @@ export { ROUTE_ADJUDICATION_CONFORMANCE_CORPUS, type RouteAdjudicationVector } f
263
274
  export { type BrainTimeoutConfig } from "./brain/timeout.js";
264
275
  export { createAssistantMessageEventStream } from "./internal/llm.js";
265
276
  export type { AssistantMessage, AssistantMessageEvent, CompleteSimpleFn, Context, DocumentContent, ImageContent, Message, StopReason, StreamFn, TextContent, ThinkingContent, ToolCall, ToolResultMessage, Usage, UserMessage, } from "./internal/llm.js";
266
- export type { AgentDefinition, BeforeWriteHook, BeforeWriteRequest, BeforeWriteResult, HandsBandOptions, Brain, BrainStatus, BrainStatusPhase, BrainRetryErrClass, ImageInput, McpElicitRequest, McpElicitResponse, McpServerSpec, A2aServerSpec, OnElicit, Model, ModelRef, ProjectMemoryLoad, RunnerDeps, ResumePreflightInfo, ResumePreflightVerdict, EngineNotice, RuntimeCaps, BackgroundChildEvent, DelegationLifecycleEvent, SkillManifest, SkillSpec, TaskEvent, TaskEventIdentity, ToolActivity, TaskLimits, StaleToolResultOffloadOptions, TaskResult, EffectiveMemoryScopes, RemoteEnvFailureNote, TaskSpec, TaskStatus, TaskStream, CompactOutcome, ThinkingLevel, ToolExecuteContext, ToolReturn, ToolSpec, ReversibilityVerdict, ToolEffect, ToolContentOrigin, WorkflowGovernanceBaseline, DelegationTaskType, } from "./core/types.js";
277
+ export type { AgentDefinition, BeforeWriteHook, BeforeWriteRequest, BeforeWriteResult, TrackFileEditHook, TrackEditRequest, TrackEditResult, HandsBandOptions, Brain, BrainStatus, BrainStatusPhase, BrainRetryErrClass, ImageInput, McpElicitRequest, McpElicitResponse, McpServerSpec, A2aServerSpec, OnElicit, Model, ModelRef, ProjectMemoryLoad, RunnerDeps, ResumePreflightInfo, ResumePreflightVerdict, EngineNotice, RuntimeCaps, BackgroundChildEvent, DelegationLifecycleEvent, SkillManifest, SkillSpec, TaskEvent, TaskEventIdentity, ToolActivity, TaskLimits, StaleToolResultOffloadOptions, TaskResult, EffectiveMemoryScopes, RemoteEnvFailureNote, TaskSpec, TaskStatus, TaskStream, CompactOutcome, ThinkingLevel, ToolExecuteContext, ToolReturn, ToolSpec, ReversibilityVerdict, ToolEffect, ToolContentOrigin, WorkflowGovernanceBaseline, DelegationTaskType, } from "./core/types.js";
267
278
  export { Type } from "typebox";
268
279
  export type { TSchema, Static } from "typebox";
269
280
  export { explainPromptAssembly, describeDefaultPack, type DefaultPackDescription, type ExplainInput } from "./prompt-assembly/explain.js";
package/dist/index.js CHANGED
@@ -79,9 +79,15 @@ export { InMemoryCheckpointStore, CheckpointError, mintCheckpointId, mintCheckpo
79
79
  export { InMemoryUsageWindowStore, GLOBAL_USAGE_KEY, EMPTY_USAGE_WINDOW_RECORD, chargeUsageRecord, readUsageRecord, usageRetryAfterMs, resolveUsageWindows, } from "./core/usage-window-store.js";
80
80
  export { FileUsageWindowStore } from "./stores/file/usage-window-store.js";
81
81
  export { ENV_LIFETIME_SUSPEND_MARGIN_MS, USAGE_WINDOW_REAP_MARGIN_MS } from "./core/runner/prepare-task.js";
82
- export { InMemoryFileSnapshotStore, DEFAULT_SNAPSHOT_BOUNDS } from "./core/file-snapshot-store.js";
83
- export { captureManifest, applyManifest } from "./core/file-snapshot-store.js";
84
- export { FileStorageBackend, FileSessionRepo, FileCheckpointStore, FileMemoryStore, FileToolResultStore, FileSessionPolicyStore, FileFileSnapshotStore, FileStrategyStore, FileWorkflowJournalStore, MAX_JOURNAL_RESULT_BYTES, oversizeJournalResult, resolveDataRoot, sanitizeScope, sanitizePathComponent, createFileConsolidationLock, atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog, FileStoreLockError, } from "./stores/file/index.js";
82
+ export { InMemoryFileHistoryStore, boundaryPublishVerdict } from "./core/file-history-store.js";
83
+ export { captureFileBackupViaEnv, applyFileRestoreViaEnv } from "./core/file-history-store.js";
84
+ export { modeProvenDifferent as fileHistoryModeProvenDifferent } from "./core/file-history-store.js";
85
+ export { previewFileDelta as fileHistoryPreviewFileDelta, countRestoreLineDiff, FILE_HISTORY_DIFF_LINE_BUDGET } from "./core/file-history-store.js";
86
+ export { worldStillMatchesMint } from "./core/file-history-store.js";
87
+ export { trackKeyOf as fileHistoryTrackKeyOf, resolveTrackKey as fileHistoryResolveTrackKey } from "./core/file-history-store.js";
88
+ export { describeTrackKey as fileHistoryDescribeTrackKey, trackKeyFamilyOf as fileHistoryKeyFamilyOf, fileHistoryExportDigest, validateFileHistoryExport } from "./core/file-history-store.js";
89
+ export { DEFAULT_FILE_HISTORY_BOUNDARY_KEEP, resolveFileHistoryRetention, fileHistoryBoundariesToKeep } from "./core/file-history-retention.js";
90
+ export { FileStorageBackend, FileSessionRepo, FileCheckpointStore, FileMemoryStore, FileToolResultStore, FileSessionPolicyStore, FileStrategyStore, FileFileHistoryStore, FileWorkflowJournalStore, MAX_JOURNAL_RESULT_BYTES, oversizeJournalResult, resolveDataRoot, sanitizeScope, sanitizePathComponent, createFileConsolidationLock, atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog, FileStoreLockError, } from "./stores/file/index.js";
85
91
  export { CacheBreakDetector } from "./core/cache-break-detector.js";
86
92
  export { maybeCompact } from "./core/auto-compaction.js";
87
93
  export { brainToRuntime } from "./core/runtime.js";
@@ -89,7 +95,7 @@ export { createSensitivePathPolicy, RECOMMENDED_SENSITIVE_PATTERNS } from "./cor
89
95
  export { createFsWriteGatePolicy } from "./core/fs-write-gate-policy.js";
90
96
  export { RETIRED_TOOL_NAMES } from "./core/tool-name-aliases.js";
91
97
  export { DEFAULT_SUBAGENT_TOOL_NAME } from "./agents/subagent.js";
92
- export { renderTaskNotificationXml, taskNotificationDedupKey, isDelegatedAgentTerminal, isTerminalTaskNotification, SystemInjectionQueue, } from "./core/task-notification.js";
98
+ export { renderTaskNotificationXml, taskNotificationDedupKey, isDelegatedAgentTerminal, isTerminalTaskNotification, SystemInjectionQueue, SYSTEM_INJECTION_PRIORITIES, isSystemInjectionPriority, } from "./core/task-notification.js";
93
99
  export { describeStaticWiring, deriveWiringManifest, deriveAskEffective, resolveDeclaredDurability, resolveSubagentTranscriptTier, resolveAskSeamForm, resolveQuestionSeam, countElicitOptIns, } from "./core/wiring-manifest.js";
94
100
  export { probeParkRoundTrip, durableParkGapOf, durableParkGapFor, PARK_SELFCHECK_SCOPE_PREFIX, } from "./core/park-selfcheck.js";
95
101
  export {} from "./core/checkpoint-store.js";
@@ -117,10 +123,13 @@ export { createAllowDenyPolicy, createApprovalPolicy, COARSE_SHELL_TOOLS, create
117
123
  export { parseAutoModeResponse, createAutoModeDecider, } from "./core/auto-mode.js";
118
124
  export { buildAutoModePrompt, renderAutoModeWindow, renderAutoModeAction, AUTO_MODE_DEFAULTS_SENTINEL, } from "./core/auto-mode-prompt.js";
119
125
  export { AUTO_MODE_BASE_PROMPT, AUTO_MODE_PERMISSIONS_EXTERNAL } from "./core/auto-mode-prompt-assets.js";
126
+ export { AUTO_MODE_ARMING_RECIPE_VERSION, autoModeArmingRecipeOf, sanitizeAutoModeArmingRecipe, foldAutoModeArming, } from "./core/auto-mode-arming.js";
127
+ export { rebuildAutoModeDecider, } from "./core/auto-mode-rebuild.js";
120
128
  export { createPermissionRulePolicy, validatePermissionRules, parsePermissionRule, wildcardMatch, isNamespacedCoveringRuleName, namespacedRuleNameCovers, } from "./core/permission-rules.js";
121
129
  export { parseAllowRuleText, formatAllowRuleText, ruleAdmitsCommand, findAdmittingRule, suggestRulesForCommand, scopeCoversCwd, pathWithinRoot, isRuleLive, renderUntrustedCommandText, BARE_INTERPRETER_NAMES, MAX_RULE_TEXT_CHARS, } from "./core/permission-rule-model.js";
122
- export { removePersistedRule, applyTombstones, sameScope, InMemoryPermissionRuleStore, EMPTY_RULE_STORE, joinRuleStates, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, sameRuleOwner, PERMISSION_RULE_WRITER, writerOf, foldDelta, addDotsOf, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, } from "./core/permission-rule-store.js";
130
+ export { removePersistedRule, applyTombstones, sameScope, isValidConsentScope, isValidDurableScope, InMemoryPermissionRuleStore, EMPTY_RULE_STORE, joinRuleStates, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, sameRuleOwner, PERMISSION_RULE_WRITER, writerOf, foldDelta, addDotsOf, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, assertWriteDeltaScopeDurable, } from "./core/permission-rule-store.js";
123
131
  export { syncPermissionRules, parseRuleSyncResponse, PERMISSION_RULE_SYNC_PATH, LOCAL_OWNER_UNSYNCABLE_CODE, } from "./core/permission-rule-sync.js";
132
+ export { InMemorySessionRuleOverlay, } from "./core/permission-rule-session.js";
124
133
  export { createOrgRuleOverlay, orgRuleVerdictFor, effectivePermissionRules, orgRuleStatePersistenceOf, ORG_UNAVAILABLE_DECISION_REASON, ORG_RULE_DECISION_REASON, ORG_ADJUDICATION_TIMEOUT_MS, } from "./core/permission-rule-org.js";
125
134
  export { RULE_SYNC_DROP_CODES } from "./core/governance-codes.js";
126
135
  export { prepareCardApproval, confirmRuleApproval, precheckEditedRuleText, redeemRuleTicket, redeemRuleBatch, prepareCcImport, prepareStarterBatch, mintRuleTicket, STARTER_RULES, InMemoryRuleApprovalRecordStore, ruleOffersOfRecord, } from "./core/permission-rule-consent.js";
@@ -130,7 +139,7 @@ export { AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootA
130
139
  export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, } from "./stores/file/adoption/adopt.js";
131
140
  export { formatHookFeedback, runToolGate, createHookEnvCapabilities, createPreToolUseConstraintPolicy, normalizePersistedRuleHit, } from "./core/hooks.js";
132
141
  export { InMemoryMemoryStore, composeMemoryBlock, composeLayeredMemoryBlock, normalizeMemorySpec, supportsConsolidation, supportsPeriodicConsolidation, firstSentence, expandLexicalTerms, lexicalSearchMatch, classifyPromotable, enforcePromotableWriteGate, guardedMemoryStore, MemoryGateError, detectSecret, enforceSecretWriteGate, enforceStructuredNoteSecretGate, } from "./core/memory.js";
133
- export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, buildMemoryInstruction, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_ORIGIN_CAUSES, committedOriginOf, originEquals, ambiguousOriginRepresentation, committedDistilledOf, distilledEquals, CONSOLIDATION_DEFAULTS, ConsolidationRefusedError, MEMORY_SEARCH_SUPERSEDED_TAG, consolidationTypeEligible, deriveSupersededSet, memorySupersededNote, readIntentCredentials, supersessionFuseCeiling, memoryConsolidationRecommendedNotice, memoryConsolidationCommittedNotice, memoryConsolidationConflictNotice, memoryConsolidationIncompleteNotice, memoryConsolidationRefusedNotice, 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, openAiCompatChatSeat, parseJsonAnswer, planParseRepairs, sanitizeLlmGroups, scheduleUnderFuse, CONSOLIDATION_DRIVER_PLANS_DIR, CONSOLIDATION_DRIVER_RUNS_FILE, CONSOLIDATION_RUN_STOP_REASONS, archiveDistillerPlan, readConsolidationDriverRun, runMemoryConsolidationDriver, isInstructionEntry, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, MEMORY_READONLY_NOTICE, readV2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, memoryExposureIndexRow, 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, erasureSelectHash, computeMemoryBundleHash, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, migrateScope, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, syncMemoryScope, } from "./core/memory-engine/index.js";
142
+ export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, buildMemoryInstruction, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_ORIGIN_CAUSES, committedOriginOf, originEquals, consolidationExposedFrontmatter, ambiguousOriginRepresentation, committedDistilledOf, distilledEquals, CONSOLIDATION_DEFAULTS, ConsolidationRefusedError, MEMORY_SEARCH_SUPERSEDED_TAG, consolidationTypeEligible, deriveSupersededSet, memorySupersededNote, readIntentCredentials, supersessionFuseCeiling, memoryConsolidationRecommendedNotice, memoryConsolidationCommittedNotice, memoryConsolidationConflictNotice, memoryConsolidationIncompleteNotice, memoryConsolidationRefusedNotice, memoryConsolidationWithheldNotice, 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, openAiCompatChatSeat, parseJsonAnswer, planParseRepairs, sanitizeLlmGroups, scheduleUnderFuse, CONSOLIDATION_DRIVER_PLANS_DIR, CONSOLIDATION_DRIVER_RUNS_FILE, CONSOLIDATION_RUN_STOP_REASONS, archiveDistillerPlan, readConsolidationDriverRun, runMemoryConsolidationDriver, isInstructionEntry, 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, readV2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, 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, MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, memoryExposureIndexRow, 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, erasureSelectHash, computeMemoryBundleHash, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, migrateScope, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, syncMemoryScope, } from "./core/memory-engine/index.js";
134
143
  export { SHARED_MEMORY_READ_CAP_BYTES, SHARED_MEMORY_LIST_PAGE_SIZE, SharedMemoryStoreError, } from "./core/shared-memory/types.js";
135
144
  export { sharedMemoryStoreContract, } from "./core/shared-memory/contract.js";
136
145
  export { termSet, jaccardDistance, cosineDistance } from "./core/memory-vector.js";
@@ -180,7 +189,7 @@ export {} from "./core/store-contracts/contract-harness.js";
180
189
  export { checkpointStoreContract } from "./core/store-contracts/checkpoint-store-contract.js";
181
190
  export { sessionRepoContract } from "./core/store-contracts/session-repo-contract.js";
182
191
  export { toolResultStoreContract } from "./core/store-contracts/tool-result-store-contract.js";
183
- export { fileSnapshotStoreContract } from "./core/store-contracts/file-snapshot-store-contract.js";
192
+ export { fileHistoryStoreContract } from "./core/store-contracts/file-history-store-contract.js";
184
193
  export { permissionRuleSyncContract } from "./core/store-contracts/permission-rule-sync-contract.js";
185
194
  export { MAILBOX_CONTRACT_SCOPE, mailboxStoreContract, mailboxAckOwnershipContract, mailboxBundledOnlyContract, mailboxTombstonedRecipientContract, } from "./core/store-contracts/mailbox-store-contract.js";
186
195
  export { BACKGROUND_AGENT_CONTRACT_SCOPE, backgroundAgentStoreContract, backgroundAgentStoreScopesContract, } from "./core/store-contracts/background-agent-store-contract.js";
@@ -230,6 +230,22 @@ export interface RunWorkflowToolDeps {
230
230
  * reason `forwardEvent`/`inheritedGateForChildren` ride deps); `ctx.interactionPosture` still
231
231
  * wins when a wrapping path provides it. */
232
232
  parentInteractionPosture?: "interactive" | "headless";
233
+ /**
234
+ * design/383 §2.5 (rescan post-6.0.0-RC) — the HOST session's live capture opt-out state,
235
+ * threaded as a MOUNT dep for the same unenriched-auto-mount reason as the posture seat above.
236
+ * A call-time GETTER on purpose (`ctx.memoryCaptureOptedOut` is live — a mid-run flip must
237
+ * floor agents the workflow spawns after it); the enriched-ctx getters win when a wrapping
238
+ * mount provides them. Rides `RunWorkflowOptions.parentMemoryCaptureState` into both spawn legs.
239
+ */
240
+ parentMemoryCaptureState?: () => {
241
+ optedOut: boolean;
242
+ indeterminate: boolean;
243
+ controlDir?: string;
244
+ ancestors?: ReadonlyArray<{
245
+ sessionId: string;
246
+ controlDir?: string;
247
+ }>;
248
+ };
233
249
  /** TRUSTED nesting depth from the run's internals (NOT a tool param) — passed to `startWorkflow` so a
234
250
  * cross-process child workflow is rejected by the one-level guard. */
235
251
  workflowDepth?: number;
@@ -317,8 +333,10 @@ export interface RunWorkflowToolDeps {
317
333
  parentCheckpointStoreDisabled?: boolean;
318
334
  /** #235 — the deployment's structured notice sink (`RunnerDeps.onNotice`), forwarded into the governed
319
335
  * build so the fields a script's agent spec wrote that did NOT reach the child are announced instead of
320
- * vanishing (`workflow.governance_key_stripped`). A dep for the same reason as the seats above: this
321
- * auto-mount's execute ctx is minimal. Absent the historic `console.warn` loudness. */
336
+ * vanishing (`workflow.governance_key_stripped`). #505 the same seat now also carries the OPTIONS
337
+ * membrane's twin announcement (`workflow.agent_option_ignored`: keys of `agent(spec, opts)`'s second
338
+ * argument that did not apply). A dep for the same reason as the seats above: this auto-mount's execute
339
+ * ctx is minimal. Absent ⇒ the historic `console.warn` loudness. */
322
340
  onNotice?: (n: import("../core/types.js").EngineNotice) => void;
323
341
  /** Twin of the above for design/148 S1's center-artifact inheritance (see the `ctx.centerArtifactDigest`/
324
342
  * `ctx.centerSourceRevision` reads at the `startWorkflow` options site) — `centerAdoption` resolves