@reinsjs/core 0.13.0 → 0.14.1

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,23 @@
1
1
  # @reinsjs/core
2
2
 
3
+ ## 0.14.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 831a50a: Tool-change note: when more than 20 tools are added or removed at once (for example an MCP server's credentials expire), that side now lists 20 names and a total instead of every name. Names that appeared earlier in the session (called, referenced, or mentioned in model-visible text) are listed first. `meta.toolsChanged` still records the full diff, and notes with 20 or fewer changes per side are unchanged.
8
+
9
+ ## 0.14.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 884c840: Session run status. Every `runLoop` run now starts with `core.tools_bound` (carrying `marksEnd: true`) and ends with exactly one end marker: `core.run_paused` as before, or the new model-invisible `core.run_ended` with `status: "done" | "handoff" | "error"`. `core.run_paused` gains `awaiting` (the pending calls waiting on an approval — with `requestedAt` —, a client tool or a sub-agent) and `stopped: true` for a user stop. A `core.error` the loop retries past, or one recorded for a throwing `pullInput`, gets no `run_ended`; an error that ends the run is written together with its `run_ended`.
14
+
15
+ `runStatusOf({ held, lastMarker })` classifies a session as running / paused / done / handoff / error / interrupted / idle / unknown from a lease flag and `lastRunMarker(timeline)`. `@reinsjs/store-pg` adds `pgRunStates(client, sessionIds)`: one SQL statement reads the leases and each session's last marker, so a session list never sees a gap between "lease released" and "outcome written". "Running" is only known for runs started through the server handler with a lease registry (`createAgent` + `pgStores`).
16
+
17
+ Log shape changes: on a resumed run `core.tools_bound` now comes before `core.run_resumed` / `core.approval_decision`, and `RunResult.lastSeq` of a done or handoff run points at its `run_ended`. Live streams carry one more event (a `CUSTOM` frame in AG-UI). The TanStack adapter writes `run_ended` too, but its `tools_bound` carries no `marksEnd` and its `run_paused` no `awaiting` / `stopped`. Lowerings drop `run_ended` like other operational events.
18
+
19
+ **Rolling upgrade:** `@reinsjs/core` 0.13 and earlier reject sessions that contain `core.run_ended` (unknown event type). Upgrade every instance to the same core version at once, and do not roll back past 0.14 once such sessions exist. Sessions whose last run finished before the upgrade read `unknown`.
20
+
3
21
  ## 0.13.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -136,6 +136,7 @@ A `Socket` is the seam brain modules use — five hooks (`beforeModel`, `afterMo
136
136
  - **Fail-closed reads.** An event type the registry does not know, or a version it cannot upgrade, is rejected before anything is written.
137
137
  - **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.
138
138
  - **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).
139
+ - **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.
139
140
  - **Deterministic given the log.** Time and ids are injected (`now`, `newId`), so a recorded session replays byte-for-byte in tests.
140
141
 
141
142
  ## Documentation
@@ -198,6 +198,7 @@ var CORE_SCHEMAS = [
198
198
  "core.run_paused",
199
199
  "core.run_resumed",
200
200
  "core.tools_bound",
201
+ "core.run_ended",
201
202
  "core.error"
202
203
  ].map((type) => ({ type, version: 1 }));
203
204
  function createCoreRegistry(extra = []) {
@@ -215,4 +216,4 @@ export {
215
216
  CORE_SCHEMAS,
216
217
  createCoreRegistry
217
218
  };
218
- //# sourceMappingURL=chunk-3QMUURRG.js.map
219
+ //# sourceMappingURL=chunk-DFXHUJV4.js.map
@@ -1 +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,KAAK;AAC3B,UAAM,CAAC,IAAI,KAAK;AAChB,SAAK,KAAK,M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,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":[]}
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.run_ended\",\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,KAAK;AAC3B,UAAM,CAAC,IAAI,KAAK;AAChB,SAAK,KAAK,MAAM,KAAK,GAAG;AAAA,EAC1B;AAEA,QAAM,CAAC,IAAM,MAAM,CAAC,IAAe,KAAQ;AAE3C,QAAM,CAAC,IAAM,MAAM,CAAC,IAAe,KAAQ;AAE3C,QAAM,MAAM,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAC7E,SAAO,GAAG,IAAI,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,EAAE,CAAC;AAC1G;;;ACiBO,SAAS,YACd,UACA,OACa;AACb,QAAM,KAAK,MAAM,MAAM,KAAK,IAAI;AAChC,QAAM,OAAkB;AAAA,IACtB,IAAI,MAAM,MAAM,OA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,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":[]}
@@ -1198,7 +1198,51 @@ interface RunPausedPayload {
1198
1198
  * 配置摘要反映暂停那一刻,绝不在读取时重算(否则暂停后改过的工具也会被签成一致)。TanStack 适配器写的 run_paused 不带
1199
1199
  */
1200
1200
  state?: SerializedRunState;
1201
+ /**
1202
+ * pending 调用中等外部答复的那些(会话运行状态,AdRate 建议 12),按时间线算(`awaitingOf`),不从本次中断列表推。
1203
+ * 用户停止收尾后为 []。可选字段,不升版本;老事件与 TanStack 适配器写的 run_paused 不带
1204
+ */
1205
+ awaiting?: AwaitingCall[];
1206
+ /** 这次暂停是停止(RunStop:用户停止或宿主收尾遗留调用)造成的,与断线中止、丢租约中止(同为 reason host)区分。可选字段,不升版本 */
1207
+ stopped?: true;
1201
1208
  }
1209
+ /**
1210
+ * 暂停那一刻在等外部答复的一个调用:
1211
+ * - approval:有 approval_request、还没有 approval_decision;`requestedAt` 是那条请求的 `at`(每个调用只写一次,跨 run 不变);
1212
+ * - client_tool:pending 且是客户端工具(`isClientTool`),等宿主回填 tool_result。只说"在等",不保证已下发:
1213
+ * 工具批中途被非停止原因中止时,排在后面的客户端调用宿主还没收到,续跑时循环才会再发出;
1214
+ * - subagent:本次 run 里子代理暂停冒泡,按 `childSessionId` 再查子会话的状态。
1215
+ */
1216
+ type AwaitingCall = {
1217
+ kind: "approval";
1218
+ toolCallId: string;
1219
+ name: string;
1220
+ requestedAt: number;
1221
+ } | {
1222
+ kind: "client_tool";
1223
+ toolCallId: string;
1224
+ name: string;
1225
+ } | {
1226
+ kind: "subagent";
1227
+ toolCallId: string;
1228
+ name: string;
1229
+ childSessionId: string;
1230
+ reason: PauseReason;
1231
+ };
1232
+ /**
1233
+ * run 的终结记号(暂停之外,会话运行状态)。写入方承诺收尾(tools_bound 带 `marksEnd`)的 run 恰好以一条终结事件收尾:
1234
+ * 暂停是 core.run_paused,其余三种结局是这条。模型不可见。
1235
+ * 暂停不写这条:server 补发判"末尾是带状态的 run_paused"才交出续跑凭据,暂停后再落一条会让关页回来的客户端拿不到 state。
1236
+ */
1237
+ type RunEndedPayload = {
1238
+ status: "done";
1239
+ } | {
1240
+ status: "handoff";
1241
+ toSessionId: string;
1242
+ } | {
1243
+ status: "error";
1244
+ category: string;
1245
+ };
1202
1246
  interface RunResumedPayload {
1203
1247
  stateRef?: string;
1204
1248
  by?: string;
@@ -1213,6 +1257,11 @@ interface ToolsBoundPayload {
1213
1257
  toolNames: string[];
1214
1258
  /** 与 SerializedRunState.configHash 同一算法(模型、工具名集合、系统提示) */
1215
1259
  configHash: string;
1260
+ /**
1261
+ * 写入方承诺本 run 以终结事件(run_paused / run_ended)收尾(会话运行状态)。只有 runLoop 写 true;
1262
+ * TanStack 适配器有不经终结钩子的出口,不写。没有这个字段 = 判不出是否中断。可选字段,不升版本
1263
+ */
1264
+ marksEnd?: true;
1216
1265
  }
1217
1266
  interface ErrorPayload {
1218
1267
  /** 粗分类:provider / tool / budget / internal 等,字符串开放给宿主扩展 */
@@ -1239,6 +1288,7 @@ interface CoreEventPayloads {
1239
1288
  "core.run_paused": RunPausedPayload;
1240
1289
  "core.run_resumed": RunResumedPayload;
1241
1290
  "core.tools_bound": ToolsBoundPayload;
1291
+ "core.run_ended": RunEndedPayload;
1242
1292
  "core.error": ErrorPayload;
1243
1293
  }
1244
1294
  type CoreEventType = keyof CoreEventPayloads;
@@ -1253,4 +1303,4 @@ type ExtEvent = Event<`ext.${string}`, unknown>;
1253
1303
  /** 日志里可能出现的任何事件 */
1254
1304
  type AnyEvent = CoreEvent | ExtEvent;
1255
1305
 
1256
- export { type EventBase as $, type Actor as A, type BudgetUsagePayload as B, type ContentPart as C, type ApprovalRequestSpec as D, type Event as E, type AudioPart as F, type BeforeModelPatch as G, type BeforeToolDecision as H, type BoundModel as I, CORE_SCHEMAS as J, type CompactionPayload as K, type LoopConfig as L, type ModelRef as M, type CoreEvent as N, type CoreEventPayloads as O, type ProjectionBudget as P, type CoreEventType as Q, type RunResult as R, type SerializedRunState as S, type ToolCallEvent as T, type CreateEventInput as U, DEFAULT_RETRY_BASE_DELAY_MS as V, DEFAULT_RETRY_MAX_ATTEMPTS as W, DEFAULT_RETRY_MAX_DELAY_MS as X, DEFAULT_TRUST as Y, type ErrorEventPayload as Z, type ErrorPayload as _, type ToolResultEvent as a, isTransientFailure as a$, type EventSchema as a0, type ExtEvent as a1, type HandoffIntent as a2, type HandoffPayload as a3, type ImagePart as a4, type Interruption as a5, type LandingRecord as a6, type LandingSpec as a7, type LossKind as a8, type LossMatrix as a9, type SocketSetup as aA, type StaticContribution as aB, type SystemNotePayload as aC, type TextPart as aD, type ToRequestInput as aE, type TokenUsage as aF, type ToolBatch as aG, type ToolCallPayload as aH, type ToolContext as aI, type ToolReferencePart as aJ, type ToolResultDraft as aK, type ToolResultPayload as aL, type ToolSide as aM, type ToolStartedPayload as aN, type ToolsBoundPayload as aO, type TurnContext as aP, type TurnDecision as aQ, type Upcaster as aR, type UserMessagePayload as aS, type VideoPart as aT, backoffDelayMs as aU, contextOverheadOf as aV, contextTokensOf as aW, createCoreEvent as aX, createCoreRegistry as aY, createEvent as aZ, defaultSleep as a_, type LoweredRequest as aa, type Lowering as ab, type LoweringCapabilities as ac, type LoweringDelta as ad, type LoweringOutcome as ae, type LoweringStreamContext as af, type MaybePromise as ag, type MemoryOpPayload as ah, type ModelCallFailure as ai, type ModelTextPayload as aj, type ModelThinkingPayload as ak, type PauseReason as al, type Principal as am, type ProjectionStep as an, type ProjectionStepStats as ao, type Provenance as ap, type PullInputContext as aq, type ResolvedRetry as ar, type RetryOptions as as, type RunPausedPayload as at, type RunResumedPayload as au, SchemaError as av, type SchemaErrorCode as aw, type SessionInfo as ax, type SkillSource as ay, type Socket as az, type EventLog as b, lossesOf as b0, renderToolReference as b1, resolveRetry as b2, statusFromMessage as b3, type EventDraft as c, type Tool as d, type SubagentInterruption as e, type ToolSpec as f, type ToolResult as g, type Trust as h, type CoreEventOf as i, type CoreEventDraft as j, type ProjectionStrategy as k, type ProjectionContext as l, type TokenEstimator as m, EventSchemaRegistry as n, type ProjectionResult as o, type ProjectionStats as p, type BlobStore as q, type BlobMeta as r, type ReadOptions as s, type MemoryStore as t, type RunLease as u, type Stores as v, type AnyEvent as w, type ApprovalDecisionInput as x, type ApprovalDecisionPayload as y, type ApprovalRequestPayload as z };
1306
+ export { DEFAULT_TRUST as $, type AwaitingCall as A, type BudgetUsagePayload as B, type ContentPart as C, type ApprovalDecisionPayload as D, type Event as E, type ApprovalRequestPayload as F, type ApprovalRequestSpec as G, type AudioPart as H, type Interruption as I, type BeforeModelPatch as J, type BeforeToolDecision as K, type LoopConfig as L, type ModelRef as M, type BoundModel as N, CORE_SCHEMAS as O, type PauseReason as P, type CompactionPayload as Q, type RunResult as R, type SerializedRunState as S, type ToolCallEvent as T, type CoreEvent as U, type CoreEventPayloads as V, type CoreEventType as W, type CreateEventInput as X, DEFAULT_RETRY_BASE_DELAY_MS as Y, DEFAULT_RETRY_MAX_ATTEMPTS as Z, DEFAULT_RETRY_MAX_DELAY_MS as _, type ToolResultEvent as a, createEvent as a$, type ErrorEventPayload as a0, type ErrorPayload as a1, type EventBase as a2, type EventSchema as a3, type ExtEvent as a4, type HandoffIntent as a5, type HandoffPayload as a6, type ImagePart as a7, type LandingRecord as a8, type LandingSpec as a9, type SkillSource as aA, type Socket as aB, type SocketSetup as aC, type StaticContribution as aD, type SystemNotePayload as aE, type TextPart as aF, type ToRequestInput as aG, type TokenUsage as aH, type ToolBatch as aI, type ToolCallPayload as aJ, type ToolContext as aK, type ToolReferencePart as aL, type ToolResultDraft as aM, type ToolResultPayload as aN, type ToolSide as aO, type ToolStartedPayload as aP, type ToolsBoundPayload as aQ, type TurnContext as aR, type TurnDecision as aS, type Upcaster as aT, type UserMessagePayload as aU, type VideoPart as aV, backoffDelayMs as aW, contextOverheadOf as aX, contextTokensOf as aY, createCoreEvent as aZ, createCoreRegistry as a_, type LossKind as aa, type LossMatrix as ab, type LoweredRequest as ac, type Lowering as ad, type LoweringCapabilities as ae, type LoweringDelta as af, type LoweringOutcome as ag, type LoweringStreamContext as ah, type MaybePromise as ai, type MemoryOpPayload as aj, type ModelCallFailure as ak, type ModelTextPayload as al, type ModelThinkingPayload as am, type Principal as an, type ProjectionStep as ao, type ProjectionStepStats as ap, type Provenance as aq, type PullInputContext as ar, type ResolvedRetry as as, type RetryOptions as at, type RunEndedPayload as au, type RunPausedPayload as av, type RunResumedPayload as aw, SchemaError as ax, type SchemaErrorCode as ay, type SessionInfo as az, type EventLog as b, defaultSleep as b0, isTransientFailure as b1, lossesOf as b2, renderToolReference as b3, resolveRetry as b4, statusFromMessage as b5, type EventDraft as c, type Tool as d, EventSchemaRegistry as e, type SubagentInterruption as f, type ToolSpec as g, type ToolResult as h, type Trust as i, type CoreEventOf as j, type CoreEventDraft as k, type ProjectionBudget as l, type ProjectionStrategy as m, type ProjectionContext as n, type TokenEstimator as o, type ProjectionResult as p, type ProjectionStats as q, type BlobStore as r, type BlobMeta as s, type ReadOptions as t, type MemoryStore as u, type RunLease as v, type Stores as w, type Actor as x, type AnyEvent as y, type ApprovalDecisionInput as z };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, L as LoopConfig, c as EventDraft, R as RunResult, S as SerializedRunState, M as ModelRef, d as Tool, e as SubagentInterruption, f as ToolSpec, C as ContentPart, g as ToolResult, h as Trust, i as CoreEventOf, j as CoreEventDraft, P as ProjectionBudget, k as ProjectionStrategy, l as ProjectionContext, m as TokenEstimator, n as EventSchemaRegistry, o as ProjectionResult, p as ProjectionStats, B as BudgetUsagePayload, q as BlobStore, r as BlobMeta, s as ReadOptions, t as MemoryStore, u as RunLease, v as Stores } from './core-h3S4jFh-.js';
2
- export { A as Actor, w as AnyEvent, x as ApprovalDecisionInput, y as ApprovalDecisionPayload, z as ApprovalRequestPayload, D as ApprovalRequestSpec, F as AudioPart, G as BeforeModelPatch, H as BeforeToolDecision, I as BoundModel, J as CORE_SCHEMAS, K as CompactionPayload, N as CoreEvent, O as CoreEventPayloads, Q as CoreEventType, U as CreateEventInput, V as DEFAULT_RETRY_BASE_DELAY_MS, W as DEFAULT_RETRY_MAX_ATTEMPTS, X as DEFAULT_RETRY_MAX_DELAY_MS, Y as DEFAULT_TRUST, Z as ErrorEventPayload, _ as ErrorPayload, $ as EventBase, a0 as EventSchema, a1 as ExtEvent, a2 as HandoffIntent, a3 as HandoffPayload, a4 as ImagePart, a5 as Interruption, a6 as LandingRecord, a7 as LandingSpec, a8 as LossKind, a9 as LossMatrix, aa as LoweredRequest, ab as Lowering, ac as LoweringCapabilities, ad as LoweringDelta, ae as LoweringOutcome, af as LoweringStreamContext, ag as MaybePromise, ah as MemoryOpPayload, ai as ModelCallFailure, aj as ModelTextPayload, ak as ModelThinkingPayload, al as PauseReason, am as Principal, an as ProjectionStep, ao as ProjectionStepStats, ap as Provenance, aq as PullInputContext, ar as ResolvedRetry, as as RetryOptions, at as RunPausedPayload, au as RunResumedPayload, av as SchemaError, aw as SchemaErrorCode, ax as SessionInfo, ay as SkillSource, az as Socket, aA as SocketSetup, aB as StaticContribution, aC as SystemNotePayload, aD as TextPart, aE as ToRequestInput, aF as TokenUsage, aG as ToolBatch, aH as ToolCallPayload, aI as ToolContext, aJ as ToolReferencePart, aK as ToolResultDraft, aL as ToolResultPayload, aM as ToolSide, aN as ToolStartedPayload, aO as ToolsBoundPayload, aP as TurnContext, aQ as TurnDecision, aR as Upcaster, aS as UserMessagePayload, aT as VideoPart, aU as backoffDelayMs, aV as contextOverheadOf, aW as contextTokensOf, aX as createCoreEvent, aY as createCoreRegistry, aZ as createEvent, a_ as defaultSleep, a$ as isTransientFailure, b0 as lossesOf, b1 as renderToolReference, b2 as resolveRetry, b3 as statusFromMessage } from './core-h3S4jFh-.js';
1
+ import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, L as LoopConfig, c as EventDraft, R as RunResult, P as PauseReason, A as AwaitingCall, d as Tool, I as Interruption, e as EventSchemaRegistry, S as SerializedRunState, M as ModelRef, f as SubagentInterruption, g as ToolSpec, C as ContentPart, h as ToolResult, i as Trust, j as CoreEventOf, k as CoreEventDraft, l as ProjectionBudget, m as ProjectionStrategy, n as ProjectionContext, o as TokenEstimator, p as ProjectionResult, q as ProjectionStats, B as BudgetUsagePayload, r as BlobStore, s as BlobMeta, t as ReadOptions, u as MemoryStore, v as RunLease, w as Stores } from './core-BhmO9N-j.js';
2
+ export { x as Actor, y as AnyEvent, z as ApprovalDecisionInput, D as ApprovalDecisionPayload, F as ApprovalRequestPayload, G as ApprovalRequestSpec, H as AudioPart, J as BeforeModelPatch, K as BeforeToolDecision, N as BoundModel, O as CORE_SCHEMAS, Q as CompactionPayload, U as CoreEvent, V as CoreEventPayloads, W as CoreEventType, X as CreateEventInput, Y as DEFAULT_RETRY_BASE_DELAY_MS, Z as DEFAULT_RETRY_MAX_ATTEMPTS, _ as DEFAULT_RETRY_MAX_DELAY_MS, $ as DEFAULT_TRUST, a0 as ErrorEventPayload, a1 as ErrorPayload, a2 as EventBase, a3 as EventSchema, a4 as ExtEvent, a5 as HandoffIntent, a6 as HandoffPayload, a7 as ImagePart, a8 as LandingRecord, a9 as LandingSpec, aa as LossKind, ab as LossMatrix, ac as LoweredRequest, ad as Lowering, ae as LoweringCapabilities, af as LoweringDelta, ag as LoweringOutcome, ah as LoweringStreamContext, ai as MaybePromise, aj as MemoryOpPayload, ak as ModelCallFailure, al as ModelTextPayload, am as ModelThinkingPayload, an as Principal, ao as ProjectionStep, ap as ProjectionStepStats, aq as Provenance, ar as PullInputContext, as as ResolvedRetry, at as RetryOptions, au as RunEndedPayload, av as RunPausedPayload, aw as RunResumedPayload, ax as SchemaError, ay as SchemaErrorCode, az as SessionInfo, aA as SkillSource, aB as Socket, aC as SocketSetup, aD as StaticContribution, aE as SystemNotePayload, aF as TextPart, aG as ToRequestInput, aH as TokenUsage, aI as ToolBatch, aJ as ToolCallPayload, aK as ToolContext, aL as ToolReferencePart, aM as ToolResultDraft, aN as ToolResultPayload, aO as ToolSide, aP as ToolStartedPayload, aQ as ToolsBoundPayload, aR as TurnContext, aS as TurnDecision, aT as Upcaster, aU as UserMessagePayload, aV as VideoPart, aW as backoffDelayMs, aX as contextOverheadOf, aY as contextTokensOf, aZ as createCoreEvent, a_ as createCoreRegistry, a$ as createEvent, b0 as defaultSleep, b1 as isTransientFailure, b2 as lossesOf, b3 as renderToolReference, b4 as resolveRetry, b5 as statusFromMessage } from './core-BhmO9N-j.js';
3
3
 
