@reinsjs/core 0.8.0 → 0.10.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,34 @@
1
1
  # @reinsjs/core
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 45bfc8d: Stop semantics, no replay of interrupted writes, a stop request in the server, and narrower resume validation.
8
+
9
+ - **Stop is a kind of abort.** `controller.abort(new RunStop())` makes every pause point close the pending tool calls with an error result ("Not executed: the run was stopped by the user…"; calls that had already started get "outcome unknown" or "interrupted"), so the next run asks the model directly instead of re-running what the user stopped. Approval-pending and client-tool calls are closed too. The result is still `paused` / `host` with the note `stopped by the user`. `new RunStop("host")` is for a host closing calls left by an interrupted run: the same closing, but the texts say an earlier run was interrupted instead of blaming the user (`stopTextsOf`). A run whose signal is already aborted when it starts no longer writes `core.tools_bound` or the tool-change note. Other abort reasons keep the old behaviour (pending calls are replayed on resume). An abort that lands while the request is still connecting now ends as `paused(host)` instead of `error`.
10
+ - **Interrupted writes are not replayed.** New `Tool.replayable` (default: only `risk: "low"` tools) and `isReplayable()`. Non-replayable tools get a model-invisible `core.tool_started` event before `execute`; on resume, a started call without a result is closed with "outcome unknown, check the current state before retrying" instead of running again. A signal-aware write tool cut off by an abort gets the same result instead of "Tool execution failed". Tools that do not declare `risk` now write one extra event per call.
11
+ - **Server stop request.** `POST { sessionId, stop: true }` answers JSON `{ status: "stopping" | "idle", sessionId }` without waiting for the run. `SessionAuthzInput.method` gains `"STOP"` — hooks that allow writes only for `"POST"` will refuse stop requests until they accept `"STOP"`.
12
+ - **`asTool`** declares `replayable: true`, resumes a child only when the parent already recorded `tool_started` for that call (a stopped expert's next task is no longer swallowed), and closes a child's leftover pending calls with `RunStop("host")` before starting a new task.
13
+ - **Narrower resume validation.** `SerializedRunState` gains optional `modelDigest` / `pendingToolsDigest` (included in the signature when present). States carrying them only check the model and the definitions of the tools behind the pending calls, so adding an unrelated tool no longer makes paused sessions answer `409 config_mismatch`; older states still compare the whole configuration hash.
14
+ - Lowerings and the AG-UI encoder declare landings for `core.tool_started` (dropped / `CUSTOM`). The TanStack adapter writes `tool_started` in `onBeforeToolCall` and applies the same no-replay rule; stop handling and resume validation stay out of its scope.
15
+
16
+ **Rollback risk:** sessions that contain `core.tool_started` cannot be read by `@reinsjs/core` 0.9 or earlier. Sessions paused inside a sub-agent before upgrading resume the child as a new task after upgrading; let them finish first.
17
+
18
+ ## 0.9.0
19
+
20
+ ### Minor Changes
21
+
22
+ - 179f891: Video and audio content parts.
23
+
24
+ - 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.
25
+ - 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.
26
+ - lowering-pi: video / audio parts become placeholder text (`lossy`); pi-ai has no such content.
27
+ - server: the HTTP whitelist accepts `video` / `audio` parts with the same shape rules as core.
28
+ - 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.
29
+ - ui-agui: video / audio parts become `[video <mime>]` / `[audio <mime>]` placeholders, recorded in `dropped`.
30
+ - tools-mcp: MCP `audio` blocks and `video/*` / `audio/*` embedded resources become audio / video parts instead of descriptions.
31
+
3
32
  ## 0.8.0
4
33
 
5
34
  ### Minor Changes
package/README.md CHANGED
@@ -37,7 +37,11 @@ type RunResult =
37
37
  | { status: "error"; sessionId; lastSeq; error }
38
38
  ```
39
39
 
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 (config drift, pending-call digest) before writing anything.
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.
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`.
43
+
44
+ **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.
41
45
 
42
46
  ## Input: background and task in one run
43
47
 
@@ -74,8 +78,18 @@ const deploy = defineTool<{ env: "staging" | "prod" }>({
74
78
 
75
79
  `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.
76
80
 
81
+ **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", and the model decides whether to look first. Read-only tools are simply re-run. Declare `risk: "low"` on tools that only read; `replayable: true` on writes that are idempotent.
82
+
77
83
  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
84
 
85
+ ## Media: images, video and audio
86
+
87
+ 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.
88
+
89
+ - **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.
90
+ - **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`.
91
+ - **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`.
92
+
79
93
  ## Sockets
80
94
 
81
95
  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`).
@@ -85,6 +99,7 @@ A `Socket` is the seam brain modules use — five hooks (`beforeModel`, `afterMo
85
99
  - **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.
86
100
  - **Fail-closed reads.** An event type the registry does not know, or a version it cannot upgrade, is rejected before anything is written.
87
101
  - **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.
102
+ - **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).
88
103
  - **Deterministic given the log.** Time and ids are injected (`now`, `newId`), so a recorded session replays byte-for-byte in tests.
89
104
 
90
105
  ## Documentation
@@ -187,6 +187,7 @@ var CORE_SCHEMAS = [
187
187
  "core.model_thinking",
188
188
  "core.tool_call",
189
189
  "core.tool_result",
190
+ "core.tool_started",
190
191
  "core.system_note",
191
192
  "core.approval_request",
192
193
  "core.approval_decision",
@@ -214,4 +215,4 @@ export {
214
215
  CORE_SCHEMAS,
215
216
  createCoreRegistry
216
217
  };
217
- //# sourceMappingURL=chunk-63AJKR7J.js.map
218
+ //# sourceMappingURL=chunk-3QMUURRG.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.tool_started\",\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,GAAG,KAAK,GAAG,K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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;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 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-DkOLu2fW.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-DkOLu2fW.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-CFO8uTd0.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 ToolStartedPayload, a9 as ToolsBoundPayload, aa as Upcaster, ab as UserMessagePayload, ac as VideoPart, ad as contextOverheadOf, ae as contextTokensOf, af as createCoreEvent, ag as createCoreRegistry, ah as createEvent, ai as lossesOf, aj as renderToolReference } from './types-CFO8uTd0.js';
3
3
 
4
4
  /**
5
5
  * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
@@ -207,6 +207,12 @@ interface Tool<TInput = unknown> {
207
207
  /** 执行前是否要人审批。循环内置兜底:为真且没有任何 Socket 做主时,直接转审批暂停(安全默认值) */
208
208
  needsApproval?: boolean | ((input: TInput, ctx: ToolContext) => Promise<boolean> | boolean);
209
209
  risk?: "low" | "medium" | "high";
210
+ /**
211
+ * 开始动手后中断(进程死亡、执行中被掐断)、没留下结果时,续跑能不能再执行一遍。缺省按 risk:只有 `"low"` 可重放(`isReplayable`)。
212
+ * 不可重放的调用在 execute 之前落一条 `core.tool_started`,续跑时见到它就落"结果未知"让模型先查再定,不再执行——写工具重复执行
213
+ * 就是重复改用户的东西。幂等的写工具可以显式 `true`;asTool 子代理显式 `true`(子会话自己能续跑)
214
+ */
215
+ replayable?: boolean;
210
216
  /**
211
217
  * 这个工具**成功**结果事件(tool_result)的 trust;缺省 `DEFAULT_TRUST.tool`(untrusted:翻译给模型时包 `<untrusted>` 标记)。
212
218
  * 只有输出等同宿主配置的工具才声明 `"system"`——如 brain 的 `skill_read`(技能是宿主写的说明书,视同系统提示)。
@@ -441,6 +447,13 @@ interface SerializedRunState {
441
447
  configHash: string;
442
448
  /** pending 调用(id、名、入参)的 SHA-256;批下去的必须是当时看到的那次调用 */
443
449
  pendingDigest: string;
450
+ /**
451
+ * 模型引用的摘要(D4,可选、不升 v)。与 `pendingToolsDigest` 同时在场时,续跑只比对模型与 pending 工具定义,
452
+ * 不再整体比 configHash(加减别的工具不再拒续跑);在场即进签名材料
453
+ */
454
+ modelDigest?: string;
455
+ /** pending 调用涉及的工具定义(名、描述、入参 schema)摘要,取基础工具表(D4) */
456
+ pendingToolsDigest?: string;
444
457
  sig?: string;
445
458
  }
446
459
  /** 宿主对某次 pending 调用的审批结论;循环记成 approval_decision 事件后按它办 */
@@ -633,6 +646,14 @@ declare function computeConfigHash(input: {
633
646
  tools: readonly Tool[];
634
647
  systemPrompt?: string;
635
648
  }): Promise<string>;
649
+ /** 模型引用的摘要(D4):续跑时模型换了要能察觉 */
650
+ declare function computeModelDigest(model: ModelRef): Promise<string>;
651
+ /**
652
+ * pending 调用涉及的工具定义摘要(D4):按名去重排序,每件取 `[name, description, inputSchema]`,不在表里记 `[name, null]`。
653
+ * 取数口径是**基础工具表**(runLoop 的 baseTools = server 预校验的 `contributions.tools`),不取 beforeModel 补丁改过的本轮工具表。
654
+ * 守的是"被批准的那次调用,执行时还是同一个工具"
655
+ */
656
+ declare function computePendingToolsDigest(calls: readonly ToolCallEvent[], tools: readonly Tool[]): Promise<string>;
636
657
  /** pending 调用的入参摘要:恢复时重算比对,保证批下去的就是当时看到的那次调用 */
637
658
  declare function computePendingDigest(calls: readonly ToolCallEvent[]): Promise<string>;
638
659
  declare function serializeRunState(input: {
@@ -640,6 +661,9 @@ declare function serializeRunState(input: {
640
661
  lastSeq: number;
641
662
  pending: readonly ToolCallEvent[];
642
663
  configHash: string;
664
+ /** 给了 model 与 tools(基础工具表)才写 D4 两个摘要,续跑只比对模型与 pending 工具;缺了退回只比 configHash */
665
+ model?: ModelRef;
666
+ tools?: readonly Tool[];
643
667
  secret?: string;
644
668
  }): Promise<SerializedRunState>;
645
669
  declare function signRunState(state: SerializedRunState, secret: string): Promise<SerializedRunState>;
@@ -654,12 +678,20 @@ declare function assertRunStateShape(raw: unknown): asserts raw is SerializedRun
654
678
  /**
655
679
  * 恢复前的全部校验。顺序有讲究:先看形状与会话,再验签名(防伪造),最后与日志对账(防篡改与错连)。
656
680
  * 通过后返回日志里的 pending 调用,供循环继续处理。
681
+ *
682
+ * 配置比对两条路(D4):状态带 `modelDigest` / `pendingToolsDigest` 且调用方给了 `model` 与 `tools`(基础工具表)时,
683
+ * 只比模型与 pending 调用涉及的工具定义——其余变化(加减别的工具、改系统提示)放行,模型会从工具变化说明里得知;
684
+ * 否则(旧状态、调用方没给)仍按 configHash 整体比对。`allowConfigDrift` 两条路都放行。
657
685
  */
658
686
  declare function validateResume(input: {
659
687
  state: unknown;
660
688
  sessionId: string;
661
689
  timeline: readonly Event[];
662
690
  configHash: string;
691
+ /** 与 `tools` 一起给才走 D4 收窄的比对 */
692
+ model?: ModelRef;
693
+ /** 基础工具表(runLoop 的 baseTools、server 的 `contributions.tools`) */
694
+ tools?: readonly Tool[];
663
695
  secret?: string;
664
696
  allowConfigDrift?: boolean;
665
697
  }): Promise<ToolCallEvent[]>;
@@ -693,6 +725,66 @@ type ContributionConfig = Pick<LoopConfig, "log" | "blobs" | "memory" | "model"
693
725
  */
694
726
  declare function resolveSocketContributions(cfg: ContributionConfig): Promise<ResolvedContributions>;
695
727
 
728
+ /**
729
+ * 停止语义与中断不重放(2026-11-05,AdRate 建议 1 / 2)。
730
+ *
731
+ * "补齐 pending"这条路原先不分 pending 是怎么来的:用户点了停止、执行途中进程死亡,下一个 run 一开头都会把调用再跑一遍。
732
+ * 对改用户广告的写工具,重复执行就是重复花钱。这里放三件纯东西,循环与 asTool 共用:
733
+ *
734
+ * - `RunStop` / `isStopReason`:停止是中止的一种原因。宿主 `controller.abort(new RunStop())`,循环在暂停时把 pending 收尾成
735
+ * "没执行"等结果,下一个 run 直接问模型;其它中止原因(丢租约、断线)照旧留 pending、恢复时补跑。
736
+ * - `isReplayable`:调用开始动手后中断了,能不能再跑一遍。缺省口径与 approval 的 byRisk 一致:只有 `risk: "low"` 的算可重放。
737
+ * - `startedToolCallIds`:时间线里已经开始动手的调用(`core.tool_started`)。
738
+ *
739
+ * 模型可见的文案在 2026-11-05 用 DeepSeek 与 Claude 实测过(spikes/stop-and-interrupt;"中断"口径两句同日 DeepSeek 补测),改字前先复跑。
740
+ */
741
+
742
+ /** 用户停止时 paused(host) 的 interruption note */
743
+ declare const STOPPED_NOTE = "stopped by the user";
744
+ /** 用户停止:调用还没开始 */
745
+ declare const STOPPED_NOT_EXECUTED_TEXT = "Not executed: the run was stopped by the user before this call started.";
746
+ /** 用户停止:可重放的调用(子代理)做了一半 */
747
+ declare const STOPPED_IN_PROGRESS_TEXT = "Interrupted: the run was stopped by the user while this call was in progress; it may have partly taken effect.";
748
+ /** 宿主收尾遗留调用(`RunStop("host")`,如 asTool 开新一轮前):调用还没开始。不说"用户停止"——多半是进程中途死亡留下的 */
749
+ declare const INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: an earlier run was interrupted before this call started.";
750
+ /** 宿主收尾遗留调用:可重放的调用(子代理)做了一半 */
751
+ declare const INTERRUPTED_IN_PROGRESS_TEXT = "Interrupted: an earlier run was interrupted while this call was in progress; it may have partly taken effect.";
752
+ /** 不可重放的调用开始动手后中断,没留下结果:上游可能已经生效 */
753
+ declare const OUTCOME_UNKNOWN_TEXT = "Execution was interrupted before a result was recorded; the outcome is unknown. Check the current state before retrying.";
754
+ /**
755
+ * 停止。作为 `AbortController.abort(reason)` 的 reason 传入:`controller.abort(new RunStop())`。
756
+ * 判据只看 `name`(`isStopReason`),宿主装了两份 core 时 `instanceof` 会失效。
757
+ *
758
+ * `by` 决定模型读到的收尾文案(`stopTextsOf`):缺省 `"user"`,用户点了停止;`"host"` 是宿主替自己收尾遗留调用
759
+ * (asTool 开新一轮前清理子会话),多半是进程中途死亡留下的,不能对模型说"用户停止"
760
+ */
761
+ declare class RunStop extends Error {
762
+ readonly by: "user" | "host";
763
+ constructor(by?: "user" | "host");
764
+ }
765
+ /** 停止收尾的三处模型 / 宿主可见文字:pending 没开始、可重放的做了一半、paused 的 interruption note */
766
+ interface StopTexts {
767
+ notExecuted: string;
768
+ inProgress: string;
769
+ note: string;
770
+ }
771
+ /**
772
+ * 按停止原因取收尾文字(真源索引)。只有 `by === "host"` 换成"中断"口径,其余(含别的 core 副本造的、没有 `by` 的)一律按用户停止。
773
+ * "结果未知"(`OUTCOME_UNKNOWN_TEXT`)两种口径通用,不在这里
774
+ */
775
+ declare function stopTextsOf(reason: unknown): StopTexts;
776
+ /** 这个中止原因是不是用户停止(`signal.reason`)。按 name 判,跨 core 副本成立 */
777
+ declare function isStopReason(reason: unknown): boolean;
778
+ /** signal 已中止且原因是用户停止 */
779
+ declare function isStopped(signal: AbortSignal | undefined): boolean;
780
+ /**
781
+ * 开始动手后中断的调用能不能再跑一遍(真源索引):显式 `replayable` 优先,否则只有 `risk: "low"` 的可重放。
782
+ * 没声明 risk 的算写工具、不重放——与 approval 缺省 byRisk 把它当要问人同一口径
783
+ */
784
+ declare function isReplayable(tool: Tool): boolean;
785
+ /** 时间线里已经开始动手(有 `core.tool_started`)的 toolCallId */
786
+ declare function startedToolCallIds(timeline: Iterable<Event>): Set<string>;
787
+
696
788
  /**
697
789
  * 子代理即工具(§10.1)的暂停标记:`asTool` 这类工具跑的子 run 暂停时,`execute` 返回 `subagentPause(detail)` 而不是结果,
698
790
  * 循环见到它不落 tool_result、把这次调用留作 pending,整个 run 以 `paused` 返回并把子的中断带给宿主(`SubagentInterruption`)。
@@ -730,7 +822,13 @@ declare function defineTool<TInput>(tool: Tool<TInput>): Tool;
730
822
  declare function toolSpecOf(tool: Tool): ToolSpec;
731
823
  /** 带"声明但不载入"标记的规格(L1):runLoop 按 BeforeModelPatch.deferredTools 对本轮工具表逐件调 */
732
824
  declare function deferredToolSpecOf(tool: Tool, deferred: boolean): ToolSpec;
733
- /** 工具返回值里能认出的内容段:文本、图片、工具定义引用(L1)。宿主经 HTTP 送来的用户消息另有白名单(server),不含引用段 */
825
+ /**
826
+ * 内容片段的形状校验,全包唯一一份(真源索引):工具返回值归一(本文件)与 runLoop 输入草稿 / 片段数组(run-loop.ts)都调它。
827
+ * 坏片段一旦进日志,之后每次读到它都会崩(会话报废),所以在写之前拦。
828
+ * 规则:text 有 `text`;image 有 `mime` 与 `data`(mime 不校验,历史行为);video / audio 的 mime 以 "video/" / "audio/" 开头、
829
+ * `durationSec` 缺省或为有限正数;tool_reference 有名字、描述与对象形 inputSchema。
830
+ * 宿主经 HTTP 送来的用户消息另有白名单(server `rebuildContentParts`,两份实现靠跨包用例锁同口径),不含引用段
831
+ */
734
832
  declare function isContentPart(x: unknown): x is ContentPart;
735
833
  /**
736
834
  * execute 的返回值 → 模型看到的内容。规则按直觉:
@@ -869,7 +967,12 @@ declare function needsUntrustedMark(e: Event): boolean;
869
967
  * 供预算裁剪兜底与感知档位使用。宿主要精确数字就注入自己的 TokenEstimator。
870
968
  *
871
969
  * 规则:ASCII 字符约 4 个一个 token;非 ASCII(中日韩等)按一字一 token 保守计;
872
- * 图片按 Anthropic 单图上限附近取常量;每条事件再加角色与分隔的固定开销。
970
+ * 图片按 Anthropic 单图上限附近取常量;视频 / 音频按时长计;每条事件再加角色与分隔的固定开销。
971
+ *
972
+ * 视频 / 音频费率来源:2026-11-05 视频音频方案 P0 实测(spikes/media-parts,中转站 Gemini flash 低分辨率档)——
973
+ * 视频每秒 91 token(含音轨,与码率、画面内容无关)、音频每秒 25;取 100 / 32 留余量(32 也是 Gemini 公开音频费率)。
974
+ * 没有 durationSec 时按字节折算:码率实测相差约 60 倍,所以按偏低码率(视频 1 Mbps、音频 64 kbps)折算并设 30 秒下限,
975
+ * 宁高勿低(偏高只是整理提前,偏低会溢出)。要别的费率就注入自己的 TokenEstimator,不另加开关。
873
976
  */
874
977
 
875
978
  declare function estimateTextTokens(text: string): number;
@@ -895,6 +998,7 @@ declare function estimateBudgetOf(budget: ProjectionBudget): number;
895
998
  * - handoff:交接后当前会话结束,新会话首条 user 消息承载 triggerMessage
896
999
  * - error:provider 级错误由循环层处理;工具错误已在 tool_result.isError
897
1000
  * - tools_bound:每次 run 起步的工具表快照(P1);工具表本身在请求里,增删由循环以 system_note(kind=host) 告知模型
1001
+ * - tool_started:调用已开始动手的标记,只给续跑与停止判断用;模型从 tool_result 得知结果
898
1002
  */
899
1003
  declare const DEFAULT_MODEL_INVISIBLE_TYPES: ReadonlySet<string>;
900
1004
  interface VisibilityFilterOptions {
@@ -1241,6 +1345,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
1241
1345
  */
1242
1346
 
1243
1347
  /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
1244
- declare const REINS_VERSION = "0.8.0";
1348
+ declare const REINS_VERSION = "0.10.0";
1245
1349
 
1246
- 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 };
1350
+ 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, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, OUTCOME_UNKNOWN_TEXT, 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, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, type StopTexts, 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, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultSleep, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDrafts, isCompaction, isContentPart, isModelOutput, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, startedToolCallIds, statusFromMessage, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter };