@reinsjs/core 0.17.0 → 0.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # @reinsjs/core
2
2
 
3
+ ## 0.18.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 729f892: The conformance suites in `@reinsjs/core/testing` now test real concurrency: two concurrent `EventLog.append` calls with the same seq must land exactly one and reject the other with `seq_conflict`; eight owners acquiring a free `RunLease` at once must produce exactly one winner; and `BlobStore.put` must store a copy, so mutating the caller's buffer afterwards does not change the blob. A check-then-write backend used to pass. The old serial duplicate-seq case is renamed, as it never tested a concurrent writer. **Third-party backends that passed before may now fail these new cases** — that is the point: they flag real contract violations.
8
+ - e04c188: The EventLog conformance suite in `@reinsjs/core/testing` now checks that every shell field round-trips verbatim — `parentId`, `provenance`, nested `replay` (thinking signatures, reasoning item ids), non-ASCII and large payloads, a non-current `schemaVersion` and `ext.*` types — through `read`, `tail` and `fork`. A backend that stored only some columns used to pass the suite while silently breaking reasoning replay. New helper `makeRichEvents(sessionId, startSeq?)`. **Third-party backends that passed before may now fail these new cases** — that is the point: they flag real contract violations.
9
+ - 4a2f5b6: `decisions` now only accept calls that are waiting for approval: pending, with a `core.approval_request` and no decision yet. A decision for a pending call that never asked for approval (for example one left over after the run was aborted mid-batch), or two decisions for the same call in one request, throws `RunStateError("unknown_tool_call")` before anything is written. Before, such a decision skipped `needsApproval`, the approval policy's `defer` and its `ttl`. The check is exported as `assertDecisionsAwaitApproval` so the HTTP handler can share it. To drop a pending call that is not waiting for approval, stop the run instead.
10
+ - 6eb8b09: `visibilityFilter` (and so the default projection) now drops `ext.*` events. No lowering sends them to the model, yet they stayed in the projected view and were counted in `stats.estimatedTokens`, the perception reading and the budget fallback — a large host extension event could trigger compaction or trimming while the real context was far from full. To show an extension event to the model, build the chain with `defaultProjectionChain({ filter: { keepExtEvents: true } })`, insert a strategy of your own right after the filter (its first element) that translates the event into a core event (a `core.system_note`, for example), and pass the result as `projection.strategies` to `runLoop` / `createAgent`.
11
+ - cf87a07: `runLoop` no longer yields the new session's opening events on a handoff; it yields only events of its own `sessionId`. Before, the summary note and trigger message written into the new session were yielded to the old session's consumer, so `createAgentHandler` streamed them on the old session's SSE stream (ids going back to 1, 2 before the old session's `run_ended`), AG-UI clients showed the trigger message in the old thread, a reconnect with that `Last-Event-ID` replayed most of the old session, and `onEvent` reported them under the old `sessionId`. The opening is still written to the log; read it from `toSessionId`. The TanStack adapter likewise no longer passes them to `onEvent`.
12
+ - 53c5561: Handoff now records who really wrote each opening event of the new session. The summary note used to be a host note (`actor: "host"`, system trust) and the trigger message a user message (`actor: "user"`, principal trust), even when the model wrote both — so a `triggerMessage` the model was talked into by a tool result showed up in the new session as the user's own instruction. Now the summary is recorded as `intent.by` (default `"model"`), and so is the trigger message unless it repeats one of the old session's user messages word for word, in which case it keeps that message's `actor` and trust (the user's stays the user's, a host-written one the host's) and `provenance.ref` points at that message. The summary and self-written trigger messages carry `provenance: { source: "handoff", ref: <core.handoff event id> }`. The shape is built by the new export `handoffOpeningDrafts`, shared by `runLoop` and the TanStack adapter. Event types, payloads and what the model sees are unchanged; code that filtered the new session by `actor` (for example "the user's first message") should read the event type or `provenance` instead.
13
+ - afcc7b7: Image parts must now use one of `image/jpeg`, `image/png`, `image/gif` or `image/webp`, inline or by reference. `isContentPart` rejects every other type, so an SVG or HEIC image from a tool can no longer enter the log and make every later request fail with a provider 400. The whitelist is exported as `SUPPORTED_IMAGE_MIMES` / `isSupportedImageMime` for other entry points to share. Breaking for hosts that wrote other image types: in a tool result, such a part (well formed apart from its type) is replaced by a sentence naming the type (`unsupportedImageText`) while the other parts are kept; `input` containing one throws `RangeError`. `@reinsjs/adapter-tanstack-ai` checks imported parts with `isContentPart`, so a client image of another type is now imported as its `[image(<mime>) part could not be imported …]` placeholder and listed in `dropped`.
14
+ - 5703a3e: A `core.tool_result` draft in the initial `input` must now answer a call that is still pending and not waiting for approval: same `toolCallId` and `name`, at most once per batch. Otherwise `runLoop` throws `RangeError` before anything is written. Before, a host that submitted the same client-tool result twice, or a result for an unknown call, wrote a duplicate or orphan result that was replayed to the provider on every later request; and a result for a call still waiting for approval skipped the approval. Breaking for hosts that relied on either: pass the decision in `decisions` first, then the result. The HTTP handler already answers `409 unknown_tool_call` / `409 approval_pending` for these cases; unlike it, in-process `input` may still fill in a result for a server-side tool.
15
+ - 6cd00cd: `project()` now rejects a bad context window or reserve with a `RangeError`: `contextLimit` must be a positive finite number, and `reserveTokens` must be a non-negative finite number below `contextLimit`. Before, a `NaN` or `0` window, or a reserve not below the window, made the threshold fallback fold everything but the last turn and write that compaction into the append-only log for good, and with `NaN` it did not even report `overBudget`. `runLoop` runs the same check on the model's `contextWindow` and `projection.reserveTokens` before it writes anything. The check is exported as `resolveReserveTokens`, which also returns the default reserve.
16
+ - 7e4f674: When the host aborts a model response (a dropped connection or a lost lease, not a user stop) after some of its tool calls were already logged, the run now settles those calls with an `isError` result (`MODEL_INTERRUPTED_NOT_EXECUTED_TEXT`) before pausing as `paused(host)`. This covers both a response that ends with `stopReason: "aborted"` and a stream that throws after the host aborted. Before, the calls stayed pending, and the next run executed them, possibly with arguments cut off mid-stream, after the user's new message but before the model had read it. A user stop is unchanged: those calls get the usual stop text. Behavior change for hosts that relied on resuming such a call: the model now sees that it was dropped and decides whether to call again.
17
+ - bdfdc7c: `MemoryStore.list(prefix)` on Postgres and SQLite now matches prefixes containing characters outside the BMP (emoji, CJK extension B). The prefix length was bound as UTF-16 code units while the database counts characters, so such prefixes always returned an empty list. The MemoryStore conformance suite in `@reinsjs/core/testing` gains a case for it. **Third-party backends that passed before may now fail these new cases** — that is the point: they flag real contract violations.
18
+ - 5c36bfd: `PgEventLog.read` and `PgBlobStore.slice` now clamp bounds to the integer column range, matching the in-memory and SQLite stores: `toSeq: Number.MAX_SAFE_INTEGER`, `end: Infinity` and similar "to the end" values read to the end instead of throwing a raw Postgres error. The EventLog and BlobStore conformance suites in `@reinsjs/core/testing` gain cases for these bounds. **Third-party backends that passed before may now fail these new cases** — that is the point: they flag real contract violations.
19
+
20
+ ### Patch Changes
21
+
22
+ - 3830f23: `budget_usage.contextEstimate` now estimates the view actually sent to the model, after `beforeModel` patches and the notes injected during `beforeModel`. Before, it was the projection estimate taken before injection, so a large injected note (such as a pins snapshot at a segment start) was counted as fixed overhead and then counted again on the next turn once it was in the timeline. That made the next turn's perception reading, compact's soft-line requests and the threshold fallback all overestimate the context, and could fold old turns while real usage was far below the line.
23
+ - 60b6052: An abort that lands in the middle of a tool batch now ends the run paused instead of calling `onTurnEnd`. This applies to any abort, such as a dropped connection or a lost lease, not only a user stop. Before, a Socket deciding `handoff` or `stop` in `onTurnEnd` could end the run as `handoff` or `done` while calls from that batch were still pending. What the pause says depends on the abort: a user stop (`RunStop`) closes the pending calls as before, with the note `stopped by the user`; any other abort keeps them pending for the next run, and when nothing else in the batch interrupted the run the pause is `paused(host)` with the note `host aborted during the tool batch`. If the batch also has a call waiting for approval or for a client result, that interruption sets the reason as usual.
24
+ - 9856645: A host abort in the middle of a tool batch now always adds the host note to `run_paused`, even when the batch already has another interruption (an approval request, a client tool, a paused sub-agent). The pause reason is unchanged (approval still comes first). Before, such a pause had no note, so `@reinsjs/server` treated the calls after the abort, which were never evaluated, as ready to be filled in, and a client-side tool that needs approval could be answered without approval (`409 call_not_evaluated` now applies as intended).
25
+ - b4de7f3: When a resumed run locates the batch of leftover tool calls, an `ext.*` event between two calls of the same model response no longer splits the batch, matching how the lowerings group that response (extension events do not break an assistant turn there).
26
+ - 040768e: `ext.*` events a socket writes during `beforeModel` no longer join that turn's view. They are not sent to the model, but they were counted in the estimate of what was sent, so the calibrated fixed overhead (`contextOverheadOf`) came out too low. "Hidden from the model by default" now has one definition, exported as `isModelInvisibleByDefault` (the operational event types plus the `ext.` prefix), used by `visibilityFilter`, `runLoop` and the TanStack AI middleware.
27
+ - da6250a: A `needsApproval` function that throws no longer crashes the run. The call is treated as denied: it is not executed and gets an `isError` result `Approval check failed: …`, and the cause is logged for the host as a model-invisible `core.error` (category `host`, `detail.phase: "needsApproval"`). Before, the generator threw without a closing event and every later run hit the same error while completing the pending call.
28
+ - b086f75: When a resumed run settles a pending call whose tool is no longer in the base tool table (for example a tool that a `beforeModel` patch added only for that turn), the model now gets `Tool not available on resume: <name> …` instead of `Unknown tool: <name>`. The call is still not executed. Tools that need approval or client execution should come from a Socket's static `tools`.
29
+ - 9291394: When a model response fails after some of its tool calls were already logged (the stream breaks, or ends with `stopReason: "error"`), the run now settles those calls with an `isError` result (`MODEL_FAILED_NOT_EXECUTED_TEXT`) in the same batch as the `core.error` and `run_ended(error)` events. Before, the calls stayed pending, and the next run executed them, possibly with truncated arguments, after the user's new message but before the model had read it.
30
+ - 9d47f4d: `runLoop` now keeps tool call ids unique within a session. When a provider or relay reuses an id from an earlier call (such as `call_0` on every turn) or sends an empty one, the call is logged under a fresh `reins_<id>` and the original goes into `payload.meta.originalToolCallId`. Before, the later call took over the earlier call's approval, denial or "already started" record. In practice it could run without approval, be rejected, or be reported as an unknown outcome without running.
31
+
32
+ The fresh id is built from `newId` and normalized to `^[A-Za-z0-9_-]{1,64}$`, so a custom `newId` cannot produce an id a provider rejects. Hosts that fill in client-tool results must use the `toolCallId` from the logged `core.tool_call` (or `run_paused.awaiting`). The TanStack adapter writes its own tool calls and does not rewrite ids.
33
+
34
+ - 01b9440: `markUntrusted` now escapes `tool_reference` parts too. An untrusted tool result's reference is expanded into text inside the `<untrusted>` wrapper, but its name, description and input schema were passed through as is, so a description containing `</untrusted>` closed the wrapper early and the rest read as trusted text. Every string in the reference (schema keys included) now gets the same `<\/untrusted` escape as text parts, and the result reports `escaped`, so the lowering layers record the landing as lossy. References that need no escaping are returned unchanged.
35
+ - 7a7fbe4: `ctx.budget.wallMs` is now refreshed right before `onTurnEnd`, so it includes the time the turn's tool batch took. Before, it was last updated after the model call, so a slow tool batch was only counted after the next model call and a `budget({ limits: { wallMs } })` limit let one extra turn (a model call plus a whole tool batch) run past the limit, with a stale `used` value in the pause note.
36
+ - 1c6fc8c: The folded-results list, `recall`'s answer for a spilled result and the `recall` tool description now say the same thing about spilled outputs: read them with `fetch_blob` "if that tool is in your tool list". The list used to state it unconditionally, though a run may not have `fetch_blob` (`spill({ tool: false })`, or spill removed later).
37
+ - 246c457: When the list of folded tool results (or of folded user messages with media) exceeds `maxItems`, it now keeps the most recent entries and collapses the older ones into a single `…N earlier (seq a–b)` line under the heading. It used to keep the oldest, so after a few compactions the results the model most likely wanted back were reduced to a bare seq range.
38
+ - 252764c: Wording made consistent about getting folded content back. The default threshold summary no longer says removed events "can be recovered by the host"; it states that they remain in the session log, and the module that provides a recall tool says how to use it (with `compact()`, `recall`). `recall` on a tool result whose output was spilled now returns a normal (non-error) result pointing to the blob and `fetch_blob` "if that tool is in your tool list", so `haltOnFailure` no longer holds back the rest of the batch.
39
+
3
40
  ## 0.17.0