4
4
  /**
5
5
  * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
@@ -80,6 +80,99 @@ declare const INPUT_DRAFT_TYPES: ReadonlySet<string>;
80
80
  declare function inputDrafts(input: NonNullable<LoopConfig["input"]>): EventDraft[];
81
81
  declare function runLoop(cfg: LoopConfig): AsyncGenerator<Event, RunResult>;
82
82
 
83
+ /**
84
+ * 会话运行状态(AdRate 建议 11 / 12):从"租约 + 最后一条 run 标记"判一个会话此刻处于什么状态。
85
+ *
86
+ * 结局在时间线上(宪法二):runLoop 让每个 run 以 tools_bound(marksEnd) 开头、以恰好一条终结事件收尾
87
+ * (暂停是 run_paused,其余是 run_ended)。所以会话的状态只看两样:
88
+ * - 租约是否持有中(在跑)——来自宿主的 run 登记表(pg 是 `reins_runs`,单进程是 `runs.get(id)`);
89
+ * - 最后一条 RUN_MARKER_TYPES 事件——上一个 run 的结局,或者"起了步却没收尾"。
90
+ *
91
+ * 这里全是纯函数:分类口径只此一处,store-pg 的批量快照与宿主自己的登记表都调 `runStatusOf`。
92
+ *
93
+ * 已知误判窗口(不用代码兜,写进文档):
94
+ * - 续期抛错只告警不中止:存储持续不可用到租约过期而 run 还在跑,会误判 interrupted,下一次心跳恢复后自愈;
95
+ * - 释放失败只告警:最多 ttl 内误判 running;
96
+ * - 进程被杀:要等租约到期才显示 interrupted;
97
+ * - run 中途 fork 出来的会话继承"未收尾",判 interrupted;
98
+ * - 起步时已中止的续跑 run 不写 tools_bound 却照写 approval_decision:进程恰好死在它与 run_paused 之间时,
99
+ * 状态仍是上一个 paused(approval)(窗口只有一次 append);
100
+ * - 子代理冒泡暂停后,下一个父 run 起步即被非停止原因中止:新的 run_paused 里没有子代理那条(父日志查不到 childSessionId),
101
+ * 判 paused(host) 而子会话其实还在等,与"不往父会话上浮子状态"同一边界。
102
+ */
103
+
104
+ /**
105
+ * 会话里"最后一个 run"的标记事件类型(真源索引)。store 查最后一条标记时按这张表过滤(store-pg 绑参数,不在 SQL 里另写一份)
106
+ */
107
+ declare const RUN_MARKER_TYPES: readonly ["core.tools_bound", "core.run_paused", "core.run_ended"];
108
+ /** 一段时间线里最后一条 RUN_MARKER_TYPES 事件。非 pg 宿主(内存 / SQLite、自己的登记表)用它取 lastMarker */
109
+ declare function lastRunMarker(events: readonly Event[]): Event | undefined;
110
+ /**
111
+ * 暂停时在等外部答复的调用(真源索引)。以时间线的 pending 为准,不从本次中断列表推:起步时已中止的 run、
112
+ * 工具批中途中止后排在后面的调用,中断列表里都没有,但它们可能仍在等审批。
113
+ *
114
+ * 逐个 pending 调用判:有 approval_request 无 approval_decision → approval;否则工具是客户端工具 → client_tool;
115
+ * 否则本次中断里有它的子代理冒泡 → subagent;都不是就不列(没执行、下次补跑)。
116
+ * 找不到对应事件或工具时只跳过该条、不抛错:一个元数据字段不能把暂停变成崩溃,否则续跑凭据就丢了。
117
+ */
118
+ declare function awaitingOf(input: {
119
+ timeline: readonly Event[];
120
+ pending: readonly ToolCallEvent[];
121
+ tools: readonly Tool[];
122
+ interruptions: readonly Interruption[];
123
+ }): AwaitingCall[];
124
+ /**
125
+ * 一个会话此刻的运行状态。
126
+ * - running:租约持有中(不看标记);
127
+ * - idle:没有任何 run 标记(新会话、交接目标会话还没起过 run);
128
+ * - unknown:最后一个 run 没承诺收尾(老版本、TanStack 适配器),或标记读不出 / 形状不合规(fail-closed,不猜);
129
+ * - interrupted:起了步(tools_bound 带 marksEnd)却没有收尾,且租约不在——进程被杀、生成器抛错;
130
+ * - 其余四种是上一个 run 的结局。`seq` 区分前后两个 run,`endedAt` / `startedAt` 与事件 `at` 同一时钟(循环时钟)。
131
+ */
132
+ type RunStatus = {
133
+ state: "running";
134
+ } | {
135
+ state: "idle";
136
+ } | {
137
+ state: "unknown";
138
+ } | {
139
+ state: "interrupted";
140
+ seq: number;
141
+ startedAt: number;
142
+ } | {
143
+ state: "done";
144
+ seq: number;
145
+ endedAt: number;
146
+ } | {
147
+ state: "handoff";
148
+ seq: number;
149
+ endedAt: number;
150
+ toSessionId: string;
151
+ } | {
152
+ state: "error";
153
+ seq: number;
154
+ endedAt: number;
155
+ category: string;
156
+ } | {
157
+ state: "paused";
158
+ seq: number;
159
+ endedAt: number;
160
+ reason: PauseReason;
161
+ stopped: boolean;
162
+ /** 老版本写的 run_paused 不带,为 undefined */
163
+ awaiting: AwaitingCall[] | undefined;
164
+ };
165
+ /**
166
+ * 纯函数:租约 + 最后一条 run 标记 → 运行状态(真源索引)。
167
+ * `lastMarker` 是存储读出的原始行即可:函数内过注册表 upcast,再自己做形状守卫——注册表只校验壳字段、不校验 payload。
168
+ * 读不出(未来版本、未登记)或形状不合规一律 unknown,不抛错。
169
+ */
170
+ declare function runStatusOf(input: {
171
+ held: boolean;
172
+ lastMarker: Event | undefined;
173
+ registry?: EventSchemaRegistry;
174
+ }): RunStatus;
175
+
83
176
  /**
84
177
  * run 状态的序列化、签名与恢复校验(§6,T9 / T10)。
85
178
  *
@@ -292,6 +385,11 @@ declare function isSubagentPause(value: unknown): value is SubagentPause;
292
385
  * "同一个判定写两处必须同一个纯函数"(踩坑记录 #3 / #20 / #40 的教训)。
293
386
  */
