@reinsjs/core 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +8 -0
- package/dist/{chunk-63AJKR7J.js → chunk-GWU2JSFA.js} +1 -1
- package/dist/chunk-GWU2JSFA.js.map +1 -0
- package/dist/index.d.ts +16 -5
- package/dist/index.js +67 -22
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/{types-DkOLu2fW.d.ts → types-BlyGZlJp.d.ts} +35 -3
- package/package.json +1 -1
- package/dist/chunk-63AJKR7J.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @reinsjs/core
|
|
2
2
|
|
|
3
|
+
## 0.9.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 179f891: Video and audio content parts.
|
|
8
|
+
|
|
9
|
+
- core: `ContentPart` gains `VideoPart` (`type: "video"`) and `AudioPart` (`type: "audio"`): `mime` must start with `video/` / `audio/`, base64 `data`, optional `durationSec` (finite, positive). `LoweringCapabilities` gains optional `video` / `audio`; absent means the model does not take them. Token estimates follow duration (100 / s for video, 32 / s for audio); without `durationSec` the byte size is converted at 1 Mbps / 64 kbps with a 30-second floor. `isContentPart` checks the new parts and is now also what `runLoop` uses to validate input — which also means `runLoop` input now rejects a `tool_reference` part whose `inputSchema` is an array (tool results already did). A tool returning an array of video / audio-shaped parts now yields media parts instead of JSON text. The budget-truncation summary writes `[video]` / `[audio]` / `[tool <name>]` instead of `[image]` for non-image parts. No `schemaVersion` bump: existing logs read unchanged, but a log containing video or audio parts cannot be read by an older version.
|
|
10
|
+
- lowering-fetch: new `video` / `audio` model options (default `false`, including every built-in model). When on, video and audio travel in each protocol's image slot — a relay dialect official endpoints reject; `input_audio` is deliberately not used. When off, they become placeholder text and the event is `lossy`. Chat lifts video / audio from tool results like images; a result with images only lowers byte-for-byte as before. Fix: `deepseek-v4-pro` is text-only (`images: false`) — the built-in table and `deepseek()` used to claim images, which the provider silently dropped.
|
|
11
|
+
- lowering-pi: video / audio parts become placeholder text (`lossy`); pi-ai has no such content.
|
|
12
|
+
- server: the HTTP whitelist accepts `video` / `audio` parts with the same shape rules as core.
|
|
13
|
+
- adapter-tanstack-ai: data-sourced video / audio parts translate both ways (TanStack has no duration field). URL-sourced parts are now reported in `dropped` as `audio(url)` / `video(url)` instead of `audio` / `video`, and data parts whose mime type does not match their kind as `video(<mime>)` / `audio(<mime>)`. Imported client parts are now checked with core's `isContentPart`: a malformed one (missing `mimeType`, non-string `value`, non-string text) becomes a placeholder reported in `dropped` instead of throwing or reaching the log.
|
|
14
|
+
- ui-agui: video / audio parts become `[video <mime>]` / `[audio <mime>]` placeholders, recorded in `dropped`.
|
|
15
|
+
- tools-mcp: MCP `audio` blocks and `video/*` / `audio/*` embedded resources become audio / video parts instead of descriptions.
|
|
16
|
+
|
|
3
17
|
## 0.8.0
|
|
4
18
|
|
|
5
19
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -76,6 +76,14 @@ const deploy = defineTool<{ env: "staging" | "prod" }>({
|
|
|
76
76
|
|
|
77
77
|
A tool can also *be* another agent: return `subagentPause(...)` from `execute` and the run pauses with `Interruption { kind: "subagent" }`, carrying the child session's own interruptions and state. `@reinsjs/agent` ships `asTool(agent, opts)` on top of this.
|
|
78
78
|
|
|
79
|
+
## Media: images, video and audio
|
|
80
|
+
|
|
81
|
+
Content parts are `text`, `image`, `video`, `audio` and `tool_reference`. A `video` / `audio` part carries `mime` (must start with `video/` / `audio/`), base64 `data` and an optional `durationSec` (a finite positive number); a malformed part is rejected before anything is written. A video's soundtrack is part of the video — use `audio` only for audio files.
|
|
82
|
+
|
|
83
|
+
- **Capabilities decide, not mime types.** `LoweringCapabilities.video` / `audio` are optional and mean "no" when absent: a lowering that does not take them replaces the part with a placeholder and records the event `lossy`, so the run goes on instead of the provider answering 400.
|
|
84
|
+
- **Estimates follow duration.** Video is estimated at 100 tokens per second and audio at 32 (measured: about 91 and 25 on a relay Gemini). Without `durationSec` the estimate falls back to the byte size at a deliberately low bitrate (1 Mbps / 64 kbps) with a 30-second floor — erring high, because bitrates differ by about 60× and underestimating leads to overflow. Give `durationSec` whenever you know it, and never `0` — a part with `durationSec: 0` (or a mime type outside `video/` / `audio/`) is malformed, and a tool result containing one is turned into JSON text as a whole, base64 included. For other rates, wrap `roughTokenEstimate` in your own `TokenEstimator`.
|
|
85
|
+
- **They stay in the log.** Media `data` is stored in the event like an image (append-only, never spilled) and is re-sent on every turn while it is in view. Cap the size and length of clips on your side; the model can fold what it has watched with `compact` and get it back with `recall`.
|
|
86
|
+
|
|
79
87
|
## Sockets
|
|
80
88
|
|
|
81
89
|
A `Socket` is the seam brain modules use — five hooks (`beforeModel`, `afterModel`, `beforeTool`, `afterTool`, `onTurnEnd`) plus two static contributions (`tools`, `systemPrompt`, resolved once per run so prompt caches stay warm). Anything a socket wants the model to see is emitted as an event and lands in the log first; nothing is injected around the log. Every hook gets `ctx.batch`: the tool calls of the current batch, the results logged so far (in `beforeTool`, only those of earlier calls), the ids left waiting for approval / a client result / a paused sub-agent, and `resumed` when the batch is one a previous run left unfinished. It is one object updated in place during the turn — copy what you need instead of keeping a reference. A batch is one contiguous stretch of model output (`toolBatchOf`).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/events/base.ts","../src/events/id.ts","../src/events/create.ts","../src/events/registry.ts"],"sourcesContent":["/**\n * 事件基础类型(技术方案 §4)。\n *\n * 宪法二:时间线是唯一真源,角色只是翻译。内部只有一种数据 —— 带发起者的事件。\n * 本文件只定义\"所有事件共有的壳\",具体载荷见 ./core.ts(内置 core.*)与宿主自定义的 ext.*。\n */\n\n/** 事件发起者。用户打断、脑子注入、宿主插话都只是不同 actor 的一次 append。 */\nexport type Actor = \"user\" | \"model\" | \"tool\" | \"system\" | \"host\"\n\n/**\n * 信任等级,供投影层与安全网判断\"这段内容能不能当指令\"。\n * - principal:主事人(用户)说的\n * - system:库或宿主注入的\n * - model:模型自己产出的\n * - untrusted:工具输出、外部抓取内容(默认值,防提示注入)\n */\nexport type Trust = \"principal\" | \"system\" | \"model\" | \"untrusted\"\n\n/** 来源:哪个工具、哪个 URL、哪个用户。用于审计与信任判断。 */\nexport interface Provenance {\n source: string\n ref?: string\n}\n\n/**\n * 所有事件的公共字段。\n * 载荷放在 payload 下(而不是平铺),这样 schema 升级函数只碰 payload,壳永远稳定。\n */\nexport interface EventBase {\n /** uuidv7,时间有序;会话内唯一。fork 复制的事件保留原 id,以维持 parentId / pinsKept 等引用 */\n id: string\n sessionId: string\n /** 会话内单调递增,从 1 起;是会话内排序的唯一依据 */\n seq: number\n /** Unix 毫秒 */\n at: number\n /** 命名空间化:内置 \"core.*\",宿主扩展 \"ext.*\" */\n type: string\n /** 该 type 自己的 schema 版本,从 1 起;读时按注册表升级(P9) */\n schemaVersion: number\n actor: Actor\n /** 因果链或分叉点:回答哪条消息、由哪次 tool_call 产生 */\n parentId?: string\n trust: Trust\n provenance?: Provenance\n /** 厂商专有回放数据(thinking signature、encrypted reasoning),不进通用字段 */\n replay?: Record<string, unknown>\n}\n\n/** 带类型载荷的事件。T 为 type 字面量,P 为 payload 形状。 */\nexport type Event<T extends string = string, P = unknown> = EventBase & {\n type: T\n payload: P\n}\n\n/**\n * 内容片段。用户消息、工具结果都由它组成;投影/降级时再翻译成各家 API 的 content block。\n * 文本、图片、视频、音频,以及\"工具定义引用\"(L1);大结果不塞进片段,走 tool_result.spilled 外溢到 BlobStore。\n *\n * 消费片段的地方一律逐类型显式分支、末尾 `const _exhaustive: never = p` 收口——\n * \"不是文本就当图片\"的 else 兜底会让新加的片段类型悄悄落进图片分支(2026-11-05 视频 / 音频方案)。\n */\nexport type ContentPart = TextPart | ImagePart | VideoPart | AudioPart | ToolReferencePart\n\nexport interface TextPart {\n type: \"text\"\n text: string\n}\n\nexport interface ImagePart {\n type: \"image\"\n mime: string\n /** base64 编码的图片字节 */\n data: string\n}\n\n/**\n * 视频片段(2026-11-05,OnSet 建议 12)。音轨算视频的一部分,不另要 `audio` 能力位;纯音频文件用 AudioPart。\n * 模型收不收看 `LoweringCapabilities.video`,不收时降级层落文字占位并记 lossy。\n */\nexport interface VideoPart {\n type: \"video\"\n /** 必须以 \"video/\" 开头 */\n mime: string\n /** base64 编码的文件字节 */\n data: string\n /** 时长(秒,有限正数);只用于 token 估算,没有时按字节折算(偏高)。宿主拿得到就该给 */\n durationSec?: number\n}\n\n/** 音频片段(2026-11-05)。模型收不收看 `LoweringCapabilities.audio` */\nexport interface AudioPart {\n type: \"audio\"\n /** 必须以 \"audio/\" 开头 */\n mime: string\n /** base64 编码的文件字节 */\n data: string\n /** 时长(秒,有限正数);只用于 token 估算,没有时按字节折算(偏高) */\n durationSec?: number\n}\n\n/**\n * 工具定义引用(L1,2026-09-15):`tool_find` 这类\"取回工具\"的结果用它表达\"这几件工具从现在起可用\"。\n * 带完整定义快照,日志自足(宪法二:模型可见的一切都在日志里);翻译时按能力分两路——\n * 支持原生延迟加载的线(Anthropic `defer_loading`)只发 `tool_reference` 块、由厂商就地展开、工具表整段不变;\n * 其余线用 `renderToolReference` 展开成文本,信息等价。宿主经 HTTP 送来的用户消息不接受这种段(server 白名单)。\n */\nexport interface ToolReferencePart {\n type: \"tool_reference\"\n name: string\n description: string\n /** JSON Schema 对象,与 Tool.inputSchema 同形 */\n inputSchema: Record<string, unknown>\n}\n\n/** 引用段展开成文本的唯一写法:非原生线的降级层、UI、投影估算都调它,别各自拼 */\nexport function renderToolReference(part: ToolReferencePart): string {\n return `### ${part.name}\\n${part.description.trim()}\\nInput schema: ${JSON.stringify(part.inputSchema)}`\n}\n\n/** 各 actor 的默认信任等级;工厂函数在未显式给出 trust 时使用。 */\nexport const DEFAULT_TRUST: Readonly<Record<Actor, Trust>> = {\n user: \"principal\",\n system: \"system\",\n host: \"system\",\n model: \"model\",\n tool: \"untrusted\",\n}\n","/**\n * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。\n * 只用 Web 标准 crypto.getRandomValues,不引依赖(P5)。\n *\n * 同一毫秒内的多个 id 之间顺序随机 —— 会话内排序以 seq 为准,id 只需全局唯一且大致有序。\n */\nexport function uuidv7(now: number = Date.now()): string {\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n\n // 48 位时间戳,大端写入 bytes[0..5]\n let ts = now\n for (let i = 5; i >= 0; i--) {\n bytes[i] = ts & 0xff\n ts = Math.floor(ts / 256)\n }\n // 版本位:byte6 高 4 位 = 0111\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x70\n // 变体位:byte8 高 2 位 = 10\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80\n\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n","/**\n * 事件工厂:补齐 id / at / schemaVersion / trust,调用方只关心\"谁、在哪个会话、第几条、说了什么\"。\n * seq 由 EventLog 的 append 方决定(T4),这里要求显式传入,不替存储层做主。\n */\nimport { type Actor, DEFAULT_TRUST, type Event, type EventBase, type Provenance, type Trust } from \"./base.js\"\nimport type { CoreEventOf, CoreEventPayloads, CoreEventType } from \"./core.js\"\nimport { uuidv7 } from \"./id.js\"\nimport type { EventSchemaRegistry } from \"./registry.js\"\n\n/**\n * 事件草稿:还没进日志的事件,缺 id / seq / at / sessionId / schemaVersion。\n * 降级层(模型输出)与脑子模块(注入的 system_note)都只产出草稿,由循环补齐后 append ——\n * 谁分配 seq 只有循环知道,草稿不替它做主。\n */\nexport interface EventDraft<T extends string = string, P = unknown> {\n type: T\n payload: P\n actor: Actor\n /** 缺省按 DEFAULT_TRUST[actor] */\n trust?: Trust\n parentId?: string\n provenance?: Provenance\n replay?: Record<string, unknown>\n}\n\n/** 内置事件的草稿联合,type 与 payload 联动 */\nexport type CoreEventDraft = { [T in CoreEventType]: EventDraft<T, CoreEventPayloads[T]> }[CoreEventType]\n\nexport interface CreateEventInput<T extends string, P> extends EventDraft<T, P> {\n sessionId: string\n seq: number\n /** 测试注入用;缺省 Date.now() */\n at?: number\n id?: string\n}\n\n/**\n * 通用工厂。schemaVersion 从注册表取当前版本,所以未登记的 type 会在这里就被拒绝,\n * 而不是写进日志后读不出来。\n */\nexport function createEvent<T extends string, P>(\n registry: EventSchemaRegistry,\n input: CreateEventInput<T, P>,\n): Event<T, P> {\n const at = input.at ?? Date.now()\n const base: EventBase = {\n id: input.id ?? uuidv7(at),\n sessionId: input.sessionId,\n seq: input.seq,\n at,\n type: input.type,\n schemaVersion: registry.currentVersion(input.type),\n actor: input.actor,\n trust: input.trust ?? DEFAULT_TRUST[input.actor],\n }\n // 可选字段只在有值时写入,避免日志里出现一堆 undefined(exactOptionalPropertyTypes 也不允许)\n if (input.parentId !== undefined) base.parentId = input.parentId\n if (input.provenance !== undefined) base.provenance = input.provenance\n if (input.replay !== undefined) base.replay = input.replay\n return { ...base, type: input.type, payload: input.payload }\n}\n\n/** 内置事件的强类型版本:type 与 payload 联动校验。 */\nexport function createCoreEvent<T extends CoreEventType>(\n registry: EventSchemaRegistry,\n input: CreateEventInput<T, CoreEventPayloads[T]>,\n): CoreEventOf<T> {\n return createEvent(registry, input) as CoreEventOf<T>\n}\n","/**\n * 事件 schema 注册表(P9:schema 有版本,读时升级,查不到即拒绝)。\n *\n * 职责:\n * 1. 登记每个 type 的当前版本与逐级升级函数 upcast(v → v+1)\n * 2. read(raw):校验壳字段 → 查 type → 逐级升级到当前版本 → 返回类型化事件\n * 3. 任何一步查不到都抛 SchemaError(fail-closed),绝不静默返回半个事件\n *\n * 日志文件不做原地迁移:存的永远是写入时的版本,读时升级。\n */\nimport type { Actor, Event, EventBase, Trust } from \"./base.js\"\nimport type { CoreEventType } from \"./core.js\"\n\n/** 把 payload 从版本 from 升到 from+1。只碰 payload,壳字段由注册表保证不变。 */\nexport type Upcaster = (payload: unknown) => unknown\n\nexport interface EventSchema {\n type: string\n /** 当前版本;新写入的事件一律打这个版本号 */\n version: number\n /**\n * 升级函数表,键为\"起点版本\":upcasters[1] 把 v1 升到 v2。\n * version 为 n 时必须覆盖 1..n-1 全部键,缺一个即注册失败 —— 宁可启动时报错,不要读到一半才发现。\n */\n upcasters?: Readonly<Record<number, Upcaster>>\n}\n\nexport type SchemaErrorCode =\n | \"malformed_base\" // 壳字段缺失或类型不对\n | \"unknown_type\" // 没登记的 type\n | \"future_version\" // 版本比注册表还新(旧代码读新日志)\n | \"missing_upcaster\" // 升级链断了\n | \"upcaster_failed\" // 升级函数自己抛了\n | \"invalid_schema\" // 登记时的定义不合法\n\nexport class SchemaError extends Error {\n constructor(\n readonly code: SchemaErrorCode,\n message: string,\n readonly context: { type?: string; version?: number } = {},\n ) {\n super(`[${code}] ${message}`)\n this.name = \"SchemaError\"\n }\n}\n\nconst ACTORS: ReadonlySet<string> = new Set<Actor>([\"user\", \"model\", \"tool\", \"system\", \"host\"])\nconst TRUSTS: ReadonlySet<string> = new Set<Trust>([\"principal\", \"system\", \"model\", \"untrusted\"])\n\nexport class EventSchemaRegistry {\n private readonly schemas = new Map<string, EventSchema>()\n\n constructor(schemas: Iterable<EventSchema> = []) {\n for (const s of schemas) this.register(s)\n }\n\n /** 登记一个 type。重复登记同一 type 视为错误,避免两处定义互相覆盖。 */\n register(schema: EventSchema): this {\n if (!schema.type || !/^(core|ext)\\.[a-z][a-z0-9_]*$/.test(schema.type)) {\n throw new SchemaError(\n \"invalid_schema\",\n `type must look like \"core.xxx\" or \"ext.xxx\", got ${schema.type}`,\n {\n type: schema.type,\n },\n )\n }\n if (!Number.isInteger(schema.version) || schema.version < 1) {\n throw new SchemaError(\"invalid_schema\", `version must be an integer >= 1, got ${schema.version}`, {\n type: schema.type,\n version: schema.version,\n })\n }\n if (this.schemas.has(schema.type)) {\n throw new SchemaError(\"invalid_schema\", `type already registered: ${schema.type}`, {\n type: schema.type,\n })\n }\n for (let v = 1; v < schema.version; v++) {\n if (typeof schema.upcasters?.[v] !== \"function\") {\n throw new SchemaError(\n \"invalid_schema\",\n `${schema.type} is at version ${schema.version} but has no v${v} -> v${v + 1} upgrade function`,\n { type: schema.type, version: v },\n )\n }\n }\n this.schemas.set(schema.type, schema)\n return this\n }\n\n has(type: string): boolean {\n return this.schemas.has(type)\n }\n\n /** 该 type 当前应写入的版本号;未登记则抛 unknown_type。 */\n currentVersion(type: string): number {\n const s = this.schemas.get(type)\n if (!s) throw new SchemaError(\"unknown_type\", `unregistered event type: ${type}`, { type })\n return s.version\n }\n\n /**\n * 从存储读出的原始对象 → 当前版本的事件。\n * 泛型只是给调用方的类型提示(如 read<CoreEvent>),运行时校验的是壳与版本,不校验 payload 形状 ——\n * payload 的正确性由写入方与升级函数负责。\n */\n read<E extends Event = Event>(raw: unknown): E {\n const base = assertBase(raw)\n const schema = this.schemas.get(base.type)\n if (!schema) {\n throw new SchemaError(\"unknown_type\", `unregistered event type: ${base.type}`, { type: base.type })\n }\n if (base.schemaVersion > schema.version) {\n throw new SchemaError(\n \"future_version\",\n `${base.type} v${base.schemaVersion} is newer than the locally known v${schema.version}; upgrade the code`,\n { type: base.type, version: base.schemaVersion },\n )\n }\n\n let payload = (raw as { payload?: unknown }).payload\n for (let v = base.schemaVersion; v < schema.version; v++) {\n const up = schema.upcasters?.[v]\n if (!up) {\n // register() 已保证不会走到这里,留作防御\n throw new SchemaError(\"missing_upcaster\", `${base.type} has no v${v} -> v${v + 1} upgrade function`, {\n type: base.type,\n version: v,\n })\n }\n try {\n payload = up(payload)\n } catch (cause) {\n throw new SchemaError(\n \"upcaster_failed\",\n `${base.type} v${v} -> v${v + 1} upgrade failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n { type: base.type, version: v },\n )\n }\n }\n\n return { ...base, schemaVersion: schema.version, payload } as E\n }\n}\n\n/** 校验壳字段。只看公共字段,payload 不管。 */\nfunction assertBase(raw: unknown): EventBase {\n if (typeof raw !== \"object\" || raw === null) {\n throw new SchemaError(\"malformed_base\", \"event must be an object\")\n }\n const r = raw as Record<string, unknown>\n const fail = (field: string, expect: string): never => {\n throw new SchemaError(\n \"malformed_base\",\n `field ${field} must be ${expect}`,\n typeof r.type === \"string\" ? { type: r.type } : {},\n )\n }\n if (typeof r.id !== \"string\" || r.id === \"\") fail(\"id\", \"a non-empty string\")\n if (typeof r.sessionId !== \"string\" || r.sessionId === \"\") fail(\"sessionId\", \"a non-empty string\")\n if (!Number.isInteger(r.seq) || (r.seq as number) < 1) fail(\"seq\", \"an integer >= 1\")\n if (typeof r.at !== \"number\" || !Number.isFinite(r.at)) fail(\"at\", \"a finite number\")\n if (typeof r.type !== \"string\" || r.type === \"\") fail(\"type\", \"a non-empty string\")\n if (!Number.isInteger(r.schemaVersion) || (r.schemaVersion as number) < 1)\n fail(\"schemaVersion\", \"an integer >= 1\")\n if (typeof r.actor !== \"string\" || !ACTORS.has(r.actor)) fail(\"actor\", \"user|model|tool|system|host\")\n if (typeof r.trust !== \"string\" || !TRUSTS.has(r.trust)) fail(\"trust\", \"principal|system|model|untrusted\")\n if (r.parentId !== undefined && typeof r.parentId !== \"string\") fail(\"parentId\", \"a string or undefined\")\n if (r.provenance !== undefined) {\n const p = r.provenance as Record<string, unknown> | null\n if (typeof p !== \"object\" || p === null || typeof p.source !== \"string\")\n fail(\"provenance\", \"{ source: string }\")\n }\n if (r.replay !== undefined && (typeof r.replay !== \"object\" || r.replay === null))\n fail(\"replay\", \"an object or undefined\")\n return r as unknown as EventBase\n}\n\n/** 全部内置事件当前都是 v1。升版本时在此加 upcasters,并在 core.ts 改载荷类型。 */\nexport const CORE_SCHEMAS: readonly EventSchema[] = (\n [\n \"core.user_message\",\n \"core.model_text\",\n \"core.model_thinking\",\n \"core.tool_call\",\n \"core.tool_result\",\n \"core.system_note\",\n \"core.approval_request\",\n \"core.approval_decision\",\n \"core.compaction\",\n \"core.handoff\",\n \"core.memory_op\",\n \"core.budget_usage\",\n \"core.run_paused\",\n \"core.run_resumed\",\n \"core.tools_bound\",\n \"core.error\",\n ] satisfies CoreEventType[]\n).map((type) => ({ type, version: 1 }))\n\n/** 预装了全部 core.* 的注册表。宿主要加 ext.* 时 new 一个并传入 [...CORE_SCHEMAS, ...自己的]。 */\nexport function createCoreRegistry(extra: Iterable<EventSchema> = []): EventSchemaRegistry {\n return new EventSchemaRegistry([...CORE_SCHEMAS, ...extra])\n}\n"],"mappings":";AAqHO,SAAS,oBAAoB,MAAiC;AACnE,SAAO,OAAO,KAAK,IAAI;AAAA,EAAK,KAAK,YAAY,KAAK,CAAC;AAAA,gBAAmB,KAAK,UAAU,KAAK,WAAW,CAAC;AACxG;AAGO,IAAM,gBAAgD;AAAA,EAC3D,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AACR;;;AC1HO,SAAS,OAAO,MAAc,KAAK,IAAI,GAAW;AACvD,QAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,SAAO,gBAAgB,KAAK;AAG5B,MAAI,KAAK;AACT,WAAS,IAAI,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,IAA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;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-
|
|
2
|
-
export { s as Actor, t as AnyEvent, u as ApprovalDecisionPayload, v as
|
|
1
|
+
import { E as Event, a as EventSchemaRegistry, b as EventLog, B as BlobStore, M as MemoryStore, c as EventDraft, T as TokenUsage, C as ContentPart, d as Trust, L as Lowering, e as ModelRef, f as LoweringCapabilities, g as CoreEventOf, h as ToolResultPayload, i as LoweringDelta, j as LandingRecord, k as LoweredRequest, l as ErrorPayload, A as ApprovalRequestPayload, m as ToolCallPayload, n as ToolSpec, o as CoreEventDraft, p as BudgetUsagePayload, q as BlobMeta, R as ReadOptions, r as RunLease, S as Stores } from './types-BlyGZlJp.js';
|
|
2
|
+
export { s as Actor, t as AnyEvent, u as ApprovalDecisionPayload, v as AudioPart, w as BoundModel, x as CORE_SCHEMAS, y as CompactionPayload, z as CoreEvent, D as CoreEventPayloads, F as CoreEventType, G as CreateEventInput, H as DEFAULT_TRUST, I as EventBase, J as EventSchema, K as ExtEvent, N as HandoffPayload, O as ImagePart, P as LandingSpec, Q as LossKind, U as LossMatrix, V as LoweringOutcome, W as LoweringStreamContext, X as MemoryOpPayload, Y as ModelTextPayload, Z as ModelThinkingPayload, _ as Provenance, $ as RunPausedPayload, a0 as RunResumedPayload, a1 as SchemaError, a2 as SchemaErrorCode, a3 as SkillSource, a4 as SystemNotePayload, a5 as TextPart, a6 as ToRequestInput, a7 as ToolReferencePart, a8 as ToolsBoundPayload, a9 as Upcaster, aa as UserMessagePayload, ab as VideoPart, ac as contextOverheadOf, ad as contextTokensOf, ae as createCoreEvent, af as createCoreRegistry, ag as createEvent, ah as lossesOf, ai as renderToolReference } from './types-BlyGZlJp.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
|
|
@@ -730,7 +730,13 @@ declare function defineTool<TInput>(tool: Tool<TInput>): Tool;
|
|
|
730
730
|
declare function toolSpecOf(tool: Tool): ToolSpec;
|
|
731
731
|
/** 带"声明但不载入"标记的规格(L1):runLoop 按 BeforeModelPatch.deferredTools 对本轮工具表逐件调 */
|
|
732
732
|
declare function deferredToolSpecOf(tool: Tool, deferred: boolean): ToolSpec;
|
|
733
|
-
/**
|
|
733
|
+
/**
|
|
734
|
+
* 内容片段的形状校验,全包唯一一份(真源索引):工具返回值归一(本文件)与 runLoop 输入草稿 / 片段数组(run-loop.ts)都调它。
|
|
735
|
+
* 坏片段一旦进日志,之后每次读到它都会崩(会话报废),所以在写之前拦。
|
|
736
|
+
* 规则:text 有 `text`;image 有 `mime` 与 `data`(mime 不校验,历史行为);video / audio 的 mime 以 "video/" / "audio/" 开头、
|
|
737
|
+
* `durationSec` 缺省或为有限正数;tool_reference 有名字、描述与对象形 inputSchema。
|
|
738
|
+
* 宿主经 HTTP 送来的用户消息另有白名单(server `rebuildContentParts`,两份实现靠跨包用例锁同口径),不含引用段
|
|
739
|
+
*/
|
|
734
740
|
declare function isContentPart(x: unknown): x is ContentPart;
|
|
735
741
|
/**
|
|
736
742
|
* execute 的返回值 → 模型看到的内容。规则按直觉:
|
|
@@ -869,7 +875,12 @@ declare function needsUntrustedMark(e: Event): boolean;
|
|
|
869
875
|
* 供预算裁剪兜底与感知档位使用。宿主要精确数字就注入自己的 TokenEstimator。
|
|
870
876
|
*
|
|
871
877
|
* 规则:ASCII 字符约 4 个一个 token;非 ASCII(中日韩等)按一字一 token 保守计;
|
|
872
|
-
* 图片按 Anthropic
|
|
878
|
+
* 图片按 Anthropic 单图上限附近取常量;视频 / 音频按时长计;每条事件再加角色与分隔的固定开销。
|
|
879
|
+
*
|
|
880
|
+
* 视频 / 音频费率来源:2026-11-05 视频音频方案 P0 实测(spikes/media-parts,中转站 Gemini flash 低分辨率档)——
|
|
881
|
+
* 视频每秒 91 token(含音轨,与码率、画面内容无关)、音频每秒 25;取 100 / 32 留余量(32 也是 Gemini 公开音频费率)。
|
|
882
|
+
* 没有 durationSec 时按字节折算:码率实测相差约 60 倍,所以按偏低码率(视频 1 Mbps、音频 64 kbps)折算并设 30 秒下限,
|
|
883
|
+
* 宁高勿低(偏高只是整理提前,偏低会溢出)。要别的费率就注入自己的 TokenEstimator,不另加开关。
|
|
873
884
|
*/
|
|
874
885
|
|
|
875
886
|
declare function estimateTextTokens(text: string): number;
|
|
@@ -1241,6 +1252,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
|
|
|
1241
1252
|
*/
|
|
1242
1253
|
|
|
1243
1254
|
/** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
|
|
1244
|
-
declare const REINS_VERSION = "0.
|
|
1255
|
+
declare const REINS_VERSION = "0.9.0";
|
|
1245
1256
|
|
|
1246
1257
|
export { type ApprovalDecisionInput, ApprovalRequestPayload, type ApprovalRequestSpec, BUILTIN_APPROVAL_POLICY, type BeforeModelPatch, type BeforeToolDecision, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, type DecodedToolArguments, type DefaultChainOptions, type ErrorEventPayload, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, type HandoffIntent, INPUT_DRAFT_TYPES, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, type PauseReason, type Principal, type ProjectOptions, type ProjectionBudget, type ProjectionContext, type ProjectionResult, type ProjectionStats, type ProjectionStep, type ProjectionStepStats, type ProjectionStrategy, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, type ResolvedRetry, type RetryOptions, RunLease, type RunResult, RunStateError, type RunStateErrorCode, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, StoreError, type StoreErrorCode, Stores, type SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, type TokenEstimator, TokenUsage, type Tool, type ToolBatch, type ToolCallEvent, ToolCallPayload, type ToolContext, type ToolNamesDiff, type ToolResult, type ToolResultDraft, type ToolResultEvent, ToolResultPayload, type ToolSide, ToolSpec, type ToolsBoundEvent, Trust, type TurnContext, type TurnDecision, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, backoffDelayMs, budgetTruncate, computeConfigHash, computePendingDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultSleep, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDrafts, isCompaction, isContentPart, isModelOutput, isPinNote, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, statusFromMessage, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter };
|
package/dist/index.js
CHANGED
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
createEvent,
|
|
9
9
|
renderToolReference,
|
|
10
10
|
uuidv7
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-GWU2JSFA.js";
|
|
12
12
|
|
|
13
13
|
// src/events/core.ts
|
|
14
14
|
function contextTokensOf(usage) {
|
|
@@ -50,6 +50,16 @@ function visibilityFilter(opts = {}) {
|
|
|
50
50
|
// src/projection/estimate.ts
|
|
51
51
|
var PER_EVENT_OVERHEAD = 4;
|
|
52
52
|
var IMAGE_TOKENS = 1600;
|
|
53
|
+
var VIDEO_TOKENS_PER_SEC = 100;
|
|
54
|
+
var AUDIO_TOKENS_PER_SEC = 32;
|
|
55
|
+
var VIDEO_BYTES_PER_SEC = 125e3;
|
|
56
|
+
var AUDIO_BYTES_PER_SEC = 8e3;
|
|
57
|
+
var MIN_GUESSED_SEC = 30;
|
|
58
|
+
function mediaSeconds(part, bytesPerSec) {
|
|
59
|
+
if (part.durationSec !== void 0) return part.durationSec;
|
|
60
|
+
const bytes = part.data.length * 3 / 4;
|
|
61
|
+
return Math.max(bytes / bytesPerSec, MIN_GUESSED_SEC);
|
|
62
|
+
}
|
|
53
63
|
function estimateTextTokens(text) {
|
|
54
64
|
let ascii = 0;
|
|
55
65
|
let other = 0;
|
|
@@ -62,9 +72,27 @@ function estimateTextTokens(text) {
|
|
|
62
72
|
function partsTokens(parts) {
|
|
63
73
|
let n = 0;
|
|
64
74
|
for (const p of parts) {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
75
|
+
switch (p.type) {
|
|
76
|
+
case "text":
|
|
77
|
+
n += estimateTextTokens(p.text);
|
|
78
|
+
break;
|
|
79
|
+
case "tool_reference":
|
|
80
|
+
n += estimateTextTokens(renderToolReference(p));
|
|
81
|
+
break;
|
|
82
|
+
case "image":
|
|
83
|
+
n += IMAGE_TOKENS;
|
|
84
|
+
break;
|
|
85
|
+
case "video":
|
|
86
|
+
n += Math.ceil(mediaSeconds(p, VIDEO_BYTES_PER_SEC) * VIDEO_TOKENS_PER_SEC);
|
|
87
|
+
break;
|
|
88
|
+
case "audio":
|
|
89
|
+
n += Math.ceil(mediaSeconds(p, AUDIO_BYTES_PER_SEC) * AUDIO_TOKENS_PER_SEC);
|
|
90
|
+
break;
|
|
91
|
+
default: {
|
|
92
|
+
const _exhaustive = p;
|
|
93
|
+
void _exhaustive;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
68
96
|
}
|
|
69
97
|
return n;
|
|
70
98
|
}
|
|
@@ -294,8 +322,24 @@ function splitTurns(events) {
|
|
|
294
322
|
return turns;
|
|
295
323
|
}
|
|
296
324
|
var DEFAULT_CUT_TO_RATIO = 0.6;
|
|
325
|
+
function partExcerpt(p) {
|
|
326
|
+
switch (p.type) {
|
|
327
|
+
case "text":
|
|
328
|
+
return p.text;
|
|
329
|
+
case "image":
|
|
330
|
+
case "video":
|
|
331
|
+
case "audio":
|
|
332
|
+
return `[${p.type}]`;
|
|
333
|
+
case "tool_reference":
|
|
334
|
+
return `[tool ${p.name}]`;
|
|
335
|
+
default: {
|
|
336
|
+
const _exhaustive = p;
|
|
337
|
+
return _exhaustive;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
297
341
|
function excerpt(parts, max = 120) {
|
|
298
|
-
const text = parts.map(
|
|
342
|
+
const text = parts.map(partExcerpt).join(" ").replace(/\s+/g, " ").trim();
|
|
299
343
|
return text.length > max ? `${text.slice(0, max)}\u2026` : text;
|
|
300
344
|
}
|
|
301
345
|
var defaultThresholdSummary = (removed, ctx) => {
|
|
@@ -925,15 +969,25 @@ function toolSpecOf(tool) {
|
|
|
925
969
|
function deferredToolSpecOf(tool, deferred) {
|
|
926
970
|
return deferred ? { ...toolSpecOf(tool), deferLoading: true } : toolSpecOf(tool);
|
|
927
971
|
}
|
|
972
|
+
function isDuration(x) {
|
|
973
|
+
return x === void 0 || typeof x === "number" && Number.isFinite(x) && x > 0;
|
|
974
|
+
}
|
|
928
975
|
function isContentPart(x) {
|
|
929
976
|
if (typeof x !== "object" || x === null) return false;
|
|
930
977
|
const p = x;
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
978
|
+
switch (p.type) {
|
|
979
|
+
case "text":
|
|
980
|
+
return typeof p.text === "string";
|
|
981
|
+
case "image":
|
|
982
|
+
return typeof p.mime === "string" && typeof p.data === "string";
|
|
983
|
+
case "video":
|
|
984
|
+
case "audio":
|
|
985
|
+
return typeof p.mime === "string" && p.mime.startsWith(`${p.type}/`) && typeof p.data === "string" && isDuration(p.durationSec);
|
|
986
|
+
case "tool_reference":
|
|
987
|
+
return typeof p.name === "string" && typeof p.description === "string" && typeof p.inputSchema === "object" && p.inputSchema !== null && !Array.isArray(p.inputSchema);
|
|
988
|
+
default:
|
|
989
|
+
return false;
|
|
935
990
|
}
|
|
936
|
-
return false;
|
|
937
991
|
}
|
|
938
992
|
function isToolResult(x) {
|
|
939
993
|
if (typeof x !== "object" || x === null) return false;
|
|
@@ -1002,7 +1056,7 @@ var INPUT_DRAFT_TYPES = /* @__PURE__ */ new Set([
|
|
|
1002
1056
|
"core.system_note"
|
|
1003
1057
|
]);
|
|
1004
1058
|
var INPUT_ACTORS = /* @__PURE__ */ new Set(["user", "model", "tool", "system", "host"]);
|
|
1005
|
-
var CONTENT_PART_TYPES = /* @__PURE__ */ new Set(["text", "image", "tool_reference"]);
|
|
1059
|
+
var CONTENT_PART_TYPES = /* @__PURE__ */ new Set(["text", "image", "video", "audio", "tool_reference"]);
|
|
1006
1060
|
function classifyInputItem(item) {
|
|
1007
1061
|
if (typeof item !== "object" || item === null) return void 0;
|
|
1008
1062
|
const { type, actor } = item;
|
|
@@ -1013,16 +1067,7 @@ function classifyInputItem(item) {
|
|
|
1013
1067
|
}
|
|
1014
1068
|
var NOTE_KINDS = /* @__PURE__ */ new Set(["perception", "pin", "budget", "host"]);
|
|
1015
1069
|
function isContentPartList(x) {
|
|
1016
|
-
|
|
1017
|
-
return x.every((p) => {
|
|
1018
|
-
if (typeof p !== "object" || p === null) return false;
|
|
1019
|
-
const part = p;
|
|
1020
|
-
if (part.type === "text") return typeof part.text === "string";
|
|
1021
|
-
if (part.type === "image") return typeof part.mime === "string" && typeof part.data === "string";
|
|
1022
|
-
if (part.type === "tool_reference")
|
|
1023
|
-
return typeof part.name === "string" && typeof part.description === "string" && typeof part.inputSchema === "object" && part.inputSchema !== null;
|
|
1024
|
-
return false;
|
|
1025
|
-
});
|
|
1070
|
+
return Array.isArray(x) && x.every(isContentPart);
|
|
1026
1071
|
}
|
|
1027
1072
|
function corePayloadProblem(draft) {
|
|
1028
1073
|
const p = typeof draft.payload === "object" && draft.payload !== null ? draft.payload : {};
|
|
@@ -1925,7 +1970,7 @@ function memoryStore() {
|
|
|
1925
1970
|
}
|
|
1926
1971
|
|
|
1927
1972
|
// src/index.ts
|
|
1928
|
-
var REINS_VERSION = "0.
|
|
1973
|
+
var REINS_VERSION = "0.9.0";
|
|
1929
1974
|
export {
|
|
1930
1975
|
BUILTIN_APPROVAL_POLICY,
|
|
1931
1976
|
CORE_SCHEMAS,
|