4
41
 
5
42
  ### Minor Changes
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @reinsjs/core
2
2
 
3
- The kernel of [reins](../../README.md): an append-only event timeline, the projection that decides what the model sees on each turn, a loop of a few hundred lines you can read and copy, a serializable run state for pause/resume across processes, and the `Socket` seam that everything else plugs into. Zero dependencies, zero `node:*` — Web standards only; verified on Node 22, Cloudflare workerd (strictest compat), Bun, Deno and Vercel's Edge Runtime (`spikes/runtime-matrix`).
3
+ The kernel of [reins](../../README.md): an append-only event timeline, the projection that decides what the model sees on each turn, a loop that is one plain async generator with no private state — long (well over a thousand lines, the edge cases are handled in the open) but readable top to bottom and copyable, a serializable run state for pause/resume across processes, and the `Socket` seam that everything else plugs into. Zero dependencies, zero `node:*` — Web standards only; verified on Node 22, Cloudflare workerd (strictest compat), Bun, Deno and Vercel's Edge Runtime (`spikes/runtime-matrix`).
4
4
 
5
5
  Two principles shape every type in here:
6
6
 
@@ -18,12 +18,12 @@ Most applications import the umbrella package `@reinsjs/agent` instead; `@reinsj
18
18
  | module | exports | purpose |
19
19
  | --- | --- | --- |
20
20
  | `events/` | `Event`, `EventDraft`, `createCoreRegistry`, `createEvent`, `CoreEvent` types | Event shell + payloads, `schemaVersion` on every type, upcast-on-read (unknown types are rejected, not skipped) |
21
- | `store/` | `EventLog`, `BlobStore`, `MemoryStore`, `InMemory*`, `memoryStore()`, `readTimeline` | Storage contracts. `EventLog.append` is the only write; `seq` is assigned by the caller and must be contiguous (optimistic concurrency) |
22
- | `projection/` | `project`, `ProjectionStrategy`, `DEFAULT_MODEL_INVISIBLE_TYPES` | Pure function: timeline → what the model sees this turn (filter → fold → pin → trim to budget). Strategies may create events, but they go through the loop into the log first |
21
+ | `store/` | `EventLog`, `BlobStore`, `MemoryStore`, `RunLease`, `InMemory*`, `memoryStore()`, `readTimeline` | Storage contracts. `EventLog.append` is the only write; `seq` is assigned by the caller and must be contiguous (optimistic concurrency). `RunLease` is the optional cross-process "one run per session" lease (`InMemoryRunLease` for a single process; `@reinsjs/store-pg` ships one) |
22
+ | `projection/` | `project`, `ProjectionStrategy`, `DEFAULT_MODEL_INVISIBLE_TYPES`, `isModelInvisibleByDefault` | Pure function: timeline → what the model sees this turn (filter → fold → pin → trim to budget). Strategies may create events, but they go through the loop into the log first. The filter also drops your `ext.*` events by default — no lowering sends them, so leaving them in would count bytes the model never sees; to show one to the model, build the chain yourself and pass it as `projection.strategies` — `const [filter, ...rest] = defaultProjectionChain({ filter: { keepExtEvents: true } })`, then `strategies: [filter, yourTranslator, ...rest]` — where your strategy turns the event into a core one (a `core.system_note`, say); an `ext.*` left as is is still not sent and still counts toward the estimate. Events a socket emits during `beforeModel` only join the view from the next turn on, through this chain |
23
23
  | `lowering/` | `Lowering`, `LoweredRequest`, `LandingRecord`, `markUntrusted` | Interface to a provider wire protocol plus the loss matrix types; implementations in `@reinsjs/lowering-fetch` (zero-dependency) and `@reinsjs/lowering-pi` (pi-ai) |
24
24
  | `loop/` | `runLoop`, `Socket`, `Tool`, `defineTool`, `RunResult`, `SerializedRunState`, `Interruption`, `subagentPause`, `retry` | The default loop and its seams |
25
25
  | `replay/` | `replayTurns` | Recompute what the model saw on every turn from the log alone (audit UIs, eval) |
26
- | `@reinsjs/core/testing` | `ScriptedLowering`, `callTool`, `say`, `think`, store conformance suites | Deterministic model scripts and a suite any `EventLog` / `BlobStore` / `MemoryStore` implementation should pass |
26
+ | `@reinsjs/core/testing` | `ScriptedLowering`, `callTool`, `say`, `think`, store conformance suites (`runLeaseConformance` among them) | Deterministic model scripts and a suite any `EventLog` / `BlobStore` / `MemoryStore` / `RunLease` implementation should pass |
27
27
 
28
28
  ## The loop in one paragraph
29
29
 
@@ -39,7 +39,9 @@ type RunResult =
39
39
 
40
40
  Pausing is a return value, not a blocking callback. `state` is small (ids and hashes, HMAC-signed when you pass `secret`) and enough to resume in another process: `runLoop({ ...config, resume: state, decisions: [...] })` re-validates it against the log (signature, pending-call digest, and that the model and the definitions of the tools behind the pending calls are unchanged — adding or removing other tools no longer blocks a resume; the model is told about the change instead) before writing anything. The same signed `state` is also written into the `core.run_paused` event (model-invisible), so whoever reads the log later can resume too: `pausedStateOf(lastEvent)` returns it when the session's last event is that pause, and `undefined` once anything else has been appended.
41
41
 
42
- **Stopping vs. aborting.** Aborting `signal` for any reason pauses the run and leaves unanswered tool calls pending, so the next run executes them first — right for a lost lease or a dropped connection. When the *user* pressed stop, abort with `controller.abort(new RunStop())` instead: every pending call (including ones waiting for approval or for a client result) is closed with an error result saying it was not executed, and the next run asks the model directly, so it can follow whatever the user says next. The result is still `paused` with reason `host` and the note `stopped by the user`.
42
+ **Stopping vs. aborting.** Aborting `signal` for any reason pauses the run (when it lands mid tool batch, without calling `onTurnEnd`). Calls the model had finished asking for are left pending, so the next run executes them first — right for a lost lease or a dropped connection. Calls from a model response that was cut off by the abort are not: they get an error result saying the response was interrupted (`MODEL_INTERRUPTED_NOT_EXECUTED_TEXT`), since their arguments may be incomplete. When the *user* pressed stop, abort with `controller.abort(new RunStop())` instead: every pending call (including ones waiting for approval or for a client result) is closed with an error result saying it was not executed, and the next run asks the model directly, so it can follow whatever the user says next. The result is still `paused` with reason `host` and the note `stopped by the user`.
43
+
44
+ **Handoff.** When `onTurnEnd` returns `{ handoff }`, the loop appends `core.handoff` to this session and opens the new one with the summary as a `system_note`, then `intent.opening`, then the `triggerMessage` as a `user_message` (`handoffOpeningDrafts`). Each opening event names who really wrote it: the summary belongs to whoever decided the handoff (`intent.by`, default `"model"`), and so does a trigger message — unless it repeats one of this session's user messages word for word (ignoring surrounding whitespace), in which case it keeps that message's `actor` and trust (the user's stays the user's, a host-written one stays the host's) and `provenance.ref` points at it. The summary note keeps `kind: "host"`: the kind is the note's category, not its author. The summary, and a trigger message that is not such a copy, carry `provenance: { source: "handoff", ref: <the core.handoff event id> }`; the events in `intent.opening` (such as pins carried over by `@reinsjs/brain`) are written as given, with their own `actor` and `provenance`. What the model sees is unchanged; trust markers only wrap `untrusted` content. `runLoop` yields only events of its own `sessionId`: the new session's opening is written to the log but not yielded (a consumer streaming one session would otherwise mix in another session's events, with `seq` going backwards) — read it from `toSessionId`.
43
45
 
44
46
  **Approval and a change of mind.** If the user sends a new message instead of approving a pending call, resume with `decisions: [{ toolCallId, approved: false, by, reason }]` (or stop); otherwise the call is held for approval again before the model reads the new message.
45
47
 
@@ -47,6 +49,7 @@ Pausing is a return value, not a blocking callback. `state` is small (ids and ha
47
49
 
48
50
  `input` takes a string, content parts, one event draft, or an array of drafts appended in order in one write. Use the array when a run brings both something to do and something to know, so the model can tell a colleague's request from the host's briefing:
49
51
 
52
+ <!-- recipe: packages/core/src/input-batch.recipe.test.ts -->
50
53
  ```ts