294
387
  declare function toolResultTrust(tool: Tool | undefined, isError: boolean): Trust | undefined;
388
+ /**
389
+ * 客户端工具:本循环不执行,等宿主回填 tool_result(真源索引)。没有 execute 或声明 `side: "client"` 的都算。
390
+ * 循环执行工具批与暂停时算 `awaiting` 共用这一个判定
391
+ */
392
+ declare function isClientTool(tool: Tool): boolean;
295
393
  /**
296
394
  * 定义一个带入参类型的工具并擦成 Tool:对象字面量里 execute / validate / needsApproval 的 input 都按 TInput 推断,
297
395
  * 返回值却能直接放进 Tool[]。不用它也行,只是 needsApproval 写成函数时 TS 会因参数逆变拒绝放进数组。
@@ -343,8 +441,14 @@ declare function diffToolNames(previous: readonly string[], next: readonly strin
343
441
  /**
344
442
  * 给模型看的变化说明(英文,进模型上下文)。只列名字:说明在工具表里,重复一遍既费 token 又可能与工具表不一致;
345
443
  * 被移除的工具明说"不能再调用",模型才不会按记忆去调一个已经不存在的工具。
444
+ *
445
+ * 一侧超过 `TOOL_CHANGE_LIST_MAX` 件(MCP 凭据过期 / 恢复会一次增删几百件,AdRate 建议 15)只列这么多个、报总数。
446
+ * `tiers` 是优先档,前档先列、档内按字母序;不在任何档的按字母序补足,让模型看得出是哪一类工具变了。
447
+ * `toolsBoundDrafts` 传 [调用过的, 只在文本里出现过的](见 `toolMentionTiers`):往期工具表不进历史,
448
+ * 模型只可能凭记忆去调这些。说明写进日志后每次请求都回放,几百个名字会常驻上下文;
449
+ * 完整增删照旧记在 `meta.toolsChanged` 与 tools_bound,压缩的只是这句话。
346
450
  */
