@reinsjs/core 0.1.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,1095 @@
1
+ import { E as EventLog, a as Event, b as EventSchemaRegistry, B as BlobStore, M as MemoryStore, c as EventDraft, T as TokenUsage, C as ContentPart, d as Trust, L as Lowering, e as ModelRef, f as LoweringCapabilities, g as CoreEventOf, h as ToolResultPayload, i as LoweringDelta, j as LandingRecord, k as LoweredRequest, l as ErrorPayload, A as ApprovalRequestPayload, m as ToolCallPayload, n as ToolSpec, o as CoreEventDraft, p as BudgetUsagePayload, q as BlobMeta, R as ReadOptions, S as Stores } from './types-BeGSiC1e.js';
2
+ export { r as Actor, s as AnyEvent, t as ApprovalDecisionPayload, u as BoundModel, v as CORE_SCHEMAS, w as CompactionPayload, x as CoreEvent, y as CoreEventPayloads, z as CoreEventType, D as CreateEventInput, F as DEFAULT_TRUST, G as EventBase, H as EventSchema, I as ExtEvent, J as HandoffPayload, K as ImagePart, N as LandingSpec, O as LossKind, P as LossMatrix, Q as LoweringOutcome, U as LoweringStreamContext, V as MemoryOpPayload, W as ModelTextPayload, X as ModelThinkingPayload, Y as Provenance, Z as RunPausedPayload, _ as RunResumedPayload, $ as SchemaError, a0 as SchemaErrorCode, a1 as SkillSource, a2 as SystemNotePayload, a3 as TextPart, a4 as ToRequestInput, a5 as ToolsBoundPayload, a6 as Upcaster, a7 as UserMessagePayload, a8 as contextTokensOf, a9 as createCoreEvent, aa as createCoreRegistry, ab as createEvent, ac as lossesOf } from './types-BeGSiC1e.js';
3
+
4
+ /**
5
+ * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
6
+ * 只用 Web 标准 crypto.getRandomValues,不引依赖(P5)。
7
+ *
8
+ * 同一毫秒内的多个 id 之间顺序随机 —— 会话内排序以 seq 为准,id 只需全局唯一且大致有序。
9
+ */
10
+ declare function uuidv7(now?: number): string;
11
+
12
+ interface ForkOptions {
13
+ fromSessionId: string;
14
+ /** 复制 [1, atSeq],含 */
15
+ atSeq: number;
16
+ /** 缺省 uuidv7 */
17
+ toSessionId?: string;
18
+ }
19
+ declare function forkSession(log: EventLog, opts: ForkOptions): Promise<{
20
+ toSessionId: string;
21
+ }>;
22
+
23
+ interface RetryOptions {
24
+ /** 最多尝试几次(含第一次)。缺省 3;1 = 不重试 */
25
+ maxAttempts?: number;
26
+ /** 首次重试前等多久(毫秒),之后每次翻倍。缺省 1000 */
27
+ baseDelayMs?: number;
28
+ /** 单次等待上限(毫秒)。缺省 8000 */
29
+ maxDelayMs?: number;
30
+ /** 覆盖瞬断判定:返回 true 表示值得重试。缺省见 isTransientFailure */
31
+ isTransient?: (failure: ModelCallFailure) => boolean;
32
+ /** 测试注入:等待实现。缺省 setTimeout,且被 signal 中止时提前结束 */
33
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
34
+ }
35
+ /** 一次模型调用失败的两种形态:降级层抛了异常,或流正常收尾但 stopReason = error */
36
+ type ModelCallFailure = {
37
+ kind: "thrown";
38
+ error: unknown;
39
+ } | {
40
+ kind: "outcome";
41
+ message: string;
42
+ };
43
+ declare const DEFAULT_RETRY_MAX_ATTEMPTS = 3;
44
+ declare const DEFAULT_RETRY_BASE_DELAY_MS = 1000;
45
+ declare const DEFAULT_RETRY_MAX_DELAY_MS = 8000;
46
+ /**
47
+ * 从错误文案里提取 HTTP 状态码:开头的三位数字(SDK 格式 "<status> <body>"),或 "status (code) 503" / "HTTP 503" 写法。
48
+ * 只认 100~599,不在这两个位置上的数字不算(正文里提到 "429" 不是状态码)
49
+ */
50
+ declare function statusFromMessage(message: string): number | undefined;
51
+ declare function isTransientFailure(failure: ModelCallFailure): boolean;
52
+ /** 第 attempt 次失败后等多久:base × 2^(attempt−1),封顶 maxDelay。不加抖动,保证可测、可回放 */
53
+ declare function backoffDelayMs(attempt: number, opts?: Pick<RetryOptions, "baseDelayMs" | "maxDelayMs">): number;
54
+ /** 缺省等待:setTimeout;signal 中止就立刻返回(由调用方检查 aborted 再决定怎么收尾) */
55
+ declare function defaultSleep(ms: number, signal?: AbortSignal): Promise<void>;
56
+ interface ResolvedRetry {
57
+ maxAttempts: number;
58
+ delayFor: (attempt: number) => number;
59
+ isTransient: (failure: ModelCallFailure) => boolean;
60
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
61
+ }
62
+ declare function resolveRetry(opts?: RetryOptions): ResolvedRetry;
63
+
64
+ /**
65
+ * 投影(技术方案 §8):输入完整时间线,输出模型本轮应看到的事件。
66
+ *
67
+ * 投影是纯函数:同一份时间线快照、同样的参数,输出必须逐字相同。这让它可单测、可回放、
68
+ * 可在 eval 里对比不同策略。任何"随机"(事件 id)与"时间"(at)都从 ctx 注入,不在策略里 Date.now()。
69
+ *
70
+ * 策略链按顺序执行,每个策略拿到上一步的结果与不变的上下文,输出新的事件序列。
71
+ * 策略可以新造事件(如阈值兜底的 compaction),但必须通过 `emitted` 交出去由循环 append 进日志,
72
+ * 否则违反"模型可见 ⟺ 已记录"。
73
+ */
74
+
75
+ interface ProjectionBudget {
76
+ /** 模型上下文窗口上限(token) */
77
+ contextLimit: number;
78
+ /** 为模型输出与工具定义预留的 token;裁剪目标 = contextLimit - reserveTokens */
79
+ reserveTokens: number;
80
+ }
81
+ /** 估算一条事件降级后大约占多少 token。核心包不带 tokenizer,默认是粗估,宿主可注入精确实现。 */
82
+ type TokenEstimator = (event: Event) => number;
83
+ /** 策略执行时能看到的一切。全部只读;策略之间不共享可变状态。 */
84
+ interface ProjectionContext {
85
+ readonly sessionId: string;
86
+ /** 完整时间线快照,按 seq 升序。策略要回看被前序策略移除的事件时用 */
87
+ readonly timeline: readonly Event[];
88
+ readonly budget: ProjectionBudget;
89
+ readonly estimate: TokenEstimator;
90
+ /** 新造事件取 schemaVersion 用 */
91
+ readonly registry: EventSchemaRegistry;
92
+ /** 本次投影的时间戳;新造事件的 at 一律取它 */
93
+ readonly now: number;
94
+ /** 新造事件的 id 工厂;测试可注入确定值 */
95
+ readonly newId: (at: number) => string;
96
+ /** 前序策略已新造、待 append 的事件 */
97
+ readonly emitted: readonly Event[];
98
+ /** 下一条新造事件应使用的 seq:时间线末尾 + 已新造数 + 1 */
99
+ nextSeq(): number;
100
+ }
101
+ interface ProjectionStep {
102
+ /** 本策略之后模型应看到的事件序列。顺序即模型看到的顺序,不必与 seq 一致 */
103
+ events: Event[];
104
+ /**
105
+ * 本策略新造、需要由循环 append 进日志的事件。
106
+ * 必须同时出现在 events 里 —— 模型看到的每一条都要落日志。
107
+ */
108
+ emitted?: Event[];
109
+ }
110
+ interface ProjectionStrategy {
111
+ readonly name: string;
112
+ apply(events: readonly Event[], ctx: ProjectionContext): ProjectionStep;
113
+ }
114
+ interface ProjectionStepStats {
115
+ name: string;
116
+ /** 进入该策略前 / 后的事件数 */
117
+ before: number;
118
+ after: number;
119
+ }
120
+ interface ProjectionStats {
121
+ /** 最终可见事件的估算 token 总量 */
122
+ estimatedTokens: number;
123
+ /** contextLimit - reserveTokens */
124
+ targetTokens: number;
125
+ /** 裁到不能再裁仍超目标:只剩最后一轮也放不下,需要 spill 或更大的窗口。循环层据此告警 */
126
+ overBudget: boolean;
127
+ steps: ProjectionStepStats[];
128
+ }
129
+ interface ProjectionResult {
130
+ /** 模型本轮看到的事件 */
131
+ events: Event[];
132
+ /**
133
+ * 投影新造、循环必须 append 进日志的事件,seq 已按时间线末尾预分配。
134
+ * append 时 seq 冲突**不重跑投影**,`StoreError("seq_conflict")` 原样抛给宿主(R4,DECISIONS 2026-09-10):
135
+ * run 进行中还有人往同一会话追加,是会话级并发违规(server 用 409 一会话一 run 挡它),静默重跑只会把并发写入藏起来
136
+ */
137
+ emitted: Event[];
138
+ stats: ProjectionStats;
139
+ }
140
+
141
+ /**
142
+ * 循环与插座的类型(技术方案 §6、§7、§10)。
143
+ *
144
+ * 三组契约:
145
+ * - Tool:宿主给模型的能力(§10 四个正交维度);循环只用 name / inputSchema / execute / needsApproval 等少数字段,
146
+ * 其余维度(lazy、resultPolicy、ui…)留给脑子模块与后续期次消费,先把形状定下来。
147
+ * - Socket:脑子与底盘之间唯一的契约,五个钩子。脑子只依赖它,不依赖 runLoop 的实现(P3、P4)。
148
+ * - RunResult / SerializedRunState:暂停是显式返回值,状态小到能放 URL 参数(P6)。
149
+ */
150
+
151
+ /** 主事人:本次 run 代表谁。库只透传给钩子与工具,不解释其字段 */
152
+ interface Principal {
153
+ id: string;
154
+ [key: string]: unknown;
155
+ }
156
+ interface SessionInfo {
157
+ id: string;
158
+ /** 本次 run 内的第几轮(从 1 起) */
159
+ turn: number;
160
+ }
161
+ type ToolSide = "server" | "client" | "sandbox" | "provider";
162
+ /** 工具执行结果的规范形态;execute 可以返回任何值,循环用 normalizeToolOutput 归一 */
163
+ interface ToolResult {
164
+ content: ContentPart[];
165
+ isError?: boolean;
166
+ }
167
+ interface ToolContext {
168
+ sessionId: string;
169
+ toolCallId: string;
170
+ principal?: Principal;
171
+ log: EventLog;
172
+ blobs?: BlobStore;
173
+ memory?: MemoryStore;
174
+ signal?: AbortSignal;
175
+ /** 工具想留痕(如 memory_op):草稿由循环补齐后、在 tool_result 之前 append */
176
+ emit(draft: EventDraft): void;
177
+ /**
178
+ * 宿主本次续跑给**别的会话**(子代理)的审批结论(`ApprovalDecisionInput.sessionId` 指向非本会话的那些),循环不校验、不记事件,
179
+ * 原样转发;`asTool` 把它们交给子 run,多层嵌套逐层下传。没有就缺省(§10.1)
180
+ */
181
+ decisions?: readonly ApprovalDecisionInput[];
182
+ /**
183
+ * 把工具代跑的模型用量(子代理的 run)计入本 run 的预算:只加 `TurnContext.budget.tokensSpent`,父的 budget 模块按总账拦。
184
+ * 不追加父的 budget_usage 事件(那条是感知校准上下文大小的依据)。宿主循环提供;没提供的环境里工具只把用量写进结果
185
+ */
186
+ spend?(usage: TokenUsage): void;
187
+ }
188
+ /**
189
+ * 工具。execute / validate 用"方法签名"而非属性函数:TS 对方法参数做双变检查,
190
+ * 这样 Tool<{ path: string }> 才能放进 Tool[](即 Tool<unknown>[])里。
191
+ * needsApproval 是 boolean | 函数 的联合,无法写成方法,带类型入参的工具请用 defineTool() 定义。
192
+ */
193
+ interface Tool<TInput = unknown> {
194
+ name: string;
195
+ description: string;
196
+ /** JSON Schema 对象,原样交给模型;不绑任何校验库 */
197
+ inputSchema: Record<string, unknown>;
198
+ /** 可选的入参校验/转换:返回规范化入参,抛错即视为入参不合法(结果以 isError 告知模型) */
199
+ validate?(input: unknown): TInput;
200
+ /** 执行位置;缺省 server。client 表示由宿主前端执行,循环遇到即暂停等结果 */
201
+ side?: ToolSide;
202
+ /** 缺省表示本循环不执行(转客户端) */
203
+ execute?(input: TInput, ctx: ToolContext): Promise<unknown> | unknown;
204
+ /** 把 execute 的返回值翻译成模型看到的内容片段;缺省规则见 normalizeToolOutput */
205
+ toModelOutput?(output: unknown): ContentPart[];
206
+ /** 结果处置:超限截断或外溢(B4 消费) */
207
+ resultPolicy?: {
208
+ maxTokens?: number;
209
+ overflow: "truncate" | "spill";
210
+ };
211
+ /** 执行前是否要人审批。循环内置兜底:为真且没有任何 Socket 做主时,直接转审批暂停(安全默认值) */
212
+ needsApproval?: boolean | ((input: TInput, ctx: ToolContext) => Promise<boolean> | boolean);
213
+ risk?: "low" | "medium" | "high";
214
+ /**
215
+ * 这个工具**成功**结果事件(tool_result)的 trust;缺省 `DEFAULT_TRUST.tool`(untrusted:翻译给模型时包 `<untrusted>` 标记)。
216
+ * 只有输出等同宿主配置的工具才声明 `"system"`——如 brain 的 `skill_read`(技能是宿主写的说明书,视同系统提示)。
217
+ * 刻意只开 system / untrusted 两档:principal 是用户本人的权威、model 是模型自己的话,工具输出冒充哪一个都不对。
218
+ * 落法只有一份纯函数 `toolResultTrust(tool, isError)`:循环(执行结果、宿主回填的客户端工具结果)与 TanStack 适配器
219
+ * (afterToolCall、toolPhaseComplete)都调它;isError 结果、未知工具、入参不合法、执行抛错一律缺省。
220
+ */
221
+ resultTrust?: Extract<Trust, "system" | "untrusted">;
222
+ /** 暴露策略:延迟加载/发现(后续期次) */
223
+ lazy?: boolean;
224
+ allowedCallers?: ("direct" | "code")[];
225
+ /** MCP Apps 形态(第三期) */
226
+ ui?: {
227
+ resourceUri: string;
228
+ };
229
+ }
230
+ type ToolCallEvent = CoreEventOf<"core.tool_call">;
231
+ type ToolResultDraft = EventDraft<"core.tool_result", ToolResultPayload>;
232
+ /** beforeModel 的返回:改投影、增删工具、换系统提示;缺省字段表示不改 */
233
+ interface BeforeModelPatch {
234
+ events?: Event[];
235
+ tools?: Tool[];
236
+ systemPrompt?: string;
237
+ }
238
+ /** 审批请求的规格;toolCallId 由循环填 */
239
+ interface ApprovalRequestSpec {
240
+ policyId: string;
241
+ summary: string;
242
+ }
243
+ type BeforeToolDecision = "proceed" | {
244
+ block: string;
245
+ } | {
246
+ defer: ApprovalRequestSpec;
247
+ } | {
248
+ rewrite: unknown;
249
+ };
250
+ interface HandoffIntent {
251
+ /** 缺省由循环生成 */
252
+ toSessionId?: string;
253
+ summary: string;
254
+ /** 触发交接的那条用户消息,新会话据此续做 */
255
+ triggerMessage?: string;
256
+ reason: string;
257
+ /** 谁决定交接:模型(默认,经 handoff 工具)或宿主 */
258
+ by?: "model" | "host";
259
+ /**
260
+ * 新会话开头额外追加的事件草稿(B5):排在摘要说明(seq 1)之后、触发消息之前,如带过去的 pin。
261
+ * 循环只补齐 id / seq / at / sessionId,不解释内容。
262
+ */
263
+ opening?: EventDraft[];
264
+ }
265
+ type TurnDecision = "continue" | "stop" | {
266
+ handoff: HandoffIntent;
267
+ } | {
268
+ pause: {
269
+ reason: "budget" | "host";
270
+ note?: string;
271
+ };
272
+ };
273
+ type MaybePromise<T> = T | Promise<T>;
274
+ interface TurnContext {
275
+ session: SessionInfo;
276
+ principal?: Principal;
277
+ /** 当前投影结果,即模型本轮将看到的事件(可读) */
278
+ events: Event[];
279
+ /** 完整时间线快照(脑子模块回看被折叠的事件时用) */
280
+ timeline: readonly Event[];
281
+ log: EventLog;
282
+ blobs?: BlobStore;
283
+ memory?: MemoryStore;
284
+ /** 本轮可用工具 */
285
+ tools: readonly Tool[];
286
+ model: ModelRef;
287
+ /** 本模型支持什么(中途 system、thinking 回放、并行工具…) */
288
+ capabilities: LoweringCapabilities;
289
+ budget: {
290
+ contextLimit: number;
291
+ /** 投影的裁剪目标 = contextLimit - reserveTokens;估算超过它库就按阈值自动折叠最旧的轮次(感知据此提醒模型) */
292
+ targetTokens: number;
293
+ /** 本轮投影的估算 token */
294
+ used: number;
295
+ /** 本次 run 累计消耗(输入 + 输出) */
296
+ tokensSpent: number;
297
+ turns: number;
298
+ toolCalls: number;
299
+ /** 距 run 开始的毫秒数;beforeModel 时是本轮开始的读数,模型调用后更新 */
300
+ wallMs: number;
301
+ /**
302
+ * 最近一次模型请求的真实用量(B8):beforeModel 时是上一次请求的(含上次 run,从日志最后一条 budget_usage 读),
303
+ * 模型调用后即本轮的。上下文大小用 contextTokensOf(lastUsage) 算,不是 input
304
+ */
305
+ lastUsage?: TokenUsage;
306
+ };
307
+ signal?: AbortSignal;
308
+ /** 草稿:无 id / seq / at / sessionId,循环补齐后 append。beforeModel 期间 emit 的本轮即可见 */
309
+ emit(draft: EventDraft): void;
310
+ }
311
+ /**
312
+ * 静态贡献的运行环境(B6):run 起步时给每个 Socket 看一次,让它按"有哪些存储、给谁跑"决定带不带工具与规则。
313
+ * 只暴露跨请求不变或整个 run 不变的东西;每轮变化的信息(视图、预算)走 TurnContext。
314
+ */
315
+ interface SocketSetup {
316
+ log: EventLog;
317
+ blobs?: BlobStore;
318
+ memory?: MemoryStore;
319
+ model: ModelRef;
320
+ principal?: Principal;
321
+ /** 宿主自己的工具(尚未并入任何 Socket 的贡献) */
322
+ hostTools: readonly Tool[];
323
+ }
324
+ /**
325
+ * 静态贡献:常量,或按运行环境算一次的函数(返回 undefined 表示这次不贡献)。
326
+ * 函数可以是异步的(P1):MCP 模块的工具表要在 run 起步时向服务器 `tools/list` 一次,同步解析不可能成立;
327
+ * 代价只是 `resolveSocketContributions` 变成 async,调用它的三处(循环起步、server 预校验、TanStack 适配器)本就在异步上下文里。
328
+ */
329
+ type StaticContribution<T> = T | ((setup: SocketSetup) => T | undefined | Promise<T | undefined>);
330
+ /**
331
+ * 脑子与底盘之间唯一的契约。多个 Socket 按注册顺序执行。
332
+ * 钩子可以不返回(无意见),返回值的合并规则见 runLoop 各处注释。
333
+ *
334
+ * 静态贡献与动态补丁分两条路:
335
+ * - `tools` / `systemPrompt` 是模块给整个 run 的**静态**贡献(如 compact 工具与它的规则提示)。循环起步时并进
336
+ * 工具表与系统提示,整个 run 不变 —— 满足 prompt cache 约束(系统提示与工具表每轮稳定,§9.1),
337
+ * 续跑补齐 pending 调用时也在场,并计入 configHash(恢复时能察觉模块被拆装)。
338
+ * - `beforeModel` 的补丁是**动态**改动(宿主换场景、按 principal 增删工具),每改一次缓存前缀重算,别拿它做每轮的事。
339
+ */
340
+ interface Socket {
341
+ /** 便于日志与排错 */
342
+ name?: string;
343
+ /**
344
+ * 模块带给模型的工具,整个 run 不变;与 LoopConfig.tools 同名时以后者为准。
345
+ * 可以是函数:run 起步时按运行环境算一次(如 memory 模块在没有 MemoryStore 时不注册工具,§5"缺则不注册")。
346
+ */
347
+ tools?: StaticContribution<readonly Tool[]>;
348
+ /** 模块的规则提示片段,追加在宿主系统提示之后(空行分隔),整个 run 不变;同样可以是按环境算一次的函数 */
349
+ systemPrompt?: StaticContribution<string>;
350
+ beforeModel?(ctx: TurnContext): MaybePromise<BeforeModelPatch | undefined>;
351
+ afterModel?(ctx: TurnContext, events: Event[]): MaybePromise<void>;
352
+ /**
353
+ * 任一 block / defer 即中止该调用;rewrite 替换入参后继续问下一个 Socket(后面的在 call.payload.args 里看到改写后的入参)。
354
+ * 宿主已批准(approval_decision.approved)的调用再遇到 defer 只是略过、继续问后面的 Socket:批准解决的是"要不要问人",
355
+ * 排在后面的审批策略仍可 block —— deny 不可被覆盖(§9.7)。
356
+ */
357
+ beforeTool?(ctx: TurnContext, call: ToolCallEvent, tool: Tool | undefined): MaybePromise<BeforeToolDecision | undefined>;
358
+ /** 返回新草稿即替换(如外溢后的指引),结果此时尚未 append */
359
+ afterTool?(ctx: TurnContext, call: ToolCallEvent, result: ToolResultDraft): MaybePromise<ToolResultDraft | undefined>;
360
+ /** 第一个给出意见的 Socket 决定;都无意见时:本轮有工具调用则继续,否则结束 */
361
+ onTurnEnd?(ctx: TurnContext): MaybePromise<TurnDecision | undefined>;
362
+ }
363
+ type PauseReason = "approval" | "budget" | "host";
364
+ type Interruption = {
365
+ kind: "approval";
366
+ toolCallId: string;
367
+ request: ApprovalRequestPayload;
368
+ call: ToolCallPayload;
369
+ } | {
370
+ kind: "client_tool";
371
+ toolCallId: string;
372
+ call: ToolCallPayload;
373
+ } | {
374
+ kind: "budget";
375
+ note: string;
376
+ } | {
377
+ kind: "host";
378
+ note: string;
379
+ } | SubagentInterruption;
380
+ /**
381
+ * 子代理即工具(§10.1,`asTool`)的暂停冒泡:工具里跑的子 run 暂停了,父 run 不落这条 tool_result(调用留作 pending),
382
+ * 而是整体暂停并把子的中断带给宿主。宿主处理子的审批时,结论带 `sessionId: childSessionId` 放进父的 `decisions` 续跑父 run,
383
+ * 父续跑补齐这条 pending 时工具再续跑子 run。子 run 任何原因的暂停(approval / budget / host)都冒泡,父的 reason 综合取最需要人的那个
384
+ */
385
+ interface SubagentInterruption {
386
+ kind: "subagent";
387
+ toolCallId: string;
388
+ call: ToolCallPayload;
389
+ childSessionId: string;
390
+ /** 子 run 的暂停原因 */
391
+ reason: PauseReason;
392
+ /** 子 run 自己的中断(可能再嵌 subagent) */
393
+ interruptions: Interruption[];
394
+ /** 子 run 的可序列化状态,给宿主看(续跑子 run 由工具凭 childSessionId 完成,不需要宿主传回) */
395
+ state: SerializedRunState;
396
+ }
397
+ /**
398
+ * 可序列化的 run 状态。只含引用,内容全部从 EventLog 重读,小到能放 URL 参数或 KV。
399
+ * 配置了密钥时 sig 为 HMAC-SHA256;恢复时先验签,再与日志对账(pending 调用的 ID 与入参摘要)。
400
+ */
401
+ interface SerializedRunState {
402
+ v: 1;
403
+ sessionId: string;
404
+ lastSeq: number;
405
+ pendingToolCallIds: string[];
406
+ /** 模型、工具集、系统提示的摘要;恢复时配置变了要能察觉 */
407
+ configHash: string;
408
+ /** pending 调用(id、名、入参)的 SHA-256;批下去的必须是当时看到的那次调用 */
409
+ pendingDigest: string;
410
+ sig?: string;
411
+ }
412
+ /** 宿主对某次 pending 调用的审批结论;循环记成 approval_decision 事件后按它办 */
413
+ interface ApprovalDecisionInput {
414
+ toolCallId: string;
415
+ approved: boolean;
416
+ /** 谁批的:用户标识或策略 ID */
417
+ by: string;
418
+ reason?: string;
419
+ /**
420
+ * 结论针对哪个会话,缺省本会话。指向别的会话(子代理,见 `SubagentInterruption.childSessionId`)的结论本循环不校验、不记事件,
421
+ * 经 `ToolContext.decisions` 原样转发给工具
422
+ */
423
+ sessionId?: string;
424
+ }
425
+ type RunResult = {
426
+ status: "done";
427
+ sessionId: string;
428
+ lastSeq: number;
429
+ } | {
430
+ status: "paused";
431
+ sessionId: string;
432
+ lastSeq: number;
433
+ reason: PauseReason;
434
+ interruptions: Interruption[];
435
+ state: SerializedRunState;
436
+ } | {
437
+ status: "handoff";
438
+ sessionId: string;
439
+ lastSeq: number;
440
+ toSessionId: string;
441
+ } | {
442
+ status: "error";
443
+ sessionId: string;
444
+ lastSeq: number;
445
+ error: CoreEventOf<"core.error">;
446
+ };
447
+ type ErrorEventPayload = ErrorPayload;
448
+ interface LoopConfig {
449
+ sessionId: string;
450
+ log: EventLog;
451
+ blobs?: BlobStore;
452
+ memory?: MemoryStore;
453
+ lowering: Lowering;
454
+ model: ModelRef;
455
+ tools?: readonly Tool[];
456
+ sockets?: readonly Socket[];
457
+ systemPrompt?: string;
458
+ /**
459
+ * 本次 run 要追加的新输入:字符串 / 内容片段 → user_message;也可直接给草稿(如宿主注入 system_note)。
460
+ * 缺省不追加(续跑:日志里有未完成的工具调用就先补齐,再问模型)。
461
+ */
462
+ input?: string | ContentPart[] | EventDraft;
463
+ principal?: Principal;
464
+ projection?: {
465
+ strategies?: readonly ProjectionStrategy[];
466
+ estimate?: TokenEstimator;
467
+ reserveTokens?: number;
468
+ };
469
+ /** 缺省内置 core 注册表;有 ext.* 事件时传自己的 */
470
+ registry?: EventSchemaRegistry;
471
+ /**
472
+ * 单次 run 的轮数上限,触顶以 paused(budget) 返回。这是循环层的兜底,不是预算模块(B8 才做细粒度预算)。
473
+ * 缺省 100。
474
+ */
475
+ maxTurns?: number;
476
+ /** 宿主中止:当前请求停止后以 paused(host) 返回,已产出的内容仍入日志 */
477
+ signal?: AbortSignal;
478
+ /**
479
+ * 模型调用遇到瞬断(连接被掐、超时、过载 / 限流 / 5xx)时的有限重试,缺省最多 3 次尝试、1s 起翻倍退避。
480
+ * 只在本次尝试尚未写进任何模型输出时重试;宿主中止与配置错不重试。每次将要重试的失败记一条 core.error(模型不可见)。
481
+ * 传 { maxAttempts: 1 } 关闭。见 retry.ts。
482
+ */
483
+ retry?: RetryOptions;
484
+ /** 流式增量,只给 UI 用;日志里只有完整内容块 */
485
+ onDelta?: (delta: LoweringDelta) => void;
486
+ /** 每次请求的落点记录(有损与丢弃在此可见),供宿主告警或统计 */
487
+ onLandings?: (records: LandingRecord[], request: LoweredRequest) => void;
488
+ /** 交接后宿主重绑对话锚点(聊天窗口、频道等) */
489
+ onHandoff?: (fromSessionId: string, toSessionId: string) => MaybePromise<void>;
490
+ /**
491
+ * 恢复:上一次 paused 返回的状态(可来自 URL 参数 / KV)。循环先校验(形状、会话、签名、配置、与日志对账),
492
+ * 不通过抛 RunStateError 且不写日志;通过则 append run_resumed,再从"补齐 pending 调用"接上。
493
+ * 不传也能续跑(同一 sessionId 再跑一次),只是少了这层校验。
494
+ */
495
+ resume?: SerializedRunState;
496
+ /** 宿主给 pending 调用的审批结论,先记成 approval_decision 再执行;指向非 pending 调用即拒绝 */
497
+ decisions?: readonly ApprovalDecisionInput[];
498
+ /** 状态签名密钥。给了就签发与校验;没给则状态不签名、恢复不验签(只适合可信环境) */
499
+ secret?: string;
500
+ /** 允许在模型 / 工具集 / 系统提示变了之后恢复;缺省拒绝 */
501
+ allowConfigDrift?: boolean;
502
+ /**
503
+ * 工具表与上一次 run 相比有增删时,是否追加一条模型可见的 `system_note(kind=host)` 列出增删的工具名(P1,缺省开)。
504
+ * 关掉只是不出说明;每次 run 起步那条模型不可见的 `core.tools_bound` 快照照样记,回放与 eval 靠它知道当时有哪些工具。
505
+ */
506
+ announceToolChanges?: boolean;
507
+ /** 测试注入:时间与 id 工厂 */
508
+ now?: () => number;
509
+ newId?: (at: number) => string;
510
+ }
511
+
512
+ /**
513
+ * runLoop:reins 的默认循环(技术方案 §2、§6、§7)。
514
+ *
515
+ * 这是一个导出的普通异步生成器,没有私有状态,用户可以整个复制去改(P3)。它每一轮做的事:
516
+ *
517
+ * timeline = readTimeline(log, session, { registry }) ← 时间线是唯一真源(宪法二);读时按注册表升级(P9)
518
+ * 补齐日志里还没结果的 tool_call ← 进程死亡 / 审批恢复 / 客户端工具回填后的续跑
519
+ * view = project(timeline) ← 过滤 → 折叠 → 钉住 → 预算裁剪
520
+ * beforeModel 钩子 ← 脑子注入 system_note(感知等)、改投影、增删工具
521
+ * request = lowering.toRequest(view, tools) ← 事件 → 某家 API 请求(角色只在这里出现)
522
+ * for draft of lowering.stream(request): append ← 模型说的每一块都立刻入日志
523
+ * afterModel 钩子
524
+ * for call of toolCalls: beforeTool → execute → afterTool → append tool_result
525
+ * append budget_usage
526
+ * onTurnEnd 钩子 → continue | stop | handoff | pause
527
+ *
528
+ * 生成器 yield 的是每一条刚 append 进日志的事件(宿主拿去推给前端);返回值是 RunResult 四态之一。
529
+ * 暂停是显式返回值(P6):审批、预算、宿主中止、客户端工具都走同一条路 —— 写 run_paused、返回可序列化状态;
530
+ * 恢复就是用同一个 sessionId 再跑一次 runLoop,第一步"补齐未完成的 tool_call"会接上。
531
+ *
532
+ * 决策权在模型(宪法一):循环自己不判断"该不该继续"以外的任何事。它只在两处兜底 ——
533
+ * 工具声明 needsApproval 而没有 Socket 做主时转审批;轮数超过 maxTurns 时暂停。
534
+ */
535
+
536
+ declare const DEFAULT_MAX_TURNS = 100;
537
+ /** 循环内置的审批策略标识:工具自己声明 needsApproval 且没有 Socket 做主 */
538
+ declare const BUILTIN_APPROVAL_POLICY = "tool.needsApproval";
539
+ /**
540
+ * 宿主经 `input` 能直接追加的草稿类型:用户说话、给客户端工具回填结果、宿主说明、宿主自己的 ext.* 事件。
541
+ * 模型输出与运维事件(approval_decision、run_resumed、compaction、budget_usage…)不许从这条路进来:
542
+ * 一条伪造的 approval_decision(approved=true) 就能让 pending 调用免审批执行,伪造的 compaction 能把历史藏起来。
543
+ * 这些事件只能由循环自己按规则产生(审批结论走 `decisions`,经 T10 校验)。
544
+ */
545
+ declare const INPUT_DRAFT_TYPES: ReadonlySet<string>;
546
+ /** 把 `input` 归一成草稿;不合规的草稿在写任何日志之前就抛 RangeError(fail-closed) */
547
+ declare function inputDraft(input: NonNullable<LoopConfig["input"]>): EventDraft;
548
+ declare function runLoop(cfg: LoopConfig): AsyncGenerator<Event, RunResult>;
549
+
550
+ /**
551
+ * run 状态的序列化、签名与恢复校验(§6,T9 / T10)。
552
+ *
553
+ * 状态只含引用:会话、最后 seq、pending 工具调用 ID、配置摘要、pending 入参摘要;内容全部从 EventLog 重读。
554
+ * 签名用 Web Crypto 的 HMAC-SHA256,密钥由宿主提供;恢复时先校验签名,再把状态与日志对账 ——
555
+ * 任何一处不一致都拒绝(fail-closed),且拒绝发生在写日志之前。
556
+ */
557
+
558
+ /** 时间线里还没有 tool_result 的 tool_call,按 seq 升序。进程死亡、审批暂停、客户端工具都会留下它们 */
559
+ declare function pendingToolCalls(timeline: readonly Event[]): ToolCallEvent[];
560
+ /** 配置摘要:模型、工具名集合、系统提示。恢复时若不一致,说明"换了配置在续跑" */
561
+ declare function computeConfigHash(input: {
562
+ model: ModelRef;
563
+ tools: readonly Tool[];
564
+ systemPrompt?: string;
565
+ }): Promise<string>;
566
+ /** pending 调用的入参摘要:恢复时重算比对,保证批下去的就是当时看到的那次调用 */
567
+ declare function computePendingDigest(calls: readonly ToolCallEvent[]): Promise<string>;
568
+ declare function serializeRunState(input: {
569
+ sessionId: string;
570
+ lastSeq: number;
571
+ pending: readonly ToolCallEvent[];
572
+ configHash: string;
573
+ secret?: string;
574
+ }): Promise<SerializedRunState>;
575
+ declare function signRunState(state: SerializedRunState, secret: string): Promise<SerializedRunState>;
576
+ declare function verifyRunState(state: SerializedRunState, secret: string): Promise<boolean>;
577
+ type RunStateErrorCode = "malformed" | "session_mismatch" | "missing_signature" | "bad_signature" | "config_mismatch" | "log_behind" | "pending_mismatch" | "unknown_tool_call";
578
+ declare class RunStateError extends Error {
579
+ readonly code: RunStateErrorCode;
580
+ readonly context: Record<string, unknown>;
581
+ constructor(code: RunStateErrorCode, message: string, context?: Record<string, unknown>);
582
+ }
583
+ declare function assertRunStateShape(raw: unknown): asserts raw is SerializedRunState;
584
+ /**
585
+ * 恢复前的全部校验。顺序有讲究:先看形状与会话,再验签名(防伪造),最后与日志对账(防篡改与错连)。
586
+ * 通过后返回日志里的 pending 调用,供循环继续处理。
587
+ */
588
+ declare function validateResume(input: {
589
+ state: unknown;
590
+ sessionId: string;
591
+ timeline: readonly Event[];
592
+ configHash: string;
593
+ secret?: string;
594
+ allowConfigDrift?: boolean;
595
+ }): Promise<ToolCallEvent[]>;
596
+
597
+ /**
598
+ * Socket 静态贡献的解析(B2 引入,B6 抽出):宿主工具 + 各 Socket 带来的工具与规则提示 → 整个 run 不变的工具表与系统提示。
599
+ *
600
+ * 为什么单独成文件:configHash 就是按这里的结果算的,循环起步与 server 的恢复预校验必须用**同一份**算法,
601
+ * 否则装了带静态贡献的模块(compact / pins / spill / memory…)后,预校验会把合法的续跑当成配置漂移。
602
+ *
603
+ * 贡献可以是常量,也可以是按运行环境算一次的函数(`StaticContribution`,可异步):函数只在这里被调用一次,
604
+ * 所以 Socket 不能靠它做每轮的事 —— 每轮的改动走 beforeModel 补丁(代价是缓存前缀重算)。
605
+ */
606
+
607
+ interface ResolvedContributions {
608
+ tools: readonly Tool[];
609
+ systemPrompt?: string;
610
+ }
611
+ /** 能算出静态贡献所需的配置子集:AgentDefinition(跨请求不变)加上本次请求的 principal */
612
+ type ContributionConfig = Pick<LoopConfig, "log" | "blobs" | "memory" | "model" | "principal" | "tools" | "sockets" | "systemPrompt">;
613
+ /**
614
+ * 宿主工具 + 各 Socket 的静态工具(同名以宿主为准,宿主想覆盖模块的默认实现时用);
615
+ * 宿主系统提示在前,各 Socket 的规则片段按注册顺序追加,空行分隔;都没有则 undefined。
616
+ *
617
+ * 异步(P1):贡献函数可以 await(MCP 的 `tools/list`)。各 Socket 仍按注册顺序**依次**解析而不是并发 ——
618
+ * 同名去重以先到者为准,顺序一变 configHash 就变,续跑会被误判配置漂移。
619
+ */
620
+ declare function resolveSocketContributions(cfg: ContributionConfig): Promise<ResolvedContributions>;
621
+
622
+ /**
623
+ * 子代理即工具(§10.1)的暂停标记:`asTool` 这类工具跑的子 run 暂停时,`execute` 返回 `subagentPause(detail)` 而不是结果,
624
+ * 循环见到它不落 tool_result、把这次调用留作 pending,整个 run 以 `paused` 返回并把子的中断带给宿主(`SubagentInterruption`)。
625
+ *
626
+ * 为什么是返回值而不是抛错:暂停不是异常,抛出去会被 execute 的 catch 当成"工具执行失败"吞成 isError。
627
+ * 品牌用 `Symbol.for`:宿主里装了两份 core 也认得。
628
+ */
629
+
630
+ declare const SUBAGENT_PAUSE: unique symbol;
631
+ /** 工具要交给循环的部分:toolCallId 与 call 由循环补 */
632
+ type SubagentPauseDetail = Omit<SubagentInterruption, "kind" | "toolCallId" | "call">;
633
+ interface SubagentPause {
634
+ readonly [SUBAGENT_PAUSE]: true;
635
+ readonly detail: SubagentPauseDetail;
636
+ }
637
+ declare function subagentPause(detail: SubagentPauseDetail): SubagentPause;
638
+ declare function isSubagentPause(value: unknown): value is SubagentPause;
639
+
640
+ /**
641
+ * 工具相关的纯函数:给模型看的声明、执行结果归一化。与循环解耦,便于适配器(TanStack / pi)复用。
642
+ */
643
+
644
+ /**
645
+ * 工具结果事件该带的 trust(§14):工具声明了 `resultTrust` 且结果不是错误 → 按声明;否则 undefined(事件工厂按 actor 缺省,即 untrusted)。
646
+ * 这是唯一的判定点——循环的两条路(execute 结果、宿主回填的客户端工具结果)与 TanStack 适配器的两条路都调它,
647
+ * "同一个判定写两处必须同一个纯函数"(踩坑记录 configHash / pendingDigest / decisions 三次教训)。
648
+ */
649
+ declare function toolResultTrust(tool: Tool | undefined, isError: boolean): Trust | undefined;
650
+ /**
651
+ * 定义一个带入参类型的工具并擦成 Tool:对象字面量里 execute / validate / needsApproval 的 input 都按 TInput 推断,
652
+ * 返回值却能直接放进 Tool[]。不用它也行,只是 needsApproval 写成函数时 TS 会因参数逆变拒绝放进数组。
653
+ */
654
+ declare function defineTool<TInput>(tool: Tool<TInput>): Tool;
655
+ /** 工具声明的模型可见部分 */
656
+ declare function toolSpecOf(tool: Tool): ToolSpec;
657
+ /**
658
+ * execute 的返回值 → 模型看到的内容。规则按直觉:
659
+ * - string → 一段文本
660
+ * - ContentPart[] → 原样
661
+ * - { content, isError? } → 原样(唯一能表达"这是错误"的形态)
662
+ * - undefined / null → 空文本(工具没话说也得给模型一个结果块)
663
+ * - 其余 → JSON 文本
664
+ */
665
+ declare function normalizeToolOutput(output: unknown): ToolResult;
666
+ declare function errorMessageOf(err: unknown): string;
667
+
668
+ /**
669
+ * 工具表快照与变化说明(P1,技术方案 §10"工具表变化告知模型")。
670
+ *
671
+ * 循环每次起步 append 一条模型不可见的 `core.tools_bound`(本次 run 的工具名与 configHash);
672
+ * 与日志里上一条 tools_bound 比对,有增删就再 append 一条模型可见的 `system_note(kind=host)`。
673
+ * 宪法一"让它看见":MCP 服务器加减了工具、宿主按请求换了配置,模型该知道自己手里的东西变了,
674
+ * 而不是从一次"未知工具"的失败里猜出来。首次 run 没有比对对象,不出说明。
675
+ *
676
+ * 这里全是纯函数,runLoop 与 TanStack 适配器共用;TanStack 那边有自己的循环,同一份文案与判定才不会两处漂移。
677
+ */
678
+
679
+ type ToolsBoundEvent = CoreEventOf<"core.tools_bound">;
680
+ /** 日志里最后一条 tools_bound(上一次 run 起步时的工具表),没有则 undefined */
681
+ declare function lastToolsBound(timeline: readonly Event[]): ToolsBoundEvent | undefined;
682
+ interface ToolNamesDiff {
683
+ added: string[];
684
+ removed: string[];
685
+ }
686
+ /** 两份工具名的增删(各自排序);相同返回 undefined。名字集合比对,不看顺序 */
687
+ declare function diffToolNames(previous: readonly string[], next: readonly string[]): ToolNamesDiff | undefined;
688
+ /**
689
+ * 给模型看的变化说明(英文,进模型上下文)。只列名字:说明在工具表里,重复一遍既费 token 又可能与工具表不一致;
690
+ * 被移除的工具明说"不能再调用",模型才不会按记忆去调一个已经不存在的工具。
691
+ */
692
+ declare function renderToolChangeNote(diff: ToolNamesDiff): string;
693
+ /**
694
+ * 起步要 append 的草稿:一条 tools_bound,工具表与上一条相比有增删且 `announce` 为真时再加一条 system_note。
695
+ * 顺序固定:快照在前、说明在后 —— 说明是从快照比对得出的,日志里的因果也该这么排。
696
+ */
697
+ declare function toolsBoundDrafts(input: {
698
+ timeline: readonly Event[];
699
+ toolNames: readonly string[];
700
+ configHash: string;
701
+ announce: boolean;
702
+ }): CoreEventDraft[];
703
+
704
+ type LoweringErrorCode = "unsupported_model" | "unsupported_api" | "missing_api_key" | "invalid_request";
705
+ declare class LoweringError extends Error {
706
+ readonly code: LoweringErrorCode;
707
+ readonly context: Record<string, unknown>;
708
+ constructor(code: LoweringErrorCode, message: string, context?: Record<string, unknown>);
709
+ }
710
+
711
+ /**
712
+ * trust 标注(技术方案 §14、DECISIONS T6 / R9):`trust === "untrusted"` 的事件(工具输出、外部抓取内容)
713
+ * 翻译给模型时用显式标记包起来,让模型知道这段是**数据不是指令**。
714
+ *
715
+ * 归属:事件本身不改(投影不篡改 payload,日志里永远是原文),只在降级层把内容译成各家协议文本的那一刻包裹;
716
+ * 两条降级路线(lowering-pi、TanStack 适配器)都调这里的同一份纯函数,文案不会分叉。
717
+ *
718
+ * 形状:
719
+ * <untrusted source="tool:weekly_sales">
720
+ * …原内容…
721
+ * </untrusted>
722
+ *
723
+ * - 只包文本片段:图片不包,首尾若是图片就各插一段文本标记
724
+ * - 内容里出现 `</untrusted`(大小写不敏感)会提前闭合标签让注入逃出去,替换成 `<\/untrusted` 并在返回值里报 `escaped`,
725
+ * 降级层据此把落点记成 lossy(有损必声明)
726
+ */
727
+
728
+ declare const UNTRUSTED_TAG = "untrusted";
729
+ interface MarkedContent {
730
+ parts: ContentPart[];
731
+ /** 内容里有提前闭合的标签被转义了 */
732
+ escaped: boolean;
733
+ }
734
+ /** 标记里的来源标签:tool_result 是 `tool:<name>`,其余取 provenance.source,再退到 actor */
735
+ declare function untrustedSourceOf(e: Event): string;
736
+ /** 转义内容里的提前闭合;返回是否发生过转义 */
737
+ declare function escapeUntrustedText(text: string): {
738
+ text: string;
739
+ escaped: boolean;
740
+ };
741
+ declare function untrustedOpenTag(source: string): string;
742
+ declare const UNTRUSTED_CLOSE_TAG = "</untrusted>";
743
+ /** 纯文本版:system_note / compaction 这类以字符串落地的内容 */
744
+ declare function markUntrustedText(text: string, source: string): {
745
+ text: string;
746
+ escaped: boolean;
747
+ };
748
+ /** 片段版:首尾文本片段就地拼接标记,首尾是图片则各插一段文本;空内容给一对空标签 */
749
+ declare function markUntrusted(parts: readonly ContentPart[], source: string): MarkedContent;
750
+ /** 这条事件的内容翻译给模型时要不要包 */
751
+ declare function needsUntrustedMark(e: Event): boolean;
752
+
753
+ /**
754
+ * 默认 token 粗估。核心包零依赖,不带任何 tokenizer;这里只求量级正确、宁高勿低,
755
+ * 供预算裁剪兜底与感知档位使用。宿主要精确数字就注入自己的 TokenEstimator。
756
+ *
757
+ * 规则:ASCII 字符约 4 个一个 token;非 ASCII(中日韩等)按一字一 token 保守计;
758
+ * 图片按 Anthropic 单图上限附近取常量;每条事件再加角色与分隔的固定开销。
759
+ */
760
+
761
+ declare function estimateTextTokens(text: string): number;
762
+ declare function roughTokenEstimate(event: Event): number;
763
+ declare function estimateTotal(events: readonly Event[], estimate: (e: Event) => number): number;
764
+
765
+ /**
766
+ * 策略 1:可见性过滤。
767
+ *
768
+ * 只做"给不给模型看",不改事件内容。trust 标注(不可信内容加显式标记)不在这里做:
769
+ * 事件已带 trust 字段,降级层翻译成文本时按它包裹,这样投影不必复制事件、不篡改 payload。
770
+ */
771
+
772
+ /**
773
+ * 默认对模型不可见的运维事件。它们服务于宿主与审计,对模型没有信息量或已由别的事件承载:
774
+ * - approval_*:审批结果由 B7 以 tool_result(isError) 告知模型
775
+ * - run_paused / run_resumed / budget_usage / memory_op:运行记录,感知模块会把要点提炼进 system_note
776
+ * - handoff:交接后当前会话结束,新会话首条 user 消息承载 triggerMessage
777
+ * - error:provider 级错误由循环层处理;工具错误已在 tool_result.isError
778
+ * - tools_bound:每次 run 起步的工具表快照(P1);工具表本身在请求里,增删由循环以 system_note(kind=host) 告知模型
779
+ */
780
+ declare const DEFAULT_MODEL_INVISIBLE_TYPES: ReadonlySet<string>;
781
+ interface VisibilityFilterOptions {
782
+ /** 覆盖默认的不可见类型集合 */
783
+ invisibleTypes?: Iterable<string>;
784
+ /** 额外判定,返回 false 即不可见。宿主放 principal 可见性等规则 */
785
+ isVisible?: (event: Event) => boolean;
786
+ }
787
+ declare function visibilityFilter(opts?: VisibilityFilterOptions): ProjectionStrategy;
788
+
789
+ /**
790
+ * 策略 2:折叠。用 compaction 事件的摘要替代它覆盖的 seq 区间;被折叠的原事件仍在日志里。
791
+ *
792
+ * 规则:
793
+ * - 每条 compaction 隐藏 coversSeq 内、seq 小于自己的事件;多条 compaction 的隐藏范围取并集,
794
+ * 被更晚的 compaction 盖住的旧 compaction 也隐藏(它的摘要已被新摘要吸收),但它的覆盖范围仍然生效。
795
+ * - 幸存判定:一条被覆盖的事件,只有当**每一条**覆盖它的 compaction 都保留它时才幸存。
796
+ * 保留 = 出现在该 compaction 的 pinsKept 里,或(默认开启)它本身是 kind=pin 的 system_note。
797
+ * 模型 pin 过的东西默认穿越折叠,除非某次 compaction 明确不再保留它。
798
+ * - 取代(B3):被后来某条 system_note 的 `supersedes` 指到的事件,一旦被覆盖就不再幸存,不论谁保留过它。
799
+ * 这是 append-only 日志里撤销一条钉住的唯一表达(宿主抽取式 pin 换了内容、模型用新 pin 替换旧 pin)。
800
+ * 取代者在完整时间线里找,不只在视图里:取代者自己也可能已被折叠。
801
+ * - 摘要放在被覆盖区间的位置(第一条 seq 大于区间上界的可见事件之前),而不是 compaction 自己的 seq 位置。
802
+ * 模型多数时候折叠的是"直到现在"的前缀,两者重合;折叠旧的中间段时,摘要出现在原段的位置读起来才顺。
803
+ * 所以投影输出的顺序可以与 seq 不一致 —— 投影是给模型看的视图,日志才按 seq。
804
+ */
805
+
806
+ type CompactionEvent = CoreEventOf<"core.compaction">;
807
+ declare function isCompaction(e: Event): e is CompactionEvent;
808
+ declare function isPinNote(e: Event): boolean;
809
+ /** c 是否覆盖 e:seq 落在闭区间内且早于 c 自身 */
810
+ declare function covers(c: CompactionEvent, e: Event): boolean;
811
+ /** 被 `system_note.supersedes` 指到的事件 id 集合。传完整时间线;取代者本身是否可见不影响取代 */
812
+ declare function supersededIds(timeline: readonly Event[]): Set<string>;
813
+ /**
814
+ * 一次 compaction 是否保留某条被它覆盖的事件。折叠与裁剪共用这一条规则。
815
+ * 被取代的事件一律不保留:pinsKept 记录的是**当时**的契约,后来的取代说明优先。
816
+ */
817
+ declare function keptBy(c: CompactionEvent, e: Event, autoKeepPinNotes: boolean, superseded?: ReadonlySet<string>): boolean;
818
+ interface FoldOptions {
819
+ /** kind=pin 的 system_note 不必出现在 pinsKept 也自动幸存;默认 true */
820
+ autoKeepPinNotes?: boolean;
821
+ }
822
+ declare function foldCompactions(opts?: FoldOptions): ProjectionStrategy;
823
+
824
+ /**
825
+ * 被折叠工具结果的清单(E3c)。
826
+ *
827
+ * 整理(模型自决或阈值兜底)把一段历史换成摘要后,原件仍在日志里(宪法二),但模型不知道**有什么**能拿回来:
828
+ * 两个模型族的实测都把"复核过的字段值"整理成了"状态正常"一句结论,被问到时只能说"没留,可以重查"。
829
+ * 这里把被折叠范围内的每条工具结果列成 `seq N tool(arguments)` 一行,附在摘要之后 —— 摘要写的是模型的取舍,
830
+ * 清单写的是事实上还在的东西。取回的动作由脑子的 recall 工具做(@reinsjs/brain),core 只负责列清单,措辞由调用方给。
831
+ *
832
+ * 纯函数:同一输入同一输出,摘要文本落在 compaction 事件里,回放时逐字一致。
833
+ */
834
+
835
+ interface FoldedToolResult {
836
+ /** tool_result 事件的 seq —— 模型取回时报这个号 */
837
+ seq: number;
838
+ name: string;
839
+ /** 对应 tool_call 的入参;找不到 tool_call 时为 undefined */
840
+ args: unknown;
841
+ /** 结果正文(文本片段)的字符数;外溢过的结果只算留下的预览 */
842
+ chars: number;
843
+ isError: boolean;
844
+ /** 结果已外溢到 BlobStore 时的 blob id:原件在 blob 里,不在事件里 */
845
+ spilledBlobId?: string;
846
+ }
847
+ interface FoldedToolResultOptions {
848
+ /** 找 tool_call 的范围(入参在 tool_call 上);缺省只在 removed 里找。传完整时间线可覆盖"调用在前一段、结果在这一段"的切法 */
849
+ lookup?: readonly Event[];
850
+ /** 不列的工具名:脑子自己的工具(整理回执、钉住回执、取回结果)列出来只是噪音 */
851
+ exclude?: ReadonlySet<string>;
852
+ }
853
+ /** 从一段被折叠(或被裁掉)的事件里挑出工具结果,按 seq 升序 */
854
+ declare function foldedToolResults(removed: readonly Event[], opts?: FoldedToolResultOptions): FoldedToolResult[];
855
+ interface RenderManifestOptions {
856
+ /** 清单标题行;调用方在这里说明怎么取回(core 不知道取回工具叫什么) */
857
+ heading: string;
858
+ /** 最多列几条,其余折成一行"…and N more (seq a–b)"。缺省 80:一条约 25 token,上限约 2k token */
859
+ maxItems?: number;
860
+ /** 入参 JSON 最多显示多少字符。缺省 100 */
861
+ maxArgsChars?: number;
862
+ }
863
+ /** 入参的短摘要:键排序后的 JSON,超长截断。模型靠它认出"是哪一次调用" */
864
+ declare function digestArgs(args: unknown, max?: number): string;
865
+ /** 渲染成给模型看的清单;没有条目返回空字符串 */
866
+ declare function renderFoldedToolResults(items: readonly FoldedToolResult[], opts: RenderManifestOptions): string;
867
+
868
+ declare function reinjectPins(): ProjectionStrategy;
869
+
870
+ /**
871
+ * 策略 5:预算裁剪 —— 模型没来得及自己整理、上下文仍然超限时的最后兜底(P1:框架动作只是兜底)。
872
+ *
873
+ * 做法:按"轮"从最旧的开始裁掉一个前缀,追加一条 compaction(decidedBy=threshold) 放在最前面,
874
+ * 幸存的 pin 紧随其后。新造的 compaction 通过 emitted 交给循环 append,下一轮投影由折叠策略正常处理它。
875
+ *
876
+ * 切点必须满足三条,否则降级层会产出厂商拒收的请求:
877
+ * 1. 只在轮边界切。assistant 轮 = 连续的 model_thinking / model_text / tool_call;其余连续事件为一轮。
878
+ * 2. 保留部分的第一轮若含 tool_result,其 tool_call 必在被裁掉的轮里 → 这种切点不合法。
879
+ * 3. seq 封闭:保留部分所有事件的 seq 都大于被裁部分的最大 seq,这样新 compaction 的 coversSeq
880
+ * 是一个干净的区间,不会误伤保留的事件(折叠可能把旧 compaction 挪到前面,顺序与 seq 不一致)。
881
+ *
882
+ * 被裁掉的旧 compaction 摘要会原文并入新摘要,模型写过的整理不丢。
883
+ */
884
+
885
+ /** 把事件序列切成轮:assistant 事件连成一轮,其余连成一轮 */
886
+ declare function splitTurns(events: readonly Event[]): Event[][];
887
+ type ThresholdSummarizer = (removed: readonly Event[], ctx: ProjectionContext) => string;
888
+ interface BudgetTruncateOptions {
889
+ /** 与折叠策略一致:kind=pin 的 system_note 自动幸存;默认 true */
890
+ autoKeepPinNotes?: boolean;
891
+ /** 生成兜底摘要的文本;默认给模型一段英文的机械描述 */
892
+ summarize?: ThresholdSummarizer;
893
+ }
894
+ /**
895
+ * 默认兜底摘要:没有模型参与,只能机械描述 —— 说明发生了什么、被裁掉多少、并入旧摘要、引用用户原话开头。
896
+ * 给模型看的默认文案用英文;宿主可整体替换。
897
+ */
898
+ declare const defaultThresholdSummary: ThresholdSummarizer;
899
+ declare function budgetTruncate(opts?: BudgetTruncateOptions): ProjectionStrategy;
900
+
901
+ /**
902
+ * 策略链执行器与默认链。
903
+ *
904
+ * 默认链(技术方案 §8):过滤 → 折叠 → 钉住 → 预算裁剪。
905
+ * 感知注入(§9.1)不在这条链上:它是 `@reinsjs/brain` 的 Socket,在 beforeModel 里把 system_note 作为新事件
906
+ * 追加到时间线末尾(prompt cache 约束:只追加、不改前缀)。投影只负责"看历史",不负责"说话"。
907
+ */
908
+
909
+ /** 未指定 reserveTokens 时,为输出与工具定义预留窗口的这个比例 */
910
+ declare const DEFAULT_RESERVE_RATIO = 0.15;
911
+ interface DefaultChainOptions {
912
+ filter?: VisibilityFilterOptions;
913
+ fold?: FoldOptions;
914
+ truncate?: BudgetTruncateOptions;
915
+ }
916
+ declare function defaultProjectionChain(opts?: DefaultChainOptions): ProjectionStrategy[];
917
+ interface ProjectOptions {
918
+ /** 完整时间线快照,按 seq 升序、同一会话 */
919
+ timeline: readonly Event[];
920
+ budget: {
921
+ contextLimit: number;
922
+ reserveTokens?: number;
923
+ };
924
+ /** 缺省 defaultProjectionChain() */
925
+ strategies?: readonly ProjectionStrategy[];
926
+ /** 缺省 roughTokenEstimate */
927
+ estimate?: TokenEstimator;
928
+ /** 缺省内置 core 注册表;宿主有 ext.* 事件时传自己的 */
929
+ registry?: EventSchemaRegistry;
930
+ /** 缺省时间线里最后一条的 sessionId;空时间线必须显式给 */
931
+ sessionId?: string;
932
+ /** 缺省 Date.now();测试注入以获得确定输出 */
933
+ now?: number;
934
+ /** 缺省 uuidv7;测试注入以获得确定输出 */
935
+ newId?: (at: number) => string;
936
+ }
937
+ /**
938
+ * 跑一遍策略链。除 now / newId 外没有任何外部输入,同一参数必得同一输出。
939
+ * 时间线必须按 seq 严格升序,否则说明调用方拼错了快照,直接拒绝而不是产出错误的投影。
940
+ */
941
+ declare function project(opts: ProjectOptions): ProjectionResult;
942
+
943
+ /**
944
+ * 回放(技术方案 §4 "审计回放(原样)"):只凭事件日志,重算出每一轮模型请求时它看到了什么。
945
+ *
946
+ * 依据是两条既有事实:
947
+ * 1. 投影是纯函数(§8):同一份日志前缀 + 同样的参数 → 逐字相同的可见事件。
948
+ * 2. 循环每轮都在请求前把"模型即将看到的一切"先写进日志(beforeModel 注入、阈值 compaction 都是先 append 再问模型)。
949
+ * 所以"第 n 轮模型看到的" = project(该轮第一条模型输出之前的全部事件)。run-loop.test 里"日志可完整回放"钉死了这一点。
950
+ *
951
+ * 用途:审计界面(examples/minimal/replay.ts)、eval 的逐轮对比(M2 E1)、排查"模型当时为什么这么做"。
952
+ *
953
+ * 轮边界按**模型输出类型**(model_thinking / model_text / tool_call)判,不按 actor:脑子模块在工具执行期间
954
+ * 留下的事件(模型自决的 compaction、模型钉的 pin、memory_op)actor 也是 model,并行工具时它们会落在
955
+ * 某条 tool_result 之后,按 actor 切会被误当成一个新的模型轮(E1 修)。
956
+ *
957
+ * 边界(如实声明):
958
+ * - Socket 在 beforeModel 里直接替换投影(patch.events)的部分无法重算,回放给出的是缺省路径的结果;
959
+ * 脑子模块新造的事件(system_note、compaction)都在日志里,不受影响。
960
+ * - 请求发出但一条模型输出都没回来(降级层异常、provider 报错)的那一轮没有模型事件,识别不出请求边界,
961
+ * 只在时间线上留一条 core.error;这类失败轮不计入 turns。
962
+ */
963
+
964
+ interface ReplayedTurn {
965
+ /** 从 1 起 */
966
+ index: number;
967
+ /** 请求发出时日志的末尾 seq。模型看到的 = timeline[seq ≤ requestAtSeq] 的投影 */
968
+ requestAtSeq: number;
969
+ /** 模型这一轮看到的事件(按当时的顺序) */
970
+ visible: Event[];
971
+ stats: ProjectionStats;
972
+ /**
973
+ * 重算投影时策略又新造了事件(如阈值 compaction)—— 当时并没有发生这件事,说明现在的策略或估算与当时不同。
974
+ * 为 true 时 visible 是"按现在的规则会看到什么",不是当时的事实。
975
+ */
976
+ diverged: boolean;
977
+ /** 模型这一轮的输出:thinking / text / tool_call,连续一段 */
978
+ output: Event[];
979
+ /** 输出之后、下一轮请求之前发生的事:工具结果、用量、暂停、审批…… */
980
+ aftermath: Event[];
981
+ /** 循环记的这一轮真实用量(core.budget_usage),没有则缺省 */
982
+ usage?: BudgetUsagePayload;
983
+ }
984
+ interface ReplayResult {
985
+ turns: ReplayedTurn[];
986
+ /** 第一轮请求之前的事件(通常是用户的第一句话) */
987
+ preamble: Event[];
988
+ }
989
+ interface ReplayOptions {
990
+ /** 与当时循环相同的预算:contextLimit 取模型的 contextWindow */
991
+ budget: {
992
+ contextLimit: number;
993
+ reserveTokens?: number;
994
+ };
995
+ /** 与当时循环相同的策略链;缺省 defaultProjectionChain() */
996
+ strategies?: readonly ProjectionStrategy[];
997
+ estimate?: TokenEstimator;
998
+ registry?: EventSchemaRegistry;
999
+ }
1000
+ /** 是否为模型这一轮的直接输出(降级层吐出的三种事件)。与投影裁剪切轮(splitTurns)同口径 */
1001
+ declare function isModelOutput(e: Event): boolean;
1002
+ /**
1003
+ * 把一条时间线切成若干"模型轮"。时间线须按 seq 升序、同一会话(日志读出来就是这样)。
1004
+ * 请求边界 = 一条模型输出事件紧跟在非输出事件之后(或位于时间线开头)。
1005
+ */
1006
+ declare function replayTurns(timeline: readonly Event[], opts: ReplayOptions): ReplayResult;
1007
+
1008
+ type StoreErrorCode = "seq_conflict" | "session_mismatch" | "empty_batch" | "not_found" | "target_not_empty" | "out_of_range" | "invalid_argument";
1009
+ declare class StoreError extends Error {
1010
+ readonly code: StoreErrorCode;
1011
+ readonly context: Record<string, unknown>;
1012
+ constructor(code: StoreErrorCode, message: string, context?: Record<string, unknown>);
1013
+ }
1014
+
1015
+ /**
1016
+ * 三个接口的内存实现:零依赖、进程内、无持久化。用途:
1017
+ * - 单测与示例
1018
+ * - 一致性套件的参考实现(其他后端的行为以此为准)
1019
+ * - 短生命周期的宿主(如一次性脚本)
1020
+ *
1021
+ * 读写都经过 structuredClone,调用方拿到的对象与内部存储互不影响。
1022
+ */
1023
+
1024
+ declare class InMemoryEventLog implements EventLog {
1025
+ private readonly sessions;
1026
+ append(events: readonly Event[]): Promise<void>;
1027
+ read(sessionId: string, opts?: ReadOptions): AsyncIterable<Event>;
1028
+ tail(sessionId: string, n: number): Promise<Event[]>;
1029
+ fork(fromSessionId: string, atSeq: number, toSessionId: string): Promise<void>;
1030
+ }
1031
+ declare class InMemoryBlobStore implements BlobStore {
1032
+ private readonly blobs;
1033
+ put(bytes: Uint8Array | string, meta: {
1034
+ mime: string;
1035
+ sessionId: string;
1036
+ }): Promise<{
1037
+ id: string;
1038
+ }>;
1039
+ get(id: string): Promise<{
1040
+ bytes: Uint8Array;
1041
+ meta: BlobMeta;
1042
+ }>;
1043
+ slice(id: string, range: {
1044
+ start: number;
1045
+ end: number;
1046
+ }): Promise<Uint8Array>;
1047
+ }
1048
+ declare class InMemoryMemoryStore implements MemoryStore {
1049
+ private readonly files;
1050
+ list(prefix: string): Promise<string[]>;
1051
+ read(path: string): Promise<string | null>;
1052
+ write(path: string, content: string): Promise<void>;
1053
+ delete(path: string): Promise<void>;
1054
+ }
1055
+ /** 一套全内存的存储,五分钟体验与测试用;进程结束即清空 */
1056
+ declare function memoryStore(): Stores;
1057
+
1058
+ /**
1059
+ * 从 EventLog 读事件的唯一正确姿势:读出来的每一条都先过注册表(P9:读时 upcast,查不到升级函数即拒绝)。
1060
+ *
1061
+ * 存储层只负责原样存取,不认识 schema;日志里可能躺着旧版本事件(升级代码后),也可能有宿主的 ext.* 事件。
1062
+ * 循环、server 补发、回放都经这里读,模型与前端看到的永远是当前版本的形状;
1063
+ * 未登记的类型或未来版本会在这里抛 SchemaError,而不是被静默透传或读到一半才发现。
1064
+ */
1065
+
1066
+ interface ReadTimelineOptions extends ReadOptions {
1067
+ /** 有 ext.* 事件时传宿主自己的注册表;缺省内置 core 注册表由调用方决定,这里不隐式创建 */
1068
+ registry: EventSchemaRegistry;
1069
+ }
1070
+ /** 流式:按 seq 升序逐条升级后产出 */
1071
+ declare function readEvents(log: EventLog, sessionId: string, opts: ReadTimelineOptions): AsyncGenerator<Event>;
1072
+ /** 整段:循环每轮都要完整时间线,这个最常用 */
1073
+ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimelineOptions): Promise<Event[]>;
1074
+
1075
+ /**
1076
+ * @reinsjs/core
1077
+ *
1078
+ * 两条原则:
1079
+ * 1. 决策权默认在模型。库只做四件事:让它看见、给它能力、给它边界、给它记录。
1080
+ * 2. 时间线是唯一真源,角色只是翻译。
1081
+ *
1082
+ * 模块:
1083
+ * - events/:事件模型、schema 注册表与升级(T3)
1084
+ * - store/:EventLog / BlobStore / MemoryStore 接口与内存实现(T4)
1085
+ * - projection/:投影策略链,从时间线算出模型本轮看到什么(T6)
1086
+ * - lowering/:降级层接口与有损矩阵类型,实现在 @reinsjs/lowering-pi(T7)
1087
+ * - loop/:runLoop 默认循环、Socket 插座、Tool 抽象、RunResult 与可序列化状态(T9)
1088
+ * - replay/:只凭日志重算每轮模型看到了什么,供审计界面与 eval 逐轮对比(T15)
1089
+ * - testing/:存储一致性套件与脚本化降级层,单独入口 @reinsjs/core/testing(T5)
1090
+ */
1091
+
1092
+ /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
1093
+ declare const REINS_VERSION = "0.1.0";
1094
+
1095
+ export { type ApprovalDecisionInput, ApprovalRequestPayload, type ApprovalRequestSpec, BUILTIN_APPROVAL_POLICY, type BeforeModelPatch, type BeforeToolDecision, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, DEFAULT_RETRY_BASE_DELAY_MS, DEFAULT_RETRY_MAX_ATTEMPTS, DEFAULT_RETRY_MAX_DELAY_MS, type DefaultChainOptions, type ErrorEventPayload, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type ForkOptions, type HandoffIntent, INPUT_DRAFT_TYPES, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, type Interruption, LandingRecord, type LoopConfig, LoweredRequest, Lowering, LoweringCapabilities, LoweringDelta, LoweringError, type LoweringErrorCode, type MarkedContent, type MaybePromise, MemoryStore, type ModelCallFailure, ModelRef, type PauseReason, type Principal, type ProjectOptions, type ProjectionBudget, type ProjectionContext, type ProjectionResult, type ProjectionStats, type ProjectionStep, type ProjectionStepStats, type ProjectionStrategy, REINS_VERSION, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, type ResolvedRetry, type RetryOptions, type RunResult, RunStateError, type RunStateErrorCode, type SerializedRunState, type SessionInfo, type Socket, type SocketSetup, type StaticContribution, StoreError, type StoreErrorCode, Stores, type SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, type TokenEstimator, TokenUsage, type Tool, type ToolCallEvent, ToolCallPayload, type ToolContext, type ToolNamesDiff, type ToolResult, type ToolResultDraft, ToolResultPayload, type ToolSide, ToolSpec, type ToolsBoundEvent, Trust, type TurnContext, type TurnDecision, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, backoffDelayMs, budgetTruncate, computeConfigHash, computePendingDigest, covers, defaultProjectionChain, defaultSleep, defaultThresholdSummary, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, forkSession, inputDraft, isCompaction, isModelOutput, isPinNote, isSubagentPause, isTransientFailure, keptBy, lastToolsBound, markUntrusted, markUntrustedText, memoryStore, needsUntrustedMark, normalizeToolOutput, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderToolChangeNote, replayTurns, resolveRetry, resolveSocketContributions, roughTokenEstimate, runLoop, serializeRunState, signRunState, splitTurns, statusFromMessage, subagentPause, supersededIds, toolResultTrust, toolSpecOf, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, uuidv7, validateResume, verifyRunState, visibilityFilter };