@reinsjs/core 0.7.0 → 0.9.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,29 @@
1
1
  # @reinsjs/core
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 179f891: Video and audio content parts.
8
+
9
+ - core: `ContentPart` gains `VideoPart` (`type: "video"`) and `AudioPart` (`type: "audio"`): `mime` must start with `video/` / `audio/`, base64 `data`, optional `durationSec` (finite, positive). `LoweringCapabilities` gains optional `video` / `audio`; absent means the model does not take them. Token estimates follow duration (100 / s for video, 32 / s for audio); without `durationSec` the byte size is converted at 1 Mbps / 64 kbps with a 30-second floor. `isContentPart` checks the new parts and is now also what `runLoop` uses to validate input — which also means `runLoop` input now rejects a `tool_reference` part whose `inputSchema` is an array (tool results already did). A tool returning an array of video / audio-shaped parts now yields media parts instead of JSON text. The budget-truncation summary writes `[video]` / `[audio]` / `[tool <name>]` instead of `[image]` for non-image parts. No `schemaVersion` bump: existing logs read unchanged, but a log containing video or audio parts cannot be read by an older version.
10
+ - lowering-fetch: new `video` / `audio` model options (default `false`, including every built-in model). When on, video and audio travel in each protocol's image slot — a relay dialect official endpoints reject; `input_audio` is deliberately not used. When off, they become placeholder text and the event is `lossy`. Chat lifts video / audio from tool results like images; a result with images only lowers byte-for-byte as before. Fix: `deepseek-v4-pro` is text-only (`images: false`) — the built-in table and `deepseek()` used to claim images, which the provider silently dropped.
11
+ - lowering-pi: video / audio parts become placeholder text (`lossy`); pi-ai has no such content.
12
+ - server: the HTTP whitelist accepts `video` / `audio` parts with the same shape rules as core.
13
+ - adapter-tanstack-ai: data-sourced video / audio parts translate both ways (TanStack has no duration field). URL-sourced parts are now reported in `dropped` as `audio(url)` / `video(url)` instead of `audio` / `video`, and data parts whose mime type does not match their kind as `video(<mime>)` / `audio(<mime>)`. Imported client parts are now checked with core's `isContentPart`: a malformed one (missing `mimeType`, non-string `value`, non-string text) becomes a placeholder reported in `dropped` instead of throwing or reaching the log.
14
+ - ui-agui: video / audio parts become `[video <mime>]` / `[audio <mime>]` placeholders, recorded in `dropped`.
15
+ - tools-mcp: MCP `audio` blocks and `video/*` / `audio/*` embedded resources become audio / video parts instead of descriptions.
16
+
17
+ ## 0.8.0
18
+
19
+ ### Minor Changes
20
+
21
+ - 54fed37: Sockets can now see the current tool batch. `TurnContext.batch` (`ToolBatch`) lists the batch's tool calls, the results logged so far (in `beforeTool`, only those of earlier calls), the ids left waiting for approval, a client result or 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. core also exports `ToolResultEvent` and `toolBatchOf(timeline, pending)`, which locates the batch of leftover calls. **`batch` is a required field**: a host that builds `TurnContext` objects itself (for example in socket unit tests) or runs its own copy of `runLoop` must fill it.
22
+
23
+ brain adds two opt-in sockets. `haltOnFailure({ counts?, applies? })` holds back the later calls of a batch once an earlier one failed or is still waiting: each gets an error result naming that call, and nothing runs. Register it first. `stopAfter({ tools })` ends the run (`done`) at the end of a turn in which the model successfully called one of `tools`, when nothing else in the batch failed or is pending. A batch resumed after an approval also ends the run, unless the resumed run brought new user input. Register it after `handoff()` and before `compact()` / `budget()`.
24
+
25
+ adapter-tanstack-ai fills `ctx.batch`. Because the engine checks a whole batch before running any of it, `beforeTool` sees no results from the same batch and `held` stays empty. A resumed batch gets no `onTurnEnd` on this path.
26
+
3
27
  ## 0.7.0
4
28
 
5
29
  ### Minor Changes