347
- declare function renderToolChangeNote(diff: ToolNamesDiff): string;
451
+ declare function renderToolChangeNote(diff: ToolNamesDiff, tiers?: readonly ReadonlySet<string>[]): string;
348
452
  /**
349
453
  * 起步要 append 的草稿:一条 tools_bound,工具表与上一条相比有增删且 `announce` 为真时再加一条 system_note。
350
454
  * 顺序固定:快照在前、说明在后 —— 说明是从快照比对得出的,日志里的因果也该这么排。
@@ -354,6 +458,8 @@ declare function toolsBoundDrafts(input: {
354
458
  toolNames: readonly string[];
355
459
  configHash: string;
356
460
  announce: boolean;
461
+ /** 写入方承诺本 run 以终结事件收尾(只有 runLoop 传 true,见 `ToolsBoundPayload.marksEnd`) */
462
+ marksEnd?: boolean;
357
463
  }): CoreEventDraft[];
358
464
 
359
465
  type LoweringErrorCode = "unsupported_model" | "unsupported_api" | "missing_api_key" | "invalid_request";
@@ -478,6 +584,7 @@ declare function estimateBudgetOf(budget: ProjectionBudget): number;
478
584
  * - error:provider 级错误由循环层处理;工具错误已在 tool_result.isError
