@reinsjs/core 0.14.1 → 0.16.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 +13 -0
- package/README.md +16 -1
- package/dist/{chunk-DFXHUJV4.js → chunk-7RHFFDGN.js} +7 -2
- package/dist/chunk-7RHFFDGN.js.map +1 -0
- package/dist/{core-BhmO9N-j.d.ts → core-BxGiBJ_p.d.ts} +58 -7
- package/dist/index.d.ts +181 -6
- package/dist/index.js +342 -39
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-DFXHUJV4.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @reinsjs/core
|
|
2
2
|
|
|
3
|
+
## 0.16.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- c47e62b: Images can be stored by reference: `{ type: "image", mime, blobId }`, with the bytes in the `BlobStore` and only the id in the log. Right before each model call `runLoop` swaps the references in view for inline images (`hydrateImageRefs`, at most one read per blob per run), so lowerings see exactly what the inline form would give; folded images are not read. References are checked before anything is written — initial `input` (`RangeError`), `pullInput` (run ends with a `core.error` of category `input`), tool results (only the offending part is replaced; the rest is kept) — and every rejection reads `Blob <id> not found in this session`. A blob that no longer exists is passed on as a reference and becomes `[image unavailable]` in the lowering; other storage errors fail the model call like a network error. New exports: `isImageRef`, `mediaRefsOf`, `blobUsableBy`, `checkImageRefs`, `imageRefNotFound`, `hydrateImageRefs`, `bytesToBase64`, `ImageInlinePart`, `ImageRefPart`; `ImagePart` is now a union of the two, so code reading `.data` must check `isImageRef` first. `core.user_message` and `core.tool_result` are written as schema v2 (v1 upgrades unchanged): sessions written by this version cannot be read by 0.15 or earlier — upgrade every instance together.
|
|
8
|
+
- 12d9343: Folded media in user messages is now listed: new exports `foldedUserMedia(removed)` and `renderFoldedUserMedia(items, { heading, maxItems })` pick the user messages that carried images, video or audio out of a folded range, by `seq`. The default threshold summary (`defaultThresholdSummary`) appends such a list when the removed range contains one; summaries without media are unchanged.
|
|
9
|
+
|
|
10
|
+
## 0.15.0
|
|
11
|
+
|
|
12
|
+
### Minor Changes
|
|
13
|
+
|
|
14
|
+
- f8a3550: Pause codes: a socket’s `onTurnEnd` may now return `{ pause: { reason, code, note } }`. The `code` (your own identifier such as `acme.credits_exhausted`, format `PAUSE_CODE_RE`) and the note are written into `core.run_paused`, the code is on the live `Interruption` and on `RunStatus.paused.code`, so a later request or another process can tell why a run paused. reins never branches on it and it is not part of the resume state. The loop’s own `maxTurns` pause carries `reins.max_turns`. A code that does not match the format is dropped: the run still pauses, and a model-invisible `core.error` (category `input`, `detail.phase: "onTurnEnd"`) is logged before the `core.run_paused`. A `reason` other than `"budget"` / `"host"` is handled the same way and pauses with `host`. New exports: `PAUSE_CODE_RE`, `isPauseCode`, `MAX_TURNS_PAUSE_CODE`, `resolveSocketPause`, `pauseDetailOf`. Note: `core.run_paused` now also records the `note` of loop-originated pauses (aborts, user stop, `maxTurns`), so code that compares that payload for exact equality sees a new optional field.
|
|
15
|
+
|
|
3
16
|
## 0.14.1
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -124,7 +124,20 @@ Content parts are `text`, `image`, `video`, `audio` and `tool_reference`. A `vid
|
|
|
124
124
|
|
|
125
125
|
- **Capabilities decide, not mime types.** `LoweringCapabilities.video` / `audio` are optional and mean "no" when absent: a lowering that does not take them replaces the part with a placeholder and records the event `lossy`, so the run goes on instead of the provider answering 400.
|
|
126
126
|
- **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`.
|
|
127
|
-
- **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
|
|
127
|
+
- **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. With `@reinsjs/brain`'s `compact`, the model can fold what it has seen and bring it back with `recall({ seq })`: from a tool result, or from a user message (a summary lists folded user messages that carried media by `seq`).
|
|
128
|
+
|
|
129
|
+
### Images by reference
|
|
130
|
+
|
|
131
|
+
An image can also be a reference: `{ type: "image", mime, blobId }`. The bytes live in the `BlobStore` (`LoopConfig.blobs`) and the log keeps only the id, so a session with many screenshots stays small and a picture is stored once. `put` the **raw bytes** (not a base64 string) under the session's id, then send the reference — `put` does not require the session to exist yet.
|
|
132
|
+
|
|
133
|
+
- **What the model sees is unchanged.** Right before each model call the loop swaps the references that are in view for inline images (`hydrateImageRefs`), so the request is byte-for-byte what the inline form would produce. Folded images are not read at all. Sockets and the token estimate keep seeing the reference (an image counts 1 600 tokens either way). Each blob is read at most once per run.
|
|
134
|
+
- **References are checked before anything is written** — the initial `input` (`RangeError`, nothing written), messages pulled mid-run (the run ends with a `core.error` of category `input`), tool results (only the offending part is replaced with the sentence below; the rest of the result is kept), and the HTTP handler (`400`). A reference is accepted when the blob belongs to this session, or when this session's timeline already shows it as an image (a forked session can show its parent's pictures), and its `mime` equals the blob's. Every failure — missing blob, someone else's blob, wrong mime, no `BlobStore` — reads `Blob <id> not found in this session`, so a client cannot probe other sessions. A storage error while checking is not a rejection: the initial `input` rethrows it, a mid-run pull logs it and tries again later, a tool result gets `Could not read blob <id>: storage error` in place of that part, with the cause in a model-invisible `core.error`.
|
|
135
|
+
- **Shape.** `mime` must start with `image/`; `blobId` is 1–128 characters; `data` and `blobId` never appear together. A spilled tool output (a text blob) can therefore never pass as an image.
|
|
136
|
+
- **When the bytes are gone.** If a referenced blob no longer exists (you deleted it, or there is no `BlobStore`), the lowering writes `[image unavailable]` in its place and records the event `lossy`; the run goes on. Any other storage error fails the model call like a network error (retried if transient), so the model never answers a placeholder because of a hiccup.
|
|
137
|
+
- **Blobs are immutable.** A `BlobStore` must never reuse an id or change bytes after `put`: "the log plus its blobs" is what the model saw. Replaying a session through a lowering (`replayTurns` + `toRequest`) needs the same `BlobStore` — call `hydrateImageRefs` first, as `examples/minimal/replay.ts` does.
|
|
138
|
+
- **Forks and cleanup.** `fork` copies events, not blobs; a forked session points at its parent's blobs. If you delete a parent session's blobs, references in its forks show as unavailable.
|
|
139
|
+
- **Only images.** Video and audio stay inline for now. The model has no separate "look again" tool: `recall({ seq })` brings back a folded message, and its result keeps the reference, so nothing is stored twice.
|
|
140
|
+
- **Paths without a `runLoop`.** The TanStack AI adapter neither checks nor loads blobs: a reference becomes `[image unavailable]` there (recorded `lossy`), and references in tool results are replaced with that text before they are logged. Hosts that call `toRequest` directly must call `hydrateImageRefs` themselves.
|
|
128
141
|
|
|
129
142
|
## Sockets
|
|
130
143
|
|
|
@@ -137,6 +150,8 @@ A `Socket` is the seam brain modules use — five hooks (`beforeModel`, `afterMo
|
|
|
137
150
|
- **Bounded retry only on zero output.** A transient failure (network, 5xx, 429 — decided from the status code first, keywords only as a fallback) is retried up to 3 times, but never after a partial response has been appended: the log must not contain two half answers.
|
|
138
151
|
- **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
152
|
- **Every run is bracketed (0.14).** `runLoop` starts each run with a model-invisible `core.tools_bound` (`marksEnd: true`) and ends it with exactly one end marker: `core.run_paused` for a pause (now with `awaiting` — the calls waiting on an approval, a client tool or a sub-agent — and `stopped` for a user stop), or `core.run_ended` with `status: "done" | "handoff" | "error"`. A `core.error` the loop retries past, or one from a throwing `pullInput`, gets no `run_ended`. `runStatusOf({ held, lastMarker })` turns a lease flag and `lastRunMarker(timeline)` into running / paused / done / handoff / error / interrupted / idle / unknown; `@reinsjs/store-pg` has `pgRunStates` for a whole session list in one statement. Sessions containing `core.run_ended` cannot be read by 0.13 or earlier: upgrade every instance together and do not roll back.
|
|
153
|
+
- **Pause codes (0.15).** A socket's `pause` may carry a `code` — your own short identifier such as `acme.credits_exhausted` — next to `reason` and `note`. It is written into `core.run_paused` together with the note and comes back as `RunStatus.paused.code`, so another request or process can tell why the run paused without guessing. reins never branches on it and it is not part of the resume state. Format: `PAUSE_CODE_RE` (lowercase letters, digits, `_ . : -`, starting with a letter or digit, at most 64 characters); a code that does not match is dropped — the run still pauses, and a model-invisible `core.error` (category `input`, `detail.phase: "onTurnEnd"`, no `run_ended` after it) is logged just before the `core.run_paused`. The same happens when `reason` is anything but `"budget"` or `"host"`: the run pauses with `host`. Put your own reasons in `code`. The `reins.` prefix is used by built-in sources: `reins.max_turns` (the loop's `maxTurns` limit), `reins.budget` and `reins.compact_stalled` (from `@reinsjs/brain`). Aborts and user stops carry no code. A paused sub-agent's code stays in the child session — look it up through `awaiting[].childSessionId`.
|
|
154
|
+
- **Rollback caveat (0.16).** `core.user_message` and `core.tool_result` are now written as schema v2 (v1 reads as v2 unchanged), because their content may hold image references. Sessions written by 0.16 cannot be read by 0.15 or earlier (`future_version`): upgrade every instance together and do not roll back.
|
|
140
155
|
- **Deterministic given the log.** Time and ids are injected (`now`, `newId`), so a recorded session replays byte-for-byte in tests.
|
|
141
156
|
|
|
142
157
|
## Documentation
|
|
@@ -181,6 +181,11 @@ function assertBase(raw) {
|
|
|
181
181
|
fail("replay", "an object or undefined");
|
|
182
182
|
return r;
|
|
183
183
|
}
|
|
184
|
+
var identity = (payload) => payload;
|
|
185
|
+
var UPGRADED = {
|
|
186
|
+
"core.user_message": { type: "core.user_message", version: 2, upcasters: { 1: identity } },
|
|
187
|
+
"core.tool_result": { type: "core.tool_result", version: 2, upcasters: { 1: identity } }
|
|
188
|
+
};
|
|
184
189
|
var CORE_SCHEMAS = [
|
|
185
190
|
"core.user_message",
|
|
186
191
|
"core.model_text",
|
|
@@ -200,7 +205,7 @@ var CORE_SCHEMAS = [
|
|
|
200
205
|
"core.tools_bound",
|
|
201
206
|
"core.run_ended",
|
|
202
207
|
"core.error"
|
|
203
|
-
].map((type) =>
|
|
208
|
+
].map((type) => UPGRADED[type] ?? { type, version: 1 });
|
|
204
209
|
function createCoreRegistry(extra = []) {
|
|
205
210
|
return new EventSchemaRegistry([...CORE_SCHEMAS, ...extra]);
|
|
206
211
|
}
|
|
@@ -216,4 +221,4 @@ export {
|
|
|
216
221
|
CORE_SCHEMAS,
|
|
217
222
|
createCoreRegistry
|
|
218
223
|
};
|
|
219
|
-
//# sourceMappingURL=chunk-
|
|
224
|
+
//# sourceMappingURL=chunk-7RHFFDGN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/events/base.ts","../src/events/id.ts","../src/events/create.ts","../src/events/registry.ts"],"sourcesContent":["/**\n * 事件基础类型(技术方案 §4)。\n *\n * 宪法二:时间线是唯一真源,角色只是翻译。内部只有一种数据 —— 带发起者的事件。\n * 本文件只定义\"所有事件共有的壳\",具体载荷见 ./core.ts(内置 core.*)与宿主自定义的 ext.*。\n */\n\n/** 事件发起者。用户打断、脑子注入、宿主插话都只是不同 actor 的一次 append。 */\nexport type Actor = \"user\" | \"model\" | \"tool\" | \"system\" | \"host\"\n\n/**\n * 信任等级,供投影层与安全网判断\"这段内容能不能当指令\"。\n * - principal:主事人(用户)说的\n * - system:库或宿主注入的\n * - model:模型自己产出的\n * - untrusted:工具输出、外部抓取内容(默认值,防提示注入)\n */\nexport type Trust = \"principal\" | \"system\" | \"model\" | \"untrusted\"\n\n/** 来源:哪个工具、哪个 URL、哪个用户。用于审计与信任判断。 */\nexport interface Provenance {\n source: string\n ref?: string\n}\n\n/**\n * 所有事件的公共字段。\n * 载荷放在 payload 下(而不是平铺),这样 schema 升级函数只碰 payload,壳永远稳定。\n */\nexport interface EventBase {\n /** uuidv7,时间有序;会话内唯一。fork 复制的事件保留原 id,以维持 parentId / pinsKept 等引用 */\n id: string\n sessionId: string\n /** 会话内单调递增,从 1 起;是会话内排序的唯一依据 */\n seq: number\n /** Unix 毫秒 */\n at: number\n /** 命名空间化:内置 \"core.*\",宿主扩展 \"ext.*\" */\n type: string\n /** 该 type 自己的 schema 版本,从 1 起;读时按注册表升级(P9) */\n schemaVersion: number\n actor: Actor\n /** 因果链或分叉点:回答哪条消息、由哪次 tool_call 产生 */\n parentId?: string\n trust: Trust\n provenance?: Provenance\n /** 厂商专有回放数据(thinking signature、encrypted reasoning),不进通用字段 */\n replay?: Record<string, unknown>\n}\n\n/** 带类型载荷的事件。T 为 type 字面量,P 为 payload 形状。 */\nexport type Event<T extends string = string, P = unknown> = EventBase & {\n type: T\n payload: P\n}\n\n/**\n * 内容片段。用户消息、工具结果都由它组成;投影/降级时再翻译成各家 API 的 content block。\n * 文本、图片、视频、音频,以及\"工具定义引用\"(L1);大结果不塞进片段,走 tool_result.spilled 外溢到 BlobStore。\n *\n * 消费片段的地方一律逐类型显式分支、末尾 `const _exhaustive: never = p` 收口——\n * \"不是文本就当图片\"的 else 兜底会让新加的片段类型悄悄落进图片分支(2026-11-05 视频 / 音频方案)。\n */\nexport type ContentPart = TextPart | ImagePart | VideoPart | AudioPart | ToolReferencePart\n\nexport interface TextPart {\n type: \"text\"\n text: string\n}\n\n/**\n * 图片片段:内联与引用两种形态的判别联合(2026-11-24 媒体引用方案,AdRate 建议 17)。\n * 读 `.data` 的消费点编译期就必须先排除引用形态(`isImageRef`),引用不会被当成内联悄悄发出去\n */\nexport type ImagePart = ImageInlinePart | ImageRefPart\n\n/** 内联图片:字节随事件进日志(改动前唯一的形态) */\nexport interface ImageInlinePart {\n type: \"image\"\n mime: string\n /** base64 编码的图片字节 */\n data: string\n}\n\n/**\n * 引用图片:字节在 BlobStore,日志只存 id。写入前校验归属(本会话的 blob,或本会话时间线已引用过的),\n * 循环在调降级层之前只把**本轮视野内的**引用换回内联(`hydrateImageRefs`),降级层看到的与内联写法逐字节相同;\n * 取不到(blob 被清理)时降级层落 `[image unavailable]` 占位并记 lossy。\n * 形状规则(`isImageRef`):mime 以 \"image/\" 开头且与 blob 的 mime 相同,blobId 非空、≤ 128 字符,不带 `data`\n */\nexport interface ImageRefPart {\n type: \"image\"\n mime: string\n /** BlobStore id;字节须以原始字节 `put`(不是 base64 串) */\n blobId: 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/** 恒等升级:载荷形状不变、只是新版本可能带旧代码不认识的写法 */\nconst identity: Upcaster = (payload) => payload\n\n/**\n * 当前版本不是 v1 的内置事件。升版本时在此加 upcasters,并在 core.ts 改载荷类型。\n *\n * - core.user_message / core.tool_result v2(2026-11-24 媒体引用方案):内容片段多了图片引用形态\n * `{ type: \"image\", mime, blobId }`。v1 → v2 恒等;**一律**按 v2 写、不按载荷选版本——\n * 注册表读时把 schemaVersion 改写成当前版本,按载荷选会让同一事件实时下发是 v1、补发读回是 v2。\n * 代价:写过 v2 的会话不能交给 ≤ core 0.15 的实例读(future_version 拒读,fail-closed),全实例须同时升级\n */\nconst UPGRADED: Readonly<Record<string, EventSchema>> = {\n \"core.user_message\": { type: \"core.user_message\", version: 2, upcasters: { 1: identity } },\n \"core.tool_result\": { type: \"core.tool_result\", version: 2, upcasters: { 1: identity } },\n}\n\n/** 内置事件的 schema 表:缺省 v1,升过版本的见 UPGRADED */\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) => UPGRADED[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":";AAyIO,SAAS,oBAAoB,MAAiC;AACnE,SAAO,OAAO,KAAK,IAAI;AAAA,EAAK,KAAK,YAAY,KAAK,CAA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AC;AAG/C,SAAS,mBAAmB,QAA+B,CAAC,GAAwB;AACzF,SAAO,IAAI,oBAAoB,CAAC,GAAG,cAAc,GAAG,KAAK,CAAC;AAC5D;","names":[]}
|
|
@@ -60,12 +60,30 @@ interface TextPart {
|
|
|
60
60
|
type: "text";
|
|
61
61
|
text: string;
|
|
62
62
|
}
|
|
63
|
-
|
|
63
|
+
/**
|
|
64
|
+
* 图片片段:内联与引用两种形态的判别联合(2026-11-24 媒体引用方案,AdRate 建议 17)。
|
|
65
|
+
* 读 `.data` 的消费点编译期就必须先排除引用形态(`isImageRef`),引用不会被当成内联悄悄发出去
|
|
66
|
+
*/
|
|
67
|
+
type ImagePart = ImageInlinePart | ImageRefPart;
|
|
68
|
+
/** 内联图片:字节随事件进日志(改动前唯一的形态) */
|
|
69
|
+
interface ImageInlinePart {
|
|
64
70
|
type: "image";
|
|
65
71
|
mime: string;
|
|
66
72
|
/** base64 编码的图片字节 */
|
|
67
73
|
data: string;
|
|
68
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* 引用图片:字节在 BlobStore,日志只存 id。写入前校验归属(本会话的 blob,或本会话时间线已引用过的),
|
|
77
|
+
* 循环在调降级层之前只把**本轮视野内的**引用换回内联(`hydrateImageRefs`),降级层看到的与内联写法逐字节相同;
|
|
78
|
+
* 取不到(blob 被清理)时降级层落 `[image unavailable]` 占位并记 lossy。
|
|
79
|
+
* 形状规则(`isImageRef`):mime 以 "image/" 开头且与 blob 的 mime 相同,blobId 非空、≤ 128 字符,不带 `data`
|
|
80
|
+
*/
|
|
81
|
+
interface ImageRefPart {
|
|
82
|
+
type: "image";
|
|
83
|
+
mime: string;
|
|
84
|
+
/** BlobStore id;字节须以原始字节 `put`(不是 base64 串) */
|
|
85
|
+
blobId: string;
|
|
86
|
+
}
|
|
69
87
|
/**
|
|
70
88
|
* 视频片段(2026-11-05,OnSet 建议 12)。音轨算视频的一部分,不另要 `audio` 能力位;纯音频文件用 AudioPart。
|
|
71
89
|
* 模型收不收看 `LoweringCapabilities.video`,不收时降级层落文字占位并记 lossy。
|
|
@@ -157,7 +175,7 @@ declare class EventSchemaRegistry {
|
|
|
157
175
|
*/
|
|
158
176
|
read<E extends Event = Event>(raw: unknown): E;
|
|
159
177
|
}
|
|
160
|
-
/**
|
|
178
|
+
/** 内置事件的 schema 表:缺省 v1,升过版本的见 UPGRADED */
|
|
161
179
|
declare const CORE_SCHEMAS: readonly EventSchema[];
|
|
162
180
|
/** 预装了全部 core.* 的注册表。宿主要加 ext.* 时 new 一个并传入 [...CORE_SCHEMAS, ...自己的]。 */
|
|
163
181
|
declare function createCoreRegistry(extra?: Iterable<EventSchema>): EventSchemaRegistry;
|
|
@@ -463,7 +481,14 @@ interface BlobMeta {
|
|
|
463
481
|
/** Unix 毫秒 */
|
|
464
482
|
createdAt: number;
|
|
465
483
|
}
|
|
466
|
-
/**
|
|
484
|
+
/**
|
|
485
|
+
* 大对象:外溢的工具结果、图片引用的字节、附件、代码执行产物。字符串按 UTF-8 编码存储。
|
|
486
|
+
*
|
|
487
|
+
* 合同(图片引用形态依赖,2026-11-24):
|
|
488
|
+
* - **id 不复用、字节写入后不可改**:日志里的引用永远指向写入时那份字节,"按日志回放"才成立
|
|
489
|
+
* - 图片要 `put` **原始字节**,不要传 base64 串——换回时会把它再编一次 base64,发给厂商的就是乱码
|
|
490
|
+
* - `put` 不检查会话是否已有事件:新会话可以先 put 再发第一条带引用的消息
|
|
491
|
+
*/
|
|
467
492
|
interface BlobStore {
|
|
468
493
|
put(bytes: Uint8Array | string, meta: {
|
|
469
494
|
mime: string;
|
|
@@ -714,9 +739,16 @@ interface HandoffIntent {
|
|
|
714
739
|
}
|
|
715
740
|
type TurnDecision = "continue" | "stop" | {
|
|
716
741
|
handoff: HandoffIntent;
|
|
717
|
-
}
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* 暂停。`code` 是可选的原因码(2026-11-23,AdRate 建议 16):随 `note` 写进 `core.run_paused`,`runStatusOf` 带出,
|
|
745
|
+
* 事后分得清是谁、为什么停的。只是标注,库不按它做分支;格式见 `PAUSE_CODE_RE`,不合规的码被丢掉并记一条非终结 `core.error`,照常暂停。
|
|
746
|
+
* `reins.` 前缀留给内置来源,宿主用自己的前缀
|
|
747
|
+
*/
|
|
748
|
+
| {
|
|
718
749
|
pause: {
|
|
719
750
|
reason: "budget" | "host";
|
|
751
|
+
code?: string;
|
|
720
752
|
note?: string;
|
|
721
753
|
};
|
|
722
754
|
};
|
|
@@ -851,12 +883,16 @@ type Interruption = {
|
|
|
851
883
|
kind: "client_tool";
|
|
852
884
|
toolCallId: string;
|
|
853
885
|
call: ToolCallPayload;
|
|
854
|
-
}
|
|
886
|
+
}
|
|
887
|
+
/** `code`:Socket 给的原因码,或内置来源的 `reins.*`(见 pause-code.ts);宿主中止、用户停止不带 */
|
|
888
|
+
| {
|
|
855
889
|
kind: "budget";
|
|
856
890
|
note: string;
|
|
891
|
+
code?: string;
|
|
857
892
|
} | {
|
|
858
893
|
kind: "host";
|
|
859
894
|
note: string;
|
|
895
|
+
code?: string;
|
|
860
896
|
} | SubagentInterruption;
|
|
861
897
|
/**
|
|
862
898
|
* 子代理即工具(§10.1,`asTool`)的暂停冒泡:工具里跑的子 run 暂停了,父 run 不落这条 tool_result(调用留作 pending),
|
|
@@ -942,6 +978,11 @@ interface PullInputContext {
|
|
|
942
978
|
interface LoopConfig {
|
|
943
979
|
sessionId: string;
|
|
944
980
|
log: EventLog;
|
|
981
|
+
/**
|
|
982
|
+
* 大对象存储:外溢(spill)的工具结果,以及图片引用形态 `{ type: "image", mime, blobId }` 的字节。
|
|
983
|
+
* 图片引用写入前按它校验归属(起步 input、pullInput、工具结果三入口),调降级层前按它把视野内的引用换回内联;
|
|
984
|
+
* 没配时任何图片引用都写不进来("not found"),日志里已有的引用落 `[image unavailable]` 占位
|
|
985
|
+
*/
|
|
945
986
|
blobs?: BlobStore;
|
|
946
987
|
memory?: MemoryStore;
|
|
947
988
|
lowering: Lowering;
|
|
@@ -1025,7 +1066,7 @@ interface LoopConfig {
|
|
|
1025
1066
|
* 版本约定(旧稿 §8,第一版即执行):
|
|
1026
1067
|
* - 只追加可选字段 → 不升版本
|
|
1027
1068
|
* - 改字段语义、删字段、改必填 → 升版本,并在注册表登记 upcast 函数
|
|
1028
|
-
*
|
|
1069
|
+
* 当前 core.user_message / core.tool_result 是 v2(图片引用形态,恒等升级),其余 v1,见 ./registry.ts 的 CORE_SCHEMAS。
|
|
1029
1070
|
*/
|
|
1030
1071
|
|
|
1031
1072
|
/** 用户说话。中途插话不需要特殊机制,再 append 一条即可。 */
|
|
@@ -1190,6 +1231,16 @@ interface BudgetUsagePayload {
|
|
|
1190
1231
|
}
|
|
1191
1232
|
interface RunPausedPayload {
|
|
1192
1233
|
reason: "approval" | "budget" | "host";
|
|
1234
|
+
/**
|
|
1235
|
+
* 这次暂停的原因码(2026-11-23,AdRate 建议 16):Socket 暂停时给的,或内置来源的 `reins.*`(轮数兜底、budget、compact)。
|
|
1236
|
+
* 只是标注,库不按它做任何分支;格式见 `PAUSE_CODE_RE`。宿主中止、用户停止、审批 / 客户端工具 / 子代理的暂停不带。
|
|
1237
|
+
* 可选字段,不升版本
|
|
1238
|
+
*/
|
|
1239
|
+
code?: string;
|
|
1240
|
+
/**
|
|
1241
|
+
* 给人看的说明,与本次 `Interruption.note` 是同一句(budget / host 那条)。排查用,不进 `RunStatus`。可选字段,不升版本
|
|
1242
|
+
*/
|
|
1243
|
+
note?: string;
|
|
1193
1244
|
/** 序列化 run 状态的外部引用(宿主 KV 键、URL 参数等),可选 */
|
|
1194
1245
|
stateRef?: string;
|
|
1195
1246
|
/**
|
|
@@ -1303,4 +1354,4 @@ type ExtEvent = Event<`ext.${string}`, unknown>;
|
|
|
1303
1354
|
/** 日志里可能出现的任何事件 */
|
|
1304
1355
|
type AnyEvent = CoreEvent | ExtEvent;
|
|
1305
1356
|
|
|
1306
|
-
export {
|
|
1357
|
+
export { DEFAULT_RETRY_MAX_ATTEMPTS as $, type AwaitingCall as A, type BlobStore as B, type ContentPart as C, type AnyEvent as D, type Event as E, type ApprovalDecisionInput as F, type ApprovalDecisionPayload as G, type ApprovalRequestPayload as H, type ImageRefPart as I, type ApprovalRequestSpec as J, type AudioPart as K, type LoopConfig as L, type ModelRef as M, type BeforeModelPatch as N, type BeforeToolDecision as O, type PauseReason as P, type BoundModel as Q, type RunResult as R, type SerializedRunState as S, type ToolCallEvent as T, CORE_SCHEMAS as U, type CompactionPayload as V, type CoreEvent as W, type CoreEventPayloads as X, type CoreEventType as Y, type CreateEventInput as Z, DEFAULT_RETRY_BASE_DELAY_MS as _, type ToolResultEvent as a, createCoreEvent as a$, DEFAULT_RETRY_MAX_DELAY_MS as a0, DEFAULT_TRUST as a1, type ErrorEventPayload as a2, type EventBase as a3, type EventSchema as a4, type ExtEvent as a5, type HandoffIntent as a6, type HandoffPayload as a7, type ImageInlinePart as a8, type ImagePart as a9, type SchemaErrorCode as aA, type SessionInfo as aB, type SkillSource as aC, type Socket as aD, type SocketSetup as aE, type StaticContribution as aF, type SystemNotePayload as aG, type TextPart as aH, type ToRequestInput as aI, type TokenUsage as aJ, type ToolBatch as aK, type ToolCallPayload as aL, type ToolContext as aM, type ToolReferencePart as aN, type ToolResultDraft as aO, type ToolResultPayload as aP, type ToolSide as aQ, type ToolStartedPayload as aR, type ToolsBoundPayload as aS, type TurnContext as aT, type TurnDecision as aU, type Upcaster as aV, type UserMessagePayload as aW, type VideoPart as aX, backoffDelayMs as aY, contextOverheadOf as aZ, contextTokensOf as a_, type LandingRecord as aa, type LandingSpec as ab, type LossKind as ac, type LossMatrix as ad, type LoweredRequest as ae, type Lowering as af, type LoweringCapabilities as ag, type LoweringDelta as ah, type LoweringOutcome as ai, type LoweringStreamContext as aj, type MaybePromise as ak, type MemoryOpPayload as al, type ModelCallFailure as am, type ModelTextPayload as an, type ModelThinkingPayload as ao, type Principal as ap, type ProjectionStep as aq, type ProjectionStepStats as ar, type Provenance as as, type PullInputContext as at, type ResolvedRetry as au, type RetryOptions as av, type RunEndedPayload as aw, type RunPausedPayload as ax, type RunResumedPayload as ay, SchemaError as az, type EventLog as b, createCoreRegistry as b0, createEvent as b1, defaultSleep as b2, isTransientFailure as b3, lossesOf as b4, renderToolReference as b5, resolveRetry as b6, statusFromMessage as b7, type BlobMeta as c, type Interruption as d, type ErrorPayload as e, type EventDraft as f, type Tool as g, EventSchemaRegistry as h, type SubagentInterruption as i, type ToolSpec as j, type ToolResult as k, type Trust as l, type CoreEventOf as m, type CoreEventDraft as n, type ProjectionBudget as o, type ProjectionStrategy as p, type ProjectionContext as q, type TokenEstimator as r, type ProjectionResult as s, type ProjectionStats as t, type BudgetUsagePayload as u, type ReadOptions as v, type MemoryStore as w, type RunLease as x, type Stores as y, type Actor as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog,
|
|
2
|
-
export {
|
|
1
|
+
import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, B as BlobStore, c as BlobMeta, C as ContentPart, I as ImageRefPart, d as Interruption, e as ErrorPayload, L as LoopConfig, f as EventDraft, R as RunResult, P as PauseReason, A as AwaitingCall, g as Tool, h as EventSchemaRegistry, S as SerializedRunState, M as ModelRef, i as SubagentInterruption, j as ToolSpec, k as ToolResult, l as Trust, m as CoreEventOf, n as CoreEventDraft, o as ProjectionBudget, p as ProjectionStrategy, q as ProjectionContext, r as TokenEstimator, s as ProjectionResult, t as ProjectionStats, u as BudgetUsagePayload, v as ReadOptions, w as MemoryStore, x as RunLease, y as Stores } from './core-BxGiBJ_p.js';
|
|
2
|
+
export { z as Actor, D as AnyEvent, F as ApprovalDecisionInput, G as ApprovalDecisionPayload, H as ApprovalRequestPayload, J as ApprovalRequestSpec, K as AudioPart, N as BeforeModelPatch, O as BeforeToolDecision, Q as BoundModel, U as CORE_SCHEMAS, V as CompactionPayload, W as CoreEvent, X as CoreEventPayloads, Y as CoreEventType, Z as CreateEventInput, _ as DEFAULT_RETRY_BASE_DELAY_MS, $ as DEFAULT_RETRY_MAX_ATTEMPTS, a0 as DEFAULT_RETRY_MAX_DELAY_MS, a1 as DEFAULT_TRUST, a2 as ErrorEventPayload, a3 as EventBase, a4 as EventSchema, a5 as ExtEvent, a6 as HandoffIntent, a7 as HandoffPayload, a8 as ImageInlinePart, a9 as ImagePart, aa as LandingRecord, ab as LandingSpec, ac as LossKind, ad as LossMatrix, ae as LoweredRequest, af as Lowering, ag as LoweringCapabilities, ah as LoweringDelta, ai as LoweringOutcome, aj as LoweringStreamContext, ak as MaybePromise, al as MemoryOpPayload, am as ModelCallFailure, an as ModelTextPayload, ao as ModelThinkingPayload, ap as Principal, aq as ProjectionStep, ar as ProjectionStepStats, as as Provenance, at as PullInputContext, au as ResolvedRetry, av as RetryOptions, aw as RunEndedPayload, ax as RunPausedPayload, ay as RunResumedPayload, az as SchemaError, aA as SchemaErrorCode, aB as SessionInfo, aC as SkillSource, aD as Socket, aE as SocketSetup, aF as StaticContribution, aG as SystemNotePayload, aH as TextPart, aI as ToRequestInput, aJ as TokenUsage, aK as ToolBatch, aL as ToolCallPayload, aM as ToolContext, aN as ToolReferencePart, aO as ToolResultDraft, aP as ToolResultPayload, aQ as ToolSide, aR as ToolStartedPayload, aS as ToolsBoundPayload, aT as TurnContext, aU as TurnDecision, aV as Upcaster, aW as UserMessagePayload, aX as VideoPart, aY as backoffDelayMs, aZ as contextOverheadOf, a_ as contextTokensOf, a$ as createCoreEvent, b0 as createCoreRegistry, b1 as createEvent, b2 as defaultSleep, b3 as isTransientFailure, b4 as lossesOf, b5 as renderToolReference, b6 as resolveRetry, b7 as statusFromMessage } from './core-BxGiBJ_p.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
|
|
@@ -39,6 +39,146 @@ declare function forkSession(log: EventLog, opts: ForkOptions): Promise<{
|
|
|
39
39
|
toSessionId: string;
|
|
40
40
|
}>;
|
|
41
41
|
|
|
42
|
+
/**
|
|
43
|
+
* 图片引用形态(2026-11-24 媒体引用方案,AdRate 建议 17 第二步):字节放 BlobStore,日志只存 `{ type: "image", mime, blobId }`。
|
|
44
|
+
*
|
|
45
|
+
* 两件事,都在本文件一份(真源索引):
|
|
46
|
+
* 1. **写入校验**(`checkImageRefs`):循环的三个写入口(起步 input、中途 pullInput、工具结果)与 server 的 HTTP 预校验共用。
|
|
47
|
+
* fail-closed,越权当不存在:不存在、不归本会话、mime 不符、没配 BlobStore 一律同一句 `Blob <id> not found in this session`,
|
|
48
|
+
* 且**先判归属、后比 mime**——不给客户端探测别的租户 blob 是否存在、是什么 mime 的机会。
|
|
49
|
+
* 存储自己抛错(非 not_found)不算"不合规",原样抛给调用方按各入口的既有口径处理。
|
|
50
|
+
* 2. **换回**(`hydrateImageRefs`):循环在调降级层之前把本轮视野内的引用换成内联,降级层合同不动;
|
|
51
|
+
* 被折叠的图一个字节都不读。只有 not_found 留着引用(降级层落占位、记 lossy),其它存储错误抛出走模型调用失败的判定——
|
|
52
|
+
* 瞬时故障不能让模型对着占位作答、再把回答永久写进日志。
|
|
53
|
+
*
|
|
54
|
+
* 归属口径(`blobUsableBy`):blob 的 meta.sessionId 就是本会话,或本会话时间线里已被**图片引用**过
|
|
55
|
+
* (fork 出的会话凭此用父会话的图;recall 取回的结果里是引用,自然合规)。图片引用集合(`mediaRefsOf`)与
|
|
56
|
+
* brain `fetch_blob` 的外溢引用集合刻意分开:只被图片引用过的 blob 不能被 fetch_blob 读出字节,外溢 blob 也当不了图片。
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
/** 图片引用的 blobId 最长字符数 */
|
|
60
|
+
declare const IMAGE_REF_ID_MAX = 128;
|
|
61
|
+
/**
|
|
62
|
+
* 图片引用形态的形状判定(真源):type 为 image、mime 以 "image/" 开头、blobId 非空且 ≤ 128 字符、不带 `data`。
|
|
63
|
+
* `isContentPart` 对引用形态调它;降级层据它区分"未换回的引用"与内联图片
|
|
64
|
+
*/
|
|
65
|
+
declare function isImageRef(p: unknown): p is ImageRefPart;
|
|
66
|
+
/**
|
|
67
|
+
* 本会话时间线里被图片引用过的 blob id 集合:只看 user_message / tool_result 的 content 里的图片引用,
|
|
68
|
+
* 不看 `spilled`、不看文本、不看 ext.*。与 fetch_blob 的"外溢引用集合"刻意分开(见文件头)
|
|
69
|
+
*/
|
|
70
|
+
declare function mediaRefsOf(timeline: readonly Event[]): ReadonlySet<string>;
|
|
71
|
+
/**
|
|
72
|
+
* 一个 blob 能不能被这个会话当图片用:`meta.sessionId === sessionId`,或已在 `mediaRefsOf(timeline)` 里。
|
|
73
|
+
* 循环写入校验、server 预校验、宿主自建的下发路由共用这一份——下发路由只比 meta.sessionId 的话,fork 会话显示不了父会话的图。
|
|
74
|
+
* 常见情况(本会话自己的 blob)不扫时间线
|
|
75
|
+
*/
|
|
76
|
+
declare function blobUsableBy(sessionId: string, meta: BlobMeta, id: string, timeline: readonly Event[]): boolean;
|
|
77
|
+
/** 写入校验不过时的唯一一句话:不存在、越权、mime 不符、没配 BlobStore 都是它 */
|
|
78
|
+
declare function imageRefNotFound(id: string): string;
|
|
79
|
+
/**
|
|
80
|
+
* run 级缓存:blobId → 字节(base64)与 blob 自己的 meta。写入校验与换回取到的都放进去,同一 blob 一个 run 只读一次;
|
|
81
|
+
* 失败结果不进缓存。带 meta 是为了命中时照样判归属、比 mime——只按 blobId 放行的话,同一 blob 换个 mime 就能写进日志
|
|
82
|
+
* (厂商收到标错类型的字节、之后每轮 400),日志里混进的引用也会被当成已校验(2026-11-24 独立审查)
|
|
83
|
+
*/
|
|
84
|
+
type ImageRefCache = Map<string, {
|
|
85
|
+
data: string;
|
|
86
|
+
meta: BlobMeta;
|
|
87
|
+
}>;
|
|
88
|
+
interface CheckImageRefsContext {
|
|
89
|
+
sessionId: string;
|
|
90
|
+
blobs?: BlobStore | undefined;
|
|
91
|
+
/** 本会话时间线(归属判定"已引用过"那一支用;只在 blob 不归本会话时才扫) */
|
|
92
|
+
timeline: readonly Event[];
|
|
93
|
+
cache: ImageRefCache;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* 校验一批片段里的图片引用。全部合规返回 undefined;任一不合规返回统一的那一句(`imageRefNotFound`)。
|
|
97
|
+
* 取到的字节顺手放进 cache(缓存命中则不再读存储,但归属与 mime 照判)。存储抛的非 not_found 错误原样抛出,
|
|
98
|
+
* 调用方按各自入口的口径处理
|
|
99
|
+
*/
|
|
100
|
+
declare function checkImageRefs(parts: readonly ContentPart[], ctx: CheckImageRefsContext): Promise<string | undefined>;
|
|
101
|
+
interface HydrateImageRefsContext {
|
|
102
|
+
blobs?: BlobStore | undefined;
|
|
103
|
+
cache: ImageRefCache;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* 视图里的图片引用换回内联(只碰 user_message / tool_result 的 content,其它事件原样返回同一对象)。
|
|
107
|
+
* - 缓存里有的直接用;同一 blob 在一次调用里只 get 一次
|
|
108
|
+
* - `StoreError("not_found")` 与没配 BlobStore:片段保持引用形态交给降级层(落 `[image unavailable]` 占位、记 lossy),不进缓存
|
|
109
|
+
* - 其它存储错误原样抛出:循环把它当模型调用失败处理(走重试判定),不让模型对着占位作答
|
|
110
|
+
*
|
|
111
|
+
* 换回后的事件只交给 `toRequest`,不回写日志、不回写 `ctx.events`(Socket 与估算看到的仍是引用)。
|
|
112
|
+
* 直接调 `toRequest` 的宿主(审计回放、探针)先过一遍它,降级层才看得到图
|
|
113
|
+
*/
|
|
114
|
+
declare function hydrateImageRefs(events: readonly Event[], ctx: HydrateImageRefsContext): Promise<Event[]>;
|
|
115
|
+
/** 零 Node 的 base64 编码:分块拼二进制串再 btoa(Web 标准,workerd / Bun / Deno / Edge 都有) */
|
|
116
|
+
declare function bytesToBase64(bytes: Uint8Array): string;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 暂停原因码(2026-11-23,AdRate 建议 16)。
|
|
120
|
+
*
|
|
121
|
+
* `reason` 是三选一的闭集(approval / budget / host),事后只凭它分不清"是谁、为什么停的":积分用完、预算触顶、
|
|
122
|
+
* 连续整理失败落库后都是 budget。Socket 暂停时可以再带一个原因码 `code`,随 `note` 一起写进 `core.run_paused`,
|
|
123
|
+
* `runStatusOf` 带出 `code`——另一个请求、另一个进程、列表轮询都读得到暂停那一刻的原因(宪法二)。
|
|
124
|
+
*
|
|
125
|
+
* `code` 只是标注:库不解释它、不按它做任何分支,也不进续跑状态与签名。`reins.` 前缀留给内置来源
|
|
126
|
+
* (循环的 `MAX_TURNS_PAUSE_CODE`、brain 的 budget / compact),靠约定不靠校验——循环分不出一个 Socket 是内置的还是宿主的;
|
|
127
|
+
* 宿主用自己的前缀(如 `acme.credits_exhausted`)。
|
|
128
|
+
*
|
|
129
|
+
* 标注写错不能改变结局:Socket 要求暂停就一定暂停(那是边界动作,也只有暂停才带续跑凭据)。意见里不合规的地方
|
|
130
|
+
* 被改正(码丢掉、reason 退成 host),改正处记一条模型不可见的非终结 `core.error`——不静默,也不把受控暂停变成 error。
|
|
131
|
+
*
|
|
132
|
+
* 这里是口径的唯一一处(真源索引):格式判定 `isPauseCode` 写入与读取共用;Socket 的暂停意见怎么变成一条中断
|
|
133
|
+
* (`resolveSocketPause`)、中断怎么变成 `run_paused` 里的字段(`pauseDetailOf`),runLoop 与 TanStack 适配器调同一对函数。
|
|
134
|
+
*/
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 原因码的格式:小写字母或数字开头,其后小写字母 / 数字 / `_` `.` `:` `-`,总长 1~64。
|
|
138
|
+
* 收这么紧是为了让它在下游能直接当标识符用(前端文案键、日志字段、switch 的 case),而不是一句自由文本。
|
|
139
|
+
* 只许收紧不许放宽:读侧对不合规的码判 unknown,放宽之后老版本的读者会把带新码的会话整个判成 unknown(连 awaiting 一起丢),
|
|
140
|
+
* 真要放宽得按"所有实例一起升级、不回滚"对待
|
|
141
|
+
*/
|
|
142
|
+
declare const PAUSE_CODE_RE: RegExp;
|
|
143
|
+
/** 写入(循环校验 Socket 给的码)与读取(`runStatusOf` 的形状守卫)共用的格式判定 */
|
|
144
|
+
declare function isPauseCode(x: unknown): x is string;
|
|
145
|
+
/** 循环自带的轮数兜底(`LoopConfig.maxTurns`)触顶时的原因码 */
|
|
146
|
+
declare const MAX_TURNS_PAUSE_CODE = "reins.max_turns";
|
|
147
|
+
/** Socket 暂停产生的中断:budget / host 两种,可带原因码 */
|
|
148
|
+
type SocketPauseInterruption = Extract<Interruption, {
|
|
149
|
+
kind: "budget" | "host";
|
|
150
|
+
}>;
|
|
151
|
+
interface SocketPauseResolution {
|
|
152
|
+
/** 按这条中断暂停:`kind` 即暂停原因 */
|
|
153
|
+
interruption: SocketPauseInterruption;
|
|
154
|
+
/**
|
|
155
|
+
* 意见里有不合规、已被改正的地方时给出:调用方在暂停之前把它记成一条非终结的 `core.error`(模型不可见)。
|
|
156
|
+
* 全合规时没有这个字段
|
|
157
|
+
*/
|
|
158
|
+
error?: ErrorPayload;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Socket 的暂停意见 → 一条中断:补上缺省 note,校验 reason 与 code。永不抛错、永远给得出一条可暂停的中断:
|
|
162
|
+
* - `reason` 不是 budget / host(JS 宿主想自定义原因时最容易这么写)→ 按 host 暂停。照原样写进 `run_paused` 的话
|
|
163
|
+
* `runStatusOf` 只能判 unknown,自定义原因该放进 `code`;
|
|
164
|
+
* - `code` 不满足 `isPauseCode` → 丢掉,不合规的码不进时间线。
|
|
165
|
+
* 入参按 unknown 对待:类型挡得住 TS 宿主,挡不住 JS 宿主与运行时算出来的码
|
|
166
|
+
*/
|
|
167
|
+
declare function resolveSocketPause(pause: {
|
|
168
|
+
reason: unknown;
|
|
169
|
+
code?: unknown;
|
|
170
|
+
note?: string;
|
|
171
|
+
}): SocketPauseResolution;
|
|
172
|
+
/**
|
|
173
|
+
* 一次暂停的中断列表 → 写进 `core.run_paused` 的原因码与说明:取 budget / host 那一条(一次暂停里至多一条)。
|
|
174
|
+
* 审批 / 客户端工具 / 子代理的暂停没有这一条,返回空对象——它们等的是谁已经在 `awaiting` 里;
|
|
175
|
+
* 子代理自己的原因码不上浮,按 `awaiting[].childSessionId` 查子会话
|
|
176
|
+
*/
|
|
177
|
+
declare function pauseDetailOf(interruptions: readonly Interruption[]): {
|
|
178
|
+
code?: string;
|
|
179
|
+
note?: string;
|
|
180
|
+
};
|
|
181
|
+
|
|
42
182
|
/**
|
|
43
183
|
* runLoop:reins 的默认循环(技术方案 §2、§6、§7)。
|
|
44
184
|
*
|
|
@@ -161,6 +301,11 @@ type RunStatus = {
|
|
|
161
301
|
stopped: boolean;
|
|
162
302
|
/** 老版本写的 run_paused 不带,为 undefined */
|
|
163
303
|
awaiting: AwaitingCall[] | undefined;
|
|
304
|
+
/**
|
|
305
|
+
* 暂停原因码(AdRate 建议 16):Socket 暂停时给的,或内置来源的 `reins.*`。没给码的暂停(宿主中止、用户停止、
|
|
306
|
+
* 审批 / 客户端工具 / 子代理)与老版本写的事件没有这个字段。给人看的 `note` 只在事件里,不进这里
|
|
307
|
+
*/
|
|
308
|
+
code?: string;
|
|
164
309
|
};
|
|
165
310
|
/**
|
|
166
311
|
* 纯函数:租约 + 最后一条 run 标记 → 运行状态(真源索引)。
|
|
@@ -402,7 +547,8 @@ declare function deferredToolSpecOf(tool: Tool, deferred: boolean): ToolSpec;
|
|
|
402
547
|
/**
|
|
403
548
|
* 内容片段的形状校验,全包唯一一份(真源索引):工具返回值归一(本文件)与 runLoop 输入草稿 / 片段数组(run-loop.ts)都调它。
|
|
404
549
|
* 坏片段一旦进日志,之后每次读到它都会崩(会话报废),所以在写之前拦。
|
|
405
|
-
* 规则:text 有 `text`;image
|
|
550
|
+
* 规则:text 有 `text`;image 是内联(`mime` 与 `data`,mime 不校验,历史行为)或引用(`isImageRef`:mime 以 "image/" 开头、
|
|
551
|
+
* blobId 非空且 ≤ 128 字符),`data` 与 `blobId` 恰好一个;video / audio 的 mime 以 "video/" / "audio/" 开头、
|
|
406
552
|
* `durationSec` 缺省或为有限正数;tool_reference 有名字、描述与对象形 inputSchema。
|
|
407
553
|
* 宿主经 HTTP 送来的用户消息另有白名单(server `rebuildContentParts`,两份实现靠跨包用例锁同口径),不含引用段
|
|
408
554
|
*/
|
|
@@ -579,7 +725,10 @@ declare function estimateBudgetOf(budget: ProjectionBudget): number;
|
|
|
579
725
|
/**
|
|
580
726
|
* 默认对模型不可见的运维事件。它们服务于宿主与审计,对模型没有信息量或已由别的事件承载:
|
|
581
727
|
* - approval_*:审批结果由 B7 以 tool_result(isError) 告知模型
|
|
582
|
-
* - run_paused / run_resumed
|
|
728
|
+
* - run_paused / run_resumed:run 的起止记录,只给宿主判状态与续跑用;没有模块把它转述给模型
|
|
729
|
+
* (宿主想让模型知道上次为什么停,自己按 run_paused 的原因码写一条 system_note)
|
|
730
|
+
* - budget_usage:用量记录,感知模块把要点提炼进 system_note
|
|
731
|
+
* - memory_op:记忆读写的审计记录,模型已从工具结果得知
|
|
583
732
|
* - handoff:交接后当前会话结束,新会话首条 user 消息承载 triggerMessage
|
|
584
733
|
* - error:provider 级错误由循环层处理;工具错误已在 tool_result.isError
|
|
585
734
|
* - tools_bound:每次 run 起步的工具表快照(P1);工具表本身在请求里,增删由循环以 system_note(kind=host) 告知模型
|
|
@@ -673,6 +822,29 @@ interface RenderManifestOptions {
|
|
|
673
822
|
declare function digestArgs(args: unknown, max?: number): string;
|
|
674
823
|
/** 渲染成给模型看的清单;没有条目返回空字符串 */
|
|
675
824
|
declare function renderFoldedToolResults(items: readonly FoldedToolResult[], opts: RenderManifestOptions): string;
|
|
825
|
+
/**
|
|
826
|
+
* 被折叠用户消息里的媒体(2026-11-24,AdRate 建议 17 第一步)。
|
|
827
|
+
*
|
|
828
|
+
* 工具结果清单只覆盖 tool_result;用户贴的截图、视频、音频一旦随旧轮被折叠,模型既看不到、也不知道它还在——
|
|
829
|
+
* 违反"会消失就要拿得回"。这里把带媒体片段的被折叠 user_message 按 seq 列出,取回仍由脑子的 recall 做。
|
|
830
|
+
* 只列带媒体的:纯文本用户消息的要点由摘要承载(兜底摘要另有原话开头),全列只会让清单变长。
|
|
831
|
+
*/
|
|
832
|
+
interface FoldedUserMedia {
|
|
833
|
+
/** user_message 事件的 seq —— 模型取回时报这个号 */
|
|
834
|
+
seq: number;
|
|
835
|
+
/** 消息里的媒体片段,按出现顺序 */
|
|
836
|
+
media: {
|
|
837
|
+
type: "image" | "video" | "audio";
|
|
838
|
+
mime: string;
|
|
839
|
+
}[];
|
|
840
|
+
}
|
|
841
|
+
/** 从一段被折叠(或被裁掉)的事件里挑出带媒体的用户消息,按 seq 升序 */
|
|
842
|
+
declare function foldedUserMedia(removed: readonly Event[]): FoldedUserMedia[];
|
|
843
|
+
/** 渲染成给模型看的清单行,例:`- seq 12 user message — 2 images (image/png, image/jpeg)`;没有条目返回空字符串 */
|
|
844
|
+
declare function renderFoldedUserMedia(items: readonly FoldedUserMedia[], opts: {
|
|
845
|
+
heading: string;
|
|
846
|
+
maxItems?: number;
|
|
847
|
+
}): string;
|
|
676
848
|
|
|
677
849
|
declare function reinjectPins(): ProjectionStrategy;
|
|
678
850
|
|
|
@@ -784,6 +956,9 @@ declare function project(opts: ProjectOptions): ProjectionResult;
|
|
|
784
956
|
* 脑子模块新造的事件(system_note、compaction)都在日志里,不受影响。
|
|
785
957
|
* - 请求发出但一条模型输出都没回来(降级层异常、provider 报错)的那一轮没有模型事件,识别不出请求边界,
|
|
786
958
|
* 只在时间线上留一条 core.error;这类失败轮不计入 turns。
|
|
959
|
+
* - 图片引用形态(2026-11-24):`visible` 里的图片是引用、字节在 BlobStore。模型当时看到的是"日志 + 不可变 blob",
|
|
960
|
+
* 要把某轮交给降级层重算请求(`toRequest`),调用方先用**录制时同一个 BlobStore** 过一遍 `hydrateImageRefs`,
|
|
961
|
+
* 与 runLoop 同一步;blob 已被清理的图落 unavailable 占位,与当时不同(examples/minimal/replay.ts 是写法样例)。
|
|
787
962
|
*/
|
|
788
963
|
|
|
789
964
|
interface ReplayedTurn {
|
|
@@ -931,6 +1106,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
|
|
|
931
1106
|
*/
|
|
932
1107
|
|
|
933
1108
|
/** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
|
|
934
|
-
declare const REINS_VERSION = "0.
|
|
1109
|
+
declare const REINS_VERSION = "0.16.0";
|
|
935
1110
|
|
|
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 };
|
|
1111
|
+
export { AwaitingCall, BUILTIN_APPROVAL_POLICY, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CheckImageRefsContext, 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, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type FoldedUserMedia, type ForkOptions, type HydrateImageRefsContext, IMAGE_REF_ID_MAX, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, type ImageRefCache, ImageRefPart, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, Interruption, LoopConfig, LoweringError, type LoweringErrorCode, MAX_TURNS_PAUSE_CODE, type MarkedContent, MemoryStore, ModelRef, OUTCOME_UNKNOWN_TEXT, PAUSE_CODE_RE, 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 SocketPauseInterruption, type SocketPauseResolution, 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, blobUsableBy, budgetTruncate, bytesToBase64, checkImageRefs, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, foldedUserMedia, forkSession, hydrateImageRefs, imageRefNotFound, inputDrafts, isClientTool, isCompaction, isContentPart, isImageRef, isModelOutput, isPauseCode, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, keptBy, lastRunMarker, lastToolsBound, markUntrusted, markUntrustedText, mediaRefsOf, memoryStore, needsUntrustedMark, normalizeToolOutput, outcomeUnknownText, pauseDetailOf, pausedStateOf, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderFoldedUserMedia, renderToolChangeNote, replayTurns, resolveSocketContributions, resolveSocketPause, roughTokenEstimate, runLoop, runStatusOf, serializeRunState, signRunState, splitTurns, startedToolCallIds, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolStartedAt, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter, withStartedAt };
|