package/README.md CHANGED
@@ -76,9 +76,17 @@ const deploy = defineTool<{ env: "staging" | "prod" }>({
76
76
 
77
77
  A tool can also *be* another agent: return `subagentPause(...)` from `execute` and the run pauses with `Interruption { kind: "subagent" }`, carrying the child session's own interruptions and state. `@reinsjs/agent` ships `asTool(agent, opts)` on top of this.
78
78
 
79
+ ## Media: images, video and audio
80
+
81
+ 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.
82
+
83
+ - **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.
84
+ - **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`.
85
+ - **They stay in the log.** Media `data` is stored in the event like an image (append-only, never spilled) and is re-sent on every turn while it is in view. Cap the size and length of clips on your side; the model can fold what it has watched with `compact` and get it back with `recall`.
86
+
79
87
  ## Sockets
80
88
 
81
- 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.
89
+ 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`).
82
90
 
83
91
  ## Guarantees worth knowing
84
92
 
@@ -214,4 +214,4 @@ export {
214
214
  CORE_SCHEMAS,
215
215
  createCoreRegistry
216
216
  };
217
- //# sourceMappingURL=chunk-63AJKR7J.js.map
217
+ //# sourceMappingURL=chunk-GWU2JSFA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/events/base.ts","../src/events/id.ts","../src/events/create.ts","../src/events/registry.ts"],"sourcesContent":["/**\n * 事件基础类型(技术方案 §4)。\n *\n * 宪法二:时间线是唯一真源,角色只是翻译。内部只有一种数据 —— 带发起者的事件。\n * 本文件只定义\"所有事件共有的壳\",具体载荷见 ./core.ts(内置 core.*)与宿主自定义的 ext.*。\n */\n\n/** 事件发起者。用户打断、脑子注入、宿主插话都只是不同 actor 的一次 append。 */\nexport type Actor = \"user\" | \"model\" | \"tool\" | \"system\" | \"host\"\n\n/**\n * 信任等级,供投影层与安全网判断\"这段内容能不能当指令\"。\n * - principal:主事人(用户)说的\n * - system:库或宿主注入的\n * - model:模型自己产出的\n * - untrusted:工具输出、外部抓取内容(默认值,防提示注入)\n */\nexport type Trust = \"principal\" | \"system\" | \"model\" | \"untrusted\"\n\n/** 来源:哪个工具、哪个 URL、哪个用户。用于审计与信任判断。 */\nexport interface Provenance {\n source: string\n ref?: string\n}\n\n/**\n * 所有事件的公共字段。\n * 载荷放在 payload 下(而不是平铺),这样 schema 升级函数只碰 payload,壳永远稳定。\n */\nexport interface EventBase {\n /** uuidv7,时间有序;会话内唯一。fork 复制的事件保留原 id,以维持 parentId / pinsKept 等引用 */\n id: string\n sessionId: string\n /** 会话内单调递增,从 1 起;是会话内排序的唯一依据 */\n seq: number\n /** Unix 毫秒 */\n at: number\n /** 命名空间化:内置 \"core.*\",宿主扩展 \"ext.*\" */\n type: string\n /** 该 type 自己的 schema 版本,从 1 起;读时按注册表升级(P9) */\n schemaVersion: number\n actor: Actor\n /** 因果链或分叉点:回答哪条消息、由哪次 tool_call 产生 */\n parentId?: string\n trust: Trust\n provenance?: Provenance\n /** 厂商专有回放数据(thinking signature、encrypted reasoning),不进通用字段 */\n replay?: Record<string, unknown>\n}\n\n/** 带类型载荷的事件。T 为 type 字面量,P 为 payload 形状。 */\nexport type Event<T extends string = string, P = unknown> = EventBase & {\n type: T\n payload: P\n}\n\n/**\n * 内容片段。用户消息、工具结果都由它组成;投影/降级时再翻译成各家 API 的 content block。\n * 文本、图片、视频、音频,以及\"工具定义引用\"(L1);大结果不塞进片段,走 tool_result.spilled 外溢到 BlobStore。\n *\n * 消费片段的地方一律逐类型显式分支、末尾 `const _exhaustive: never = p` 收口——\n * \"不是文本就当图片\"的 else 兜底会让新加的片段类型悄悄落进图片分支(2026-11-05 视频 / 音频方案)。\n */\nexport type ContentPart = TextPart | ImagePart | VideoPart | AudioPart | ToolReferencePart\n\nexport interface TextPart {\n type: \"text\"\n text: string\n}\n\nexport interface ImagePart {\n type: \"image\"\n mime: string\n /** base64 编码的图片字节 */\n data: string\n}\n\n/**\n * 视频片段(2026-11-05,OnSet 建议 12)。音轨算视频的一部分,不另要 `audio` 能力位;纯音频文件用 AudioPart。\n * 模型收不收看 `LoweringCapabilities.video`,不收时降级层落文字占位并记 lossy。\n */\nexport interface VideoPart {\n type: \"video\"\n /** 必须以 \"video/\" 开头 */\n mime: string\n /** base64 编码的文件字节 */\n data: string\n /** 时长(秒,有限正数);只用于 token 估算,没有时按字节折算(偏高)。宿主拿得到就该给 */\n durationSec?: number\n}\n\n/** 音频片段(2026-11-05)。模型收不收看 `LoweringCapabilities.audio` */\nexport interface AudioPart {\n type: \"audio\"\n /** 必须以 \"audio/\" 开头 */\n mime: string\n /** base64 编码的文件字节 */\n data: string\n /** 时长(秒,有限正数);只用于 token 估算,没有时按字节折算(偏高) */\n durationSec?: number\n}\n\n/**\n * 工具定义引用(L1,2026-09-15):`tool_find` 这类\"取回工具\"的结果用它表达\"这几件工具从现在起可用\"。\n * 带完整定义快照,日志自足(宪法二:模型可见的一切都在日志里);翻译时按能力分两路——\n * 支持原生延迟加载的线(Anthropic `defer_loading`)只发 `tool_reference` 块、由厂商就地展开、工具表整段不变;\n * 其余线用 `renderToolReference` 展开成文本,信息等价。宿主经 HTTP 送来的用户消息不接受这种段(server 白名单)。\n */\nexport interface ToolReferencePart {\n type: \"tool_reference\"\n name: string\n description: string\n /** JSON Schema 对象,与 Tool.inputSchema 同形 */\n inputSchema: Record<string, unknown>\n}\n\n/** 引用段展开成文本的唯一写法:非原生线的降级层、UI、投影估算都调它,别各自拼 */\nexport function renderToolReference(part: ToolReferencePart): string {\n return `### ${part.name}\\n${part.description.trim()}\\nInput schema: ${JSON.stringify(part.inputSchema)}`\n}\n\n/** 各 actor 的默认信任等级;工厂函数在未显式给出 trust 时使用。 */\nexport const DEFAULT_TRUST: Readonly<Record<Actor, Trust>> = {\n user: \"principal\",\n system: \"system\",\n host: \"system\",\n model: \"model\",\n tool: \"untrusted\",\n}\n","/**\n * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。\n * 只用 Web 标准 crypto.getRandomValues,不引依赖(P5)。\n *\n * 同一毫秒内的多个 id 之间顺序随机 —— 会话内排序以 seq 为准,id 只需全局唯一且大致有序。\n */\nexport function uuidv7(now: number = Date.now()): string {\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n\n // 48 位时间戳,大端写入 bytes[0..5]\n let ts = now\n for (let i = 5; i >= 0; i--) {\n bytes[i] = ts & 0xff\n ts = Math.floor(ts / 256)\n }\n // 版本位:byte6 高 4 位 = 0111\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x70\n // 变体位:byte8 高 2 位 = 10\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80\n\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n","/**\n * 事件工厂:补齐 id / at / schemaVersion / trust,调用方只关心\"谁、在哪个会话、第几条、说了什么\"。\n * seq 由 EventLog 的 append 方决定(T4),这里要求显式传入,不替存储层做主。\n */\nimport { type Actor, DEFAULT_TRUST, type Event, type EventBase, type Provenance, type Trust } from \"./base.js\"\nimport type { CoreEventOf, CoreEventPayloads, CoreEventType } from \"./core.js\"\nimport { uuidv7 } from \"./id.js\"\nimport type { EventSchemaRegistry } from \"./registry.js\"\n\n/**\n * 事件草稿:还没进日志的事件,缺 id / seq / at / sessionId / schemaVersion。\n * 降级层(模型输出)与脑子模块(注入的 system_note)都只产出草稿,由循环补齐后 append ——\n * 谁分配 seq 只有循环知道,草稿不替它做主。\n */\nexport interface EventDraft<T extends string = string, P = unknown> {\n type: T\n payload: P\n actor: Actor\n /** 缺省按 DEFAULT_TRUST[actor] */\n trust?: Trust\n parentId?: string\n provenance?: Provenance\n replay?: Record<string, unknown>\n}\n\n/** 内置事件的草稿联合,type 与 payload 联动 */\nexport type CoreEventDraft = { [T in CoreEventType]: EventDraft<T, CoreEventPayloads[T]> }[CoreEventType]\n\nexport interface CreateEventInput<T extends string, P> extends EventDraft<T, P> {\n sessionId: string\n seq: number\n /** 测试注入用;缺省 Date.now() */\n at?: number\n id?: string\n}\n\n/**\n * 通用工厂。schemaVersion 从注册表取当前版本,所以未登记的 type 会在这里就被拒绝,\n * 而不是写进日志后读不出来。\n */\nexport function createEvent<T extends string, P>(\n registry: EventSchemaRegistry,\n input: CreateEventInput<T, P>,\n): Event<T, P> {\n const at = input.at ?? Date.now()\n const base: EventBase = {\n id: input.id ?? uuidv7(at),\n sessionId: input.sessionId,\n seq: input.seq,\n at,\n type: input.type,\n schemaVersion: registry.currentVersion(input.type),\n actor: input.actor,\n trust: input.trust ?? DEFAULT_TRUST[input.actor],\n }\n // 可选字段只在有值时写入,避免日志里出现一堆 undefined(exactOptionalPropertyTypes 也不允许)\n if (input.parentId !== undefined) base.parentId = input.parentId\n if (input.provenance !== undefined) base.provenance = input.provenance\n if (input.replay !== undefined) base.replay = input.replay\n return { ...base, type: input.type, payload: input.payload }\n}\n\n/** 内置事件的强类型版本:type 与 payload 联动校验。 */\nexport function createCoreEvent<T extends CoreEventType>(\n registry: EventSchemaRegistry,\n input: CreateEventInput<T, CoreEventPayloads[T]>,\n): CoreEventOf<T> {\n return createEvent(registry, input) as CoreEventOf<T>\n}\n","/**\n * 事件 schema 注册表(P9:schema 有版本,读时升级,查不到即拒绝)。\n *\n * 职责:\n * 1. 登记每个 type 的当前版本与逐级升级函数 upcast(v → v+1)\n * 2. read(raw):校验壳字段 → 查 type → 逐级升级到当前版本 → 返回类型化事件\n * 3. 任何一步查不到都抛 SchemaError(fail-closed),绝不静默返回半个事件\n *\n * 日志文件不做原地迁移:存的永远是写入时的版本,读时升级。\n */\nimport type { Actor, Event, EventBase, Trust } from \"./base.js\"\nimport type { CoreEventType } from \"./core.js\"\n\n/** 把 payload 从版本 from 升到 from+1。只碰 payload,壳字段由注册表保证不变。 */\nexport type Upcaster = (payload: unknown) => unknown\n\nexport interface EventSchema {\n type: string\n /** 当前版本;新写入的事件一律打这个版本号 */\n version: number\n /**\n * 升级函数表,键为\"起点版本\":upcasters[1] 把 v1 升到 v2。\n * version 为 n 时必须覆盖 1..n-1 全部键,缺一个即注册失败 —— 宁可启动时报错,不要读到一半才发现。\n */\n upcasters?: Readonly<Record<number, Upcaster>>\n}\n\nexport type SchemaErrorCode =\n | \"malformed_base\" // 壳字段缺失或类型不对\n | \"unknown_type\" // 没登记的 type\n | \"future_version\" // 版本比注册表还新(旧代码读新日志)\n | \"missing_upcaster\" // 升级链断了\n | \"upcaster_failed\" // 升级函数自己抛了\n | \"invalid_schema\" // 登记时的定义不合法\n\nexport class SchemaError extends Error {\n constructor(\n readonly code: SchemaErrorCode,\n message: string,\n readonly context: { type?: string; version?: number } = {},\n ) {\n super(`[${code}] ${message}`)\n this.name = \"SchemaError\"\n }\n}\n\nconst ACTORS: ReadonlySet<string> = new Set<Actor>([\"user\", \"model\", \"tool\", \"system\", \"host\"])\nconst TRUSTS: ReadonlySet<string> = new Set<Trust>([\"principal\", \"system\", \"model\", \"untrusted\"])\n\nexport class EventSchemaRegistry {\n private readonly schemas = new Map<string, EventSchema>()\n\n constructor(schemas: Iterable<EventSchema> = []) {\n for (const s of schemas) this.register(s)\n }\n\n /** 登记一个 type。重复登记同一 type 视为错误,避免两处定义互相覆盖。 */\n register(schema: EventSchema): this {\n if (!schema.type || !/^(core|ext)\\.[a-z][a-z0-9_]*$/.test(schema.type)) {\n throw new SchemaError(\n \"invalid_schema\",\n `type must look like \"core.xxx\" or \"ext.xxx\", got ${schema.type}`,\n {\n type: schema.type,\n },\n )\n }\n if (!Number.isInteger(schema.version) || schema.version < 1) {\n throw new SchemaError(\"invalid_schema\", `version must be an integer >= 1, got ${schema.version}`, {\n type: schema.type,\n version: schema.version,\n })\n }\n if (this.schemas.has(schema.type)) {\n throw new SchemaError(\"invalid_schema\", `type already registered: ${schema.type}`, {\n type: schema.type,\n })\n }\n for (let v = 1; v < schema.version; v++) {\n if (typeof schema.upcasters?.[v] !== \"function\") {\n throw new SchemaError(\n \"invalid_schema\",\n `${schema.type} is at version ${schema.version} but has no v${v} -> v${v + 1} upgrade function`,\n { type: schema.type, version: v },\n )\n }\n }\n this.schemas.set(schema.type, schema)\n return this\n }\n\n has(type: string): boolean {\n return this.schemas.has(type)\n }\n\n /** 该 type 当前应写入的版本号;未登记则抛 unknown_type。 */\n currentVersion(type: string): number {\n const s = this.schemas.get(type)\n if (!s) throw new SchemaError(\"unknown_type\", `unregistered event type: ${type}`, { type })\n return s.version\n }\n\n /**\n * 从存储读出的原始对象 → 当前版本的事件。\n * 泛型只是给调用方的类型提示(如 read<CoreEvent>),运行时校验的是壳与版本,不校验 payload 形状 ——\n * payload 的正确性由写入方与升级函数负责。\n */\n read<E extends Event = Event>(raw: unknown): E {\n const base = assertBase(raw)\n const schema = this.schemas.get(base.type)\n if (!schema) {\n throw new SchemaError(\"unknown_type\", `unregistered event type: ${base.type}`, { type: base.type })\n }\n if (base.schemaVersion > schema.version) {\n throw new SchemaError(\n \"future_version\",\n `${base.type} v${base.schemaVersion} is newer than the locally known v${schema.version}; upgrade the code`,\n { type: base.type, version: base.schemaVersion },\n )\n }\n\n let payload = (raw as { payload?: unknown }).payload\n for (let v = base.schemaVersion; v < schema.version; v++) {\n const up = schema.upcasters?.[v]\n if (!up) {\n // register() 已保证不会走到这里,留作防御\n throw new SchemaError(\"missing_upcaster\", `${base.type} has no v${v} -> v${v + 1} upgrade function`, {\n type: base.type,\n version: v,\n })\n }\n try {\n payload = up(payload)\n } catch (cause) {\n throw new SchemaError(\n \"upcaster_failed\",\n `${base.type} v${v} -> v${v + 1} upgrade failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n { type: base.type, version: v },\n )\n }\n }\n\n return { ...base, schemaVersion: schema.version, payload } as E\n }\n}\n\n/** 校验壳字段。只看公共字段,payload 不管。 */\nfunction assertBase(raw: unknown): EventBase {\n if (typeof raw !== \"object\" || raw === null) {\n throw new SchemaError(\"malformed_base\", \"event must be an object\")\n }\n const r = raw as Record<string, unknown>\n const fail = (field: string, expect: string): never => {\n throw new SchemaError(\n \"malformed_base\",\n `field ${field} must be ${expect}`,\n typeof r.type === \"string\" ? { type: r.type } : {},\n )\n }\n if (typeof r.id !== \"string\" || r.id === \"\") fail(\"id\", \"a non-empty string\")\n if (typeof r.sessionId !== \"string\" || r.sessionId === \"\") fail(\"sessionId\", \"a non-empty string\")\n if (!Number.isInteger(r.seq) || (r.seq as number) < 1) fail(\"seq\", \"an integer >= 1\")\n if (typeof r.at !== \"number\" || !Number.isFinite(r.at)) fail(\"at\", \"a finite number\")\n if (typeof r.type !== \"string\" || r.type === \"\") fail(\"type\", \"a non-empty string\")\n if (!Number.isInteger(r.schemaVersion) || (r.schemaVersion as number) < 1)\n fail(\"schemaVersion\", \"an integer >= 1\")\n if (typeof r.actor !== \"string\" || !ACTORS.has(r.actor)) fail(\"actor\", \"user|model|tool|system|host\")\n if (typeof r.trust !== \"string\" || !TRUSTS.has(r.trust)) fail(\"trust\", \"principal|system|model|untrusted\")\n if (r.parentId !== undefined && typeof r.parentId !== \"string\") fail(\"parentId\", \"a string or undefined\")\n if (r.provenance !== undefined) {\n const p = r.provenance as Record<string, unknown> | null\n if (typeof p !== \"object\" || p === null || typeof p.source !== \"string\")\n fail(\"provenance\", \"{ source: string }\")\n }\n if (r.replay !== undefined && (typeof r.replay !== \"object\" || r.replay === null))\n fail(\"replay\", \"an object or undefined\")\n return r as unknown as EventBase\n}\n\n/** 全部内置事件当前都是 v1。升版本时在此加 upcasters,并在 core.ts 改载荷类型。 */\nexport const CORE_SCHEMAS: readonly EventSchema[] = (\n [\n \"core.user_message\",\n \"core.model_text\",\n \"core.model_thinking\",\n \"core.tool_call\",\n \"core.tool_result\",\n \"core.system_note\",\n \"core.approval_request\",\n \"core.approval_decision\",\n \"core.compaction\",\n \"core.handoff\",\n \"core.memory_op\",\n \"core.budget_usage\",\n \"core.run_paused\",\n \"core.run_resumed\",\n \"core.tools_bound\",\n \"core.error\",\n ] satisfies CoreEventType[]\n).map((type) => ({ type, version: 1 }))\n\n/** 预装了全部 core.* 的注册表。宿主要加 ext.* 时 new 一个并传入 [...CORE_SCHEMAS, ...自己的]。 */\nexport function createCoreRegistry(extra: Iterable<EventSchema> = []): EventSchemaRegistry {\n return new EventSchemaRegistry([...CORE_SCHEMAS, ...extra])\n}\n"],"mappings":";AAqHO,SAAS,oBAAoB,MAAiC;AACnE,SAAO,OAAO,KAAK,IAAI;AAAA,EAAK,KAAK,YAAY,KAAK,CAAC;AAAA,gBAAmB,KAAK,UAAU,KAAK,WAAW,CAAC;AACxG;AAGO,IAAM,gBAAgD;AAAA,EAC3D,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AACR;;;AC1HO,SAAS,OAAO,MAAc,KAAK,IAAI,GAAW;AACvD,QAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,SAAO,gBAAgB,KAAK;AAG5B,MAAI,KAAK;AACT,WAAS,IAAI,GAA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AU,YAAY,CAAC,OAAO,IAAI,EAAE,KAAK,EAAG,MAAK,SAAS,kCAAkC;AACzG,MAAI,EAAE,aAAa,UAAa,OAAO,EAAE,aAAa,SAAU,MAAK,YAAY,uBAAuB;AACxG,MAAI,EAAE,eAAe,QAAW;AAC9B,UAAM,IAAI,EAAE;AACZ,QAAI,OAAO,MAAM,YAAY,MAAM,QAAQ,OAAO,EAAE,WAAW;AAC7D,WAAK,cAAc,oBAAoB;AAAA,EAC3C;AACA,MAAI,EAAE,WAAW,WAAc,OAAO,EAAE,WAAW,YAAY,EAAE,WAAW;AAC1E,SAAK,UAAU,wBAAwB;AACzC,SAAO;AACT;AAGO,IAAM,eACX;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,EACA,IAAI,CAAC,UAAU,EAAE,MAAM,SAAS,EAAE,EAAE;AAG/B,SAAS,mBAAmB,QAA+B,CAAC,GAAwB;AACzF,SAAO,IAAI,oBAAoB,CAAC,GAAG,cAAc,GAAG,KAAK,CAAC;AAC5D;","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EventLog, a as Event, b as EventSchemaRegistry, B as BlobStore, M as MemoryStore, c as EventDraft, T as TokenUsage, C as ContentPart, d as Trust, L as Lowering, e as ModelRef, f as LoweringCapabilities, g as CoreEventOf, h as ToolResultPayload, i as LoweringDelta, j as LandingRecord, k as LoweredRequest, l as ErrorPayload, A as ApprovalRequestPayload, m as ToolCallPayload, n as ToolSpec, o as CoreEventDraft, p as BudgetUsagePayload, q as BlobMeta, R as ReadOptions, r as RunLease, S as Stores } from './types-DrzC9Mfc.js';
2
- export { s as Actor, t as AnyEvent, u as ApprovalDecisionPayload, v as BoundModel, w as CORE_SCHEMAS, x as CompactionPayload, y as CoreEvent, z as CoreEventPayloads, D as CoreEventType, F as CreateEventInput, G as DEFAULT_TRUST, H as EventBase, I as EventSchema, J as ExtEvent, K as HandoffPayload, N as ImagePart, O as LandingSpec, P as LossKind, Q as LossMatrix, U as LoweringOutcome, V as LoweringStreamContext, W as MemoryOpPayload, X as ModelTextPayload, Y as ModelThinkingPayload, Z as Provenance, _ as RunPausedPayload, $ as RunResumedPayload, a0 as SchemaError, a1 as SchemaErrorCode, a2 as SkillSource, a3 as SystemNotePayload, a4 as TextPart, a5 as ToRequestInput, a6 as ToolReferencePart, a7 as ToolsBoundPayload, a8 as Upcaster, a9 as UserMessagePayload, aa as contextOverheadOf, ab as contextTokensOf, ac as createCoreEvent, ad as createCoreRegistry, ae as createEvent, af as lossesOf, ag as renderToolReference } from './types-DrzC9Mfc.js';
1
+ import { E as Event, a as EventSchemaRegistry, b as EventLog, B as BlobStore, M as MemoryStore, c as EventDraft, T as TokenUsage, C as ContentPart, d as Trust, L as Lowering, e as ModelRef, f as LoweringCapabilities, g as CoreEventOf, h as ToolResultPayload, i as LoweringDelta, j as LandingRecord, k as LoweredRequest, l as ErrorPayload, A as ApprovalRequestPayload, m as ToolCallPayload, n as ToolSpec, o as CoreEventDraft, p as BudgetUsagePayload, q as BlobMeta, R as ReadOptions, r as RunLease, S as Stores } from './types-BlyGZlJp.js';
2
+ export { s as Actor, t as AnyEvent, u as ApprovalDecisionPayload, v as AudioPart, w as BoundModel, x as CORE_SCHEMAS, y as CompactionPayload, z as CoreEvent, D as CoreEventPayloads, F as CoreEventType, G as CreateEventInput, H as DEFAULT_TRUST, I as EventBase, J as EventSchema, K as ExtEvent, N as HandoffPayload, O as ImagePart, P as LandingSpec, Q as LossKind, U as LossMatrix, V as LoweringOutcome, W as LoweringStreamContext, X as MemoryOpPayload, Y as ModelTextPayload, Z as ModelThinkingPayload, _ as Provenance, $ as RunPausedPayload, a0 as RunResumedPayload, a1 as SchemaError, a2 as SchemaErrorCode, a3 as SkillSource, a4 as SystemNotePayload, a5 as TextPart, a6 as ToRequestInput, a7 as ToolReferencePart, a8 as ToolsBoundPayload, a9 as Upcaster, aa as UserMessagePayload, ab as VideoPart, ac as contextOverheadOf, ad as contextTokensOf, ae as createCoreEvent, af as createCoreRegistry, ag as createEvent, ah as lossesOf, ai as renderToolReference } from './types-BlyGZlJp.js';
3
3
 
4
4
  /**
5
5
  * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
@@ -9,58 +9,6 @@ export { s as Actor, t as AnyEvent, u as ApprovalDecisionPayload, v as BoundMode
9
9
  */
10
10
  declare function uuidv7(now?: number): string;
11
11
 
12
- interface ForkOptions {
13
- fromSessionId: string;
14
- /** 复制 [1, atSeq],含 */
15
- atSeq: number;
16
- /** 缺省 uuidv7 */
17
- toSessionId?: string;
18
- }
19
- declare function forkSession(log: EventLog, opts: ForkOptions): Promise<{
20
- toSessionId: string;
21
- }>;
22
-
23
- interface RetryOptions {
24
- /** 最多尝试几次(含第一次)。缺省 3;1 = 不重试 */
25
- maxAttempts?: number;
26
- /** 首次重试前等多久(毫秒),之后每次翻倍。缺省 1000 */
27
- baseDelayMs?: number;
28
- /** 单次等待上限(毫秒)。缺省 8000 */
29
- maxDelayMs?: number;
30
- /** 覆盖瞬断判定:返回 true 表示值得重试。缺省见 isTransientFailure */
31
- isTransient?: (failure: ModelCallFailure) => boolean;
32
- /** 测试注入:等待实现。缺省 setTimeout,且被 signal 中止时提前结束 */
33
- sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
34
- }
35
- /** 一次模型调用失败的两种形态:降级层抛了异常,或流正常收尾但 stopReason = error */
36
- type ModelCallFailure = {
37
- kind: "thrown";
38
- error: unknown;
39
- } | {
40
- kind: "outcome";
41
- message: string;
42
- };
43
- declare const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
44
- declare const DEFAULT_RETRY_BASE_DELAY_MS = 1000;
45
- declare const DEFAULT_RETRY_MAX_DELAY_MS = 8000;
46
- /**
47
- * 从错误文案里提取 HTTP 状态码:开头的三位数字(SDK 格式 "<status> <body>"),或 "status (code) 503" / "HTTP 503" 写法。
48
- * 只认 100~599,不在这两个位置上的数字不算(正文里提到 "429" 不是状态码)
49
- */
50
- declare function statusFromMessage(message: string): number | undefined;
51
- declare function isTransientFailure(failure: ModelCallFailure): boolean;
52
- /** 第 attempt 次失败后等多久:base × 2^(attempt−1),封顶 maxDelay。不加抖动,保证可测、可回放 */
53
- declare function backoffDelayMs(attempt: number, opts?: Pick<RetryOptions, "baseDelayMs" | "maxDelayMs">): number;
54
- /** 缺省等待:setTimeout;signal 中止就立刻返回(由调用方检查 aborted 再决定怎么收尾) */
55
- declare function defaultSleep(ms: number, signal?: AbortSignal): Promise<void>;
56
- interface ResolvedRetry {
57
- maxAttempts: number;
58
- delayFor: (attempt: number) => number;
59
- isTransient: (failure: ModelCallFailure) => boolean;
60
- sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
61
- }
62
- declare function resolveRetry(opts?: RetryOptions): ResolvedRetry;
63
-
64
12
  /**
65
13
  * 投影(技术方案 §8):输入完整时间线,输出模型本轮应看到的事件。
66
14
  *
@@ -145,6 +93,47 @@ interface ProjectionResult {
145
93
  stats: ProjectionStats;
146
94
  }
147
95
 
96
+ interface RetryOptions {
97
+ /** 最多尝试几次(含第一次)。缺省 3;1 = 不重试 */
98
+ maxAttempts?: number;
99
+ /** 首次重试前等多久(毫秒),之后每次翻倍。缺省 1000 */
100
+ baseDelayMs?: number;
101
+ /** 单次等待上限(毫秒)。缺省 8000 */
102
+ maxDelayMs?: number;
103
+ /** 覆盖瞬断判定:返回 true 表示值得重试。缺省见 isTransientFailure */
104
+ isTransient?: (failure: ModelCallFailure) => boolean;
105
+ /** 测试注入:等待实现。缺省 setTimeout,且被 signal 中止时提前结束 */
106
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
107
+ }
108
+ /** 一次模型调用失败的两种形态:降级层抛了异常,或流正常收尾但 stopReason = error */
109
+ type ModelCallFailure = {
110
+ kind: "thrown";
111
+ error: unknown;
112
+ } | {
113
+ kind: "outcome";
114
+ message: string;
115
+ };
116
+ declare const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
117
+ declare const DEFAULT_RETRY_BASE_DELAY_MS = 1000;
118
+ declare const DEFAULT_RETRY_MAX_DELAY_MS = 8000;
119
+ /**
120
+ * 从错误文案里提取 HTTP 状态码:开头的三位数字(SDK 格式 "<status> <body>"),或 "status (code) 503" / "HTTP 503" 写法。
121
+ * 只认 100~599,不在这两个位置上的数字不算(正文里提到 "429" 不是状态码)
122
+ */
123
+ declare function statusFromMessage(message: string): number | undefined;
124
+ declare function isTransientFailure(failure: ModelCallFailure): boolean;
125
+ /** 第 attempt 次失败后等多久:base × 2^(attempt−1),封顶 maxDelay。不加抖动,保证可测、可回放 */
126
+ declare function backoffDelayMs(attempt: number, opts?: Pick<RetryOptions, "baseDelayMs" | "maxDelayMs">): number;
127
+ /** 缺省等待:setTimeout;signal 中止就立刻返回(由调用方检查 aborted 再决定怎么收尾) */
128
+ declare function defaultSleep(ms: number, signal?: AbortSignal): Promise<void>;
129
+ interface ResolvedRetry {
130
+ maxAttempts: number;
131
+ delayFor: (attempt: number) => number;
132
+ isTransient: (failure: ModelCallFailure) => boolean;
133
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
134
+ }
135
+ declare function resolveRetry(opts?: RetryOptions): ResolvedRetry;
136
+
148
137
  /**
149
138
  * 循环与插座的类型(技术方案 §6、§7、§10)。
150
139
  *
@@ -235,6 +224,7 @@ interface Tool<TInput = unknown> {
235
224
  };
236
225
  }
237
226
  type ToolCallEvent = CoreEventOf<"core.tool_call">;
227
+ type ToolResultEvent = CoreEventOf<"core.tool_result">;
238
228
  type ToolResultDraft = EventDraft<"core.tool_result", ToolResultPayload>;
239
229
  /** beforeModel 的返回:改投影、增删工具、换系统提示;缺省字段表示不改 */