479
585
  * - tools_bound:每次 run 起步的工具表快照(P1);工具表本身在请求里,增删由循环以 system_note(kind=host) 告知模型
480
586
  * - tool_started:调用已开始动手的标记,只给续跑与停止判断用;模型从 tool_result 得知结果
587
+ * - run_ended:run 的终结记号(跑完 / 交接 / 出错),只给宿主判会话状态用
481
588
  */
482
589
  declare const DEFAULT_MODEL_INVISIBLE_TYPES: ReadonlySet<string>;
483
590
  interface VisibilityFilterOptions {
@@ -824,6 +931,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
824
931
  */
825
932
 
826
933
  /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
827
- declare const REINS_VERSION = "0.13.0";
934
+ declare const REINS_VERSION = "0.14.1";
828
935
 
829
- export { BUILTIN_APPROVAL_POLICY, 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, type DecodedToolArguments, type DefaultChainOptions, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, LoopConfig, LoweringError, type LoweringErrorCode, type MarkedContent, MemoryStore, ModelRef, OUTCOME_UNKNOWN_TEXT, type ProjectOptions, ProjectionBudget, ProjectionContext, ProjectionResult, ProjectionStats, ProjectionStrategy, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, RunLease, RunResult, RunStateError, type RunStateErrorCode, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, SerializedRunState, type StopTexts, StoreError, type StoreErrorCode, Stores, SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, TokenEstimator, Tool, ToolCallEvent, type ToolNamesDiff, ToolResult, ToolResultEvent, ToolSpec, type ToolsBoundEvent, Trust, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, budgetTruncate, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDrafts, isCompaction, isContentPart, isModelOutput, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, outcomeUnknownText, pausedStateOf, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, startedToolCallIds, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolStartedAt, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter, withStartedAt };
936
+ export { AwaitingCall, BUILTIN_APPROVAL_POLICY, 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, type DecodedToolArguments, type DefaultChainOptions, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, Interruption, LoopConfig, LoweringError, type LoweringErrorCode, type MarkedContent, MemoryStore, ModelRef, OUTCOME_UNKNOWN_TEXT, PauseReason, type ProjectOptions, ProjectionBudget, ProjectionContext, ProjectionResult, ProjectionStats, ProjectionStrategy, REINS_VERSION, RUN_MARKER_TYPES, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, RunLease, RunResult, RunStateError, type RunStateErrorCode, type RunStatus, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, SerializedRunState, type StopTexts, StoreError, type StoreErrorCode, Stores, SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, TokenEstimator, Tool, ToolCallEvent, type ToolNamesDiff, ToolResult, ToolResultEvent, ToolSpec, type ToolsBoundEvent, Trust, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, awaitingOf, budgetTruncate, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDrafts, isClientTool, isCompaction, isContentPart, isModelOutput, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, keptBy, lastRunMarker, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, outcomeUnknownText, pausedStateOf, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveSocketContributions, roughTokenEstimate, runLoop, runStatusOf, serializeRunState, signRunState, splitTurns, startedToolCallIds, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolStartedAt, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter, withStartedAt };