51
54
  /** Host briefing as a system note, then the actual request. One user message per batch. */
52
55
  function briefedInput(background: string, request: string): EventDraft[] {
@@ -59,12 +62,13 @@ function briefedInput(background: string, request: string): EventDraft[] {
59
62
  runLoop({ ...config, input: briefedInput("Ticket #12 was edited by Ana an hour ago.", "Review ticket #12.") })
60
63
  ```
61
64
 
62
- Every draft goes through the same checks — type whitelist (`core.user_message`, `core.tool_result`, `core.system_note`, `ext.*`), a valid actor, the basic payload shape of the three core types, and registration in your registry — and one bad draft rejects the whole batch before anything is written; content parts cannot be mixed with drafts. The envelope (`actor`, `trust`) and the shape of your own `ext.*` payloads are yours to get right: in-process input is trusted host code. Keep one user message per batch: compaction keeps only the most recent one verbatim, while background notes fold like any other note (put what must stay in a pin). Lowering keeps the order on Chat and Responses; on Anthropic models that accept mid-conversation system messages the note lands right after the user message, because a system message may not come first or follow an assistant one. The HTTP handler in `@reinsjs/server` does not accept draft arrays — this is for in-process hosts.
65
+ Every draft goes through the same checks — type whitelist (`core.user_message`, `core.tool_result`, `core.system_note`, `ext.*`), a valid actor, the basic payload shape of the three core types, that each `core.tool_result` answers a call that is still pending and not waiting for approval (same `name`, at most once per batch — a duplicate or orphan result would be replayed to the provider on every later request, and a result for a call awaiting approval would skip it: pass `decisions` first), and registration in your registry — and one bad draft rejects the whole batch before anything is written; content parts cannot be mixed with drafts. The envelope (`actor`, `trust`) and the shape of your own `ext.*` payloads are yours to get right: in-process input is trusted host code. Keep one user message per batch: compaction keeps only the most recent one verbatim, while background notes fold like any other note (put what must stay in a pin). Lowering keeps the order on Chat and Responses; on Anthropic models that accept mid-conversation system messages the note lands right after the user message, because a system message may not come first or follow an assistant one. The HTTP handler in `@reinsjs/server` does not accept draft arrays — this is for in-process hosts.
63
66
 
64
67
  ## Input that arrives mid-run
65
68
 
66
69
  A run can take minutes. Messages that reach your host meanwhile (a teammate changed direction, someone signed off a plan) can be handed to the model before its next call instead of waiting for the run to end. Pass `pullInput`: the loop calls it before every model call — not on a turn that only finishes leftover tool calls, and not once `maxTurns` is reached — and appends whatever drafts it returns, ahead of that turn's socket notes. Your queue stays the source of truth: offer what is waiting, and claim a delivery only when its event comes back out of the loop.
67
70
 
71
+ <!-- recipe: packages/core/src/pull-input.recipe.test.ts -->
68
72
  ```ts
69
73
  /** A host mailbox: offer everything unclaimed at each gap; claim when the loop has written it. */
70
74
  function mailbox() {
@@ -112,7 +116,7 @@ const deploy = defineTool<{ env: "staging" | "prod" }>({
112
116
  })
113
117
  ```
114
118
 
115
- `validate` runs before the approval check so the approver sees exactly the input that will execute. Tools without `execute` (or with `side: "client"`) pause the run until the host appends the `tool_result`. Tool output is `untrusted` by default and is wrapped in `<untrusted source="tool:…">` when lowered to the model. A tool may declare `resultTrust: "system"` to opt its **successful** results out of that wrapper — reserve it for content the host itself authored (this is how `@reinsjs/brain`'s `skill_read` works); error results and thrown exceptions stay `untrusted` regardless, and the same rule applies to client-tool results the host appends.
119
+ `validate` runs before the approval check so the approver sees exactly the input that will execute. Tools without `execute` (or with `side: "client"`) pause the run until the host appends the `tool_result` — use the `toolCallId` of the logged `core.tool_call` (or `run_paused.awaiting`): call ids are unique within a session, and when a provider reuses an id from an earlier call or sends none, the loop logs the call under a fresh `reins_…` id and keeps the original in `payload.meta.originalToolCallId`. Tool output is `untrusted` by default and is wrapped in `<untrusted source="tool:…">` when lowered to the model. A tool may declare `resultTrust: "system"` to opt its **successful** results out of that wrapper — reserve it for content the host itself authored (this is how `@reinsjs/brain`'s `skill_read` works); error results and thrown exceptions stay `untrusted` regardless, and the same rule applies to client-tool results the host appends.
116
120
 
117
121
  **Interrupted writes are not replayed.** A tool that is not replayable — by default any tool not declared `risk: "low"`; override with `replayable: true | false` — gets a model-invisible `core.tool_started` event right before `execute`. If the process dies mid-call (or a signal-aware tool is cut off by an abort), resuming does not run it again: the call is closed with "the outcome is unknown, check the current state before retrying", followed by the time the call started (`This call started at 2026-11-08T16:08:02.123Z.`, from the `core.tool_started` event), and the model decides whether to look first. The time lets the model tell the object this call created from an earlier one with the same parameters; make your read tools report timestamps in an unambiguous form (UTC ISO is safest). The exported text constants are exact prefixes of what lands — compare with `startsWith`, not `===`. Read-only tools are simply re-run. Declare `risk: "low"` on tools that only read; `replayable: true` on writes that are idempotent.
118
122
 
@@ -120,7 +124,7 @@ A tool can also *be* another agent: return `subagentPause(...)` from `execute` a
120
124
 
121
125
  ## Media: images, video and audio
122
126
 
123
- Content parts are `text`, `image`, `video`, `audio` and `tool_reference`. A `video` / `audio` part carries `mime` (must start with `video/` / `audio/`), base64 `data` and an optional `durationSec` (a finite positive number); a malformed part is rejected before anything is written. A video's soundtrack is part of the video — use `audio` only for audio files.
127
+ Content parts are `text`, `image`, `video`, `audio` and `tool_reference`. A `video` / `audio` part carries `mime` (must start with `video/` / `audio/`), base64 `data` and an optional `durationSec` (a finite positive number); a malformed part is rejected before anything is written. A video's soundtrack is part of the video — use `audio` only for audio files. An `image` part's `mime` must be one of `image/jpeg`, `image/png`, `image/gif` or `image/webp` (`SUPPORTED_IMAGE_MIMES`, checked by `isSupportedImageMime`), inline or by reference: providers reject other types with a 400, and since the log only grows, one such part written into a session would fail every later request. In a tool result, an image part that is well formed except for its type is replaced by a short sentence naming the type (`unsupportedImageText`); the other parts are kept, and the bytes never reach the model. Convert SVG or HEIC to PNG / JPEG in the tool if the model should see it. Content parts in `input`, by contrast, are rejected with `RangeError`.
124
128
 
125
129
  - **Capabilities decide, not mime types.** `LoweringCapabilities.video` / `audio` are optional and mean "no" when absent: a lowering that does not take them replaces the part with a placeholder and records the event `lossy`, so the run goes on instead of the provider answering 400.
126
130
  - **Estimates follow duration.** Video is estimated at 100 tokens per second and audio at 32 (measured: about 91 and 25 on a relay Gemini). Without `durationSec` the estimate falls back to the byte size at a deliberately low bitrate (1 Mbps / 64 kbps) with a 30-second floor — erring high, because bitrates differ by about 60× and underestimating leads to overflow. Give `durationSec` whenever you know it, and never `0` — a part with `durationSec: 0` (or a mime type outside `video/` / `audio/`) is malformed, and a tool result containing one is turned into JSON text as a whole, base64 included. For other rates, wrap `roughTokenEstimate` in your own `TokenEstimator`.
@@ -132,7 +136,8 @@ An image can also be a reference: `{ type: "image", mime, blobId }`. The bytes l
132
136
 
133
137
  - **What the model sees is unchanged.** Right before each model call the loop swaps the references that are in view for inline images (`hydrateImageRefs`), so the request is byte-for-byte what the inline form would produce. Folded images are not read at all. Sockets and the token estimate keep seeing the reference (an image counts 1 600 tokens either way). Each blob is read at most once per run.
134
138
  - **References are checked before anything is written** — the initial `input` (`RangeError`, nothing written), messages pulled mid-run (the run ends with a `core.error` of category `input`), tool results (only the offending part is replaced with the sentence below; the rest of the result is kept), and the HTTP handler (`400`). A reference is accepted when the blob belongs to this session, or when this session's timeline already shows it as an image (a forked session can show its parent's pictures), and its `mime` equals the blob's. Every failure — missing blob, someone else's blob, wrong mime, no `BlobStore` — reads `Blob <id> not found in this session`, so a client cannot probe other sessions. A storage error while checking is not a rejection: the initial `input` rethrows it, a mid-run pull logs it and tries again later, a tool result gets `Could not read blob <id>: storage error` in place of that part, with the cause in a model-invisible `core.error`.
135
- - **Shape.** `mime` must start with `image/`; `blobId` is 1–128 characters; `data` and `blobId` never appear together. A spilled tool output (a text blob) can therefore never pass as an image.
139
+ - **Shape.** `mime` must be one of the four supported image types (see above); `blobId` is 1–128 characters; `data` and `blobId` never appear together. A spilled tool output (a text blob) can therefore never pass as an image.
140
+ - **Images logged before the type check.** An image of another type already in an older log (an SVG, a mislabelled `text/plain`) is not sent either: both lowering packages and the TanStack AI adapter put the `unsupportedImageText` sentence in its place and record the event `lossy`, instead of replaying a part the provider rejects on every request.
136
141
  - **When the bytes are gone.** If a referenced blob no longer exists (you deleted it, or there is no `BlobStore`), the lowering writes `[image unavailable]` in its place and records the event `lossy`; the run goes on. Any other storage error fails the model call like a network error (retried if transient), so the model never answers a placeholder because of a hiccup.
137
142
  - **Blobs are immutable.** A `BlobStore` must never reuse an id or change bytes after `put`: "the log plus its blobs" is what the model saw. Replaying a session through a lowering (`replayTurns` + `toRequest`) needs the same `BlobStore` — call `hydrateImageRefs` first, as `examples/minimal/replay.ts` does.
138
143
  - **Reads are concurrent.** Checking a batch of references and swapping the images in view each read the uncached blobs in one wave — up to 16 at a time, each id once — then judge them in order, so the first problem reported is the same as one-by-one reading would give. On object storage, ten new images cost one round trip instead of ten. Need a lower limit? Throttle inside your `BlobStore`.
@@ -145,11 +150,13 @@ An image can also be a reference: `{ type: "image", mime, blobId }`. The bytes l
145
150
 
146
151
  A `Socket` is the seam brain modules use — five hooks (`beforeModel`, `afterModel`, `beforeTool`, `afterTool`, `onTurnEnd`) plus two static contributions (`tools`, `systemPrompt`, resolved once per run so prompt caches stay warm). Anything a socket wants the model to see is emitted as an event and lands in the log first; nothing is injected around the log. Every hook gets `ctx.batch`: the tool calls of the current batch, the results logged so far (in `beforeTool`, only those of earlier calls), the ids left waiting for approval / a client result / a paused sub-agent, and `resumed` when the batch is one a previous run left unfinished. It is one object updated in place during the turn — copy what you need instead of keeping a reference. A batch is one contiguous stretch of model output (`toolBatchOf`).
147
152
 
153
+ **Tools added by a `beforeModel` patch are not there when a resume settles pending calls.** That happens before any model turn, with the base tool table (your tools plus the sockets' static `tools`), so `beforeModel` has not run yet: a patch-added tool that paused for approval is not executed after it is approved — the model gets an error result starting with `Tool not available on resume:` — and a patch-added client-side tool is missing from `run_paused.awaiting`. Any tool that may need approval or is executed by the client must come from a socket's static `tools` contribution (which can be a function, resolved once per run), not from a `beforeModel` patch.
154
+
148
155
  ## Guarantees worth knowing
149
156
 
150
157
  - **Append-only.** Compaction, spill and handoff are all expressed as appended events. Forking a session copies a prefix verbatim (ids and `seq` kept), so references such as `recall({ seq })` survive.
151
158
  - **Fail-closed reads.** An event type the registry does not know, or a version it cannot upgrade, is rejected before anything is written.
152
- - **Bounded retry only on zero output.** A transient failure (network, 5xx, 429 — decided from the status code first, keywords only as a fallback) is retried up to 3 times, but never after a partial response has been appended: the log must not contain two half answers.
159
+ - **Bounded retry only on zero output.** A transient failure (network, 5xx, 429 — decided from the status code first, keywords only as a fallback) is retried — up to 3 attempts in total by default, i.e. 2 retries (`retry.maxAttempts`) — but never after a partial response has been appended: the log must not contain two half answers.
153
160
  - **Rollback caveat (0.10).** Sessions that contain a `core.tool_started` event cannot be read by `@reinsjs/core` 0.9 or earlier (unknown event types are rejected).
154
161
  - **Every run is bracketed (0.14).** `runLoop` starts each run with a model-invisible `core.tools_bound` (`marksEnd: true`) and ends it with exactly one end marker: `core.run_paused` for a pause (now with `awaiting` — the calls waiting on an approval, a client tool or a sub-agent — and `stopped` for a user stop), or `core.run_ended` with `status: "done" | "handoff" | "error"`. A `core.error` the loop retries past, or one from a throwing `pullInput`, gets no `run_ended`. `runStatusOf({ held, lastMarker })` turns a lease flag and `lastRunMarker(timeline)` into running / paused / done / handoff / error / interrupted / idle / unknown; `@reinsjs/store-pg` has `pgRunStates` for a whole session list in one statement. Sessions containing `core.run_ended` cannot be read by 0.13 or earlier: upgrade every instance together and do not roll back.
155
162
  - **Pause codes (0.15).** A socket's `pause` may carry a `code` — your own short identifier such as `acme.credits_exhausted` — next to `reason` and `note`. It is written into `core.run_paused` together with the note and comes back as `RunStatus.paused.code`, so another request or process can tell why the run paused without guessing. reins never branches on it and it is not part of the resume state. Format: `PAUSE_CODE_RE` (lowercase letters, digits, `_ . : -`, starting with a letter or digit, at most 64 characters); a code that does not match is dropped — the run still pauses, and a model-invisible `core.error` (category `input`, `detail.phase: "onTurnEnd"`, no `run_ended` after it) is logged just before the `core.run_paused`. The same happens when `reason` is anything but `"budget"` or `"host"`: the run pauses with `host`. Put your own reasons in `code`. The `reins.` prefix is used by built-in sources: `reins.max_turns` (the loop's `maxTurns` limit), `reins.budget` and `reins.compact_stalled` (from `@reinsjs/brain`). Aborts and user stops carry no code. A paused sub-agent's code stays in the child session — look it up through `awaiting[].childSessionId`.
@@ -678,7 +678,10 @@ interface Tool<TInput = unknown> {
678
678
  maxTokens?: number;
679
679
  overflow: "truncate" | "spill";
680
680
  };
681
- /** 执行前是否要人审批。循环内置兜底:为真且没有任何 Socket 做主时,直接转审批暂停(安全默认值) */
681
+ /**
682
+ * 执行前是否要人审批。循环内置兜底:为真且没有任何 Socket 做主时,直接转审批暂停(安全默认值)。
683
+ * 函数形态抛错按拒绝处理:不执行,落 isError 结果 "Approval check failed: …",原因另记一条模型不可见的 core.error(category "host"、detail.phase "needsApproval")
684
+ */
682
685
  needsApproval?: boolean | ((input: TInput, ctx: ToolContext) => Promise<boolean> | boolean);
683
686
  risk?: "low" | "medium" | "high";
684
687
  /**
@@ -709,6 +712,12 @@ type ToolResultDraft = EventDraft<"core.tool_result", ToolResultPayload>;
709
712
  /** beforeModel 的返回:改投影、增删工具、换系统提示;缺省字段表示不改 */
710
713
  interface BeforeModelPatch {
711
714
  events?: Event[];
715
+ /**
716
+ * 本轮工具表(整体替换)。⚠️ 补丁加进来的工具只活在调过 beforeModel 的模型轮里:续跑补齐 pending 调用发生在任何
717
+ * 模型轮之前,用的是基础工具表(宿主工具 + Socket 静态 `tools`),补丁工具不在场——被审批暂停的补丁工具批准后不执行,落
718
+ * "Tool not available on resume: …",补丁加的客户端工具也不进 `run_paused.awaiting`。需要审批或由客户端执行的工具必须走
719
+ * Socket 的静态 `tools` 贡献(可以是按运行环境算一次的函数),不要靠这里加(全景图决策「补丁工具不跨暂停」)。
720
+ */
712
721
  tools?: Tool[];
713
722
  systemPrompt?: string;
714
723
  /**
@@ -783,13 +792,17 @@ interface TurnContext {
783
792
  * 超过它库就按阈值自动折叠最旧的轮次(感知用同一函数校准、据此提醒模型)
784
793
  */
785
794
  targetTokens: number;
786
- /** 本轮投影的估算 token */
795
+ /**
796
+ * 本轮投影的估算 token(beforeModel 补丁之前)。注意与固定开销口径不同:开销按补丁与注入**之后**送出视图的估算校准
797
+ * (`budget_usage.contextEstimate`)。宿主 Socket 若每轮用 `patch.events` 剔掉同样的内容,
798
+ * "used + contextOverheadOf" 会稳定高估被剔掉的那一部分(感知读数、到线请求、阈值兜底同此)
799
+ */
787
800
  used: number;
788
801
  /** 本次 run 累计消耗(输入 + 输出) */
789
802
  tokensSpent: number;
790
803
  turns: number;
791
804
  toolCalls: number;
792
- /** 距 run 开始的毫秒数;beforeModel 时是本轮开始的读数,模型调用后更新 */
805
+ /** 距 run 开始的毫秒数;beforeModel 时是本轮开始的读数,模型调用后更新,onTurnEnd 前再刷新一次(含本轮工具耗时) */
793
806
  wallMs: number;
794
807
  /**
795
808
  * 最近一次模型请求的真实用量(B8):beforeModel 时是上一次请求的(含上次 run,从日志最后一条 budget_usage 读),
@@ -1031,7 +1044,10 @@ interface LoopConfig {
1031
1044
  * 缺省 100。
1032
1045
  */
1033
1046
  maxTurns?: number;
1034
- /** 宿主中止:当前请求停止后以 paused(host) 返回,已产出的内容仍入日志 */
1047
+ /**
1048
+ * 宿主中止:当前请求停止后暂停(工具批里还有没轮到的调用时不进 onTurnEnd;批里另有审批 / 客户端工具中断时 reason 随它,否则 paused(host)),已产出的内容仍入日志。
1049
+ * 原因是 `RunStop` 时 pending 全部收尾成"没执行";其它原因下工具批里没轮到的调用留 pending 补跑,被掐断的模型响应里的调用收尾成"响应被中断"
1050
+ */
1035
1051
  signal?: AbortSignal;
1036
1052
  /**
1037
1053
  * 模型调用遇到瞬断(连接被掐、超时、过载 / 限流 / 5xx)时的有限重试,缺省最多 3 次尝试、1s 起翻倍退避。
@@ -1051,7 +1067,11 @@ interface LoopConfig {
1051
1067
  * 不传也能续跑(同一 sessionId 再跑一次),只是少了这层校验。
1052
1068
  */
1053
1069
  resume?: SerializedRunState;
1054
- /** 宿主给 pending 调用的审批结论,先记成 approval_decision 再执行;指向非 pending 调用即拒绝 */
1070
+ /**
1071
+ * 宿主给**正在等审批**的调用(有 approval_request、还没有结论)的审批结论,先记成 approval_decision 再执行。
1072
+ * 指向不在等审批的调用(不 pending、或从没发出审批请求)、或同一调用给了两条,即抛 RunStateError("unknown_tool_call")、不写日志
1073
+ * (`assertDecisionsAwaitApproval`)。要取消一个没在等审批的 pending 调用,用停止(`RunStop`)
1074
+ */
1055
1075
  decisions?: readonly ApprovalDecisionInput[];
1056
1076
  /** 状态签名密钥。给了就签发与校验;没给则状态不签名、恢复不验签(只适合可信环境) */
1057
1077
  secret?: string;
@@ -1222,7 +1242,8 @@ declare function contextTokensOf(usage: TokenUsage): number;
1222
1242
  declare function contextOverheadOf(timeline: readonly Event[]): number;
1223
1243
  /**
1224
1244
  * 用量是事件,宿主可按会话或用户聚合出配额(库不做配额)。
1225
- * `contextEstimate`(B8):这次请求投影的估算 token(= 当轮 TurnContext.budget.used),与真实用量放在同一条事件里,
1245
+ * `contextEstimate`(B8):这次请求**真正送出视图**的估算 token(beforeModel 补丁与注入之后;全库审查 2026-11-25 #20 起,
1246
+ * 此前取投影那一刻的 TurnContext.budget.used,注入的大快照会被算成开销、下一轮再估一遍),与真实用量放在同一条事件里,
1226
1247
  * 感知模块用"真实上下文 − 估算"得到系统提示、工具表、thinking 等估算不含的固定开销,校准下一轮的使用率读数。
1227
1248
  * `remaining` 预留给宿主 / 适配器自己追加的聚合用量;循环不填(上限属于 brain budget 模块,循环不知道)。
1228
1249
  */
@@ -1362,4 +1383,4 @@ type ExtEvent = Event<`ext.${string}`, unknown>;
1362
1383
  /** 日志里可能出现的任何事件 */
1363
1384
  type AnyEvent = CoreEvent | ExtEvent;
1364
1385
 
1365
- export { DEFAULT_RETRY_MAX_ATTEMPTS as $, type AwaitingCall as A, type BlobStore as B, type ContentPart as C, type AnyEvent as D, type Event as E, type ApprovalDecisionInput as F, type ApprovalDecisionPayload as G, type ApprovalRequestPayload as H, type ImageRefPart as I, type ApprovalRequestSpec as J, type AudioPart as K, type LoopConfig as L, type ModelRef as M, type BeforeModelPatch as N, type BeforeToolDecision as O, type PauseReason as P, type BoundModel as Q, type RunResult as R, type SerializedRunState as S, type ToolCallEvent as T, CORE_SCHEMAS as U, type CompactionPayload as V, type CoreEvent as W, type CoreEventPayloads as X, type CoreEventType as Y, type CreateEventInput as Z, DEFAULT_RETRY_BASE_DELAY_MS as _, type ToolResultEvent as a, createCoreEvent as a$, DEFAULT_RETRY_MAX_DELAY_MS as a0, DEFAULT_TRUST as a1, type ErrorEventPayload as a2, type EventBase as a3, type EventSchema as a4, type ExtEvent as a5, type HandoffIntent as a6, type HandoffPayload as a7, type ImageInlinePart as a8, type ImagePart as a9, type SchemaErrorCode as aA, type SessionInfo as aB, type SkillSource as aC, type Socket as aD, type SocketSetup as aE, type StaticContribution as aF, type SystemNotePayload as aG, type TextPart as aH, type ToRequestInput as aI, type TokenUsage as aJ, type ToolBatch as aK, type ToolCallPayload as aL, type ToolContext as aM, type ToolReferencePart as aN, type ToolResultDraft as aO, type ToolResultPayload as aP, type ToolSide as aQ, type ToolStartedPayload as aR, type ToolsBoundPayload as aS, type TurnContext as aT, type TurnDecision as aU, type Upcaster as aV, type UserMessagePayload as aW, type VideoPart as aX, backoffDelayMs as aY, contextOverheadOf as aZ, contextTokensOf as a_, type LandingRecord as aa, type LandingSpec as ab, type LossKind as ac, type LossMatrix as ad, type LoweredRequest as ae, type Lowering as af, type LoweringCapabilities as ag, type LoweringDelta as ah, type LoweringOutcome as ai, type LoweringStreamContext as aj, type MaybePromise as ak, type MemoryOpPayload as al, type ModelCallFailure as am, type ModelTextPayload as an, type ModelThinkingPayload as ao, type Principal as ap, type ProjectionStep as aq, type ProjectionStepStats as ar, type Provenance as as, type PullInputContext as at, type ResolvedRetry as au, type RetryOptions as av, type RunEndedPayload as aw, type RunPausedPayload as ax, type RunResumedPayload as ay, SchemaError as az, type EventLog as b, createCoreRegistry as b0, createEvent as b1, defaultSleep as b2, isTransientFailure as b3, lossesOf as b4, renderToolReference as b5, resolveRetry as b6, statusFromMessage as b7, type BlobMeta as c, type Interruption as d, type ErrorPayload as e, type EventDraft as f, type Tool as g, EventSchemaRegistry as h, type SubagentInterruption as i, type ToolSpec as j, type ToolResult as k, type Trust as l, type CoreEventOf as m, type CoreEventDraft as n, type ProjectionBudget as o, type ProjectionStrategy as p, type ProjectionContext as q, type TokenEstimator as r, type ProjectionResult as s, type ProjectionStats as t, type BudgetUsagePayload as u, type ReadOptions as v, type MemoryStore as w, type RunLease as x, type Stores as y, type Actor as z };
1386
+ export { DEFAULT_RETRY_BASE_DELAY_MS as $, type AwaitingCall as A, type BlobStore as B, type ContentPart as C, type Actor as D, type Event as E, type AnyEvent as F, type ApprovalDecisionPayload as G, type HandoffIntent as H, type ImageRefPart as I, type ApprovalRequestPayload as J, type ApprovalRequestSpec as K, type LoopConfig as L, type ModelRef as M, type AudioPart as N, type BeforeModelPatch as O, type PauseReason as P, type BeforeToolDecision as Q, type RunResult as R, type SerializedRunState as S, type ToolCallEvent as T, type BoundModel as U, CORE_SCHEMAS as V, type CompactionPayload as W, type CoreEvent as X, type CoreEventPayloads as Y, type CoreEventType as Z, type CreateEventInput as _, type ToolResultEvent as a, createCoreEvent as a$, DEFAULT_RETRY_MAX_ATTEMPTS as a0, DEFAULT_RETRY_MAX_DELAY_MS as a1, DEFAULT_TRUST as a2, type ErrorEventPayload as a3, type EventBase as a4, type EventSchema as a5, type ExtEvent as a6, type HandoffPayload as a7, type ImageInlinePart as a8, type ImagePart as a9, type SchemaErrorCode as aA, type SessionInfo as aB, type SkillSource as aC, type Socket as aD, type SocketSetup as aE, type StaticContribution as aF, type SystemNotePayload as aG, type TextPart as aH, type ToRequestInput as aI, type TokenUsage as aJ, type ToolBatch as aK, type ToolCallPayload as aL, type ToolContext as aM, type ToolReferencePart as aN, type ToolResultDraft as aO, type ToolResultPayload as aP, type ToolSide as aQ, type ToolStartedPayload as aR, type ToolsBoundPayload as aS, type TurnContext as aT, type TurnDecision as aU, type Upcaster as aV, type UserMessagePayload as aW, type VideoPart as aX, backoffDelayMs as aY, contextOverheadOf as aZ, contextTokensOf as a_, type LandingRecord as aa, type LandingSpec as ab, type LossKind as ac, type LossMatrix as ad, type LoweredRequest as ae, type Lowering as af, type LoweringCapabilities as ag, type LoweringDelta as ah, type LoweringOutcome as ai, type LoweringStreamContext as aj, type MaybePromise as ak, type MemoryOpPayload as al, type ModelCallFailure as am, type ModelTextPayload as an, type ModelThinkingPayload as ao, type Principal as ap, type ProjectionStep as aq, type ProjectionStepStats as ar, type Provenance as as, type PullInputContext as at, type ResolvedRetry as au, type RetryOptions as av, type RunEndedPayload as aw, type RunPausedPayload as ax, type RunResumedPayload as ay, SchemaError as az, type EventLog as b, createCoreRegistry as b0, createEvent as b1, defaultSleep as b2, isTransientFailure as b3, lossesOf as b4, renderToolReference as b5, resolveRetry as b6, statusFromMessage as b7, type EventDraft as c, type BlobMeta as d, type Interruption as e, type ErrorPayload as f, type Tool as g, EventSchemaRegistry as h, type ApprovalDecisionInput as i, type SubagentInterruption as j, type ToolSpec as k, type ToolResult as l, type Trust as m, type CoreEventOf as n, type CoreEventDraft as o, type ProjectionBudget as p, type ProjectionStrategy as q, type ProjectionContext as r, type TokenEstimator as s, type ProjectionResult as t, type ProjectionStats as u, type BudgetUsagePayload as v, type ReadOptions as w, type MemoryStore as x, type RunLease as y, type Stores as z };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, B as BlobStore, c as BlobMeta, C as ContentPart, I as ImageRefPart, d as Interruption, e as ErrorPayload, L as LoopConfig, f as EventDraft, R as RunResult, P as PauseReason, A as AwaitingCall, g as Tool, h as EventSchemaRegistry, S as SerializedRunState, M as ModelRef, i as SubagentInterruption, j as ToolSpec, k as ToolResult, l as Trust, m as CoreEventOf, n as CoreEventDraft, o as ProjectionBudget, p as ProjectionStrategy, q as ProjectionContext, r as TokenEstimator, s as ProjectionResult, t as ProjectionStats, u as BudgetUsagePayload, v as ReadOptions, w as MemoryStore, x as RunLease, y as Stores } from './core-2MZcObOK.js';
2
- export { z as Actor, D as AnyEvent, F as ApprovalDecisionInput, G as ApprovalDecisionPayload, H as ApprovalRequestPayload, J as ApprovalRequestSpec, K as AudioPart, N as BeforeModelPatch, O as BeforeToolDecision, Q as BoundModel, U as CORE_SCHEMAS, V as CompactionPayload, W as CoreEvent, X as CoreEventPayloads, Y as CoreEventType, Z as CreateEventInput, _ as DEFAULT_RETRY_BASE_DELAY_MS, $ as DEFAULT_RETRY_MAX_ATTEMPTS, a0 as DEFAULT_RETRY_MAX_DELAY_MS, a1 as DEFAULT_TRUST, a2 as ErrorEventPayload, a3 as EventBase, a4 as EventSchema, a5 as ExtEvent, a6 as HandoffIntent, a7 as HandoffPayload, a8 as ImageInlinePart, a9 as ImagePart, aa as LandingRecord, ab as LandingSpec, ac as LossKind, ad as LossMatrix, ae as LoweredRequest, af as Lowering, ag as LoweringCapabilities, ah as LoweringDelta, ai as LoweringOutcome, aj as LoweringStreamContext, ak as MaybePromise, al as MemoryOpPayload, am as ModelCallFailure, an as ModelTextPayload, ao as ModelThinkingPayload, ap as Principal, aq as ProjectionStep, ar as ProjectionStepStats, as as Provenance, at as PullInputContext, au as ResolvedRetry, av as RetryOptions, aw as RunEndedPayload, ax as RunPausedPayload, ay as RunResumedPayload, az as SchemaError, aA as SchemaErrorCode, aB as SessionInfo, aC as SkillSource, aD as Socket, aE as SocketSetup, aF as StaticContribution, aG as SystemNotePayload, aH as TextPart, aI as ToRequestInput, aJ as TokenUsage, aK as ToolBatch, aL as ToolCallPayload, aM as ToolContext, aN as ToolReferencePart, aO as ToolResultDraft, aP as ToolResultPayload, aQ as ToolSide, aR as ToolStartedPayload, aS as ToolsBoundPayload, aT as TurnContext, aU as TurnDecision, aV as Upcaster, aW as UserMessagePayload, aX as VideoPart, aY as backoffDelayMs, aZ as contextOverheadOf, a_ as contextTokensOf, a$ as createCoreEvent, b0 as createCoreRegistry, b1 as createEvent, b2 as defaultSleep, b3 as isTransientFailure, b4 as lossesOf, b5 as renderToolReference, b6 as resolveRetry, b7 as statusFromMessage } from './core-2MZcObOK.js';
1
+ import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, H as HandoffIntent, c as EventDraft, B as BlobStore, d as BlobMeta, C as ContentPart, I as ImageRefPart, e as Interruption, f as ErrorPayload, L as LoopConfig, R as RunResult, P as PauseReason, A as AwaitingCall, g as Tool, h as EventSchemaRegistry, i as ApprovalDecisionInput, S as SerializedRunState, M as ModelRef, j as SubagentInterruption, k as ToolSpec, l as ToolResult, m as Trust, n as CoreEventOf, o as CoreEventDraft, p as ProjectionBudget, q as ProjectionStrategy, r as ProjectionContext, s as TokenEstimator, t as ProjectionResult, u as ProjectionStats, v as BudgetUsagePayload, w as ReadOptions, x as MemoryStore, y as RunLease, z as Stores } from './core-CfHjZdUU.js';
2
+ export { D as Actor, F as AnyEvent, G as ApprovalDecisionPayload, J as ApprovalRequestPayload, K as ApprovalRequestSpec, N as AudioPart, O as BeforeModelPatch, Q as BeforeToolDecision, U as BoundModel, V as CORE_SCHEMAS, W as CompactionPayload, X as CoreEvent, Y as CoreEventPayloads, Z as CoreEventType, _ as CreateEventInput, $ as DEFAULT_RETRY_BASE_DELAY_MS, a0 as DEFAULT_RETRY_MAX_ATTEMPTS, a1 as DEFAULT_RETRY_MAX_DELAY_MS, a2 as DEFAULT_TRUST, a3 as ErrorEventPayload, a4 as EventBase, a5 as EventSchema, a6 as ExtEvent, a7 as HandoffPayload, a8 as ImageInlinePart, a9 as ImagePart, aa as LandingRecord, ab as LandingSpec, ac as LossKind, ad as LossMatrix, ae as LoweredRequest, af as Lowering, ag as LoweringCapabilities, ah as LoweringDelta, ai as LoweringOutcome, aj as LoweringStreamContext, ak as MaybePromise, al as MemoryOpPayload, am as ModelCallFailure, an as ModelTextPayload, ao as ModelThinkingPayload, ap as Principal, aq as ProjectionStep, ar as ProjectionStepStats, as as Provenance, at as PullInputContext, au as ResolvedRetry, av as RetryOptions, aw as RunEndedPayload, ax as RunPausedPayload, ay as RunResumedPayload, az as SchemaError, aA as SchemaErrorCode, aB as SessionInfo, aC as SkillSource, aD as Socket, aE as SocketSetup, aF as StaticContribution, aG as SystemNotePayload, aH as TextPart, aI as ToRequestInput, aJ as TokenUsage, aK as ToolBatch, aL as ToolCallPayload, aM as ToolContext, aN as ToolReferencePart, aO as ToolResultDraft, aP as ToolResultPayload, aQ as ToolSide, aR as ToolStartedPayload, aS as ToolsBoundPayload, aT as TurnContext, aU as TurnDecision, aV as Upcaster, aW as UserMessagePayload, aX as VideoPart, aY as backoffDelayMs, aZ as contextOverheadOf, a_ as contextTokensOf, a$ as createCoreEvent, b0 as createCoreRegistry, b1 as createEvent, b2 as defaultSleep, b3 as isTransientFailure, b4 as lossesOf, b5 as renderToolReference, b6 as resolveRetry, b7 as statusFromMessage } from './core-CfHjZdUU.js';
3
3
 
4
4
  /**
5
5
  * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
@@ -12,8 +12,8 @@ declare function uuidv7(now?: number): string;
12
12
  /**
13
13
  * 工具批的定位(2026-11-02,OnSet 建议 9 / 10)。
14
14
  *
15
- * "一批" = 一段连续模型输出里的 tool_call。与 replay 切轮(`isModelOutput`)同口径,另外跳过模型不可见的运维事件
16
- * (budget_usage、approval_request、run_paused…)——它们可能夹在同一次输出中间(TanStack 的 onUsage 早于输出收尾时),
15
+ * "一批" = 一段连续模型输出里的 tool_call。与 replay 切轮(`isModelOutput`)同口径,另外跳过缺省对模型不可见的事件
16
+ * (budget_usage、approval_request、run_paused…与宿主 ext.*)——它们可能夹在同一次输出中间(TanStack 的 onUsage 早于输出收尾时),
17
17
  * 与 lowering-fetch IR"运维事件不打断 assistant 分组"同一条规矩。runLoop 与 TanStack 适配器补跑时都调它(真源索引)。
18
18
  */
19
19
 
@@ -39,6 +39,34 @@ declare function forkSession(log: EventLog, opts: ForkOptions): Promise<{
39
39
  toSessionId: string;
40
40
  }>;
41
41
 
42
+ /**
43
+ * 交接新会话的开场草稿(runLoop 与 TanStack 适配器共用,两处开场形状不分叉)。
44
+ *
45
+ * 形状:seq 1 摘要说明 → 意图带来的开场事件(如 pin,原样)→ 触发消息(有才写)。
46
+ *
47
+ * 发起者如实记(宪法二:事件带真实发起者;全库审查 2026-11-25 #52):
48
+ * - 摘要是交接决定者写的:`intent.by`(缺省 model),不再一律记成宿主说明——模型写的摘要不该拿 system 信任;
49
+ * - 触发消息逐字(去首尾空白)取自旧会话一条用户消息时,按原事件的发起者与 trust 记(用户的仍是用户、宿主写的仍是宿主、
50
+ * 上一次交接里模型自拟的仍是模型),provenance 指回原事件;否则是交接决定者自拟的(模型被工具结果里的注入诱导写的
51
+ * 也在此列),记在它名下;
52
+ * - 摘要与自拟触发消息的 provenance 指回旧会话的 `core.handoff` 事件,审计分得清这句话从哪来。
53
+ *
54
+ * 摘要说明的 `payload.kind` 刻意仍是 `"host"`、不随 actor 改:kind 是说明的类别("perception" / "pin" / "budget"
55
+ * 之外的通用说明一律 host,工具表变化说明也是 actor system + kind host),不表示谁写的——谁写的只看 actor。
56
+ * 另加 "handoff" 类别要扩 SystemNotePayload 闭集、升 schemaVersion 写 upcast,而降级层与脑子模块按 kind 的分支
57
+ * 对它都该与 host 同样处理,换来的只是重复 actor + provenance 已经给出的信息。
58
+ *
59
+ * 模型看到的字节不变:降级层按事件类型落角色、只看 `trust === "untrusted"` 包标记,不读 actor。
60
+ */
61
+
62
+ /** 交接开场事件 provenance 的来源名(与 brain handoff 模块带过去的 pin 同名) */
63
+ declare const HANDOFF_PROVENANCE_SOURCE = "handoff";
64
+ /**
65
+ * @param handoffEvent 旧会话刚写下的 `core.handoff`(摘要与自拟触发消息的出处)
66
+ * @param timeline 旧会话完整时间线(找触发消息逐字出自哪条用户消息;取最近的一条)
67
+ */
68
+ declare function handoffOpeningDrafts(intent: HandoffIntent, handoffEvent: Event, timeline: readonly Event[]): EventDraft[];
69
+
42
70
  /**
43
71
  * 图片引用形态(2026-11-24 媒体引用方案,AdRate 建议 17 第二步):字节放 BlobStore,日志只存 `{ type: "image", mime, blobId }`。
44
72
  *
@@ -400,6 +428,19 @@ declare function validateResume(input: {
400
428
  secret?: string;
401
429
  allowConfigDrift?: boolean;
402
430
  }): Promise<ToolCallEvent[]>;
431
+ /**
432
+ * 本会话审批结论的对账(真源索引,全库审查 2026-11-25 #12):每条结论指向的调用必须**正在等审批**——
433
+ * pending、有 approval_request、还没有结论,判定只走 `awaitingOf`(与 run_paused.awaiting 同一口径)。
434
+ * 只查 pending 的话,一个从没发出审批请求的调用(工具批中途被普通中止、排在后面的)也能被"预先批准",
435
+ * needsApproval、审批策略的 defer 与 ttl 都会被跳过。同一调用在一批结论里出现两次也拒(第一条落下后它就不在等了)。
436
+ * 指向别的会话(子代理)的结论不在这里校验,原样转发。不合规抛 `RunStateError("unknown_tool_call")`,调用方须在写日志前调。
437
+ * server 的 decisions 预校验调本函数(HTTP 回 409),与 runLoop 同判由 server/handler.test.ts 穿过两个入口的用例锁住
438
+ */
439
+ declare function assertDecisionsAwaitApproval(input: {
440
+ sessionId: string;
441
+ timeline: readonly Event[];
442
+ decisions: readonly ApprovalDecisionInput[];
443
+ }): void;
403
444
 
404
445
  /**
405
446
  * Socket 静态贡献的解析(B2 引入,B6 抽出):宿主工具 + 各 Socket 带来的工具与规则提示 → 整个 run 不变的工具表与系统提示。
@@ -418,7 +459,8 @@ interface ResolvedContributions {
418
459
  /** 能算出静态贡献所需的配置子集:AgentDefinition(跨请求不变)加上本次请求的 principal */
419
460
  type ContributionConfig = Pick<LoopConfig, "log" | "blobs" | "memory" | "model" | "principal" | "tools" | "sockets" | "systemPrompt">;
420
461
  /**
421
- * 宿主工具 + 各 Socket 的静态工具(同名以宿主为准,宿主想覆盖模块的默认实现时用);
462
+ * 宿主工具 + 各 Socket 的静态工具(同名以宿主为准,宿主想覆盖模块的默认实现时用——但对 brain 自带工具的模块,按名字覆盖会让
463
+ * 整个模块停摆,见 brain `shared/own-tools.ts`;只想换读法用 `spill({ tool: false })` 这类开关);
422
464
  * 宿主系统提示在前,各 Socket 的规则片段按注册顺序追加,空行分隔;都没有则 undefined。
423
465
  *
424
466
  * 异步(P1):贡献函数可以 await(MCP 的 `tools/list`)。各 Socket 仍按注册顺序**依次**解析而不是并发 ——
@@ -437,7 +479,7 @@ declare function resolveSocketContributions(cfg: ContributionConfig): Promise<Re
437
479
  * 对改用户广告的写工具,重复执行就是重复花钱。这里放三件纯东西,循环与 asTool 共用:
438
480
  *
439
481
  * - `RunStop` / `isStopReason`:停止是中止的一种原因。宿主 `controller.abort(new RunStop())`,循环在暂停时把 pending 收尾成
440
- * "没执行"等结果,下一个 run 直接问模型;其它中止原因(丢租约、断线)照旧留 pending、恢复时补跑。
482
+ * "没执行"等结果,下一个 run 直接问模型;其它中止原因(丢租约、断线)落在工具批中途时照旧留 pending、恢复时补跑(落在模型响应中途时那次响应里的调用收尾成"响应被中断")。
441
483
  * - `isReplayable`:调用开始动手后中断了,能不能再跑一遍。缺省口径与 approval 的 byRisk 一致:只有 `risk: "low"` 的算可重放。
442
484
  * - `startedToolCallIds` / `toolStartedAt`:时间线里已经开始动手的调用(`core.tool_started`)及其开始时间。
443
485
  * - `outcomeUnknownText` / `withStartedAt`:"结果未知"缀上调用开始时间(2026-11-09,AdRate 建议 10)。
@@ -451,6 +493,17 @@ declare const STOPPED_NOTE = "stopped by the user";
451
493
  declare const STOPPED_NOT_EXECUTED_TEXT = "Not executed: the run was stopped by the user before this call started.";
452
494
  /** 用户停止:可重放的调用(子代理)做了一半 */
453
495
  declare const STOPPED_IN_PROGRESS_TEXT = "Interrupted: the run was stopped by the user while this call was in progress; it may have partly taken effect.";
496
+ /**
497
+ * 模型响应在落下 tool_call 之后才失败(断流、stopReason error):run 以 error 收尾前把这次响应里的调用收尾成这句(全库审查 2026-11-25 #13)。
498
+ * 入参可能是截断的,也不知道模型原本还要说什么;留作 pending 的话,下一个 run 会在用户的新话之后、模型读到它之前先执行
499
+ */
500
+ declare const MODEL_FAILED_NOT_EXECUTED_TEXT = "Not executed: the model response failed before it was complete, so this call was dropped.";
501
+ /**
502
+ * 模型响应被宿主中止(断线、丢租约,`stopReason: "aborted"` 或连接阶段被掐)而这次响应里已落了 tool_call:
503
+ * 暂停前把这些调用收尾成这句(全库审查 2026-11-25 返修,与 #13 同一形状)。降级层被中止时可能按已累积的半截入参吐出调用,
504
+ * 留作 pending 的话下一个 run 会在用户的新话之后先补跑它。用户停止不用这句,走 `stopTextsOf` 的"没执行"
505
+ */
506
+ declare const MODEL_INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: the model response was interrupted before it was complete, so this call was dropped.";
454
507
  /** 宿主收尾遗留调用(`RunStop("host")`,如 asTool 开新一轮前):调用还没开始。不说"用户停止"——多半是进程中途死亡留下的 */
455
508
  declare const INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: an earlier run was interrupted before this call started.";
456
509
  /** 宿主收尾遗留调用:可重放的调用(子代理)做了一半 */
@@ -555,20 +608,34 @@ declare function defineTool<TInput>(tool: Tool<TInput>): Tool;
555
608
  declare function toolSpecOf(tool: Tool): ToolSpec;
556
609
  /** 带"声明但不载入"标记的规格(L1):runLoop 按 BeforeModelPatch.deferredTools 对本轮工具表逐件调 */
557
610
  declare function deferredToolSpecOf(tool: Tool, deferred: boolean): ToolSpec;
611
+ /**
612
+ * 图片片段可写进日志的 mime 白名单(真源索引):Anthropic / OpenAI / Gemini 都收的四种,逐字比对、不做大小写或别名归一。
613
+ * 不在表里的(svg、heic、`image/jpg` 写法、非图片类型)一旦以图片片段进日志,之后每次请求都整段回放、厂商回非瞬断 400,
614
+ * 会话卡死(全库审查 2026-11-25 #9)。片段形状(`isContentPart`)、server 网络白名单(`rebuildContentParts`)、tools-mcp 翻译(`toContentParts`)都调这一份
615
+ */
616
+ declare const SUPPORTED_IMAGE_MIMES: ReadonlySet<string>;
617
+ /** mime 是否在图片白名单里(`SUPPORTED_IMAGE_MIMES`);非字符串一律 false */
618
+ declare function isSupportedImageMime(mime: unknown): boolean;
558
619
  /**
559
620
  * 内容片段的形状校验,全包唯一一份(真源索引):工具返回值归一(本文件)与 runLoop 输入草稿 / 片段数组(run-loop.ts)都调它。
560
621
  * 坏片段一旦进日志,之后每次读到它都会崩(会话报废),所以在写之前拦。
561
- * 规则:text 有 `text`;image 是内联(`mime` 与 `data`,mime 不校验,历史行为)或引用(`isImageRef`:mime 以 "image/" 开头、
562
- * blobId 非空且 ≤ 128 字符),`data` 与 `blobId` 恰好一个;video / audio 的 mime 以 "video/" / "audio/" 开头、
622
+ * 规则:text 有 `text`;image 是内联(`mime` 与 `data`)或引用(`isImageRef`:blobId 非空且 ≤ 128 字符),`data` 与 `blobId`
623
+ * 恰好一个,两种形态的 mime 都必须在白名单里(`isSupportedImageMime`);video / audio 的 mime 以 "video/" / "audio/" 开头、
563
624
  * `durationSec` 缺省或为有限正数;tool_reference 有名字、描述与对象形 inputSchema。
564
625
  * 宿主经 HTTP 送来的用户消息另有白名单(server `rebuildContentParts`,两份实现靠跨包用例锁同口径),不含引用段
565
626
  */
566
627
  declare function isContentPart(x: unknown): x is ContentPart;
628
+ /**
629
+ * 工具结果里只有 mime 不在白名单、其余形状都对的图片片段(内联 `data` 或引用 `blobId` 是字符串)换成的说明(模型可见)。
630
+ * 例:图表类 MCP 返回 svg。整条结果 JSON 化会把 base64 原样当文本塞进上下文,这里只换掉那一段,其余片段照旧
631
+ */
632
+ declare function unsupportedImageText(mime: string): string;
567
633
  /**
568
634
  * execute 的返回值 → 模型看到的内容。规则按直觉:
569
635
  * - string → 一段文本
570
636
  * - ContentPart[] → 原样
571
637
  * - { content, isError? } → 原样(唯一能表达"这是错误"的形态)
638
+ * - 上两种里只有白名单外的图片(svg 等)不合规 → 只把那几段换成说明(`unsupportedImageText`),其余照旧
572
639
  * - undefined / null → 空文本(工具没话说也得给模型一个结果块)
573
640
  * - 其余 → JSON 文本
574
641
  */
@@ -667,7 +734,7 @@ declare function toolCallArgumentsMeta(decoded: DecodedToolArguments): {
667
734
  * 翻译给模型时用显式标记包起来,让模型知道这段是**数据不是指令**。
668
735
  *
669
736
  * 归属:事件本身不改(投影不篡改 payload,日志里永远是原文),只在降级层把内容译成各家协议文本的那一刻包裹;
670
- * 两条降级路线(lowering-pi、TanStack 适配器)都调这里的同一份纯函数,文案不会分叉。
737
+ * 各降级路线(lowering-fetch、lowering-pi、TanStack 适配器)都调这里的同一份纯函数,文案不会分叉。
671
738
  *
672
739
  * 形状:
673
740
  * <untrusted source="tool:weekly_sales">
@@ -677,6 +744,8 @@ declare function toolCallArgumentsMeta(decoded: DecodedToolArguments): {
677
744
  * - 只包文本片段:图片不包,首尾若是图片就各插一段文本标记
678
745
  * - 内容里出现 `</untrusted`(大小写不敏感)会提前闭合标签让注入逃出去,替换成 `<\/untrusted` 并在返回值里报 `escaped`,
679
746
  * 降级层据此把落点记成 lossy(有损必声明)
747
+ * - `tool_reference` 片段保持片段形状(降级层还要按它判原生落点与备注),但它在 untrusted 结果里一律被展开成文本
748
+ * (`renderToolReference`),所以名字、描述与 schema 里的每个字符串(含键)同样转义、同样计入 `escaped`
680
749
  */
681
750
 
682
751
  declare const UNTRUSTED_TAG = "untrusted";
@@ -745,11 +814,29 @@ declare function estimateBudgetOf(budget: ProjectionBudget): number;
745
814
  * - tools_bound:每次 run 起步的工具表快照(P1);工具表本身在请求里,增删由循环以 system_note(kind=host) 告知模型
746
815
  * - tool_started:调用已开始动手的标记,只给续跑与停止判断用;模型从 tool_result 得知结果
747
816
  * - run_ended:run 的终结记号(跑完 / 交接 / 出错),只给宿主判会话状态用
817
+ *
818
+ * 宿主扩展事件 `ext.*` 不在这张表里,但 visibilityFilter 缺省同样剔除:降级层对它没有通用落点(三条 fetch 线与 pi 版
819
+ * 都记 dropped、不下发),留在视图里只会让估算、感知读数、兜底裁剪把模型看不到的字节算作上下文占用(全库审查 2026-11-25 #19)。
820
+ * 宿主要让模型看见某条 ext.*,设 `keepExtEvents` 并在排在后面的自有策略里把它翻成 core 事件(system_note 等)
748
821
  */
749
822
  declare const DEFAULT_MODEL_INVISIBLE_TYPES: ReadonlySet<string>;
823
+ /**
824
+ * "缺省对模型不可见"的唯一口径(真源索引):运维事件表 + `ext.*` 前缀。
825
+ * visibilityFilter 缺省配置、runLoop 与 TanStack 适配器对 beforeModel 期间注入事件的过滤都调它——
826
+ * 注入过滤若只看运维事件表,Socket 写的 ext.* 会进本轮视图、被算进送出估算却不下发,
827
+ * contextOverheadOf 校准出的固定开销随之偏低(全库审查 2026-11-25 第二波返修)
828
+ */
829
+ declare function isModelInvisibleByDefault(type: string): boolean;
750
830
  interface VisibilityFilterOptions {
751
- /** 覆盖默认的不可见类型集合 */
831
+ /** 覆盖默认的不可见 core 类型集合(ext.* 另由 keepExtEvents 管,不受它影响) */
752
832
  invisibleTypes?: Iterable<string>;
833
+ /**
834
+ * 缺省 false:ext.* 一律剔除。设 true 时留在视图里,交给排在后面的宿主策略翻成 core 事件——
835
+ * 原样留到降级层仍是 dropped,且会计入估算。runLoop / createAgent 上没有直达选项:用
836
+ * `defaultProjectionChain({ filter: { keepExtEvents: true } })` 自建链、把翻译策略插在第一个(过滤)之后,经 `projection.strategies` 传入。
837
+ * beforeModel 期间注入的 ext.* 不受它影响(注入过滤按 isModelInvisibleByDefault),下一轮起经投影进视图
838
+ */
839
+ keepExtEvents?: boolean;
753
840
  /** 额外判定,返回 false 即不可见。宿主放 principal 可见性等规则 */
754
841
  isVisible?: (event: Event) => boolean;
755
842
  }
@@ -824,7 +911,10 @@ declare function foldedToolResults(removed: readonly Event[], opts?: FoldedToolR
824
911
  interface RenderManifestOptions {
825
912
  /** 清单标题行;调用方在这里说明怎么取回(core 不知道取回工具叫什么) */
826
913
  heading: string;
827
- /** 最多列几条,其余折成一行"…and N more (seq a–b)"。缺省 80:一条约 25 token,上限约 2k token */
914
+ /**
915
+ * 最多列几条,超出时留 seq 最大(最近被折叠)的这些,较旧的折成标题下的一行"…N earlier (seq a–b)"。
916
+ * 缺省 80:一条约 25 token,上限约 2k token
917
+ */
828
918
  maxItems?: number;
829
919
  /** 入参 JSON 最多显示多少字符。缺省 100 */
830
920
  maxArgsChars?: number;
@@ -942,6 +1032,16 @@ interface ProjectOptions {
942
1032
  /** 缺省 uuidv7;测试注入以获得确定输出 */
943
1033
  newId?: (at: number) => string;
944
1034
  }
1035
+ /**
1036
+ * 校验窗口与预留并解出缺省预留(全库审查 2026-11-25 #17)。纯函数,不合规抛 RangeError。
1037
+ * contextLimit 须是有限正数;reserveTokens(缺省 contextLimit × DEFAULT_RESERVE_RATIO 取整)须是有限非负数且小于 contextLimit。
1038
+ * 不校验时 NaN / 0 / 预留不小于窗口会让阈值兜底把历史裁到只剩最后一轮,并把这条 compaction 永久写进只追加的日志
1039
+ * (NaN 时 overBudget 还是 false,连告警都没有)。project() 与 runLoop 起步都调这一个函数:runLoop 在写任何日志之前就拒
1040
+ */
1041
+ declare function resolveReserveTokens(budget: {
1042
+ contextLimit: number;
1043
+ reserveTokens?: number;
1044
+ }): number;
945
1045
  /**
946
1046
  * 跑一遍策略链。除 now / newId 外没有任何外部输入,同一参数必得同一输出。
947
1047
  * 时间线必须按 seq 严格升序,否则说明调用方拼错了快照,直接拒绝而不是产出错误的投影。
@@ -1118,6 +1218,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
1118
1218
  */
1119
1219
 
1120
1220
  /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
1121
- declare const REINS_VERSION = "0.17.0";
1221
+ declare const REINS_VERSION = "0.18.0";
1122
1222
 
1123
- export { AwaitingCall, BUILTIN_APPROVAL_POLICY, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CheckImageRefsContext, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, type DecodedToolArguments, type DefaultChainOptions, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type FoldedUserMedia, type ForkOptions, type HydrateImageRefsContext, IMAGE_REF_ID_MAX, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, type ImageRefCache, ImageRefPart, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, Interruption, LoopConfig, LoweringError, type LoweringErrorCode, MAX_TURNS_PAUSE_CODE, type MarkedContent, MemoryStore, ModelRef, OUTCOME_UNKNOWN_TEXT, PAUSE_CODE_RE, PauseReason, type ProjectOptions, ProjectionBudget, ProjectionContext, ProjectionResult, ProjectionStats, ProjectionStrategy, REINS_VERSION, RUN_MARKER_TYPES, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, RunLease, RunResult, RunStateError, type RunStateErrorCode, type RunStatus, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, SerializedRunState, type SocketPauseInterruption, type SocketPauseResolution, type StopTexts, StoreError, type StoreErrorCode, Stores, SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, TokenEstimator, Tool, ToolCallEvent, type ToolNamesDiff, ToolResult, ToolResultEvent, ToolSpec, type ToolsBoundEvent, Trust, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, awaitingOf, blobUsableBy, budgetTruncate, bytesToBase64, checkImageRefs, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, foldedUserMedia, forkSession, hydrateImageRefs, imageRefNotFound, inputDrafts, isClientTool, isCompaction, isContentPart, isImageRef, isModelOutput, isPauseCode, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, keptBy, lastRunMarker, lastToolsBound, markUntrusted, markUntrustedText, mediaRefsOf, memoryStore, needsUntrustedMark, normalizeToolOutput, outcomeUnknownText, pauseDetailOf, pausedStateOf, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderFoldedUserMedia, renderToolChangeNote, replayTurns, resolveSocketContributions, resolveSocketPause, roughTokenEstimate, runLoop, runStatusOf, serializeRunState, signRunState, splitTurns, startedToolCallIds, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolStartedAt, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter, withStartedAt };
1223
+ export { ApprovalDecisionInput, AwaitingCall, BUILTIN_APPROVAL_POLICY, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CheckImageRefsContext, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, type DecodedToolArguments, type DefaultChainOptions, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type FoldedUserMedia, type ForkOptions, HANDOFF_PROVENANCE_SOURCE, HandoffIntent, type HydrateImageRefsContext, IMAGE_REF_ID_MAX, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, type ImageRefCache, ImageRefPart, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, Interruption, LoopConfig, LoweringError, type LoweringErrorCode, MAX_TURNS_PAUSE_CODE, MODEL_FAILED_NOT_EXECUTED_TEXT, MODEL_INTERRUPTED_NOT_EXECUTED_TEXT, type MarkedContent, MemoryStore, ModelRef, OUTCOME_UNKNOWN_TEXT, PAUSE_CODE_RE, PauseReason, type ProjectOptions, ProjectionBudget, ProjectionContext, ProjectionResult, ProjectionStats, ProjectionStrategy, REINS_VERSION, RUN_MARKER_TYPES, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, RunLease, RunResult, RunStateError, type RunStateErrorCode, type RunStatus, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, SUPPORTED_IMAGE_MIMES, SerializedRunState, type SocketPauseInterruption, type SocketPauseResolution, type StopTexts, StoreError, type StoreErrorCode, Stores, SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, TokenEstimator, Tool, ToolCallEvent, type ToolNamesDiff, ToolResult, ToolResultEvent, ToolSpec, type ToolsBoundEvent, Trust, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertDecisionsAwaitApproval, assertRunStateShape, awaitingOf, blobUsableBy, budgetTruncate, bytesToBase64, checkImageRefs, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, foldedUserMedia, forkSession, handoffOpeningDrafts, hydrateImageRefs, imageRefNotFound, inputDrafts, isClientTool, isCompaction, isContentPart, isImageRef, isModelInvisibleByDefault, isModelOutput, isPauseCode, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, isSupportedImageMime, keptBy, lastRunMarker, lastToolsBound, markUntrusted, markUntrustedText, mediaRefsOf, memoryStore, needsUntrustedMark, normalizeToolOutput, outcomeUnknownText, pauseDetailOf, pausedStateOf, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderFoldedUserMedia, renderToolChangeNote, replayTurns, resolveReserveTokens, resolveSocketContributions, resolveSocketPause, roughTokenEstimate, runLoop, runStatusOf, serializeRunState, signRunState, splitTurns, startedToolCallIds, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolStartedAt, toolsBoundDrafts, unsupportedImageText, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter, withStartedAt };