240
230
  interface BeforeModelPatch {
@@ -321,9 +311,31 @@ interface TurnContext {
321
311
  lastUsage?: TokenUsage;
322
312
  };
323
313
  signal?: AbortSignal;
314
+ /**
315
+ * 本批工具调用的活动(2026-11-02,OnSet 建议 9 / 10):模型这次发了哪些调用、已落了哪些结果、哪些被挂起、是不是补跑。
316
+ * 同一个对象在本轮内由循环随落随更——beforeTool 处理第 k 个调用时只看得见它之前落下的结果;不要拿快照比较
317
+ */
318
+ batch: ToolBatch;
324
319
  /** 草稿:无 id / seq / at / sessionId,循环补齐后 append。beforeModel 期间 emit 的本轮即可见 */
325
320
  emit(draft: EventDraft): void;
326
321
  }
322
+ /**
323
+ * "一批" = 一段连续模型输出里的 tool_call(与 replay 切轮 `isModelOutput` 同口径,模型不可见的运维事件不切段),
324
+ * 定位规则只有一份:`toolBatchOf`。Socket 只读;循环(runLoop、TanStack 适配器)负责填。
325
+ */
326
+ interface ToolBatch {
327
+ /** 本批调用,按执行顺序。模型输出前(beforeModel)为空;补跑时是遗留调用所在那批的全部 tool_call */
328
+ readonly calls: readonly ToolCallEvent[];
329
+ /**
330
+ * 本批已落日志的 tool_result(afterTool 替换之后、真正落日志的那条),按落下顺序。
331
+ * 补跑时预置上次已落的(含宿主经 input 回填的客户端工具结果)
332
+ */
333
+ readonly results: readonly ToolResultEvent[];
334
+ /** 本批已处理但被挂起、没落结果的 toolCallId(等审批 / 等客户端回填 / 子代理暂停)。TanStack 路径恒为空(defer 让整批暂停) */
335
+ readonly held: readonly string[];
336
+ /** 本批是续跑补齐上次遗留的调用(没有新的模型输出) */
337
+ readonly resumed: boolean;
338
+ }
327
339
  /**
328
340
  * 静态贡献的运行环境(B6):run 起步时给每个 Socket 看一次,让它按"有哪些存储、给谁跑"决定带不带工具与规则。
329
341
  * 只暴露跨请求不变或整个 run 不变的东西;每轮变化的信息(视图、预算)走 TurnContext。
@@ -534,6 +546,36 @@ interface LoopConfig {
534
546
  newId?: (at: number) => string;
535
547
  }
536
548
 
549
+ /**
550
+ * 工具批的定位(2026-11-02,OnSet 建议 9 / 10)。
551
+ *
552
+ * "一批" = 一段连续模型输出里的 tool_call。与 replay 切轮(`isModelOutput`)同口径,另外跳过模型不可见的运维事件
553
+ * (budget_usage、approval_request、run_paused…)——它们可能夹在同一次输出中间(TanStack 的 onUsage 早于输出收尾时),
554
+ * 与 lowering-fetch IR"运维事件不打断 assistant 分组"同一条规矩。runLoop 与 TanStack 适配器补跑时都调它(真源索引)。
555
+ */
556
+
557
+ /**
558
+ * 遗留调用所在的那批:以第一条 pending 为锚,前后扩到不属于同一段的事件为止,收其中的 tool_call;
559
+ * 并按时间线顺序收这些调用已落的 tool_result(上次 run 已执行的、宿主经 input 回填的)。
560
+ * pending 跨多批(fork、混用两种循环才会出现)时只取第一批——其余 pending 照样会被执行,只是不在 `calls` 里。
561
+ * 纯函数;`pending` 为空返回空批
562
+ */
563
+ declare function toolBatchOf(timeline: readonly Event[], pending: readonly ToolCallEvent[]): {
564
+ calls: ToolCallEvent[];
565
+ results: ToolResultEvent[];
566
+ };
567
+
568
+ interface ForkOptions {
569
+ fromSessionId: string;
570
+ /** 复制 [1, atSeq],含 */
571
+ atSeq: number;
572
+ /** 缺省 uuidv7 */
573
+ toSessionId?: string;
574
+ }
575
+ declare function forkSession(log: EventLog, opts: ForkOptions): Promise<{
576
+ toSessionId: string;
577
+ }>;
578
+
537
579
  /**
538
580
  * runLoop:reins 的默认循环(技术方案 §2、§6、§7)。
539
581
  *
@@ -688,7 +730,13 @@ declare function defineTool<TInput>(tool: Tool<TInput>): Tool;
688
730
  declare function toolSpecOf(tool: Tool): ToolSpec;
689
731
  /** 带"声明但不载入"标记的规格(L1):runLoop 按 BeforeModelPatch.deferredTools 对本轮工具表逐件调 */
