@reinsjs/core 0.11.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.
@@ -0,0 +1,1256 @@
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
+ * 事件 schema 注册表(P9:schema 有版本,读时升级,查不到即拒绝)。
112
+ *
113
+ * 职责:
114
+ * 1. 登记每个 type 的当前版本与逐级升级函数 upcast(v → v+1)
115
+ * 2. read(raw):校验壳字段 → 查 type → 逐级升级到当前版本 → 返回类型化事件
116
+ * 3. 任何一步查不到都抛 SchemaError(fail-closed),绝不静默返回半个事件
117
+ *
118
+ * 日志文件不做原地迁移:存的永远是写入时的版本,读时升级。
119
+ */
120
+
121
+ /** 把 payload 从版本 from 升到 from+1。只碰 payload,壳字段由注册表保证不变。 */
122
+ type Upcaster = (payload: unknown) => unknown;
123
+ interface EventSchema {
124
+ type: string;
125
+ /** 当前版本;新写入的事件一律打这个版本号 */
126
+ version: number;
127
+ /**
128
+ * 升级函数表,键为"起点版本":upcasters[1] 把 v1 升到 v2。
129
+ * version 为 n 时必须覆盖 1..n-1 全部键,缺一个即注册失败 —— 宁可启动时报错,不要读到一半才发现。
130
+ */
131
+ upcasters?: Readonly<Record<number, Upcaster>>;
132
+ }
133
+ type SchemaErrorCode = "malformed_base" | "unknown_type" | "future_version" | "missing_upcaster" | "upcaster_failed" | "invalid_schema";
134
+ declare class SchemaError extends Error {
135
+ readonly code: SchemaErrorCode;
136
+ readonly context: {
137
+ type?: string;
138
+ version?: number;
139
+ };
140
+ constructor(code: SchemaErrorCode, message: string, context?: {
141
+ type?: string;
142
+ version?: number;
143
+ });
144
+ }
145
+ declare class EventSchemaRegistry {
146
+ private readonly schemas;
147
+ constructor(schemas?: Iterable<EventSchema>);
148
+ /** 登记一个 type。重复登记同一 type 视为错误,避免两处定义互相覆盖。 */
149
+ register(schema: EventSchema): this;
150
+ has(type: string): boolean;
151
+ /** 该 type 当前应写入的版本号;未登记则抛 unknown_type。 */
152
+ currentVersion(type: string): number;
153
+ /**
154
+ * 从存储读出的原始对象 → 当前版本的事件。
155
+ * 泛型只是给调用方的类型提示(如 read<CoreEvent>),运行时校验的是壳与版本,不校验 payload 形状 ——
156
+ * payload 的正确性由写入方与升级函数负责。
157
+ */
158
+ read<E extends Event = Event>(raw: unknown): E;
159
+ }
160
+ /** 全部内置事件当前都是 v1。升版本时在此加 upcasters,并在 core.ts 改载荷类型。 */
161
+ declare const CORE_SCHEMAS: readonly EventSchema[];
162
+ /** 预装了全部 core.* 的注册表。宿主要加 ext.* 时 new 一个并传入 [...CORE_SCHEMAS, ...自己的]。 */
163
+ declare function createCoreRegistry(extra?: Iterable<EventSchema>): EventSchemaRegistry;
164
+
165
+ /**
166
+ * 事件工厂:补齐 id / at / schemaVersion / trust,调用方只关心"谁、在哪个会话、第几条、说了什么"。
167
+ * seq 由 EventLog 的 append 方决定(T4),这里要求显式传入,不替存储层做主。
168
+ */
169
+
170
+ /**
171
+ * 事件草稿:还没进日志的事件,缺 id / seq / at / sessionId / schemaVersion。
172
+ * 降级层(模型输出)与脑子模块(注入的 system_note)都只产出草稿,由循环补齐后 append ——
173
+ * 谁分配 seq 只有循环知道,草稿不替它做主。
174
+ */
175
+ interface EventDraft<T extends string = string, P = unknown> {
176
+ type: T;
177
+ payload: P;
178
+ actor: Actor;
179
+ /** 缺省按 DEFAULT_TRUST[actor] */
180
+ trust?: Trust;
181
+ parentId?: string;
182
+ provenance?: Provenance;
183
+ replay?: Record<string, unknown>;
184
+ }
185
+ /** 内置事件的草稿联合,type 与 payload 联动 */
186
+ type CoreEventDraft = {
187
+ [T in CoreEventType]: EventDraft<T, CoreEventPayloads[T]>;
188
+ }[CoreEventType];
189
+ interface CreateEventInput<T extends string, P> extends EventDraft<T, P> {
190
+ sessionId: string;
191
+ seq: number;
192
+ /** 测试注入用;缺省 Date.now() */
193
+ at?: number;
194
+ id?: string;
195
+ }
196
+ /**
197
+ * 通用工厂。schemaVersion 从注册表取当前版本,所以未登记的 type 会在这里就被拒绝,
198
+ * 而不是写进日志后读不出来。
199
+ */
200
+ declare function createEvent<T extends string, P>(registry: EventSchemaRegistry, input: CreateEventInput<T, P>): Event<T, P>;
201
+ /** 内置事件的强类型版本:type 与 payload 联动校验。 */
202
+ declare function createCoreEvent<T extends CoreEventType>(registry: EventSchemaRegistry, input: CreateEventInput<T, CoreEventPayloads[T]>): CoreEventOf<T>;
203
+
204
+ /**
205
+ * 降级层接口(技术方案 §11;宪法二:角色只是翻译)。
206
+ *
207
+ * 降级层把投影后的事件翻译成某家 API 的请求,再把流式响应翻译回事件草稿。
208
+ * 它是唯一允许出现"角色"概念的地方。每种事件在每家 API 上落到哪里、有没有损失,
209
+ * 必须在 LossMatrix 里声明,并在每次 toRequest 的 landings 里逐条记录 —— 禁止静默丢弃(P7)。
210
+ *
211
+ * 本文件只有类型;具体实现(如 @reinsjs/lowering-pi)在可选包里,厂商 SDK 类型不得出现在这里。
212
+ */
213
+
214
+ /** 模型引用:宿主用它指定"哪家的哪个模型",具体解析交给降级层实现 */
215
+ interface ModelRef {
216
+ provider: string;
217
+ id: string;
218
+ }
219
+ /** 工具声明的模型可见部分。执行、审批、结果处置等维度在工具模型(§10)里,不进降级层 */
220
+ interface ToolSpec {
221
+ name: string;
222
+ description: string;
223
+ /** JSON Schema 对象;不绑任何校验库 */
224
+ inputSchema: Record<string, unknown>;
225
+ /**
226
+ * 向厂商声明但不载入模型上下文(L1):Anthropic 的 `defer_loading: true`——工具留在 tools 块里(表整段不变、缓存前缀不动),
227
+ * 模型只有在历史里出现指向它的 `tool_reference` 后才看得见。没有等价表达的线**不发**这件工具(模型看不见也调不了,
228
+ * 与过滤掉同义)。只有 `LoweringCapabilities.deferredTools` 为真的降级层会收到带这个标记的规格(lazy-tools 据能力位决定)。
229
+ */
230
+ deferLoading?: boolean;
231
+ }
232
+ /** 本模型在本 API 上支持什么。脑子模块据此选择等价表达 */
233
+ interface LoweringCapabilities {
234
+ /** 线协议标识,如 "anthropic-messages" / "openai-responses" */
235
+ api: string;
236
+ /** 会话中途能否发带正文的 system 消息(S1 结论:按模型族) */
237
+ midConversationSystem: boolean;
238
+ /** thinking / reasoning 能否带签名原样回放 */
239
+ thinkingReplay: boolean;
240
+ parallelTools: boolean;
241
+ /** 服务端 task budget 倒计时(仅部分 Anthropic 模型) */
242
+ taskBudget: boolean;
243
+ /**
244
+ * 工具能否"声明但不载入"(L1):真则 `ToolSpec.deferLoading` 与结果里的 `tool_reference` 段有原生落点
245
+ * (Anthropic `defer_loading` + `tool_reference` 块,官方模型 Haiku 4.5 起);假则引用段展开成文本、deferLoading 的工具不发
246
+ */
247
+ deferredTools: boolean;
248
+ images: boolean;
249
+ /**
250
+ * 模型收不收视频 / 音频片段(2026-11-05)。没写 = 不收(fail-closed),降级层落文字占位并记 lossy。
251
+ * 可选是为了宿主自写的 Lowering 不改也能编译;视频里的音轨不要求 `audio`
252
+ */
253
+ video?: boolean;
254
+ audio?: boolean;
255
+ contextWindow: number;
256
+ maxOutputTokens: number;
257
+ }
258
+ /**
259
+ * 一条事件在某家 API 上的落点。
260
+ * - exact:语义完整落地
261
+ * - lossy:落地了但有损(角色降级、签名缺失等),note 说明损失了什么
262
+ * - dropped:没有下发,note 说明为什么以及信息由谁承载
263
+ */
264
+ type LossKind = "exact" | "lossy" | "dropped";
265
+ /** 矩阵中的一种可能落点;when 描述触发条件(如"模型族支持中途 system") */
266
+ interface LandingSpec {
267
+ kind: LossKind;
268
+ /** 落点标识,如 "user" / "system" / "thinking-block" / "reasoning-item" */
269
+ landing: string;
270
+ when?: string;
271
+ note?: string;
272
+ }
273
+ /** 有损矩阵:api → 事件 type → 可能的落点列表。每个降级层实现导出自己的矩阵,测试据此逐项断言 */
274
+ type LossMatrix = Readonly<Record<string, Readonly<Record<string, readonly LandingSpec[]>>>>;
275
+ /** 一次 toRequest 中,某条具体事件实际落到了哪里 */
276
+ interface LandingRecord {
277
+ eventId: string;
278
+ type: string;
279
+ kind: LossKind;
280
+ landing: string;
281
+ note?: string;
282
+ }
283
+ interface LoweredRequest<TPayload = unknown> {
284
+ model: ModelRef;
285
+ capabilities: LoweringCapabilities;
286
+ /** 每条输入事件一条记录,顺序与输入一致 */
287
+ landings: LandingRecord[];
288
+ /** 降级层专有的请求体,对核心不透明 */
289
+ payload: TPayload;
290
+ }
291
+ /** 只取有损与丢弃的记录,供循环写日志或告警 */
292
+ declare function lossesOf(req: LoweredRequest): LandingRecord[];
293
+ interface ToRequestInput {
294
+ /** 投影后的事件,顺序即模型看到的顺序 */
295
+ events: readonly Event[];
296
+ tools?: readonly ToolSpec[];
297
+ model: ModelRef;
298
+ systemPrompt?: string;
299
+ }
300
+ /** 流式增量,只给 UI 实时显示用;日志里只存 *_end 后的完整事件 */
301
+ interface LoweringDelta {
302
+ kind: "text" | "thinking" | "tool_args";
303
+ /** 本次响应内的内容块序号 */
304
+ index: number;
305
+ delta: string;
306
+ }
307
+ interface LoweringStreamContext {
308
+ signal?: AbortSignal;
309
+ onDelta?: (delta: LoweringDelta) => void;
310
+ }
311
+ interface LoweringOutcome {
312
+ stopReason: "stop" | "length" | "toolUse" | "error" | "aborted";
313
+ usage: TokenUsage;
314
+ /** 降级层按模型价目算出的美元成本;算不出则缺省 */
315
+ costUsd?: number;
316
+ errorMessage?: string;
317
+ /** 厂商实际用的模型(可能因回退与请求的不同) */
318
+ responseModel?: string;
319
+ }
320
+ /**
321
+ * 绑定了降级层的模型:`anthropic("claude-opus-5", { apiKey })` 这类工厂的返回值,
322
+ * 给 `createAgent({ model })` 一个参数就够。循环本身仍分开接收 model 与 lowering。
323
+ */
324
+ interface BoundModel {
325
+ model: ModelRef;
326
+ lowering: Lowering;
327
+ }
328
+ interface Lowering<TPayload = unknown> {
329
+ capabilities(model: ModelRef): LoweringCapabilities;
330
+ toRequest(input: ToRequestInput): LoweredRequest<TPayload>;
331
+ /**
332
+ * 发请求并把流式响应翻译成事件草稿;草稿只在内容块完整后产出。
333
+ * 返回值是这次响应的收尾信息(停止原因、用量),由循环记成 budget_usage / error 事件。
334
+ */
335
+ stream(req: LoweredRequest<TPayload>, ctx?: LoweringStreamContext): AsyncGenerator<EventDraft, LoweringOutcome>;
336
+ }
337
+
338
+ /**
339
+ * 投影(技术方案 §8):输入完整时间线,输出模型本轮应看到的事件。
340
+ *
341
+ * 投影是纯函数:同一份时间线快照、同样的参数,输出必须逐字相同。这让它可单测、可回放、
342
+ * 可在 eval 里对比不同策略。任何"随机"(事件 id)与"时间"(at)都从 ctx 注入,不在策略里 Date.now()。
343
+ *
344
+ * 策略链按顺序执行,每个策略拿到上一步的结果与不变的上下文,输出新的事件序列。
345
+ * 策略可以新造事件(如阈值兜底的 compaction),但必须通过 `emitted` 交出去由循环 append 进日志,
346
+ * 否则违反"模型可见 ⟺ 已记录"。
347
+ */
348
+
349
+ interface ProjectionBudget {
350
+ /** 模型上下文窗口上限(token) */
351
+ contextLimit: number;
352
+ /** 为模型输出预留的 token;裁剪目标 = contextLimit - reserveTokens,按真实上下文(估算 + overheadTokens)比 */
353
+ reserveTokens: number;
354
+ /**
355
+ * 估算不含的固定开销(系统提示、工具表、thinking 等),见 contextOverheadOf。project() 总会填;
356
+ * 自己拼上下文直接调策略时缺省按 0
357
+ */
358
+ overheadTokens?: number;
359
+ }
360
+ /** 估算一条事件降级后大约占多少 token。核心包不带 tokenizer,默认是粗估,宿主可注入精确实现。 */
361
+ type TokenEstimator = (event: Event) => number;
362
+ /** 策略执行时能看到的一切。全部只读;策略之间不共享可变状态。 */
363
+ interface ProjectionContext {
364
+ readonly sessionId: string;
365
+ /** 完整时间线快照,按 seq 升序。策略要回看被前序策略移除的事件时用 */
366
+ readonly timeline: readonly Event[];
367
+ readonly budget: ProjectionBudget;
368
+ readonly estimate: TokenEstimator;
369
+ /** 新造事件取 schemaVersion 用 */
370
+ readonly registry: EventSchemaRegistry;
371
+ /** 本次投影的时间戳;新造事件的 at 一律取它 */
372
+ readonly now: number;
373
+ /** 新造事件的 id 工厂;测试可注入确定值 */
374
+ readonly newId: (at: number) => string;
375
+ /** 前序策略已新造、待 append 的事件 */
376
+ readonly emitted: readonly Event[];
377
+ /** 下一条新造事件应使用的 seq:时间线末尾 + 已新造数 + 1 */
378
+ nextSeq(): number;
379
+ }
380
+ interface ProjectionStep {
381
+ /** 本策略之后模型应看到的事件序列。顺序即模型看到的顺序,不必与 seq 一致 */
382
+ events: Event[];
383
+ /**
384
+ * 本策略新造、需要由循环 append 进日志的事件。
385
+ * 必须同时出现在 events 里 —— 模型看到的每一条都要落日志。
386
+ */
387
+ emitted?: Event[];
388
+ }
389
+ interface ProjectionStrategy {
390
+ readonly name: string;
391
+ apply(events: readonly Event[], ctx: ProjectionContext): ProjectionStep;
392
+ }
393
+ interface ProjectionStepStats {
394
+ name: string;
395
+ /** 进入该策略前 / 后的事件数 */
396
+ before: number;
397
+ after: number;
398
+ }
399
+ interface ProjectionStats {
400
+ /** 最终可见事件的估算 token 总量 */
401
+ estimatedTokens: number;
402
+ /** contextLimit - reserveTokens,真实上下文口径:estimatedTokens + overheadTokens 超过它就兜底裁剪 */
403
+ targetTokens: number;
404
+ /** 本次投影用的固定开销(缺省从时间线校准,见 contextOverheadOf) */
405
+ overheadTokens: number;
406
+ /** 裁到不能再裁仍超目标(估算 + 开销):只剩最后一轮也放不下,需要 spill 或更大的窗口。循环层据此告警 */
407
+ overBudget: boolean;
408
+ steps: ProjectionStepStats[];
409
+ }
410
+ interface ProjectionResult {
411
+ /** 模型本轮看到的事件 */
412
+ events: Event[];
413
+ /**
414
+ * 投影新造、循环必须 append 进日志的事件,seq 已按时间线末尾预分配。
415
+ * append 时 seq 冲突**不重跑投影**,`StoreError("seq_conflict")` 原样抛给宿主(R4,DECISIONS 2026-09-10):
416
+ * run 进行中还有人往同一会话追加,是会话级并发违规(server 用 409 一会话一 run 挡它),静默重跑只会把并发写入藏起来
417
+ */
418
+ emitted: Event[];
419
+ stats: ProjectionStats;
420
+ }
421
+
422
+ /**
423
+ * 存储接口(技术方案 §5)。四者相互独立,允许部分实现:
424
+ * - 只有 EventLog 就能跑
425
+ * - 缺 BlobStore → spill 模块自动关闭并告警
426
+ * - 缺 MemoryStore → memory 工具不注册
427
+ * - 缺 RunLease → run 登记只在进程内(多实例部署要它,见 D4)
428
+ *
429
+ * 每个接口的行为契约由 ../testing 下的一致性套件定义,第三方后端跑同一套件即可自证合规。
430
+ */
431
+
432
+ interface ReadOptions {
433
+ /** 起始 seq,含;缺省从 1 */
434
+ fromSeq?: number;
435
+ /** 结束 seq,含;缺省到末尾 */
436
+ toSeq?: number;
437
+ }
438
+ /**
439
+ * 事件日志:只 append,永不 update / delete(宪法二)。
440
+ *
441
+ * seq 由调用方分配(通常是 runLoop),日志只校验:同一批必须同会话、seq 从当前末尾 +1 起连续。
442
+ * 这样并发写入者会在 append 时收到 seq_conflict,而不是静默交错 —— 乐观并发控制就这么简单。
443
+ */
444
+ interface EventLog {
445
+ /** 同会话原子:整批要么全部写入,要么一个都不写 */
446
+ append(events: readonly Event[]): Promise<void>;
447
+ /** 按 seq 升序流式读取;不存在的会话得到空流 */
448
+ read(sessionId: string, opts?: ReadOptions): AsyncIterable<Event>;
449
+ /** 最后 n 条,按 seq 升序;不够 n 条就返回全部 */
450
+ tail(sessionId: string, n: number): Promise<Event[]>;
451
+ /**
452
+ * 从 fromSessionId 的 [1, atSeq] 分叉出新会话 toSessionId。
453
+ * 事件原样复制(保留 id 与 seq,只换 sessionId),以维持 parentId / pinsKept 等会话内引用。
454
+ * 目标会话必须为空;atSeq 超出范围报错。
455
+ */
456
+ fork(fromSessionId: string, atSeq: number, toSessionId: string): Promise<void>;
457
+ }
458
+ interface BlobMeta {
459
+ mime: string;
460
+ sessionId: string;
461
+ /** 字节数 */
462
+ size: number;
463
+ /** Unix 毫秒 */
464
+ createdAt: number;
465
+ }
466
+ /** 大对象:外溢的工具结果、附件、代码执行产物。字符串按 UTF-8 编码存储。 */
467
+ interface BlobStore {
468
+ put(bytes: Uint8Array | string, meta: {
469
+ mime: string;
470
+ sessionId: string;
471
+ }): Promise<{
472
+ id: string;
473
+ }>;
474
+ /** 不存在抛 StoreError("not_found") */
475
+ get(id: string): Promise<{
476
+ bytes: Uint8Array;
477
+ meta: BlobMeta;
478
+ }>;
479
+ /** 可选:分段取回 [start, end),供模型分页读大结果;越界部分截断 */
480
+ slice?(id: string, range: {
481
+ start: number;
482
+ end: number;
483
+ }): Promise<Uint8Array>;
484
+ }
485
+ /**
486
+ * 记忆后端:一个极简的文本 KV,键是路径。
487
+ * 路径限定(必须在 /memories 下、禁止 ..)由 memory 工具层负责(B6),存储层只管存取。
488
+ */
489
+ interface MemoryStore {
490
+ /** 所有以 prefix 开头的路径,按字典序 */
491
+ list(prefix: string): Promise<string[]>;
492
+ /** 不存在返回 null */
493
+ read(path: string): Promise<string | null>;
494
+ /** 覆盖写 */
495
+ write(path: string, content: string): Promise<void>;
496
+ /** 幂等:不存在也不报错 */
497
+ delete(path: string): Promise<void>;
498
+ }
499
+ /**
500
+ * 技能载体(技术方案 §9.9,S1):MemoryStore 的只读子集。任何 MemoryStore(内存 / sqlite / pg)天然满足,
501
+ * 数据库载体零新代码;文件系统载体 `fsSkillSource(dir)` 在 `@reinsjs/brain/node`。刻意不新造接口——"存哪"由宿主定。
502
+ */
503
+ type SkillSource = Pick<MemoryStore, "list" | "read">;
504
+ /**
505
+ * run 租约(D4,2026-09-14):多实例部署下"同一会话同时只允许一个 run"的跨进程登记表。
506
+ *
507
+ * 语义是**带过期时间的独占锁**:`acquire` 在无人持有、持有者已过期、或持有者就是自己时成功;
508
+ * 持有者每隔一段时间 `renew` 续期,进程崩了不续期,到期后别的实例就能接手;`release` 只删自己持有的。
509
+ * 过期判定用**存储层自己的时钟**(数据库时间),不用各实例本机时钟——租约的意义是各实例对"谁持有"达成一致,
510
+ * 判定时钟必须唯一。三个方法都不抛"冲突"类错误,用返回值说话;存储不可用时照常抛。
511
+ *
512
+ * 心跳、丢租约中止、失败告警这些行为放在 `@reinsjs/server` 的 `leasedRunRegistry` 一份,store 只做三条语句。
513
+ * 单进程部署不需要它(进程内登记表已够),`memoryStore()` 刻意不带;`InMemoryRunLease` 是参考实现与测试用。
514
+ */
515
+ interface RunLease {
516
+ /**
517
+ * 为会话占租约 ttlMs 毫秒。无人持有、持有者已过期、或持有者就是 owner(幂等,等于续期)→ true;
518
+ * 别人仍持有且未过期 → false。
519
+ */
520
+ acquire(sessionId: string, owner: string, ttlMs: number): Promise<boolean>;
521
+ /** 续期:owner 仍持有且未过期 → true 并延长到 now + ttlMs;已过期、被别人接手、或从未持有 → false */
522
+ renew(sessionId: string, owner: string, ttlMs: number): Promise<boolean>;
523
+ /** 释放:只删 owner 自己持有的那条;不是自己的、或不存在,静默返回 */
524
+ release(sessionId: string, owner: string): Promise<void>;
525
+ }
526
+ /**
527
+ * 一套存储:只有 log 是必需的(§5 允许部分实现),`createAgent({ store })` 接收的就是它。
528
+ * 带 `runLease` 时 `createAgent` 自动把 handler 的 run 登记表换成跨进程的租约登记(D4)。
529
+ */
530
+ interface Stores {
531
+ log: EventLog;
532
+ blobs?: BlobStore;
533
+ memory?: MemoryStore;
534
+ runLease?: RunLease;
535
+ }
536
+
537
+ interface RetryOptions {
538
+ /** 最多尝试几次(含第一次)。缺省 3;1 = 不重试 */
539
+ maxAttempts?: number;
540
+ /** 首次重试前等多久(毫秒),之后每次翻倍。缺省 1000 */
541
+ baseDelayMs?: number;
542
+ /** 单次等待上限(毫秒)。缺省 8000 */
543
+ maxDelayMs?: number;
544
+ /** 覆盖瞬断判定:返回 true 表示值得重试。缺省见 isTransientFailure */
545
+ isTransient?: (failure: ModelCallFailure) => boolean;
546
+ /** 测试注入:等待实现。缺省 setTimeout,且被 signal 中止时提前结束 */
547
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
548
+ }
549
+ /** 一次模型调用失败的两种形态:降级层抛了异常,或流正常收尾但 stopReason = error */
550
+ type ModelCallFailure = {
551
+ kind: "thrown";
552
+ error: unknown;
553
+ } | {
554
+ kind: "outcome";
555
+ message: string;
556
+ };
557
+ declare const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
558
+ declare const DEFAULT_RETRY_BASE_DELAY_MS = 1000;
559
+ declare const DEFAULT_RETRY_MAX_DELAY_MS = 8000;
560
+ /**
561
+ * 从错误文案里提取 HTTP 状态码:开头的三位数字(SDK 格式 "<status> <body>"),或 "status (code) 503" / "HTTP 503" 写法。
562
+ * 只认 100~599,不在这两个位置上的数字不算(正文里提到 "429" 不是状态码)
563
+ */
564
+ declare function statusFromMessage(message: string): number | undefined;
565
+ declare function isTransientFailure(failure: ModelCallFailure): boolean;
566
+ /** 第 attempt 次失败后等多久:base × 2^(attempt−1),封顶 maxDelay。不加抖动,保证可测、可回放 */
567
+ declare function backoffDelayMs(attempt: number, opts?: Pick<RetryOptions, "baseDelayMs" | "maxDelayMs">): number;
568
+ /** 缺省等待:setTimeout;signal 中止就立刻返回(由调用方检查 aborted 再决定怎么收尾) */
569
+ declare function defaultSleep(ms: number, signal?: AbortSignal): Promise<void>;
570
+ interface ResolvedRetry {
571
+ maxAttempts: number;
572
+ delayFor: (attempt: number) => number;
573
+ isTransient: (failure: ModelCallFailure) => boolean;
574
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
575
+ }
576
+ declare function resolveRetry(opts?: RetryOptions): ResolvedRetry;
577
+
578
+ /**
579
+ * 循环与插座的类型(技术方案 §6、§7、§10)。
580
+ *
581
+ * 三组契约:
582
+ * - Tool:宿主给模型的能力(§10 四个正交维度);循环只用 name / inputSchema / execute / needsApproval 等少数字段,
583
+ * 其余维度(lazy、resultPolicy、ui…)留给脑子模块与后续期次消费,先把形状定下来。
584
+ * - Socket:脑子与底盘之间唯一的契约,五个钩子。脑子只依赖它,不依赖 runLoop 的实现(P3、P4)。
585
+ * - RunResult / SerializedRunState:暂停是显式返回值,状态小到能放 URL 参数(P6)。
586
+ */
587
+
588
+ /** 主事人:本次 run 代表谁。库只透传给钩子与工具,不解释其字段 */
589
+ interface Principal {
590
+ id: string;
591
+ [key: string]: unknown;
592
+ }
593
+ interface SessionInfo {
594
+ id: string;
595
+ /** 本次 run 内的第几轮(从 1 起) */
596
+ turn: number;
597
+ }
598
+ type ToolSide = "server" | "client" | "sandbox" | "provider";
599
+ /** 工具执行结果的规范形态;execute 可以返回任何值,循环用 normalizeToolOutput 归一 */
600
+ interface ToolResult {
601
+ content: ContentPart[];
602
+ isError?: boolean;
603
+ }
604
+ interface ToolContext {
605
+ sessionId: string;
606
+ toolCallId: string;
607
+ principal?: Principal;
608
+ log: EventLog;
609
+ blobs?: BlobStore;
610
+ memory?: MemoryStore;
611
+ signal?: AbortSignal;
612
+ /** 工具想留痕(如 memory_op):草稿由循环补齐后、在 tool_result 之前 append */
613
+ emit(draft: EventDraft): void;
614
+ /**
615
+ * 宿主本次续跑给**别的会话**(子代理)的审批结论(`ApprovalDecisionInput.sessionId` 指向非本会话的那些),循环不校验、不记事件,
616
+ * 原样转发;`asTool` 把它们交给子 run,多层嵌套逐层下传。没有就缺省(§10.1)
617
+ */
618
+ decisions?: readonly ApprovalDecisionInput[];
619
+ /**
620
+ * 把工具代跑的模型用量(子代理的 run)计入本 run 的预算:只加 `TurnContext.budget.tokensSpent`,父的 budget 模块按总账拦。
621
+ * 不追加父的 budget_usage 事件(那条是感知校准上下文大小的依据)。宿主循环提供;没提供的环境里工具只把用量写进结果
622
+ */
623
+ spend?(usage: TokenUsage): void;
624
+ }
625
+ /**
626
+ * 工具。execute / validate 用"方法签名"而非属性函数:TS 对方法参数做双变检查,
627
+ * 这样 Tool<{ path: string }> 才能放进 Tool[](即 Tool<unknown>[])里。
628
+ * needsApproval 是 boolean | 函数 的联合,无法写成方法,带类型入参的工具请用 defineTool() 定义。
629
+ */
630
+ interface Tool<TInput = unknown> {
631
+ name: string;
632
+ description: string;
633
+ /** JSON Schema 对象,原样交给模型;不绑任何校验库 */
634
+ inputSchema: Record<string, unknown>;
635
+ /** 可选的入参校验/转换:返回规范化入参,抛错即视为入参不合法(结果以 isError 告知模型) */
636
+ validate?(input: unknown): TInput;
637
+ /** 执行位置;缺省 server。client 表示由宿主前端执行,循环遇到即暂停等结果 */
638
+ side?: ToolSide;
639
+ /** 缺省表示本循环不执行(转客户端) */
640
+ execute?(input: TInput, ctx: ToolContext): Promise<unknown> | unknown;
641
+ /** 把 execute 的返回值翻译成模型看到的内容片段;缺省规则见 normalizeToolOutput */
642
+ toModelOutput?(output: unknown): ContentPart[];
643
+ /** 结果处置:超限截断或外溢(B4 消费) */
644
+ resultPolicy?: {
645
+ maxTokens?: number;
646
+ overflow: "truncate" | "spill";
647
+ };
648
+ /** 执行前是否要人审批。循环内置兜底:为真且没有任何 Socket 做主时,直接转审批暂停(安全默认值) */
649
+ needsApproval?: boolean | ((input: TInput, ctx: ToolContext) => Promise<boolean> | boolean);
650
+ risk?: "low" | "medium" | "high";
651
+ /**
652
+ * 开始动手后中断(进程死亡、执行中被掐断)、没留下结果时,续跑能不能再执行一遍。缺省按 risk:只有 `"low"` 可重放(`isReplayable`)。
653
+ * 不可重放的调用在 execute 之前落一条 `core.tool_started`,续跑时见到它就落"结果未知"让模型先查再定,不再执行——写工具重复执行
654
+ * 就是重复改用户的东西。幂等的写工具可以显式 `true`;asTool 子代理显式 `true`(子会话自己能续跑)
655
+ */
656
+ replayable?: boolean;
657
+ /**
658
+ * 这个工具**成功**结果事件(tool_result)的 trust;缺省 `DEFAULT_TRUST.tool`(untrusted:翻译给模型时包 `<untrusted>` 标记)。
659
+ * 只有输出等同宿主配置的工具才声明 `"system"`——如 brain 的 `skill_read`(技能是宿主写的说明书,视同系统提示)。
660
+ * 刻意只开 system / untrusted 两档:principal 是用户本人的权威、model 是模型自己的话,工具输出冒充哪一个都不对。
661
+ * 落法只有一份纯函数 `toolResultTrust(tool, isError)`:循环(执行结果、宿主回填的客户端工具结果)与 TanStack 适配器
662
+ * (afterToolCall、toolPhaseComplete)都调它;isError 结果、未知工具、入参不合法、执行抛错一律缺省。
663
+ */
664
+ resultTrust?: Extract<Trust, "system" | "untrusted">;
665
+ /** 暴露策略:延迟加载/发现(后续期次) */
666
+ lazy?: boolean;
667
+ allowedCallers?: ("direct" | "code")[];
668
+ /** MCP Apps 形态(第三期) */
669
+ ui?: {
670
+ resourceUri: string;
671
+ };
672
+ }
673
+ type ToolCallEvent = CoreEventOf<"core.tool_call">;
674
+ type ToolResultEvent = CoreEventOf<"core.tool_result">;
675
+ type ToolResultDraft = EventDraft<"core.tool_result", ToolResultPayload>;
676
+ /** beforeModel 的返回:改投影、增删工具、换系统提示;缺省字段表示不改 */
677
+ interface BeforeModelPatch {
678
+ events?: Event[];
679
+ tools?: Tool[];
680
+ systemPrompt?: string;
681
+ /**
682
+ * 本轮工具表里哪些只"向厂商声明、不载入上下文"(按名字;L1)。循环把它翻成 `ToolSpec.deferLoading`,
683
+ * 名字不在最终工具表里的忽略。只在 `ctx.capabilities.deferredTools` 为真时有意义——没有原生落点的降级层会直接不发这些工具。
684
+ * 后一个 Socket 给了就整体替换前一个的;没给就沿用
685
+ */
686
+ deferredTools?: readonly string[];
687
+ }
688
+ /** 审批请求的规格;toolCallId 由循环填 */
689
+ interface ApprovalRequestSpec {
690
+ policyId: string;
691
+ summary: string;
692
+ }
693
+ type BeforeToolDecision = "proceed" | {
694
+ block: string;
695
+ } | {
696
+ defer: ApprovalRequestSpec;
697
+ } | {
698
+ rewrite: unknown;
699
+ };
700
+ interface HandoffIntent {
701
+ /** 缺省由循环生成 */
702
+ toSessionId?: string;
703
+ summary: string;
704
+ /** 触发交接的那条用户消息,新会话据此续做 */
705
+ triggerMessage?: string;
706
+ reason: string;
707
+ /** 谁决定交接:模型(默认,经 handoff 工具)或宿主 */
708
+ by?: "model" | "host";
709
+ /**
710
+ * 新会话开头额外追加的事件草稿(B5):排在摘要说明(seq 1)之后、触发消息之前,如带过去的 pin。
711
+ * 循环只补齐 id / seq / at / sessionId,不解释内容。
712
+ */
713
+ opening?: EventDraft[];
714
+ }
715
+ type TurnDecision = "continue" | "stop" | {
716
+ handoff: HandoffIntent;
717
+ } | {
718
+ pause: {
719
+ reason: "budget" | "host";
720
+ note?: string;
721
+ };
722
+ };
723
+ type MaybePromise<T> = T | Promise<T>;
724
+ interface TurnContext {
725
+ session: SessionInfo;
726
+ principal?: Principal;
727
+ /** 当前投影结果,即模型本轮将看到的事件(可读) */
728
+ events: Event[];
729
+ /** 完整时间线快照(脑子模块回看被折叠的事件时用) */
730
+ timeline: readonly Event[];
731
+ log: EventLog;
732
+ blobs?: BlobStore;
733
+ memory?: MemoryStore;
734
+ /** 本轮可用工具 */
735
+ tools: readonly Tool[];
736
+ model: ModelRef;
737
+ /** 本模型支持什么(中途 system、thinking 回放、并行工具…) */
738
+ capabilities: LoweringCapabilities;
739
+ budget: {
740
+ contextLimit: number;
741
+ /**
742
+ * 投影的裁剪目标 = contextLimit - reserveTokens,真实上下文口径:本轮估算 + 固定开销(contextOverheadOf(timeline))
743
+ * 超过它库就按阈值自动折叠最旧的轮次(感知用同一函数校准、据此提醒模型)
744
+ */
745
+ targetTokens: number;
746
+ /** 本轮投影的估算 token */
747
+ used: number;
748
+ /** 本次 run 累计消耗(输入 + 输出) */
749
+ tokensSpent: number;
750
+ turns: number;
751
+ toolCalls: number;
752
+ /** 距 run 开始的毫秒数;beforeModel 时是本轮开始的读数,模型调用后更新 */
753
+ wallMs: number;
754
+ /**
755
+ * 最近一次模型请求的真实用量(B8):beforeModel 时是上一次请求的(含上次 run,从日志最后一条 budget_usage 读),
756
+ * 模型调用后即本轮的。上下文大小用 contextTokensOf(lastUsage) 算,不是 input
757
+ */
758
+ lastUsage?: TokenUsage;
759
+ };
760
+ signal?: AbortSignal;
761
+ /**
762
+ * 本批工具调用的活动(2026-11-02,OnSet 建议 9 / 10):模型这次发了哪些调用、已落了哪些结果、哪些被挂起、是不是补跑。
763
+ * 同一个对象在本轮内由循环随落随更——beforeTool 处理第 k 个调用时只看得见它之前落下的结果;不要拿快照比较
764
+ */
765
+ batch: ToolBatch;
766
+ /** 草稿:无 id / seq / at / sessionId,循环补齐后 append。beforeModel 期间 emit 的本轮即可见 */
767
+ emit(draft: EventDraft): void;
768
+ }
769
+ /**
770
+ * "一批" = 一段连续模型输出里的 tool_call(与 replay 切轮 `isModelOutput` 同口径,模型不可见的运维事件不切段),
771
+ * 定位规则只有一份:`toolBatchOf`。Socket 只读;循环(runLoop、TanStack 适配器)负责填。
772
+ */
773
+ interface ToolBatch {
774
+ /** 本批调用,按执行顺序。模型输出前(beforeModel)为空;补跑时是遗留调用所在那批的全部 tool_call */
775
+ readonly calls: readonly ToolCallEvent[];
776
+ /**
777
+ * 本批已落日志的 tool_result(afterTool 替换之后、真正落日志的那条),按落下顺序。
778
+ * 补跑时预置上次已落的(含宿主经 input 回填的客户端工具结果)
779
+ */
780
+ readonly results: readonly ToolResultEvent[];
781
+ /** 本批已处理但被挂起、没落结果的 toolCallId(等审批 / 等客户端回填 / 子代理暂停)。TanStack 路径恒为空(defer 让整批暂停) */
782
+ readonly held: readonly string[];
783
+ /** 本批是续跑补齐上次遗留的调用(没有新的模型输出) */
784
+ readonly resumed: boolean;
785
+ }
786
+ /**
787
+ * 静态贡献的运行环境(B6):run 起步时给每个 Socket 看一次,让它按"有哪些存储、给谁跑"决定带不带工具与规则。
788
+ * 只暴露跨请求不变或整个 run 不变的东西;每轮变化的信息(视图、预算)走 TurnContext。
789
+ */
790
+ interface SocketSetup {
791
+ log: EventLog;
792
+ blobs?: BlobStore;
793
+ memory?: MemoryStore;
794
+ model: ModelRef;
795
+ principal?: Principal;
796
+ /** 宿主自己的工具(尚未并入任何 Socket 的贡献) */
797
+ hostTools: readonly Tool[];
798
+ /**
799
+ * 到本 Socket 为止已并入的工具表(2026-09-22):宿主工具 + 注册在本 Socket **之前**的各 Socket 贡献,按同名先到者为准去重后。
800
+ * 各 Socket 按注册顺序依次解析,所以排在后面的能看见前面的,反过来不行——lazy-tools 靠它把 MCP 等 Socket 贡献的
801
+ * `lazy: true` 工具也收进菜单,前提是 `lazyTools()` 注册在 `mcpTools()` 之后。本 Socket 自己的贡献不在其中
802
+ */
803
+ tools: readonly Tool[];
804
+ }
805
+ /**
806
+ * 静态贡献:常量,或按运行环境算一次的函数(返回 undefined 表示这次不贡献)。
807
+ * 函数可以是异步的(P1):MCP 模块的工具表要在 run 起步时向服务器 `tools/list` 一次,同步解析不可能成立;
808
+ * 代价只是 `resolveSocketContributions` 变成 async,调用它的三处(循环起步、server 预校验、TanStack 适配器)本就在异步上下文里。
809
+ */
810
+ type StaticContribution<T> = T | ((setup: SocketSetup) => T | undefined | Promise<T | undefined>);
811
+ /**
812
+ * 脑子与底盘之间唯一的契约。多个 Socket 按注册顺序执行。
813
+ * 钩子可以不返回(无意见),返回值的合并规则见 runLoop 各处注释。
814
+ *
815
+ * 静态贡献与动态补丁分两条路:
816
+ * - `tools` / `systemPrompt` 是模块给整个 run 的**静态**贡献(如 compact 工具与它的规则提示)。循环起步时并进
817
+ * 工具表与系统提示,整个 run 不变 —— 满足 prompt cache 约束(系统提示与工具表每轮稳定,§9.1),
818
+ * 续跑补齐 pending 调用时也在场,并计入 configHash(恢复时能察觉模块被拆装)。
819
+ * - `beforeModel` 的补丁是**动态**改动(宿主换场景、按 principal 增删工具),每改一次缓存前缀重算,别拿它做每轮的事。
820
+ */
821
+ interface Socket {
822
+ /** 便于日志与排错 */
823
+ name?: string;
824
+ /**
825
+ * 模块带给模型的工具,整个 run 不变;与 LoopConfig.tools 同名时以后者为准。
826
+ * 可以是函数:run 起步时按运行环境算一次(如 memory 模块在没有 MemoryStore 时不注册工具,§5"缺则不注册")。
827
+ */
828
+ tools?: StaticContribution<readonly Tool[]>;
829
+ /** 模块的规则提示片段,追加在宿主系统提示之后(空行分隔),整个 run 不变;同样可以是按环境算一次的函数 */
830
+ systemPrompt?: StaticContribution<string>;
831
+ beforeModel?(ctx: TurnContext): MaybePromise<BeforeModelPatch | undefined>;
832
+ afterModel?(ctx: TurnContext, events: Event[]): MaybePromise<void>;
833
+ /**
834
+ * 任一 block / defer 即中止该调用;rewrite 替换入参后继续问下一个 Socket(后面的在 call.payload.args 里看到改写后的入参)。
835
+ * 宿主已批准(approval_decision.approved)的调用再遇到 defer 只是略过、继续问后面的 Socket:批准解决的是"要不要问人",
836
+ * 排在后面的审批策略仍可 block —— deny 不可被覆盖(§9.7)。
837
+ */
838
+ beforeTool?(ctx: TurnContext, call: ToolCallEvent, tool: Tool | undefined): MaybePromise<BeforeToolDecision | undefined>;
839
+ /** 返回新草稿即替换(如外溢后的指引),结果此时尚未 append */
840
+ afterTool?(ctx: TurnContext, call: ToolCallEvent, result: ToolResultDraft): MaybePromise<ToolResultDraft | undefined>;
841
+ /** 第一个给出意见的 Socket 决定;都无意见时:本轮有工具调用则继续,否则结束 */
842
+ onTurnEnd?(ctx: TurnContext): MaybePromise<TurnDecision | undefined>;
843
+ }
844
+ type PauseReason = "approval" | "budget" | "host";
845
+ type Interruption = {
846
+ kind: "approval";
847
+ toolCallId: string;
848
+ request: ApprovalRequestPayload;
849
+ call: ToolCallPayload;
850
+ } | {
851
+ kind: "client_tool";
852
+ toolCallId: string;
853
+ call: ToolCallPayload;
854
+ } | {
855
+ kind: "budget";
856
+ note: string;
857
+ } | {
858
+ kind: "host";
859
+ note: string;
860
+ } | SubagentInterruption;
861
+ /**
862
+ * 子代理即工具(§10.1,`asTool`)的暂停冒泡:工具里跑的子 run 暂停了,父 run 不落这条 tool_result(调用留作 pending),
863
+ * 而是整体暂停并把子的中断带给宿主。宿主处理子的审批时,结论带 `sessionId: childSessionId` 放进父的 `decisions` 续跑父 run,
864
+ * 父续跑补齐这条 pending 时工具再续跑子 run。子 run 任何原因的暂停(approval / budget / host)都冒泡,父的 reason 综合取最需要人的那个
865
+ */
866
+ interface SubagentInterruption {
867
+ kind: "subagent";
868
+ toolCallId: string;
869
+ call: ToolCallPayload;
870
+ childSessionId: string;
871
+ /** 子 run 的暂停原因 */
872
+ reason: PauseReason;
873
+ /** 子 run 自己的中断(可能再嵌 subagent) */
874
+ interruptions: Interruption[];
875
+ /** 子 run 的可序列化状态,给宿主看(续跑子 run 由工具凭 childSessionId 完成,不需要宿主传回) */
876
+ state: SerializedRunState;
877
+ }
878
+ /**
879
+ * 可序列化的 run 状态。只含引用,内容全部从 EventLog 重读,小到能放 URL 参数或 KV。
880
+ * 配置了密钥时 sig 为 HMAC-SHA256;恢复时先验签,再与日志对账(pending 调用的 ID 与入参摘要)。
881
+ */
882
+ interface SerializedRunState {
883
+ v: 1;
884
+ sessionId: string;
885
+ lastSeq: number;
886
+ pendingToolCallIds: string[];
887
+ /** 模型、工具集、系统提示的摘要;恢复时配置变了要能察觉 */
888
+ configHash: string;
889
+ /** pending 调用(id、名、入参)的 SHA-256;批下去的必须是当时看到的那次调用 */
890
+ pendingDigest: string;
891
+ /**
892
+ * 模型引用的摘要(D4,可选、不升 v)。与 `pendingToolsDigest` 同时在场时,续跑只比对模型与 pending 工具定义,
893
+ * 不再整体比 configHash(加减别的工具不再拒续跑);在场即进签名材料
894
+ */
895
+ modelDigest?: string;
896
+ /** pending 调用涉及的工具定义(名、描述、入参 schema)摘要,取基础工具表(D4) */
897
+ pendingToolsDigest?: string;
898
+ sig?: string;
899
+ }
900
+ /** 宿主对某次 pending 调用的审批结论;循环记成 approval_decision 事件后按它办 */
901
+ interface ApprovalDecisionInput {
902
+ toolCallId: string;
903
+ approved: boolean;
904
+ /** 谁批的:用户标识或策略 ID */
905
+ by: string;
906
+ reason?: string;
907
+ /**
908
+ * 结论针对哪个会话,缺省本会话。指向别的会话(子代理,见 `SubagentInterruption.childSessionId`)的结论本循环不校验、不记事件,
909
+ * 经 `ToolContext.decisions` 原样转发给工具
910
+ */
911
+ sessionId?: string;
912
+ }
913
+ type RunResult = {
914
+ status: "done";
915
+ sessionId: string;
916
+ lastSeq: number;
917
+ } | {
918
+ status: "paused";
919
+ sessionId: string;
920
+ lastSeq: number;
921
+ reason: PauseReason;
922
+ interruptions: Interruption[];
923
+ state: SerializedRunState;
924
+ } | {
925
+ status: "handoff";
926
+ sessionId: string;
927
+ lastSeq: number;
928
+ toSessionId: string;
929
+ } | {
930
+ status: "error";
931
+ sessionId: string;
932
+ lastSeq: number;
933
+ error: CoreEventOf<"core.error">;
934
+ };
935
+ type ErrorEventPayload = ErrorPayload;
936
+ /** `LoopConfig.pullInput` 的参数 */
937
+ interface PullInputContext {
938
+ sessionId: string;
939
+ /** 将要进行的轮次(本 run 内从 1 起):拉到的输入就给这一轮的模型看 */
940
+ turn: number;
941
+ }
942
+ interface LoopConfig {
943
+ sessionId: string;
944
+ log: EventLog;
945
+ blobs?: BlobStore;
946
+ memory?: MemoryStore;
947
+ lowering: Lowering;
948
+ model: ModelRef;
949
+ tools?: readonly Tool[];
950
+ sockets?: readonly Socket[];
951
+ systemPrompt?: string;
952
+ /**
953
+ * 本次 run 要追加的新输入:字符串 / 内容片段 → user_message;也可直接给草稿(如宿主注入 system_note),
954
+ * 或草稿数组——一次 append、按给定顺序写入,适合"背景 + 任务":`[system_note(kind: "host"), user_message]`,
955
+ * 每批只放一条 user_message(compact 只保最后一条)。片段与草稿不能混排;任一草稿不合规整批拒绝、日志不写。
956
+ * 草稿数组只给进程内宿主,HTTP 入口只收文本 / 内容片段与两种重建过的草稿(刻意不对称)。
957
+ * 缺省不追加(续跑:日志里有未完成的工具调用就先补齐,再问模型)。
958
+ */
959
+ input?: string | ContentPart[] | EventDraft | readonly EventDraft[];
960
+ /**
961
+ * run 进行中的新输入(拉,OnSet 建议 13)。循环在每次调模型前调一次——补跑 pending 的那轮与已触顶 `maxTurns` 时不调;
962
+ * 返回非空即一次 append 写入时间线,排在本轮 beforeModel 说明之前,空数组表示没有。
963
+ * 只收 `core.user_message` / `core.system_note` / `ext.*`(比 `input` 窄:拉取点上没有可回答的 pending 调用,不收 tool_result)。
964
+ * - 返回值不合规(非数组、白名单外类型、未登记的 ext.*):run 以 error 结束(`core.error` category "input"),这一批一条不写。
965
+ * - 回调抛错:记一条模型不可见的 `core.error`(category "host"),当这次没有、run 照跑(fail-open:消息还在宿主队列里)。
966
+ * - 拉完发现已中止:拉到的不写,按"本轮开始前中止"暂停。
967
+ * 宿主须在处理到写入事件时(await 完)完成认领再继续迭代,否则下一次会再拉到同一批;推荐草稿带 `provenance.ref` 记投递 id。
968
+ * 最后一次拉取到 run 结束之间来的消息不会进本 run:run 结束后宿主仍须查一次队列。回调挂住不返回 run 就挂住,超时由宿主自带。
969
+ * 每次 run 的字段:不进 `AgentDefinition`(HTTP run、asTool 子 run 不拉)。
970
+ */
971
+ pullInput?: (ctx: PullInputContext) => MaybePromise<readonly EventDraft[]>;
972
+ principal?: Principal;
973
+ projection?: {
974
+ strategies?: readonly ProjectionStrategy[];
975
+ estimate?: TokenEstimator;
976
+ reserveTokens?: number;
977
+ };
978
+ /** 缺省内置 core 注册表;有 ext.* 事件时传自己的 */
979
+ registry?: EventSchemaRegistry;
980
+ /**
981
+ * 单次 run 的轮数上限,触顶以 paused(budget) 返回。这是循环层的兜底,不是预算模块(B8 才做细粒度预算)。
982
+ * 缺省 100。
983
+ */
984
+ maxTurns?: number;
985
+ /** 宿主中止:当前请求停止后以 paused(host) 返回,已产出的内容仍入日志 */
986
+ signal?: AbortSignal;
987
+ /**
988
+ * 模型调用遇到瞬断(连接被掐、超时、过载 / 限流 / 5xx)时的有限重试,缺省最多 3 次尝试、1s 起翻倍退避。
989
+ * 只在本次尝试尚未写进任何模型输出时重试;宿主中止与配置错不重试。每次将要重试的失败记一条 core.error(模型不可见)。
990
+ * 传 { maxAttempts: 1 } 关闭。见 retry.ts。
991
+ */
992
+ retry?: RetryOptions;
993
+ /** 流式增量,只给 UI 用;日志里只有完整内容块 */
994
+ onDelta?: (delta: LoweringDelta) => void;
995
+ /** 每次请求的落点记录(有损与丢弃在此可见),供宿主告警或统计 */
996
+ onLandings?: (records: LandingRecord[], request: LoweredRequest) => void;
997
+ /** 交接后宿主重绑对话锚点(聊天窗口、频道等) */
998
+ onHandoff?: (fromSessionId: string, toSessionId: string) => MaybePromise<void>;
999
+ /**
1000
+ * 恢复:上一次 paused 返回的状态(可来自 URL 参数 / KV)。循环先校验(形状、会话、签名、配置、与日志对账),
1001
+ * 不通过抛 RunStateError 且不写日志;通过则 append run_resumed,再从"补齐 pending 调用"接上。
1002
+ * 不传也能续跑(同一 sessionId 再跑一次),只是少了这层校验。
1003
+ */
1004
+ resume?: SerializedRunState;
1005
+ /** 宿主给 pending 调用的审批结论,先记成 approval_decision 再执行;指向非 pending 调用即拒绝 */
1006
+ decisions?: readonly ApprovalDecisionInput[];
1007
+ /** 状态签名密钥。给了就签发与校验;没给则状态不签名、恢复不验签(只适合可信环境) */
1008
+ secret?: string;
1009
+ /** 允许在模型 / 工具集 / 系统提示变了之后恢复;缺省拒绝 */
1010
+ allowConfigDrift?: boolean;
1011
+ /**
1012
+ * 工具表与上一次 run 相比有增删时,是否追加一条模型可见的 `system_note(kind=host)` 列出增删的工具名(P1,缺省开)。
1013
+ * 关掉只是不出说明;每次 run 起步那条模型不可见的 `core.tools_bound` 快照照样记,回放与 eval 靠它知道当时有哪些工具。
1014
+ */
1015
+ announceToolChanges?: boolean;
1016
+ /** 测试注入:时间与 id 工厂 */
1017
+ now?: () => number;
1018
+ newId?: (at: number) => string;
1019
+ }
1020
+
1021
+ /**
1022
+ * 内置事件类型 core.*(技术方案 §4 表)。
1023
+ *
1024
+ * 每种事件的载荷单独成 interface,命名 `<Type>Payload`,便于 schema 升级时按 type 逐个演进。
1025
+ * 版本约定(旧稿 §8,第一版即执行):
1026
+ * - 只追加可选字段 → 不升版本
1027
+ * - 改字段语义、删字段、改必填 → 升版本,并在注册表登记 upcast 函数
1028
+ * 当前全部为 v1,见 ./registry.ts 的 CORE_SCHEMAS。
1029
+ */
1030
+
1031
+ /** 用户说话。中途插话不需要特殊机制,再 append 一条即可。 */
1032
+ interface UserMessagePayload {
1033
+ content: ContentPart[];
1034
+ }
1035
+ /** 模型正文。流式增量在降级层聚合,日志里只存完整的一段。 */
1036
+ interface ModelTextPayload {
1037
+ text: string;
1038
+ }
1039
+ /** 模型思考。文本可空(加密 reasoning 只有 replay);签名等回放数据放 EventBase.replay。 */
1040
+ interface ModelThinkingPayload {
1041
+ text: string;
1042
+ }
1043
+ interface ToolCallPayload {
1044
+ toolCallId: string;
1045
+ name: string;
1046
+ /** 模型给的原始入参(已解析为 JSON 值);校验在工具执行前做,事件里存原样 */
1047
+ args: unknown;
1048
+ /**
1049
+ * 降级层附带的读侧记录,**不进模型上下文**。目前只有 `argumentsUnwrapped: true`:模型把整个入参二次编码成了
1050
+ * JSON 文本,降级层多解了一层(core/lowering/tool-arguments.ts)。可选字段,不升版本。
1051
+ */
1052
+ meta?: Record<string, unknown>;
1053
+ }
1054
+ interface ToolResultPayload {
1055
+ toolCallId: string;
1056
+ /** 冗余存一份工具名,回放时不必反查 tool_call */
1057
+ name: string;
1058
+ content: ContentPart[];
1059
+ isError: boolean;
1060
+ /** 结果外溢到 BlobStore 时填写;此时 content 只留给模型的取回指引 */
1061
+ spilled?: {
1062
+ blobId: string;
1063
+ summary: string;
1064
+ };
1065
+ }
1066
+ /**
1067
+ * 这次工具调用**已经开始动手**(2026-11-05,停止语义与中断不重放),模型不可见。循环在两种时候写:
1068
+ * - 不可重放的工具(`isReplayable(tool)` 为假,缺省即没声明 `risk: "low"` 的写工具)在 `execute` 之前写;
1069
+ * - 任何工具返回 `subagentPause` 之后补写(子代理已经动过手了)。
1070
+ * 有它、没有 tool_result 的调用,续跑时不可重放的落"结果未知"、不再执行;停止时按它分辨"没执行"与"做了一半"。
1071
+ */
1072
+ interface ToolStartedPayload {
1073
+ toolCallId: string;
1074
+ }
1075
+ /**
1076
+ * 脑子/宿主注入给模型看的说明。"模型可见 ⟺ 已记录",所以感知、钉住提示、预算提醒都是事件。
1077
+ * 降级时按模型族落到中途 system 或 user 角色(S1 结论),两种落点都在有损矩阵声明。
1078
+ */
1079
+ interface SystemNotePayload {
1080
+ kind: "perception" | "pin" | "budget" | "host";
1081
+ text: string;
1082
+ /**
1083
+ * 注入者附带的结构化数据(如感知的各档位读数),**不进模型上下文**:降级层只翻译 text。
1084
+ * 给回放界面与 eval 用,免得从文本里反解。可选字段,不升版本。
1085
+ */
1086
+ meta?: Record<string, unknown>;
1087
+ /**
1088
+ * 本条说明**取代**的旧说明 id(B3)。被取代的 pin 在折叠 / 裁剪时不再自动幸存,也不再因出现在
1089
+ * 旧 compaction 的 pinsKept 里而幸存 —— 这是 append-only 日志里"撤销一条钉住"的唯一表达。
1090
+ * 折叠之前它照常可见(未折叠的历史原样展示)。可选字段,不升版本。
1091
+ */
1092
+ supersedes?: string[];
1093
+ /**
1094
+ * 注入者声明这是要模型**去做**的指令(如 compact 的整理请求,OPT-261031-1),不是陈述。降级层据此选送达方式:
1095
+ * 有的上游收下中途 system 却不执行其中的指令(踩坑 42),指令类说明一律以带标签的 user 文本送达,陈述类(感知、钉住)不受影响。
1096
+ * 角色仍只由降级层决定(宪法二),这里只写语义。写进日志即定格:历史说明的送达方式不随升级变化,缓存前缀稳定。可选字段,不升版本。
1097
+ */
1098
+ directive?: true;
1099
+ }
1100
+ interface ApprovalRequestPayload {
1101
+ toolCallId: string;
1102
+ policyId: string;
1103
+ /** 给审批人看的一句话摘要 */
1104
+ summary: string;
1105
+ }
1106
+ interface ApprovalDecisionPayload {
1107
+ toolCallId: string;
1108
+ approved: boolean;
1109
+ /** 谁批的:用户标识、策略 ID 或 "auto" */
1110
+ by: string;
1111
+ reason?: string;
1112
+ }
1113
+ /**
1114
+ * 压缩不删原事件,只追加这一条:投影层看到它就用 summary 替代 coversSeq 范围内的事件。
1115
+ * decidedBy 记"谁定的时机":
1116
+ * - `model`:模型自己挑的时机(默认路径,P1);
1117
+ * - `forced`:用量过了软线、框架请它整理后模型照做的——时机是框架定的,摘要仍是模型写的(OPT-261030-3);
1118
+ * - `threshold`:模型没整理、过了触发线,投影链机械裁剪。
1119
+ * 新增取值不升 schemaVersion:注册表不校验载荷,旧日志照读。
1120
+ */
1121
+ interface CompactionPayload {
1122
+ /** 闭区间 [from, to],按 seq */
1123
+ coversSeq: [number, number];
1124
+ summary: string;
1125
+ decidedBy: "model" | "forced" | "threshold";
1126
+ /** 折叠后仍需重注入的钉住事件 id */
1127
+ pinsKept: string[];
1128
+ }
1129
+ interface HandoffPayload {
1130
+ toSessionId: string;
1131
+ summary: string;
1132
+ /** 触发交接的那条用户消息文本,新会话据此续做 */
1133
+ triggerMessage?: string;
1134
+ reason: string;
1135
+ }
1136
+ /**
1137
+ * 模型读写记忆留痕。op 与 Anthropic memory_20250818 工具的 command 同名。
1138
+ * 只在操作成功时记录(失败的尝试已由 tool_call 入参 + tool_result(isError) 留痕)。
1139
+ */
1140
+ interface MemoryOpPayload {
1141
+ op: "view" | "create" | "str_replace" | "insert" | "delete" | "rename";
1142
+ /** 模型可见形态的路径(/memories/...),rename 时是源路径 */
1143
+ path: string;
1144
+ /** rename 的目标路径(B6 新增可选字段,不升版本) */
1145
+ toPath?: string;
1146
+ /** 涉及的 UTF-8 字节数:view 是读到的、写类是写后的大小、delete / rename 是涉及的文件总量;目录列表不记 */
1147
+ bytes?: number;
1148
+ }
1149
+ /**
1150
+ * 一次模型请求的用量。字段语义跟随 Anthropic:`input` 是未命中缓存的输入 token,缓存读 / 写另计,
1151
+ * 所以"这次请求的上下文有多大"= input + cacheRead + cacheWrite(见 contextTokensOf),不是 input 本身。
1152
+ */
1153
+ interface TokenUsage {
1154
+ input: number;
1155
+ output: number;
1156
+ cacheRead?: number;
1157
+ cacheWrite?: number;
1158
+ }
1159
+ /** 该请求实际送进模型的上下文大小:未命中 + 缓存读 + 缓存写 */
1160
+ declare function contextTokensOf(usage: TokenUsage): number;
1161
+ /**
1162
+ * 估算与真实之间的固定开销(B8):上一次请求的真实上下文 − 当时的投影估算。
1163
+ *
1164
+ * 投影只数模型可见事件的正文,系统提示、工具表、thinking 签名块等都不在内,真实 input 可高出一倍。
1165
+ * 这些多出来的部分在一个 run 里基本是常量(系统提示与工具表整轮不变),所以用**加法**校准而不是比例:
1166
+ * 比例会随历史变长把误差放大,加法只补那块固定的开销。
1167
+ * 数据来自日志最后一条同时带 tokens 与 contextEstimate 的 budget_usage;没有可对照的请求时为 0,不为负。
1168
+ * 那条记录算出非有限值(宿主 / 适配器写进 NaN、Infinity)也回 0:日志里一条坏用量不该让 project() 的开销校验
1169
+ * 在 run 起步就抛错,退化成"不校准"即可。
1170
+ *
1171
+ * 阈值兜底(投影)与感知读数**必须**都调这一个函数:两处口径一分叉,模型被告知"到 85% 自动折叠"就不成立。
1172
+ */
1173
+ declare function contextOverheadOf(timeline: readonly Event[]): number;
1174
+ /**
1175
+ * 用量是事件,宿主可按会话或用户聚合出配额(库不做配额)。
1176
+ * `contextEstimate`(B8):这次请求投影的估算 token(= 当轮 TurnContext.budget.used),与真实用量放在同一条事件里,
1177
+ * 感知模块用"真实上下文 − 估算"得到系统提示、工具表、thinking 等估算不含的固定开销,校准下一轮的使用率读数。
1178
+ * `remaining` 预留给宿主 / 适配器自己追加的聚合用量;循环不填(上限属于 brain budget 模块,循环不知道)。
1179
+ */
1180
+ interface BudgetUsagePayload {
1181
+ tokens: TokenUsage;
1182
+ toolCalls: number;
1183
+ wallMs: number;
1184
+ contextEstimate?: number;
1185
+ remaining?: {
1186
+ tokens?: number;
1187
+ toolCalls?: number;
1188
+ wallMs?: number;
1189
+ };
1190
+ }
1191
+ interface RunPausedPayload {
1192
+ reason: "approval" | "budget" | "host";
1193
+ /** 序列化 run 状态的外部引用(宿主 KV 键、URL 参数等),可选 */
1194
+ stateRef?: string;
1195
+ /**
1196
+ * 暂停那一刻签好的可续跑状态,与 `RunResult.state` 是同一份(AdRate 建议 8)。模型不可见(投影过滤 run_paused)。
1197
+ * 补发结束时若这条事件就是会话末尾,server 在 end 帧带出它,关页 / 换设备回来也能续跑;判据只走 `pausedStateOf`。
1198
+ * 配置摘要反映暂停那一刻,绝不在读取时重算(否则暂停后改过的工具也会被签成一致)。TanStack 适配器写的 run_paused 不带
1199
+ */
1200
+ state?: SerializedRunState;
1201
+ }
1202
+ interface RunResumedPayload {
1203
+ stateRef?: string;
1204
+ by?: string;
1205
+ }
1206
+ /**
1207
+ * 每次 run 起步时的工具表快照(P1,模型不可见)。宪法二:日志里要能看出"那次 run 模型手里有哪些工具",
1208
+ * 而不是从 tool_call 反推;也是"工具表变化告知模型"的比对依据 —— 与上一条 tools_bound 比对有增删,
1209
+ * 循环就再追加一条模型可见的 system_note(kind=host)。MCP 服务器加减工具、宿主按请求换配置,都从这里被看见。
1210
+ */
1211
+ interface ToolsBoundPayload {
1212
+ /** 本次 run 模型可用的全部工具名(宿主工具 + 各 Socket 的静态贡献),已排序 */
1213
+ toolNames: string[];
1214
+ /** 与 SerializedRunState.configHash 同一算法(模型、工具名集合、系统提示) */
1215
+ configHash: string;
1216
+ }
1217
+ interface ErrorPayload {
1218
+ /** 粗分类:provider / tool / budget / internal 等,字符串开放给宿主扩展 */
1219
+ category: string;
1220
+ message: string;
1221
+ retryable: boolean;
1222
+ detail?: Record<string, unknown>;
1223
+ }
1224
+ /** type 字面量 → 载荷。新增内置事件只需在此加一行并在注册表登记。 */
1225
+ interface CoreEventPayloads {
1226
+ "core.user_message": UserMessagePayload;
1227
+ "core.model_text": ModelTextPayload;
1228
+ "core.model_thinking": ModelThinkingPayload;
1229
+ "core.tool_call": ToolCallPayload;
1230
+ "core.tool_result": ToolResultPayload;
1231
+ "core.tool_started": ToolStartedPayload;
1232
+ "core.system_note": SystemNotePayload;
1233
+ "core.approval_request": ApprovalRequestPayload;
1234
+ "core.approval_decision": ApprovalDecisionPayload;
1235
+ "core.compaction": CompactionPayload;
1236
+ "core.handoff": HandoffPayload;
1237
+ "core.memory_op": MemoryOpPayload;
1238
+ "core.budget_usage": BudgetUsagePayload;
1239
+ "core.run_paused": RunPausedPayload;
1240
+ "core.run_resumed": RunResumedPayload;
1241
+ "core.tools_bound": ToolsBoundPayload;
1242
+ "core.error": ErrorPayload;
1243
+ }
1244
+ type CoreEventType = keyof CoreEventPayloads;
1245
+ /** 按 type 取出对应事件类型,如 CoreEventOf<"core.tool_call"> */
1246
+ type CoreEventOf<T extends CoreEventType> = Event<T, CoreEventPayloads[T]>;
1247
+ /** 全部内置事件的可判别联合,switch (e.type) 即可收窄 payload */
1248
+ type CoreEvent = {
1249
+ [T in CoreEventType]: CoreEventOf<T>;
1250
+ }[CoreEventType];
1251
+ /** 宿主扩展事件:type 必须以 "ext." 开头,载荷由宿主在注册表登记 */
1252
+ type ExtEvent = Event<`ext.${string}`, unknown>;
1253
+ /** 日志里可能出现的任何事件 */
1254
+ type AnyEvent = CoreEvent | ExtEvent;
1255
+
1256
+ export { type EventBase as $, type Actor as A, type BudgetUsagePayload as B, type ContentPart as C, type ApprovalRequestSpec as D, type Event as E, type AudioPart as F, type BeforeModelPatch as G, type BeforeToolDecision as H, type BoundModel as I, CORE_SCHEMAS as J, type CompactionPayload as K, type LoopConfig as L, type ModelRef as M, type CoreEvent as N, type CoreEventPayloads as O, type ProjectionBudget as P, type CoreEventType as Q, type RunResult as R, type SerializedRunState as S, type ToolCallEvent as T, type CreateEventInput as U, DEFAULT_RETRY_BASE_DELAY_MS as V, DEFAULT_RETRY_MAX_ATTEMPTS as W, DEFAULT_RETRY_MAX_DELAY_MS as X, DEFAULT_TRUST as Y, type ErrorEventPayload as Z, type ErrorPayload as _, type ToolResultEvent as a, isTransientFailure as a$, type EventSchema as a0, type ExtEvent as a1, type HandoffIntent as a2, type HandoffPayload as a3, type ImagePart as a4, type Interruption as a5, type LandingRecord as a6, type LandingSpec as a7, type LossKind as a8, type LossMatrix as a9, type SocketSetup as aA, type StaticContribution as aB, type SystemNotePayload as aC, type TextPart as aD, type ToRequestInput as aE, type TokenUsage as aF, type ToolBatch as aG, type ToolCallPayload as aH, type ToolContext as aI, type ToolReferencePart as aJ, type ToolResultDraft as aK, type ToolResultPayload as aL, type ToolSide as aM, type ToolStartedPayload as aN, type ToolsBoundPayload as aO, type TurnContext as aP, type TurnDecision as aQ, type Upcaster as aR, type UserMessagePayload as aS, type VideoPart as aT, backoffDelayMs as aU, contextOverheadOf as aV, contextTokensOf as aW, createCoreEvent as aX, createCoreRegistry as aY, createEvent as aZ, defaultSleep as a_, type LoweredRequest as aa, type Lowering as ab, type LoweringCapabilities as ac, type LoweringDelta as ad, type LoweringOutcome as ae, type LoweringStreamContext as af, type MaybePromise as ag, type MemoryOpPayload as ah, type ModelCallFailure as ai, type ModelTextPayload as aj, type ModelThinkingPayload as ak, type PauseReason as al, type Principal as am, type ProjectionStep as an, type ProjectionStepStats as ao, type Provenance as ap, type PullInputContext as aq, type ResolvedRetry as ar, type RetryOptions as as, type RunPausedPayload as at, type RunResumedPayload as au, SchemaError as av, type SchemaErrorCode as aw, type SessionInfo as ax, type SkillSource as ay, type Socket as az, type EventLog as b, lossesOf as b0, renderToolReference as b1, resolveRetry as b2, statusFromMessage as b3, type EventDraft as c, type Tool as d, type SubagentInterruption as e, type ToolSpec as f, type ToolResult as g, type Trust as h, type CoreEventOf as i, type CoreEventDraft as j, type ProjectionStrategy as k, type ProjectionContext as l, type TokenEstimator as m, EventSchemaRegistry as n, type ProjectionResult as o, type ProjectionStats as p, type BlobStore as q, type BlobMeta as r, type ReadOptions as s, type MemoryStore as t, type RunLease as u, type Stores as v, type AnyEvent as w, type ApprovalDecisionInput as x, type ApprovalDecisionPayload as y, type ApprovalRequestPayload as z };