@reinsjs/core 0.16.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,48 @@
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
+
40
+ ## 0.17.0
41
+
42
+ ### Minor Changes
43
+
44
+ - 420e0f7: Image references are read concurrently. Checking a batch of references (initial `input`, everything one `pullInput` returns, a whole tool result) and swapping the images in view before a model call each read the uncached blobs in one wave — up to 16 at a time, each id once — then judge them in their original order, so the first problem reported is the same as before. On object storage, ten new images now cost one round trip instead of ten. `BlobStore` gains an optional `stat(id): Promise<BlobMeta>` (metadata without bytes; must throw `StoreError("not_found")` for an unknown id and equal `get(id).meta`); the in-memory store implements it and `blobStoreConformance` checks it. `checkImageRefs` takes `metaOnly: true` to use `stat` when present and keep nothing in the cache — the HTTP handler uses it; the loop still decides with `get`. A `get` or `stat` that returns a non-object is treated as not found. Behaviour changes: when the same image appears twice in one tool result and the read fails transiently, both parts now get `storage error` (it is read once); after the first problem in a batch the remaining references are still read, so failing batches may read more than before. Successful batches read the same number of blobs as before.
45
+
3
46
  ## 0.16.0
4
47
 
5
48
  ### 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,9 +136,12 @@ 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.
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`.
144
+ - **Optional `stat(id)`.** A `BlobStore` may add `stat(id): Promise<BlobMeta>` that returns the metadata without the bytes. It must throw `StoreError("not_found")` for an unknown id (never return `null`) and must equal `get(id).meta`; `blobStoreConformance` checks both. Only the HTTP handler's pre-check uses it — the loop still decides with `get`, so the bytes sent to the provider and the check that let them into the log come from the same read. A `get` or `stat` that returns something other than an object is treated as not found.
138
145
  - **Forks and cleanup.** `fork` copies events, not blobs; a forked session points at its parent's blobs. If you delete a parent session's blobs, references in its forks show as unavailable.
139
146
  - **Only images.** Video and audio stay inline for now. The model has no separate "look again" tool: `recall({ seq })` brings back a folded message, and its result keeps the reference, so nothing is stored twice.
140
147
  - **Paths without a `runLoop`.** The TanStack AI adapter neither checks nor loads blobs: a reference becomes `[image unavailable]` there (recorded `lossy`), and references in tool results are replaced with that text before they are logged. Hosts that call `toRequest` directly must call `hydrateImageRefs` themselves.
@@ -143,11 +150,13 @@ An image can also be a reference: `{ type: "image", mime, blobId }`. The bytes l
143
150
 
144
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`).
145
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
+
146
155
  ## Guarantees worth knowing
147
156
 
148
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.
149
158
  - **Fail-closed reads.** An event type the registry does not know, or a version it cannot upgrade, is rejected before anything is written.