690
732
  declare function deferredToolSpecOf(tool: Tool, deferred: boolean): ToolSpec;
691
- /** 工具返回值里能认出的内容段:文本、图片、工具定义引用(L1)。宿主经 HTTP 送来的用户消息另有白名单(server),不含引用段 */
733
+ /**
734
+ * 内容片段的形状校验,全包唯一一份(真源索引):工具返回值归一(本文件)与 runLoop 输入草稿 / 片段数组(run-loop.ts)都调它。
735
+ * 坏片段一旦进日志,之后每次读到它都会崩(会话报废),所以在写之前拦。
736
+ * 规则:text 有 `text`;image 有 `mime` 与 `data`(mime 不校验,历史行为);video / audio 的 mime 以 "video/" / "audio/" 开头、
737
+ * `durationSec` 缺省或为有限正数;tool_reference 有名字、描述与对象形 inputSchema。
738
+ * 宿主经 HTTP 送来的用户消息另有白名单(server `rebuildContentParts`,两份实现靠跨包用例锁同口径),不含引用段
739
+ */
692
740
  declare function isContentPart(x: unknown): x is ContentPart;
693
741
  /**
694
742
  * execute 的返回值 → 模型看到的内容。规则按直觉:
@@ -827,7 +875,12 @@ declare function needsUntrustedMark(e: Event): boolean;
827
875
  * 供预算裁剪兜底与感知档位使用。宿主要精确数字就注入自己的 TokenEstimator。
828
876
  *
829
877
  * 规则:ASCII 字符约 4 个一个 token;非 ASCII(中日韩等)按一字一 token 保守计;
830
- * 图片按 Anthropic 单图上限附近取常量;每条事件再加角色与分隔的固定开销。
878
+ * 图片按 Anthropic 单图上限附近取常量;视频 / 音频按时长计;每条事件再加角色与分隔的固定开销。
879
+ *
880
+ * 视频 / 音频费率来源:2026-11-05 视频音频方案 P0 实测(spikes/media-parts,中转站 Gemini flash 低分辨率档)——
881
+ * 视频每秒 91 token(含音轨,与码率、画面内容无关)、音频每秒 25;取 100 / 32 留余量(32 也是 Gemini 公开音频费率)。
882
+ * 没有 durationSec 时按字节折算:码率实测相差约 60 倍,所以按偏低码率(视频 1 Mbps、音频 64 kbps)折算并设 30 秒下限,
883
+ * 宁高勿低(偏高只是整理提前,偏低会溢出)。要别的费率就注入自己的 TokenEstimator,不另加开关。
831
884
  */
