@reinsjs/core 0.10.0 → 0.12.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.
@@ -1,682 +0,0 @@
1
- /**
2
- * 事件基础类型(技术方案 §4)。
3
- *
4
- * 宪法二:时间线是唯一真源,角色只是翻译。内部只有一种数据 —— 带发起者的事件。
5
- * 本文件只定义"所有事件共有的壳",具体载荷见 ./core.ts(内置 core.*)与宿主自定义的 ext.*。
6
- */
7
- /** 事件发起者。用户打断、脑子注入、宿主插话都只是不同 actor 的一次 append。 */
8
- type Actor = "user" | "model" | "tool" | "system" | "host";
9
- /**
10
- * 信任等级,供投影层与安全网判断"这段内容能不能当指令"。
11
- * - principal:主事人(用户)说的
12
- * - system:库或宿主注入的
13
- * - model:模型自己产出的
14
- * - untrusted:工具输出、外部抓取内容(默认值,防提示注入)
15
- */
16
- type Trust = "principal" | "system" | "model" | "untrusted";
17
- /** 来源:哪个工具、哪个 URL、哪个用户。用于审计与信任判断。 */
18
- interface Provenance {
19
- source: string;
20
- ref?: string;
21
- }
22
- /**
23
- * 所有事件的公共字段。
24
- * 载荷放在 payload 下(而不是平铺),这样 schema 升级函数只碰 payload,壳永远稳定。
25
- */
26
- interface EventBase {
27
- /** uuidv7,时间有序;会话内唯一。fork 复制的事件保留原 id,以维持 parentId / pinsKept 等引用 */
28
- id: string;
29
- sessionId: string;
30
- /** 会话内单调递增,从 1 起;是会话内排序的唯一依据 */
31
- seq: number;
32
- /** Unix 毫秒 */
33
- at: number;
34
- /** 命名空间化:内置 "core.*",宿主扩展 "ext.*" */
35
- type: string;
36
- /** 该 type 自己的 schema 版本,从 1 起;读时按注册表升级(P9) */
37
- schemaVersion: number;
38
- actor: Actor;
39
- /** 因果链或分叉点:回答哪条消息、由哪次 tool_call 产生 */
40
- parentId?: string;
41
- trust: Trust;
42
- provenance?: Provenance;
43
- /** 厂商专有回放数据(thinking signature、encrypted reasoning),不进通用字段 */
44
- replay?: Record<string, unknown>;
45
- }
46
- /** 带类型载荷的事件。T 为 type 字面量,P 为 payload 形状。 */
47
- type Event<T extends string = string, P = unknown> = EventBase & {
48
- type: T;
49
- payload: P;
50
- };
51
- /**
52
- * 内容片段。用户消息、工具结果都由它组成;投影/降级时再翻译成各家 API 的 content block。
53
- * 文本、图片、视频、音频,以及"工具定义引用"(L1);大结果不塞进片段,走 tool_result.spilled 外溢到 BlobStore。
54
- *
55
- * 消费片段的地方一律逐类型显式分支、末尾 `const _exhaustive: never = p` 收口——
56
- * "不是文本就当图片"的 else 兜底会让新加的片段类型悄悄落进图片分支(2026-11-05 视频 / 音频方案)。
57
- */
58
- type ContentPart = TextPart | ImagePart | VideoPart | AudioPart | ToolReferencePart;
59
- interface TextPart {
60
- type: "text";
61
- text: string;
62
- }
63
- interface ImagePart {
64
- type: "image";
65
- mime: string;
66
- /** base64 编码的图片字节 */
67
- data: string;
68
- }
69
- /**
70
- * 视频片段(2026-11-05,OnSet 建议 12)。音轨算视频的一部分,不另要 `audio` 能力位;纯音频文件用 AudioPart。
71
- * 模型收不收看 `LoweringCapabilities.video`,不收时降级层落文字占位并记 lossy。
72
- */
73
- interface VideoPart {
74
- type: "video";
75
- /** 必须以 "video/" 开头 */
76
- mime: string;
77
- /** base64 编码的文件字节 */
78
- data: string;
79
- /** 时长(秒,有限正数);只用于 token 估算,没有时按字节折算(偏高)。宿主拿得到就该给 */
80
- durationSec?: number;
81
- }
82
- /** 音频片段(2026-11-05)。模型收不收看 `LoweringCapabilities.audio` */
83
- interface AudioPart {
84
- type: "audio";
85
- /** 必须以 "audio/" 开头 */
86
- mime: string;
87
- /** base64 编码的文件字节 */
88
- data: string;
89
- /** 时长(秒,有限正数);只用于 token 估算,没有时按字节折算(偏高) */
90
- durationSec?: number;
91
- }
92
- /**
93
- * 工具定义引用(L1,2026-09-15):`tool_find` 这类"取回工具"的结果用它表达"这几件工具从现在起可用"。
94
- * 带完整定义快照,日志自足(宪法二:模型可见的一切都在日志里);翻译时按能力分两路——
95
- * 支持原生延迟加载的线(Anthropic `defer_loading`)只发 `tool_reference` 块、由厂商就地展开、工具表整段不变;
96
- * 其余线用 `renderToolReference` 展开成文本,信息等价。宿主经 HTTP 送来的用户消息不接受这种段(server 白名单)。
97
- */
98
- interface ToolReferencePart {
99
- type: "tool_reference";
100
- name: string;
101
- description: string;
102
- /** JSON Schema 对象,与 Tool.inputSchema 同形 */
103
- inputSchema: Record<string, unknown>;
104
- }
105
- /** 引用段展开成文本的唯一写法:非原生线的降级层、UI、投影估算都调它,别各自拼 */
106
- declare function renderToolReference(part: ToolReferencePart): string;
107
- /** 各 actor 的默认信任等级;工厂函数在未显式给出 trust 时使用。 */
108
- declare const DEFAULT_TRUST: Readonly<Record<Actor, Trust>>;
109
-
110
- /**
111
- * 内置事件类型 core.*(技术方案 §4 表)。
112
- *
113
- * 每种事件的载荷单独成 interface,命名 `<Type>Payload`,便于 schema 升级时按 type 逐个演进。
114
- * 版本约定(旧稿 §8,第一版即执行):
115
- * - 只追加可选字段 → 不升版本
116
- * - 改字段语义、删字段、改必填 → 升版本,并在注册表登记 upcast 函数
117
- * 当前全部为 v1,见 ./registry.ts 的 CORE_SCHEMAS。
118
- */
119
-
120
- /** 用户说话。中途插话不需要特殊机制,再 append 一条即可。 */
121
- interface UserMessagePayload {
122
- content: ContentPart[];
123
- }
124
- /** 模型正文。流式增量在降级层聚合,日志里只存完整的一段。 */
125
- interface ModelTextPayload {
126
- text: string;
127
- }
128
- /** 模型思考。文本可空(加密 reasoning 只有 replay);签名等回放数据放 EventBase.replay。 */
129
- interface ModelThinkingPayload {
130
- text: string;
131
- }
132
- interface ToolCallPayload {
133
- toolCallId: string;
134
- name: string;
135
- /** 模型给的原始入参(已解析为 JSON 值);校验在工具执行前做,事件里存原样 */
136
- args: unknown;
137
- /**
138
- * 降级层附带的读侧记录,**不进模型上下文**。目前只有 `argumentsUnwrapped: true`:模型把整个入参二次编码成了
139
- * JSON 文本,降级层多解了一层(core/lowering/tool-arguments.ts)。可选字段,不升版本。
140
- */
141
- meta?: Record<string, unknown>;
142
- }
143
- interface ToolResultPayload {
144
- toolCallId: string;
145
- /** 冗余存一份工具名,回放时不必反查 tool_call */
146
- name: string;
147
- content: ContentPart[];
148
- isError: boolean;
149
- /** 结果外溢到 BlobStore 时填写;此时 content 只留给模型的取回指引 */
150
- spilled?: {
151
- blobId: string;
152
- summary: string;
153
- };
154
- }
155
- /**
156
- * 这次工具调用**已经开始动手**(2026-11-05,停止语义与中断不重放),模型不可见。循环在两种时候写:
157
- * - 不可重放的工具(`isReplayable(tool)` 为假,缺省即没声明 `risk: "low"` 的写工具)在 `execute` 之前写;
158
- * - 任何工具返回 `subagentPause` 之后补写(子代理已经动过手了)。
159
- * 有它、没有 tool_result 的调用,续跑时不可重放的落"结果未知"、不再执行;停止时按它分辨"没执行"与"做了一半"。
160
- */
161
- interface ToolStartedPayload {
162
- toolCallId: string;
163
- }
164
- /**
165
- * 脑子/宿主注入给模型看的说明。"模型可见 ⟺ 已记录",所以感知、钉住提示、预算提醒都是事件。
166
- * 降级时按模型族落到中途 system 或 user 角色(S1 结论),两种落点都在有损矩阵声明。
167
- */
168
- interface SystemNotePayload {
169
- kind: "perception" | "pin" | "budget" | "host";
170
- text: string;
171
- /**
172
- * 注入者附带的结构化数据(如感知的各档位读数),**不进模型上下文**:降级层只翻译 text。
173
- * 给回放界面与 eval 用,免得从文本里反解。可选字段,不升版本。
174
- */
175
- meta?: Record<string, unknown>;
176
- /**
177
- * 本条说明**取代**的旧说明 id(B3)。被取代的 pin 在折叠 / 裁剪时不再自动幸存,也不再因出现在
178
- * 旧 compaction 的 pinsKept 里而幸存 —— 这是 append-only 日志里"撤销一条钉住"的唯一表达。
179
- * 折叠之前它照常可见(未折叠的历史原样展示)。可选字段,不升版本。
180
- */
181
- supersedes?: string[];
182
- /**
183
- * 注入者声明这是要模型**去做**的指令(如 compact 的整理请求,OPT-261031-1),不是陈述。降级层据此选送达方式:
184
- * 有的上游收下中途 system 却不执行其中的指令(踩坑 42),指令类说明一律以带标签的 user 文本送达,陈述类(感知、钉住)不受影响。
185
- * 角色仍只由降级层决定(宪法二),这里只写语义。写进日志即定格:历史说明的送达方式不随升级变化,缓存前缀稳定。可选字段,不升版本。
186
- */
187
- directive?: true;
188
- }
189
- interface ApprovalRequestPayload {
190
- toolCallId: string;
191
- policyId: string;
192
- /** 给审批人看的一句话摘要 */
193
- summary: string;
194
- }
195
- interface ApprovalDecisionPayload {
196
- toolCallId: string;
197
- approved: boolean;
198
- /** 谁批的:用户标识、策略 ID 或 "auto" */
199
- by: string;
200
- reason?: string;
201
- }
202
- /**
203
- * 压缩不删原事件,只追加这一条:投影层看到它就用 summary 替代 coversSeq 范围内的事件。
204
- * decidedBy 记"谁定的时机":
205
- * - `model`:模型自己挑的时机(默认路径,P1);
206
- * - `forced`:用量过了软线、框架请它整理后模型照做的——时机是框架定的,摘要仍是模型写的(OPT-261030-3);
207
- * - `threshold`:模型没整理、过了触发线,投影链机械裁剪。
208
- * 新增取值不升 schemaVersion:注册表不校验载荷,旧日志照读。
209
- */
210
- interface CompactionPayload {
211
- /** 闭区间 [from, to],按 seq */
212
- coversSeq: [number, number];
213
- summary: string;
214
- decidedBy: "model" | "forced" | "threshold";
215
- /** 折叠后仍需重注入的钉住事件 id */
216
- pinsKept: string[];
217
- }
218
- interface HandoffPayload {
219
- toSessionId: string;
220
- summary: string;
221
- /** 触发交接的那条用户消息文本,新会话据此续做 */
222
- triggerMessage?: string;
223
- reason: string;
224
- }
225
- /**
226
- * 模型读写记忆留痕。op 与 Anthropic memory_20250818 工具的 command 同名。
227
- * 只在操作成功时记录(失败的尝试已由 tool_call 入参 + tool_result(isError) 留痕)。
228
- */
229
- interface MemoryOpPayload {
230
- op: "view" | "create" | "str_replace" | "insert" | "delete" | "rename";
231
- /** 模型可见形态的路径(/memories/...),rename 时是源路径 */
232
- path: string;
233
- /** rename 的目标路径(B6 新增可选字段,不升版本) */
234
- toPath?: string;
235
- /** 涉及的 UTF-8 字节数:view 是读到的、写类是写后的大小、delete / rename 是涉及的文件总量;目录列表不记 */
236
- bytes?: number;
237
- }
238
- /**
239
- * 一次模型请求的用量。字段语义跟随 Anthropic:`input` 是未命中缓存的输入 token,缓存读 / 写另计,
240
- * 所以"这次请求的上下文有多大"= input + cacheRead + cacheWrite(见 contextTokensOf),不是 input 本身。
241
- */
242
- interface TokenUsage {
243
- input: number;
244
- output: number;
245
- cacheRead?: number;
246
- cacheWrite?: number;
247
- }
248
- /** 该请求实际送进模型的上下文大小:未命中 + 缓存读 + 缓存写 */
249
- declare function contextTokensOf(usage: TokenUsage): number;
250
- /**
251
- * 估算与真实之间的固定开销(B8):上一次请求的真实上下文 − 当时的投影估算。
252
- *
253
- * 投影只数模型可见事件的正文,系统提示、工具表、thinking 签名块等都不在内,真实 input 可高出一倍。
254
- * 这些多出来的部分在一个 run 里基本是常量(系统提示与工具表整轮不变),所以用**加法**校准而不是比例:
255
- * 比例会随历史变长把误差放大,加法只补那块固定的开销。
256
- * 数据来自日志最后一条同时带 tokens 与 contextEstimate 的 budget_usage;没有可对照的请求时为 0,不为负。
257
- * 那条记录算出非有限值(宿主 / 适配器写进 NaN、Infinity)也回 0:日志里一条坏用量不该让 project() 的开销校验
258
- * 在 run 起步就抛错,退化成"不校准"即可。
259
- *
260
- * 阈值兜底(投影)与感知读数**必须**都调这一个函数:两处口径一分叉,模型被告知"到 85% 自动折叠"就不成立。
261
- */
262
- declare function contextOverheadOf(timeline: readonly Event[]): number;
263
- /**
264
- * 用量是事件,宿主可按会话或用户聚合出配额(库不做配额)。
265
- * `contextEstimate`(B8):这次请求投影的估算 token(= 当轮 TurnContext.budget.used),与真实用量放在同一条事件里,
266
- * 感知模块用"真实上下文 − 估算"得到系统提示、工具表、thinking 等估算不含的固定开销,校准下一轮的使用率读数。
267
- * `remaining` 预留给宿主 / 适配器自己追加的聚合用量;循环不填(上限属于 brain budget 模块,循环不知道)。
268
- */
269
- interface BudgetUsagePayload {
270
- tokens: TokenUsage;
271
- toolCalls: number;
272
- wallMs: number;
273
- contextEstimate?: number;
274
- remaining?: {
275
- tokens?: number;
276
- toolCalls?: number;
277
- wallMs?: number;
278
- };
279
- }
280
- interface RunPausedPayload {
281
- reason: "approval" | "budget" | "host";
282
- /** 序列化 run 状态的外部引用(宿主 KV 键、URL 参数等),可选 */
283
- stateRef?: string;
284
- }
285
- interface RunResumedPayload {
286
- stateRef?: string;
287
- by?: string;
288
- }
289
- /**
290
- * 每次 run 起步时的工具表快照(P1,模型不可见)。宪法二:日志里要能看出"那次 run 模型手里有哪些工具",
291
- * 而不是从 tool_call 反推;也是"工具表变化告知模型"的比对依据 —— 与上一条 tools_bound 比对有增删,
292
- * 循环就再追加一条模型可见的 system_note(kind=host)。MCP 服务器加减工具、宿主按请求换配置,都从这里被看见。
293
- */
294
- interface ToolsBoundPayload {
295
- /** 本次 run 模型可用的全部工具名(宿主工具 + 各 Socket 的静态贡献),已排序 */
296
- toolNames: string[];
297
- /** 与 SerializedRunState.configHash 同一算法(模型、工具名集合、系统提示) */
298
- configHash: string;
299
- }
300
- interface ErrorPayload {
301
- /** 粗分类:provider / tool / budget / internal 等,字符串开放给宿主扩展 */
302
- category: string;
303
- message: string;
304
- retryable: boolean;
305
- detail?: Record<string, unknown>;
306
- }
307
- /** type 字面量 → 载荷。新增内置事件只需在此加一行并在注册表登记。 */
308
- interface CoreEventPayloads {
309
- "core.user_message": UserMessagePayload;
310
- "core.model_text": ModelTextPayload;
311
- "core.model_thinking": ModelThinkingPayload;
312
- "core.tool_call": ToolCallPayload;
313
- "core.tool_result": ToolResultPayload;
314
- "core.tool_started": ToolStartedPayload;
315
- "core.system_note": SystemNotePayload;
316
- "core.approval_request": ApprovalRequestPayload;
317
- "core.approval_decision": ApprovalDecisionPayload;
318
- "core.compaction": CompactionPayload;
319
- "core.handoff": HandoffPayload;
320
- "core.memory_op": MemoryOpPayload;
321
- "core.budget_usage": BudgetUsagePayload;
322
- "core.run_paused": RunPausedPayload;
323
- "core.run_resumed": RunResumedPayload;
324
- "core.tools_bound": ToolsBoundPayload;
325
- "core.error": ErrorPayload;
326
- }
327
- type CoreEventType = keyof CoreEventPayloads;
328
- /** 按 type 取出对应事件类型,如 CoreEventOf<"core.tool_call"> */
329
- type CoreEventOf<T extends CoreEventType> = Event<T, CoreEventPayloads[T]>;
330
- /** 全部内置事件的可判别联合,switch (e.type) 即可收窄 payload */
331
- type CoreEvent = {
332
- [T in CoreEventType]: CoreEventOf<T>;
333
- }[CoreEventType];
334
- /** 宿主扩展事件:type 必须以 "ext." 开头,载荷由宿主在注册表登记 */
335
- type ExtEvent = Event<`ext.${string}`, unknown>;
336
- /** 日志里可能出现的任何事件 */
337
- type AnyEvent = CoreEvent | ExtEvent;
338
-
339
- /**
340
- * 事件 schema 注册表(P9:schema 有版本,读时升级,查不到即拒绝)。
341
- *
342
- * 职责:
343
- * 1. 登记每个 type 的当前版本与逐级升级函数 upcast(v → v+1)
344
- * 2. read(raw):校验壳字段 → 查 type → 逐级升级到当前版本 → 返回类型化事件
345
- * 3. 任何一步查不到都抛 SchemaError(fail-closed),绝不静默返回半个事件
346
- *
347
- * 日志文件不做原地迁移:存的永远是写入时的版本,读时升级。
348
- */
349
-
350
- /** 把 payload 从版本 from 升到 from+1。只碰 payload,壳字段由注册表保证不变。 */
351
- type Upcaster = (payload: unknown) => unknown;
352
- interface EventSchema {
353
- type: string;
354
- /** 当前版本;新写入的事件一律打这个版本号 */
355
- version: number;
356
- /**
357
- * 升级函数表,键为"起点版本":upcasters[1] 把 v1 升到 v2。
358
- * version 为 n 时必须覆盖 1..n-1 全部键,缺一个即注册失败 —— 宁可启动时报错,不要读到一半才发现。
359
- */
360
- upcasters?: Readonly<Record<number, Upcaster>>;
361
- }
362
- type SchemaErrorCode = "malformed_base" | "unknown_type" | "future_version" | "missing_upcaster" | "upcaster_failed" | "invalid_schema";
363
- declare class SchemaError extends Error {
364
- readonly code: SchemaErrorCode;
365
- readonly context: {
366
- type?: string;
367
- version?: number;
368
- };
369
- constructor(code: SchemaErrorCode, message: string, context?: {
370
- type?: string;
371
- version?: number;
372
- });
373
- }
374
- declare class EventSchemaRegistry {
375
- private readonly schemas;
376
- constructor(schemas?: Iterable<EventSchema>);
377
- /** 登记一个 type。重复登记同一 type 视为错误,避免两处定义互相覆盖。 */
378
- register(schema: EventSchema): this;
379
- has(type: string): boolean;
380
- /** 该 type 当前应写入的版本号;未登记则抛 unknown_type。 */
381
- currentVersion(type: string): number;
382
- /**
383
- * 从存储读出的原始对象 → 当前版本的事件。
384
- * 泛型只是给调用方的类型提示(如 read<CoreEvent>),运行时校验的是壳与版本,不校验 payload 形状 ——
385
- * payload 的正确性由写入方与升级函数负责。
386
- */
387
- read<E extends Event = Event>(raw: unknown): E;
388
- }
389
- /** 全部内置事件当前都是 v1。升版本时在此加 upcasters,并在 core.ts 改载荷类型。 */
390
- declare const CORE_SCHEMAS: readonly EventSchema[];
391
- /** 预装了全部 core.* 的注册表。宿主要加 ext.* 时 new 一个并传入 [...CORE_SCHEMAS, ...自己的]。 */
392
- declare function createCoreRegistry(extra?: Iterable<EventSchema>): EventSchemaRegistry;
393
-
394
- /**
395
- * 事件工厂:补齐 id / at / schemaVersion / trust,调用方只关心"谁、在哪个会话、第几条、说了什么"。
396
- * seq 由 EventLog 的 append 方决定(T4),这里要求显式传入,不替存储层做主。
397
- */
398
-
399
- /**
400
- * 事件草稿:还没进日志的事件,缺 id / seq / at / sessionId / schemaVersion。
401
- * 降级层(模型输出)与脑子模块(注入的 system_note)都只产出草稿,由循环补齐后 append ——
402
- * 谁分配 seq 只有循环知道,草稿不替它做主。
403
- */
404
- interface EventDraft<T extends string = string, P = unknown> {
405
- type: T;
406
- payload: P;
407
- actor: Actor;
408
- /** 缺省按 DEFAULT_TRUST[actor] */
409
- trust?: Trust;
410
- parentId?: string;
411
- provenance?: Provenance;
412
- replay?: Record<string, unknown>;
413
- }
414
- /** 内置事件的草稿联合,type 与 payload 联动 */
415
- type CoreEventDraft = {
416
- [T in CoreEventType]: EventDraft<T, CoreEventPayloads[T]>;
417
- }[CoreEventType];
418
- interface CreateEventInput<T extends string, P> extends EventDraft<T, P> {
419
- sessionId: string;
420
- seq: number;
421
- /** 测试注入用;缺省 Date.now() */
422
- at?: number;
423
- id?: string;
424
- }
425
- /**
426
- * 通用工厂。schemaVersion 从注册表取当前版本,所以未登记的 type 会在这里就被拒绝,
427
- * 而不是写进日志后读不出来。
428
- */
429
- declare function createEvent<T extends string, P>(registry: EventSchemaRegistry, input: CreateEventInput<T, P>): Event<T, P>;
430
- /** 内置事件的强类型版本:type 与 payload 联动校验。 */
431
- declare function createCoreEvent<T extends CoreEventType>(registry: EventSchemaRegistry, input: CreateEventInput<T, CoreEventPayloads[T]>): CoreEventOf<T>;
432
-
433
- /**
434
- * 降级层接口(技术方案 §11;宪法二:角色只是翻译)。
435
- *
436
- * 降级层把投影后的事件翻译成某家 API 的请求,再把流式响应翻译回事件草稿。
437
- * 它是唯一允许出现"角色"概念的地方。每种事件在每家 API 上落到哪里、有没有损失,
438
- * 必须在 LossMatrix 里声明,并在每次 toRequest 的 landings 里逐条记录 —— 禁止静默丢弃(P7)。
439
- *
440
- * 本文件只有类型;具体实现(如 @reinsjs/lowering-pi)在可选包里,厂商 SDK 类型不得出现在这里。
441
- */
442
-
443
- /** 模型引用:宿主用它指定"哪家的哪个模型",具体解析交给降级层实现 */
444
- interface ModelRef {
445
- provider: string;
446
- id: string;
447
- }
448
- /** 工具声明的模型可见部分。执行、审批、结果处置等维度在工具模型(§10)里,不进降级层 */
449
- interface ToolSpec {
450
- name: string;
451
- description: string;
452
- /** JSON Schema 对象;不绑任何校验库 */
453
- inputSchema: Record<string, unknown>;
454
- /**
455
- * 向厂商声明但不载入模型上下文(L1):Anthropic 的 `defer_loading: true`——工具留在 tools 块里(表整段不变、缓存前缀不动),
456
- * 模型只有在历史里出现指向它的 `tool_reference` 后才看得见。没有等价表达的线**不发**这件工具(模型看不见也调不了,
457
- * 与过滤掉同义)。只有 `LoweringCapabilities.deferredTools` 为真的降级层会收到带这个标记的规格(lazy-tools 据能力位决定)。
458
- */
459
- deferLoading?: boolean;
460
- }
461
- /** 本模型在本 API 上支持什么。脑子模块据此选择等价表达 */
462
- interface LoweringCapabilities {
463
- /** 线协议标识,如 "anthropic-messages" / "openai-responses" */
464
- api: string;
465
- /** 会话中途能否发带正文的 system 消息(S1 结论:按模型族) */
466
- midConversationSystem: boolean;
467
- /** thinking / reasoning 能否带签名原样回放 */
468
- thinkingReplay: boolean;
469
- parallelTools: boolean;
470
- /** 服务端 task budget 倒计时(仅部分 Anthropic 模型) */
471
- taskBudget: boolean;
472
- /**
473
- * 工具能否"声明但不载入"(L1):真则 `ToolSpec.deferLoading` 与结果里的 `tool_reference` 段有原生落点
474
- * (Anthropic `defer_loading` + `tool_reference` 块,官方模型 Haiku 4.5 起);假则引用段展开成文本、deferLoading 的工具不发
475
- */
476
- deferredTools: boolean;
477
- images: boolean;
478
- /**
479
- * 模型收不收视频 / 音频片段(2026-11-05)。没写 = 不收(fail-closed),降级层落文字占位并记 lossy。
480
- * 可选是为了宿主自写的 Lowering 不改也能编译;视频里的音轨不要求 `audio`
481
- */
482
- video?: boolean;
483
- audio?: boolean;
484
- contextWindow: number;
485
- maxOutputTokens: number;
486
- }
487
- /**
488
- * 一条事件在某家 API 上的落点。
489
- * - exact:语义完整落地
490
- * - lossy:落地了但有损(角色降级、签名缺失等),note 说明损失了什么
491
- * - dropped:没有下发,note 说明为什么以及信息由谁承载
492
- */
493
- type LossKind = "exact" | "lossy" | "dropped";
494
- /** 矩阵中的一种可能落点;when 描述触发条件(如"模型族支持中途 system") */
495
- interface LandingSpec {
496
- kind: LossKind;
497
- /** 落点标识,如 "user" / "system" / "thinking-block" / "reasoning-item" */
498
- landing: string;
499
- when?: string;
500
- note?: string;
501
- }
502
- /** 有损矩阵:api → 事件 type → 可能的落点列表。每个降级层实现导出自己的矩阵,测试据此逐项断言 */
503
- type LossMatrix = Readonly<Record<string, Readonly<Record<string, readonly LandingSpec[]>>>>;
504
- /** 一次 toRequest 中,某条具体事件实际落到了哪里 */
505
- interface LandingRecord {
506
- eventId: string;
507
- type: string;
508
- kind: LossKind;
509
- landing: string;
510
- note?: string;
511
- }
512
- interface LoweredRequest<TPayload = unknown> {
513
- model: ModelRef;
514
- capabilities: LoweringCapabilities;
515
- /** 每条输入事件一条记录,顺序与输入一致 */
516
- landings: LandingRecord[];
517
- /** 降级层专有的请求体,对核心不透明 */
518
- payload: TPayload;
519
- }
520
- /** 只取有损与丢弃的记录,供循环写日志或告警 */
521
- declare function lossesOf(req: LoweredRequest): LandingRecord[];
522
- interface ToRequestInput {
523
- /** 投影后的事件,顺序即模型看到的顺序 */
524
- events: readonly Event[];
525
- tools?: readonly ToolSpec[];
526
- model: ModelRef;
527
- systemPrompt?: string;
528
- }
529
- /** 流式增量,只给 UI 实时显示用;日志里只存 *_end 后的完整事件 */
530
- interface LoweringDelta {
531
- kind: "text" | "thinking" | "tool_args";
532
- /** 本次响应内的内容块序号 */
533
- index: number;
534
- delta: string;
535
- }
536
- interface LoweringStreamContext {
537
- signal?: AbortSignal;
538
- onDelta?: (delta: LoweringDelta) => void;
539
- }
540
- interface LoweringOutcome {
541
- stopReason: "stop" | "length" | "toolUse" | "error" | "aborted";
542
- usage: TokenUsage;
543
- /** 降级层按模型价目算出的美元成本;算不出则缺省 */
544
- costUsd?: number;
545
- errorMessage?: string;
546
- /** 厂商实际用的模型(可能因回退与请求的不同) */
547
- responseModel?: string;
548
- }
549
- /**
550
- * 绑定了降级层的模型:`anthropic("claude-opus-5", { apiKey })` 这类工厂的返回值,
551
- * 给 `createAgent({ model })` 一个参数就够。循环本身仍分开接收 model 与 lowering。
552
- */
553
- interface BoundModel {
554
- model: ModelRef;
555
- lowering: Lowering;
556
- }
557
- interface Lowering<TPayload = unknown> {
558
- capabilities(model: ModelRef): LoweringCapabilities;
559
- toRequest(input: ToRequestInput): LoweredRequest<TPayload>;
560
- /**
561
- * 发请求并把流式响应翻译成事件草稿;草稿只在内容块完整后产出。
562
- * 返回值是这次响应的收尾信息(停止原因、用量),由循环记成 budget_usage / error 事件。
563
- */
564
- stream(req: LoweredRequest<TPayload>, ctx?: LoweringStreamContext): AsyncGenerator<EventDraft, LoweringOutcome>;
565
- }
566
-
567
- /**
568
- * 存储接口(技术方案 §5)。四者相互独立,允许部分实现:
569
- * - 只有 EventLog 就能跑
570
- * - 缺 BlobStore → spill 模块自动关闭并告警
571
- * - 缺 MemoryStore → memory 工具不注册
572
- * - 缺 RunLease → run 登记只在进程内(多实例部署要它,见 D4)
573
- *
574
- * 每个接口的行为契约由 ../testing 下的一致性套件定义,第三方后端跑同一套件即可自证合规。
575
- */
576
-
577
- interface ReadOptions {
578
- /** 起始 seq,含;缺省从 1 */
579
- fromSeq?: number;
580
- /** 结束 seq,含;缺省到末尾 */
581
- toSeq?: number;
582
- }
583
- /**
584
- * 事件日志:只 append,永不 update / delete(宪法二)。
585
- *
586
- * seq 由调用方分配(通常是 runLoop),日志只校验:同一批必须同会话、seq 从当前末尾 +1 起连续。
587
- * 这样并发写入者会在 append 时收到 seq_conflict,而不是静默交错 —— 乐观并发控制就这么简单。
588
- */
589
- interface EventLog {
590
- /** 同会话原子:整批要么全部写入,要么一个都不写 */
591
- append(events: readonly Event[]): Promise<void>;
592
- /** 按 seq 升序流式读取;不存在的会话得到空流 */
593
- read(sessionId: string, opts?: ReadOptions): AsyncIterable<Event>;
594
- /** 最后 n 条,按 seq 升序;不够 n 条就返回全部 */
595
- tail(sessionId: string, n: number): Promise<Event[]>;
596
- /**
597
- * 从 fromSessionId 的 [1, atSeq] 分叉出新会话 toSessionId。
598
- * 事件原样复制(保留 id 与 seq,只换 sessionId),以维持 parentId / pinsKept 等会话内引用。
599
- * 目标会话必须为空;atSeq 超出范围报错。
600
- */
601
- fork(fromSessionId: string, atSeq: number, toSessionId: string): Promise<void>;
602
- }
603
- interface BlobMeta {
604
- mime: string;
605
- sessionId: string;
606
- /** 字节数 */
607
- size: number;
608
- /** Unix 毫秒 */
609
- createdAt: number;
610
- }
611
- /** 大对象:外溢的工具结果、附件、代码执行产物。字符串按 UTF-8 编码存储。 */
612
- interface BlobStore {
613
- put(bytes: Uint8Array | string, meta: {
614
- mime: string;
615
- sessionId: string;
616
- }): Promise<{
617
- id: string;
618
- }>;
619
- /** 不存在抛 StoreError("not_found") */
620
- get(id: string): Promise<{
621
- bytes: Uint8Array;
622
- meta: BlobMeta;
623
- }>;
624
- /** 可选:分段取回 [start, end),供模型分页读大结果;越界部分截断 */
625
- slice?(id: string, range: {
626
- start: number;
627
- end: number;
628
- }): Promise<Uint8Array>;
629
- }
630
- /**
631
- * 记忆后端:一个极简的文本 KV,键是路径。
632
- * 路径限定(必须在 /memories 下、禁止 ..)由 memory 工具层负责(B6),存储层只管存取。
633
- */
634
- interface MemoryStore {
635
- /** 所有以 prefix 开头的路径,按字典序 */
636
- list(prefix: string): Promise<string[]>;
637
- /** 不存在返回 null */
638
- read(path: string): Promise<string | null>;
639
- /** 覆盖写 */
640
- write(path: string, content: string): Promise<void>;
641
- /** 幂等:不存在也不报错 */
642
- delete(path: string): Promise<void>;
643
- }
644
- /**
645
- * 技能载体(技术方案 §9.9,S1):MemoryStore 的只读子集。任何 MemoryStore(内存 / sqlite / pg)天然满足,
646
- * 数据库载体零新代码;文件系统载体 `fsSkillSource(dir)` 在 `@reinsjs/brain/node`。刻意不新造接口——"存哪"由宿主定。
647
- */
648
- type SkillSource = Pick<MemoryStore, "list" | "read">;
649
- /**
650
- * run 租约(D4,2026-09-14):多实例部署下"同一会话同时只允许一个 run"的跨进程登记表。
651
- *
652
- * 语义是**带过期时间的独占锁**:`acquire` 在无人持有、持有者已过期、或持有者就是自己时成功;
653
- * 持有者每隔一段时间 `renew` 续期,进程崩了不续期,到期后别的实例就能接手;`release` 只删自己持有的。
654
- * 过期判定用**存储层自己的时钟**(数据库时间),不用各实例本机时钟——租约的意义是各实例对"谁持有"达成一致,
655
- * 判定时钟必须唯一。三个方法都不抛"冲突"类错误,用返回值说话;存储不可用时照常抛。
656
- *
657
- * 心跳、丢租约中止、失败告警这些行为放在 `@reinsjs/server` 的 `leasedRunRegistry` 一份,store 只做三条语句。
658
- * 单进程部署不需要它(进程内登记表已够),`memoryStore()` 刻意不带;`InMemoryRunLease` 是参考实现与测试用。
659
- */
660
- interface RunLease {
661
- /**
662
- * 为会话占租约 ttlMs 毫秒。无人持有、持有者已过期、或持有者就是 owner(幂等,等于续期)→ true;
663
- * 别人仍持有且未过期 → false。
664
- */
665
- acquire(sessionId: string, owner: string, ttlMs: number): Promise<boolean>;
666
- /** 续期:owner 仍持有且未过期 → true 并延长到 now + ttlMs;已过期、被别人接手、或从未持有 → false */
667
- renew(sessionId: string, owner: string, ttlMs: number): Promise<boolean>;
668
- /** 释放:只删 owner 自己持有的那条;不是自己的、或不存在,静默返回 */
669
- release(sessionId: string, owner: string): Promise<void>;
670
- }
671
- /**
672
- * 一套存储:只有 log 是必需的(§5 允许部分实现),`createAgent({ store })` 接收的就是它。
673
- * 带 `runLease` 时 `createAgent` 自动把 handler 的 run 登记表换成跨进程的租约登记(D4)。
674
- */
675
- interface Stores {
676
- log: EventLog;
677
- blobs?: BlobStore;
678
- memory?: MemoryStore;
679
- runLease?: RunLease;
680
- }
681
-
682
- export { type RunPausedPayload as $, type ApprovalRequestPayload as A, type BlobStore as B, type ContentPart as C, type CoreEventPayloads as D, type Event as E, type CoreEventType as F, type CreateEventInput as G, DEFAULT_TRUST as H, type EventBase as I, type EventSchema as J, type ExtEvent as K, type Lowering as L, type MemoryStore as M, type HandoffPayload as N, type ImagePart as O, type LandingSpec as P, type LossKind as Q, type ReadOptions as R, type Stores as S, type TokenUsage as T, type LossMatrix as U, type LoweringOutcome as V, type LoweringStreamContext as W, type MemoryOpPayload as X, type ModelTextPayload as Y, type ModelThinkingPayload as Z, type Provenance as _, EventSchemaRegistry as a, type RunResumedPayload as a0, SchemaError as a1, type SchemaErrorCode as a2, type SkillSource as a3, type SystemNotePayload as a4, type TextPart as a5, type ToRequestInput as a6, type ToolReferencePart as a7, type ToolStartedPayload as a8, type ToolsBoundPayload as a9, type Upcaster as aa, type UserMessagePayload as ab, type VideoPart as ac, contextOverheadOf as ad, contextTokensOf as ae, createCoreEvent as af, createCoreRegistry as ag, createEvent as ah, lossesOf as ai, renderToolReference as aj, type EventLog as b, type EventDraft as c, type Trust as d, type ModelRef as e, type LoweringCapabilities as f, type CoreEventOf as g, type ToolResultPayload as h, type LoweringDelta as i, type LandingRecord as j, type LoweredRequest as k, type ErrorPayload as l, type ToolCallPayload as m, type ToolSpec as n, type CoreEventDraft as o, type BudgetUsagePayload as p, type BlobMeta as q, type RunLease as r, type Actor as s, type AnyEvent as t, type ApprovalDecisionPayload as u, type AudioPart as v, type BoundModel as w, CORE_SCHEMAS as x, type CompactionPayload as y, type CoreEvent as z };