150
- - **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.
151
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).
152
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.
153
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`.
@@ -506,6 +506,14 @@ interface BlobStore {
506
506
  start: number;
507
507
  end: number;
508
508
  }): Promise<Uint8Array>;
509
+ /**
510
+ * 可选:只取元信息、不读字节(对象存储上省一次整份下载)。合同:
511
+ * - 不存在必须抛 `StoreError("not_found")`,与 `get` 同一语义——**不能返回 null**(返回非对象会被当 not_found 处理,但请照合同写)
512
+ * - 返回值必须与 `get(id).meta` 逐字段一致(宿主若读独立登记表,登记表须与对象同批写入)
513
+ *
514
+ * 目前只有 server 的 HTTP 预校验用它;循环内写进日志前的最终裁决仍按 `get`,与发给厂商的字节出自同一次读取
515
+ */
516
+ stat?(id: string): Promise<BlobMeta>;
509
517
  }
510
518
  /**
511
519
  * 记忆后端:一个极简的文本 KV,键是路径。
@@ -670,7 +678,10 @@ interface Tool<TInput = unknown> {
670
678
  maxTokens?: number;
671
679
  overflow: "truncate" | "spill";
672
680
  };
673
- /** 执行前是否要人审批。循环内置兜底:为真且没有任何 Socket 做主时,直接转审批暂停(安全默认值) */
681
+ /**
682
+ * 执行前是否要人审批。循环内置兜底:为真且没有任何 Socket 做主时,直接转审批暂停(安全默认值)。
683
+ * 函数形态抛错按拒绝处理:不执行,落 isError 结果 "Approval check failed: …",原因另记一条模型不可见的 core.error(category "host"、detail.phase "needsApproval")
684
+ */
674
685
  needsApproval?: boolean | ((input: TInput, ctx: ToolContext) => Promise<boolean> | boolean);
675
686
  risk?: "low" | "medium" | "high";
676
687
  /**
@@ -701,6 +712,12 @@ type ToolResultDraft = EventDraft<"core.tool_result", ToolResultPayload>;
701
712
  /** beforeModel 的返回:改投影、增删工具、换系统提示;缺省字段表示不改 */
702
713
  interface BeforeModelPatch {
703
714
  events?: Event[];
715
+ /**
716
+ * 本轮工具表(整体替换)。⚠️ 补丁加进来的工具只活在调过 beforeModel 的模型轮里:续跑补齐 pending 调用发生在任何
717
+ * 模型轮之前,用的是基础工具表(宿主工具 + Socket 静态 `tools`),补丁工具不在场——被审批暂停的补丁工具批准后不执行,落
718
+ * "Tool not available on resume: …",补丁加的客户端工具也不进 `run_paused.awaiting`。需要审批或由客户端执行的工具必须走
719
+ * Socket 的静态 `tools` 贡献(可以是按运行环境算一次的函数),不要靠这里加(全景图决策「补丁工具不跨暂停」)。
720
+ */
704
721
  tools?: Tool[];
705
722
  systemPrompt?: string;
706
723
  /**
@@ -775,13 +792,17 @@ interface TurnContext {
775
792
  * 超过它库就按阈值自动折叠最旧的轮次(感知用同一函数校准、据此提醒模型)
776
793
  */
777
794
  targetTokens: number;
778
- /** 本轮投影的估算 token */
795
+ /**
796
+ * 本轮投影的估算 token(beforeModel 补丁之前)。注意与固定开销口径不同:开销按补丁与注入**之后**送出视图的估算校准
797
+ * (`budget_usage.contextEstimate`)。宿主 Socket 若每轮用 `patch.events` 剔掉同样的内容,
798
+ * "used + contextOverheadOf" 会稳定高估被剔掉的那一部分(感知读数、到线请求、阈值兜底同此)
799
+ */
779
800
  used: number;
780
801
  /** 本次 run 累计消耗(输入 + 输出) */
781
802
  tokensSpent: number;
782
803
  turns: number;
783
804
  toolCalls: number;
784
- /** 距 run 开始的毫秒数;beforeModel 时是本轮开始的读数,模型调用后更新 */
805
+ /** 距 run 开始的毫秒数;beforeModel 时是本轮开始的读数,模型调用后更新,onTurnEnd 前再刷新一次(含本轮工具耗时) */
785
806
  wallMs: number;
786
807
  /**
787
808
  * 最近一次模型请求的真实用量(B8):beforeModel 时是上一次请求的(含上次 run,从日志最后一条 budget_usage 读),
@@ -1023,7 +1044,10 @@ interface LoopConfig {
1023
1044
  * 缺省 100。
1024
1045
  */
1025
1046
  maxTurns?: number;
1026
- /** 宿主中止:当前请求停止后以 paused(host) 返回,已产出的内容仍入日志 */
1047
+ /**
1048
+ * 宿主中止:当前请求停止后暂停(工具批里还有没轮到的调用时不进 onTurnEnd;批里另有审批 / 客户端工具中断时 reason 随它,否则 paused(host)),已产出的内容仍入日志。
1049
+ * 原因是 `RunStop` 时 pending 全部收尾成"没执行";其它原因下工具批里没轮到的调用留 pending 补跑,被掐断的模型响应里的调用收尾成"响应被中断"
1050
+ */
1027
1051
  signal?: AbortSignal;
1028
1052
  /**
1029
1053
  * 模型调用遇到瞬断(连接被掐、超时、过载 / 限流 / 5xx)时的有限重试,缺省最多 3 次尝试、1s 起翻倍退避。
@@ -1043,7 +1067,11 @@ interface LoopConfig {
1043
1067
  * 不传也能续跑(同一 sessionId 再跑一次),只是少了这层校验。
1044
1068
  */
1045
1069
  resume?: SerializedRunState;
1046
- /** 宿主给 pending 调用的审批结论,先记成 approval_decision 再执行;指向非 pending 调用即拒绝 */
1070
+ /**
1071
+ * 宿主给**正在等审批**的调用(有 approval_request、还没有结论)的审批结论,先记成 approval_decision 再执行。
1072
+ * 指向不在等审批的调用(不 pending、或从没发出审批请求)、或同一调用给了两条,即抛 RunStateError("unknown_tool_call")、不写日志
1073
+ * (`assertDecisionsAwaitApproval`)。要取消一个没在等审批的 pending 调用,用停止(`RunStop`)
1074
+ */
1047
1075
  decisions?: readonly ApprovalDecisionInput[];
1048
1076
  /** 状态签名密钥。给了就签发与校验;没给则状态不签名、恢复不验签(只适合可信环境) */
1049
1077
  secret?: string;
@@ -1214,7 +1242,8 @@ declare function contextTokensOf(usage: TokenUsage): number;
1214
1242
  declare function contextOverheadOf(timeline: readonly Event[]): number;
1215
1243
  /**
1216
1244
  * 用量是事件,宿主可按会话或用户聚合出配额(库不做配额)。
1217
- * `contextEstimate`(B8):这次请求投影的估算 token(= 当轮 TurnContext.budget.used),与真实用量放在同一条事件里,
1245
+ * `contextEstimate`(B8):这次请求**真正送出视图**的估算 token(beforeModel 补丁与注入之后;全库审查 2026-11-25 #20 起,
1246
+ * 此前取投影那一刻的 TurnContext.budget.used,注入的大快照会被算成开销、下一轮再估一遍),与真实用量放在同一条事件里,
1218
1247
  * 感知模块用"真实上下文 − 估算"得到系统提示、工具表、thinking 等估算不含的固定开销,校准下一轮的使用率读数。
1219
1248
  * `remaining` 预留给宿主 / 适配器自己追加的聚合用量;循环不填(上限属于 brain budget 模块,循环不知道)。
1220
1249
  */
@@ -1354,4 +1383,4 @@ type ExtEvent = Event<`ext.${string}`, unknown>;
1354
1383
  /** 日志里可能出现的任何事件 */
1355
1384
  type AnyEvent = CoreEvent | ExtEvent;
1356
1385
 
1357
- 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 };