832
885
 
833
886
  declare function estimateTextTokens(text: string): number;
@@ -1199,6 +1252,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
1199
1252
  */
1200
1253
 
1201
1254
  /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
1202
- declare const REINS_VERSION = "0.7.0";
1255
+ declare const REINS_VERSION = "0.9.0";
1203
1256
 
1204
- export { type ApprovalDecisionInput, ApprovalRequestPayload, type ApprovalRequestSpec, BUILTIN_APPROVAL_POLICY, type BeforeModelPatch, type BeforeToolDecision, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, type DecodedToolArguments, type DefaultChainOptions, type ErrorEventPayload, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, type HandoffIntent, INPUT_DRAFT_TYPES, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, type PauseReason, type Principal, type ProjectOptions, type ProjectionBudget, type ProjectionContext, type ProjectionResult, type ProjectionStats, type ProjectionStep, type ProjectionStepStats, type ProjectionStrategy, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, type ResolvedRetry, type RetryOptions, RunLease, type RunResult, RunStateError, type RunStateErrorCode, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, StoreError, type StoreErrorCode, Stores, type SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, type TokenEstimator, TokenUsage, type Tool, type ToolCallEvent, ToolCallPayload, type ToolContext, type ToolNamesDiff, type ToolResult, type ToolResultDraft, ToolResultPayload, type ToolSide, ToolSpec, type ToolsBoundEvent, Trust, type TurnContext, type TurnDecision, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, backoffDelayMs, budgetTruncate, computeConfigHash, computePendingDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultSleep, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDrafts, isCompaction, isContentPart, isModelOutput, isPinNote, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, statusFromMessage, subagentPause, supersededIds, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter };
1257
+ export { type ApprovalDecisionInput, ApprovalRequestPayload, type ApprovalRequestSpec, BUILTIN_APPROVAL_POLICY, type BeforeModelPatch, type BeforeToolDecision, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, type DecodedToolArguments, type DefaultChainOptions, type ErrorEventPayload, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, type HandoffIntent, INPUT_DRAFT_TYPES, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, type PauseReason, type Principal, type ProjectOptions, type ProjectionBudget, type ProjectionContext, type ProjectionResult, type ProjectionStats, type ProjectionStep, type ProjectionStepStats, type ProjectionStrategy, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, type ResolvedRetry, type RetryOptions, RunLease, type RunResult, RunStateError, type RunStateErrorCode, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, StoreError, type StoreErrorCode, Stores, type SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, type TokenEstimator, TokenUsage, type Tool, type ToolBatch, type ToolCallEvent, ToolCallPayload, type ToolContext, type ToolNamesDiff, type ToolResult, type ToolResultDraft, type ToolResultEvent, ToolResultPayload, type ToolSide, ToolSpec, type ToolsBoundEvent, Trust, type TurnContext, type TurnDecision, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, backoffDelayMs, budgetTruncate, computeConfigHash, computePendingDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultSleep, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDrafts, isCompaction, isContentPart, isModelOutput, isPinNote, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, statusFromMessage, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter };