@reinsjs/core 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, B as BlobStore, c as BlobMeta, C as ContentPart, I as ImageRefPart, d as Interruption, e as ErrorPayload, L as LoopConfig, f as EventDraft, R as RunResult, P as PauseReason, A as AwaitingCall, g as Tool, h as EventSchemaRegistry, S as SerializedRunState, M as ModelRef, i as SubagentInterruption, j as ToolSpec, k as ToolResult, l as Trust, m as CoreEventOf, n as CoreEventDraft, o as ProjectionBudget, p as ProjectionStrategy, q as ProjectionContext, r as TokenEstimator, s as ProjectionResult, t as ProjectionStats, u as BudgetUsagePayload, v as ReadOptions, w as MemoryStore, x as RunLease, y as Stores } from './core-BxGiBJ_p.js';
2
- export { z as Actor, D as AnyEvent, F as ApprovalDecisionInput, G as ApprovalDecisionPayload, H as ApprovalRequestPayload, J as ApprovalRequestSpec, K as AudioPart, N as BeforeModelPatch, O as BeforeToolDecision, Q as BoundModel, U as CORE_SCHEMAS, V as CompactionPayload, W as CoreEvent, X as CoreEventPayloads, Y as CoreEventType, Z as CreateEventInput, _ as DEFAULT_RETRY_BASE_DELAY_MS, $ as DEFAULT_RETRY_MAX_ATTEMPTS, a0 as DEFAULT_RETRY_MAX_DELAY_MS, a1 as DEFAULT_TRUST, a2 as ErrorEventPayload, a3 as EventBase, a4 as EventSchema, a5 as ExtEvent, a6 as HandoffIntent, a7 as HandoffPayload, a8 as ImageInlinePart, a9 as ImagePart, aa as LandingRecord, ab as LandingSpec, ac as LossKind, ad as LossMatrix, ae as LoweredRequest, af as Lowering, ag as LoweringCapabilities, ah as LoweringDelta, ai as LoweringOutcome, aj as LoweringStreamContext, ak as MaybePromise, al as MemoryOpPayload, am as ModelCallFailure, an as ModelTextPayload, ao as ModelThinkingPayload, ap as Principal, aq as ProjectionStep, ar as ProjectionStepStats, as as Provenance, at as PullInputContext, au as ResolvedRetry, av as RetryOptions, aw as RunEndedPayload, ax as RunPausedPayload, ay as RunResumedPayload, az as SchemaError, aA as SchemaErrorCode, aB as SessionInfo, aC as SkillSource, aD as Socket, aE as SocketSetup, aF as StaticContribution, aG as SystemNotePayload, aH as TextPart, aI as ToRequestInput, aJ as TokenUsage, aK as ToolBatch, aL as ToolCallPayload, aM as ToolContext, aN as ToolReferencePart, aO as ToolResultDraft, aP as ToolResultPayload, aQ as ToolSide, aR as ToolStartedPayload, aS as ToolsBoundPayload, aT as TurnContext, aU as TurnDecision, aV as Upcaster, aW as UserMessagePayload, aX as VideoPart, aY as backoffDelayMs, aZ as contextOverheadOf, a_ as contextTokensOf, a$ as createCoreEvent, b0 as createCoreRegistry, b1 as createEvent, b2 as defaultSleep, b3 as isTransientFailure, b4 as lossesOf, b5 as renderToolReference, b6 as resolveRetry, b7 as statusFromMessage } from './core-BxGiBJ_p.js';
1
+ import { E as Event, T as ToolCallEvent, a as ToolResultEvent, b as EventLog, H as HandoffIntent, c as EventDraft, B as BlobStore, d as BlobMeta, C as ContentPart, I as ImageRefPart, e as Interruption, f as ErrorPayload, L as LoopConfig, R as RunResult, P as PauseReason, A as AwaitingCall, g as Tool, h as EventSchemaRegistry, i as ApprovalDecisionInput, S as SerializedRunState, M as ModelRef, j as SubagentInterruption, k as ToolSpec, l as ToolResult, m as Trust, n as CoreEventOf, o as CoreEventDraft, p as ProjectionBudget, q as ProjectionStrategy, r as ProjectionContext, s as TokenEstimator, t as ProjectionResult, u as ProjectionStats, v as BudgetUsagePayload, w as ReadOptions, x as MemoryStore, y as RunLease, z as Stores } from './core-CfHjZdUU.js';
2
+ export { D as Actor, F as AnyEvent, G as ApprovalDecisionPayload, J as ApprovalRequestPayload, K as ApprovalRequestSpec, N as AudioPart, O as BeforeModelPatch, Q as BeforeToolDecision, U as BoundModel, V as CORE_SCHEMAS, W as CompactionPayload, X as CoreEvent, Y as CoreEventPayloads, Z as CoreEventType, _ as CreateEventInput, $ as DEFAULT_RETRY_BASE_DELAY_MS, a0 as DEFAULT_RETRY_MAX_ATTEMPTS, a1 as DEFAULT_RETRY_MAX_DELAY_MS, a2 as DEFAULT_TRUST, a3 as ErrorEventPayload, a4 as EventBase, a5 as EventSchema, a6 as ExtEvent, a7 as HandoffPayload, a8 as ImageInlinePart, a9 as ImagePart, aa as LandingRecord, ab as LandingSpec, ac as LossKind, ad as LossMatrix, ae as LoweredRequest, af as Lowering, ag as LoweringCapabilities, ah as LoweringDelta, ai as LoweringOutcome, aj as LoweringStreamContext, ak as MaybePromise, al as MemoryOpPayload, am as ModelCallFailure, an as ModelTextPayload, ao as ModelThinkingPayload, ap as Principal, aq as ProjectionStep, ar as ProjectionStepStats, as as Provenance, at as PullInputContext, au as ResolvedRetry, av as RetryOptions, aw as RunEndedPayload, ax as RunPausedPayload, ay as RunResumedPayload, az as SchemaError, aA as SchemaErrorCode, aB as SessionInfo, aC as SkillSource, aD as Socket, aE as SocketSetup, aF as StaticContribution, aG as SystemNotePayload, aH as TextPart, aI as ToRequestInput, aJ as TokenUsage, aK as ToolBatch, aL as ToolCallPayload, aM as ToolContext, aN as ToolReferencePart, aO as ToolResultDraft, aP as ToolResultPayload, aQ as ToolSide, aR as ToolStartedPayload, aS as ToolsBoundPayload, aT as TurnContext, aU as TurnDecision, aV as Upcaster, aW as UserMessagePayload, aX as VideoPart, aY as backoffDelayMs, aZ as contextOverheadOf, a_ as contextTokensOf, a$ as createCoreEvent, b0 as createCoreRegistry, b1 as createEvent, b2 as defaultSleep, b3 as isTransientFailure, b4 as lossesOf, b5 as renderToolReference, b6 as resolveRetry, b7 as statusFromMessage } from './core-CfHjZdUU.js';
3
3
 
4
4
  /**
5
5
  * UUID v7 生成(RFC 9562):前 48 位为 Unix 毫秒时间戳,字典序即时间序。
@@ -12,8 +12,8 @@ declare function uuidv7(now?: number): string;
12
12
  /**
13
13
  * 工具批的定位(2026-11-02,OnSet 建议 9 / 10)。
14
14
  *
15
- * "一批" = 一段连续模型输出里的 tool_call。与 replay 切轮(`isModelOutput`)同口径,另外跳过模型不可见的运维事件
16
- * (budget_usage、approval_request、run_paused…)——它们可能夹在同一次输出中间(TanStack 的 onUsage 早于输出收尾时),
15
+ * "一批" = 一段连续模型输出里的 tool_call。与 replay 切轮(`isModelOutput`)同口径,另外跳过缺省对模型不可见的事件
16
+ * (budget_usage、approval_request、run_paused…与宿主 ext.*)——它们可能夹在同一次输出中间(TanStack 的 onUsage 早于输出收尾时),
17
17
  * 与 lowering-fetch IR"运维事件不打断 assistant 分组"同一条规矩。runLoop 与 TanStack 适配器补跑时都调它(真源索引)。
18
18
  */
19
19
 
@@ -39,6 +39,34 @@ declare function forkSession(log: EventLog, opts: ForkOptions): Promise<{
39
39
  toSessionId: string;
40
40
  }>;
41
41
 
42
+ /**
43
+ * 交接新会话的开场草稿(runLoop 与 TanStack 适配器共用,两处开场形状不分叉)。
44
+ *
45
+ * 形状:seq 1 摘要说明 → 意图带来的开场事件(如 pin,原样)→ 触发消息(有才写)。
46
+ *
47
+ * 发起者如实记(宪法二:事件带真实发起者;全库审查 2026-11-25 #52):
48
+ * - 摘要是交接决定者写的:`intent.by`(缺省 model),不再一律记成宿主说明——模型写的摘要不该拿 system 信任;
49
+ * - 触发消息逐字(去首尾空白)取自旧会话一条用户消息时,按原事件的发起者与 trust 记(用户的仍是用户、宿主写的仍是宿主、
50
+ * 上一次交接里模型自拟的仍是模型),provenance 指回原事件;否则是交接决定者自拟的(模型被工具结果里的注入诱导写的
51
+ * 也在此列),记在它名下;
52
+ * - 摘要与自拟触发消息的 provenance 指回旧会话的 `core.handoff` 事件,审计分得清这句话从哪来。
53
+ *
54
+ * 摘要说明的 `payload.kind` 刻意仍是 `"host"`、不随 actor 改:kind 是说明的类别("perception" / "pin" / "budget"
55
+ * 之外的通用说明一律 host,工具表变化说明也是 actor system + kind host),不表示谁写的——谁写的只看 actor。
56
+ * 另加 "handoff" 类别要扩 SystemNotePayload 闭集、升 schemaVersion 写 upcast,而降级层与脑子模块按 kind 的分支
57
+ * 对它都该与 host 同样处理,换来的只是重复 actor + provenance 已经给出的信息。
58
+ *
59
+ * 模型看到的字节不变:降级层按事件类型落角色、只看 `trust === "untrusted"` 包标记,不读 actor。
60
+ */
61
+
62
+ /** 交接开场事件 provenance 的来源名(与 brain handoff 模块带过去的 pin 同名) */
63
+ declare const HANDOFF_PROVENANCE_SOURCE = "handoff";
64
+ /**
65
+ * @param handoffEvent 旧会话刚写下的 `core.handoff`(摘要与自拟触发消息的出处)
66
+ * @param timeline 旧会话完整时间线(找触发消息逐字出自哪条用户消息;取最近的一条)
67
+ */
68
+ declare function handoffOpeningDrafts(intent: HandoffIntent, handoffEvent: Event, timeline: readonly Event[]): EventDraft[];
69
+
42
70
  /**
43
71
  * 图片引用形态(2026-11-24 媒体引用方案,AdRate 建议 17 第二步):字节放 BlobStore,日志只存 `{ type: "image", mime, blobId }`。
44
72
  *
@@ -51,6 +79,10 @@ declare function forkSession(log: EventLog, opts: ForkOptions): Promise<{
51
79
  * 被折叠的图一个字节都不读。只有 not_found 留着引用(降级层落占位、记 lossy),其它存储错误抛出走模型调用失败的判定——
52
80
  * 瞬时故障不能让模型对着占位作答、再把回答永久写进日志。
53
81
  *
82
+ * 两件事的读取都走同一个并发池(`readBlobs`,2026-11-24 AdRate 建议 18):去重、在途 ≤ 16、等全部落定,
83
+ * 再按片段 / 视野原顺序判定——结局与串行逐个读完全一致,只是对象存储上 N 张图从 N 次往返变成一波。
84
+ * `get` / `stat` 返回的不是对象一律当 not_found(防探测,见 `readOne`)。
85
+ *
54
86
  * 归属口径(`blobUsableBy`):blob 的 meta.sessionId 就是本会话,或本会话时间线里已被**图片引用**过
55
87
  * (fork 出的会话凭此用父会话的图;recall 取回的结果里是引用,自然合规)。图片引用集合(`mediaRefsOf`)与
56
88
  * brain `fetch_blob` 的外溢引用集合刻意分开:只被图片引用过的 blob 不能被 fetch_blob 读出字节,外溢 blob 也当不了图片。
@@ -91,11 +123,17 @@ interface CheckImageRefsContext {
91
123
  /** 本会话时间线(归属判定"已引用过"那一支用;只在 blob 不归本会话时才扫) */
92
124
  timeline: readonly Event[];
93
125
  cache: ImageRefCache;
126
+ /**
127
+ * 只判归属与 mime、不留字节:存储有 `stat` 用 `stat`,否则退回 `get`;读到的不放进 cache。
128
+ * server 的 HTTP 预校验用(那份缓存用完即弃);循环内不传——写进日志前的最终裁决与发给厂商的字节出自同一次 `get`
129
+ */
130
+ metaOnly?: boolean;
94
131
  }
95
132
  /**
96
133
  * 校验一批片段里的图片引用。全部合规返回 undefined;任一不合规返回统一的那一句(`imageRefNotFound`)。
97
- * 取到的字节顺手放进 cache(缓存命中则不再读存储,但归属与 mime 照判)。存储抛的非 not_found 错误原样抛出,
98
- * 调用方按各自入口的口径处理
134
+ * 未缓存的 blob 先去重、并发读完,再**按片段顺序**逐个判、报第一个问题(与读取完成先后无关);
135
+ * 取到的字节放进 cache(`metaOnly` 时不放;缓存命中不再读存储,但归属与 mime 照判)。
136
+ * 存储抛的非 not_found 错误原样抛出(按片段顺序第一个),调用方按各自入口的口径处理
99
137
  */
100
138
  declare function checkImageRefs(parts: readonly ContentPart[], ctx: CheckImageRefsContext): Promise<string | undefined>;
101
139
  interface HydrateImageRefsContext {
@@ -104,9 +142,10 @@ interface HydrateImageRefsContext {
104
142
  }
105
143
  /**
106
144
  * 视图里的图片引用换回内联(只碰 user_message / tool_result 的 content,其它事件原样返回同一对象)。
107
- * - 缓存里有的直接用;同一 blob 在一次调用里只 get 一次
145
+ * - 缓存里有的直接用;视野内未缓存的去重后并发 `get`(上限见 `BLOB_READ_CONCURRENCY`),读完按原顺序换回
108
146
  * - `StoreError("not_found")` 与没配 BlobStore:片段保持引用形态交给降级层(落 `[image unavailable]` 占位、记 lossy),不进缓存
109
- * - 其它存储错误原样抛出:循环把它当模型调用失败处理(走重试判定),不让模型对着占位作答
147
+ * - 其它存储错误:读成功的先进缓存(重试只重读失败的),再按视野顺序抛第一个——循环把它当模型调用失败处理(走重试判定),
148
+ * 不让模型对着占位作答
110
149
  *
111
150
  * 换回后的事件只交给 `toRequest`,不回写日志、不回写 `ctx.events`(Socket 与估算看到的仍是引用)。
112
151
  * 直接调 `toRequest` 的宿主(审计回放、探针)先过一遍它,降级层才看得到图
@@ -389,6 +428,19 @@ declare function validateResume(input: {
389
428
  secret?: string;
390
429
  allowConfigDrift?: boolean;
391
430
  }): Promise<ToolCallEvent[]>;
431
+ /**
432
+ * 本会话审批结论的对账(真源索引,全库审查 2026-11-25 #12):每条结论指向的调用必须**正在等审批**——
433
+ * pending、有 approval_request、还没有结论,判定只走 `awaitingOf`(与 run_paused.awaiting 同一口径)。
434
+ * 只查 pending 的话,一个从没发出审批请求的调用(工具批中途被普通中止、排在后面的)也能被"预先批准",
435
+ * needsApproval、审批策略的 defer 与 ttl 都会被跳过。同一调用在一批结论里出现两次也拒(第一条落下后它就不在等了)。
436
+ * 指向别的会话(子代理)的结论不在这里校验,原样转发。不合规抛 `RunStateError("unknown_tool_call")`,调用方须在写日志前调。
437
+ * server 的 decisions 预校验调本函数(HTTP 回 409),与 runLoop 同判由 server/handler.test.ts 穿过两个入口的用例锁住
438
+ */
439
+ declare function assertDecisionsAwaitApproval(input: {
440
+ sessionId: string;
441
+ timeline: readonly Event[];
442
+ decisions: readonly ApprovalDecisionInput[];
443
+ }): void;
392
444
 
393
445
  /**
394
446
  * Socket 静态贡献的解析(B2 引入,B6 抽出):宿主工具 + 各 Socket 带来的工具与规则提示 → 整个 run 不变的工具表与系统提示。
@@ -407,7 +459,8 @@ interface ResolvedContributions {
407
459
  /** 能算出静态贡献所需的配置子集:AgentDefinition(跨请求不变)加上本次请求的 principal */
408
460
  type ContributionConfig = Pick<LoopConfig, "log" | "blobs" | "memory" | "model" | "principal" | "tools" | "sockets" | "systemPrompt">;
409
461
  /**
410
- * 宿主工具 + 各 Socket 的静态工具(同名以宿主为准,宿主想覆盖模块的默认实现时用);
462
+ * 宿主工具 + 各 Socket 的静态工具(同名以宿主为准,宿主想覆盖模块的默认实现时用——但对 brain 自带工具的模块,按名字覆盖会让
463
+ * 整个模块停摆,见 brain `shared/own-tools.ts`;只想换读法用 `spill({ tool: false })` 这类开关);
411
464
  * 宿主系统提示在前,各 Socket 的规则片段按注册顺序追加,空行分隔;都没有则 undefined。
412
465
  *
413
466
  * 异步(P1):贡献函数可以 await(MCP 的 `tools/list`)。各 Socket 仍按注册顺序**依次**解析而不是并发 ——
@@ -426,7 +479,7 @@ declare function resolveSocketContributions(cfg: ContributionConfig): Promise<Re
426
479
  * 对改用户广告的写工具,重复执行就是重复花钱。这里放三件纯东西,循环与 asTool 共用:
427
480
  *
428
481
  * - `RunStop` / `isStopReason`:停止是中止的一种原因。宿主 `controller.abort(new RunStop())`,循环在暂停时把 pending 收尾成
429
- * "没执行"等结果,下一个 run 直接问模型;其它中止原因(丢租约、断线)照旧留 pending、恢复时补跑。
482
+ * "没执行"等结果,下一个 run 直接问模型;其它中止原因(丢租约、断线)落在工具批中途时照旧留 pending、恢复时补跑(落在模型响应中途时那次响应里的调用收尾成"响应被中断")。
430
483
  * - `isReplayable`:调用开始动手后中断了,能不能再跑一遍。缺省口径与 approval 的 byRisk 一致:只有 `risk: "low"` 的算可重放。
431
484
  * - `startedToolCallIds` / `toolStartedAt`:时间线里已经开始动手的调用(`core.tool_started`)及其开始时间。
432
485
  * - `outcomeUnknownText` / `withStartedAt`:"结果未知"缀上调用开始时间(2026-11-09,AdRate 建议 10)。
@@ -440,6 +493,17 @@ declare const STOPPED_NOTE = "stopped by the user";
440
493
  declare const STOPPED_NOT_EXECUTED_TEXT = "Not executed: the run was stopped by the user before this call started.";
441
494
  /** 用户停止:可重放的调用(子代理)做了一半 */
442
495
  declare const STOPPED_IN_PROGRESS_TEXT = "Interrupted: the run was stopped by the user while this call was in progress; it may have partly taken effect.";
496
+ /**
497
+ * 模型响应在落下 tool_call 之后才失败(断流、stopReason error):run 以 error 收尾前把这次响应里的调用收尾成这句(全库审查 2026-11-25 #13)。
498
+ * 入参可能是截断的,也不知道模型原本还要说什么;留作 pending 的话,下一个 run 会在用户的新话之后、模型读到它之前先执行
499
+ */
500
+ declare const MODEL_FAILED_NOT_EXECUTED_TEXT = "Not executed: the model response failed before it was complete, so this call was dropped.";
501
+ /**
502
+ * 模型响应被宿主中止(断线、丢租约,`stopReason: "aborted"` 或连接阶段被掐)而这次响应里已落了 tool_call:
503
+ * 暂停前把这些调用收尾成这句(全库审查 2026-11-25 返修,与 #13 同一形状)。降级层被中止时可能按已累积的半截入参吐出调用,
504
+ * 留作 pending 的话下一个 run 会在用户的新话之后先补跑它。用户停止不用这句,走 `stopTextsOf` 的"没执行"
505
+ */
506
+ declare const MODEL_INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: the model response was interrupted before it was complete, so this call was dropped.";
443
507
  /** 宿主收尾遗留调用(`RunStop("host")`,如 asTool 开新一轮前):调用还没开始。不说"用户停止"——多半是进程中途死亡留下的 */
444
508
  declare const INTERRUPTED_NOT_EXECUTED_TEXT = "Not executed: an earlier run was interrupted before this call started.";
445
509
  /** 宿主收尾遗留调用:可重放的调用(子代理)做了一半 */
@@ -544,20 +608,34 @@ declare function defineTool<TInput>(tool: Tool<TInput>): Tool;
544
608
  declare function toolSpecOf(tool: Tool): ToolSpec;
545
609
  /** 带"声明但不载入"标记的规格(L1):runLoop 按 BeforeModelPatch.deferredTools 对本轮工具表逐件调 */
546
610
  declare function deferredToolSpecOf(tool: Tool, deferred: boolean): ToolSpec;
611
+ /**
612
+ * 图片片段可写进日志的 mime 白名单(真源索引):Anthropic / OpenAI / Gemini 都收的四种,逐字比对、不做大小写或别名归一。
613
+ * 不在表里的(svg、heic、`image/jpg` 写法、非图片类型)一旦以图片片段进日志,之后每次请求都整段回放、厂商回非瞬断 400,
614
+ * 会话卡死(全库审查 2026-11-25 #9)。片段形状(`isContentPart`)、server 网络白名单(`rebuildContentParts`)、tools-mcp 翻译(`toContentParts`)都调这一份
615
+ */
616
+ declare const SUPPORTED_IMAGE_MIMES: ReadonlySet<string>;
617
+ /** mime 是否在图片白名单里(`SUPPORTED_IMAGE_MIMES`);非字符串一律 false */
618
+ declare function isSupportedImageMime(mime: unknown): boolean;
547
619
  /**
548
620
  * 内容片段的形状校验,全包唯一一份(真源索引):工具返回值归一(本文件)与 runLoop 输入草稿 / 片段数组(run-loop.ts)都调它。
549
621
  * 坏片段一旦进日志,之后每次读到它都会崩(会话报废),所以在写之前拦。
550
- * 规则:text 有 `text`;image 是内联(`mime` 与 `data`,mime 不校验,历史行为)或引用(`isImageRef`:mime 以 "image/" 开头、
551
- * blobId 非空且 ≤ 128 字符),`data` 与 `blobId` 恰好一个;video / audio 的 mime 以 "video/" / "audio/" 开头、
622
+ * 规则:text 有 `text`;image 是内联(`mime` 与 `data`)或引用(`isImageRef`:blobId 非空且 ≤ 128 字符),`data` 与 `blobId`
623
+ * 恰好一个,两种形态的 mime 都必须在白名单里(`isSupportedImageMime`);video / audio 的 mime 以 "video/" / "audio/" 开头、
552
624
  * `durationSec` 缺省或为有限正数;tool_reference 有名字、描述与对象形 inputSchema。
553
625
  * 宿主经 HTTP 送来的用户消息另有白名单(server `rebuildContentParts`,两份实现靠跨包用例锁同口径),不含引用段
554
626
  */
555
627
  declare function isContentPart(x: unknown): x is ContentPart;
628
+ /**
629
+ * 工具结果里只有 mime 不在白名单、其余形状都对的图片片段(内联 `data` 或引用 `blobId` 是字符串)换成的说明(模型可见)。
630
+ * 例:图表类 MCP 返回 svg。整条结果 JSON 化会把 base64 原样当文本塞进上下文,这里只换掉那一段,其余片段照旧
631
+ */
632
+ declare function unsupportedImageText(mime: string): string;
556
633
  /**
557
634
  * execute 的返回值 → 模型看到的内容。规则按直觉:
558
635
  * - string → 一段文本
559
636
  * - ContentPart[] → 原样
560
637
  * - { content, isError? } → 原样(唯一能表达"这是错误"的形态)
638
+ * - 上两种里只有白名单外的图片(svg 等)不合规 → 只把那几段换成说明(`unsupportedImageText`),其余照旧
561
639
  * - undefined / null → 空文本(工具没话说也得给模型一个结果块)
562
640
  * - 其余 → JSON 文本
563
641
  */
@@ -656,7 +734,7 @@ declare function toolCallArgumentsMeta(decoded: DecodedToolArguments): {
656
734
  * 翻译给模型时用显式标记包起来,让模型知道这段是**数据不是指令**。
657
735
  *
658
736
  * 归属:事件本身不改(投影不篡改 payload,日志里永远是原文),只在降级层把内容译成各家协议文本的那一刻包裹;
659
- * 两条降级路线(lowering-pi、TanStack 适配器)都调这里的同一份纯函数,文案不会分叉。
737
+ * 各降级路线(lowering-fetch、lowering-pi、TanStack 适配器)都调这里的同一份纯函数,文案不会分叉。
660
738
  *
661
739
  * 形状:
662
740
  * <untrusted source="tool:weekly_sales">
@@ -666,6 +744,8 @@ declare function toolCallArgumentsMeta(decoded: DecodedToolArguments): {
666
744
  * - 只包文本片段:图片不包,首尾若是图片就各插一段文本标记
667
745
  * - 内容里出现 `</untrusted`(大小写不敏感)会提前闭合标签让注入逃出去,替换成 `<\/untrusted` 并在返回值里报 `escaped`,
668
746
  * 降级层据此把落点记成 lossy(有损必声明)
747
+ * - `tool_reference` 片段保持片段形状(降级层还要按它判原生落点与备注),但它在 untrusted 结果里一律被展开成文本
748
+ * (`renderToolReference`),所以名字、描述与 schema 里的每个字符串(含键)同样转义、同样计入 `escaped`
669
749
  */
670
750
 
671
751
  declare const UNTRUSTED_TAG = "untrusted";
@@ -734,11 +814,29 @@ declare function estimateBudgetOf(budget: ProjectionBudget): number;
734
814
  * - tools_bound:每次 run 起步的工具表快照(P1);工具表本身在请求里,增删由循环以 system_note(kind=host) 告知模型
735
815
  * - tool_started:调用已开始动手的标记,只给续跑与停止判断用;模型从 tool_result 得知结果
736
816
  * - run_ended:run 的终结记号(跑完 / 交接 / 出错),只给宿主判会话状态用
817
+ *
818
+ * 宿主扩展事件 `ext.*` 不在这张表里,但 visibilityFilter 缺省同样剔除:降级层对它没有通用落点(三条 fetch 线与 pi 版
819
+ * 都记 dropped、不下发),留在视图里只会让估算、感知读数、兜底裁剪把模型看不到的字节算作上下文占用(全库审查 2026-11-25 #19)。
820
+ * 宿主要让模型看见某条 ext.*,设 `keepExtEvents` 并在排在后面的自有策略里把它翻成 core 事件(system_note 等)
737
821
  */
738
822
  declare const DEFAULT_MODEL_INVISIBLE_TYPES: ReadonlySet<string>;
823
+ /**
824
+ * "缺省对模型不可见"的唯一口径(真源索引):运维事件表 + `ext.*` 前缀。
825
+ * visibilityFilter 缺省配置、runLoop 与 TanStack 适配器对 beforeModel 期间注入事件的过滤都调它——
826
+ * 注入过滤若只看运维事件表,Socket 写的 ext.* 会进本轮视图、被算进送出估算却不下发,
827
+ * contextOverheadOf 校准出的固定开销随之偏低(全库审查 2026-11-25 第二波返修)
828
+ */
829
+ declare function isModelInvisibleByDefault(type: string): boolean;
739
830
  interface VisibilityFilterOptions {
740
- /** 覆盖默认的不可见类型集合 */
831
+ /** 覆盖默认的不可见 core 类型集合(ext.* 另由 keepExtEvents 管,不受它影响) */
741
832
  invisibleTypes?: Iterable<string>;
833
+ /**
834
+ * 缺省 false:ext.* 一律剔除。设 true 时留在视图里,交给排在后面的宿主策略翻成 core 事件——
835
+ * 原样留到降级层仍是 dropped,且会计入估算。runLoop / createAgent 上没有直达选项:用
836
+ * `defaultProjectionChain({ filter: { keepExtEvents: true } })` 自建链、把翻译策略插在第一个(过滤)之后,经 `projection.strategies` 传入。
837
+ * beforeModel 期间注入的 ext.* 不受它影响(注入过滤按 isModelInvisibleByDefault),下一轮起经投影进视图
838
+ */
839
+ keepExtEvents?: boolean;
742
840
  /** 额外判定,返回 false 即不可见。宿主放 principal 可见性等规则 */
743
841
  isVisible?: (event: Event) => boolean;
744
842
  }
@@ -813,7 +911,10 @@ declare function foldedToolResults(removed: readonly Event[], opts?: FoldedToolR
813
911
  interface RenderManifestOptions {
814
912
  /** 清单标题行;调用方在这里说明怎么取回(core 不知道取回工具叫什么) */
815
913
  heading: string;
816
- /** 最多列几条,其余折成一行"…and N more (seq a–b)"。缺省 80:一条约 25 token,上限约 2k token */
914
+ /**
915
+ * 最多列几条,超出时留 seq 最大(最近被折叠)的这些,较旧的折成标题下的一行"…N earlier (seq a–b)"。
916
+ * 缺省 80:一条约 25 token,上限约 2k token
917
+ */
817
918
  maxItems?: number;
818
919
  /** 入参 JSON 最多显示多少字符。缺省 100 */
819
920
  maxArgsChars?: number;
@@ -931,6 +1032,16 @@ interface ProjectOptions {
931
1032
  /** 缺省 uuidv7;测试注入以获得确定输出 */
932
1033
  newId?: (at: number) => string;
933
1034
  }
1035
+ /**
1036
+ * 校验窗口与预留并解出缺省预留(全库审查 2026-11-25 #17)。纯函数,不合规抛 RangeError。
1037
+ * contextLimit 须是有限正数;reserveTokens(缺省 contextLimit × DEFAULT_RESERVE_RATIO 取整)须是有限非负数且小于 contextLimit。
1038
+ * 不校验时 NaN / 0 / 预留不小于窗口会让阈值兜底把历史裁到只剩最后一轮,并把这条 compaction 永久写进只追加的日志
1039
+ * (NaN 时 overBudget 还是 false,连告警都没有)。project() 与 runLoop 起步都调这一个函数:runLoop 在写任何日志之前就拒
1040
+ */
1041
+ declare function resolveReserveTokens(budget: {
1042
+ contextLimit: number;
1043
+ reserveTokens?: number;
1044
+ }): number;
934
1045
  /**
935
1046
  * 跑一遍策略链。除 now / newId 外没有任何外部输入,同一参数必得同一输出。
936
1047
  * 时间线必须按 seq 严格升序,否则说明调用方拼错了快照,直接拒绝而不是产出错误的投影。
@@ -1040,6 +1151,7 @@ declare class InMemoryBlobStore implements BlobStore {
1040
1151
  bytes: Uint8Array;
1041
1152
  meta: BlobMeta;
1042
1153
  }>;
1154
+ stat(id: string): Promise<BlobMeta>;
1043
1155
  slice(id: string, range: {
1044
1156
  start: number;
1045
1157
  end: number;
@@ -1106,6 +1218,6 @@ declare function readTimeline(log: EventLog, sessionId: string, opts: ReadTimeli
1106
1218
  */
1107
1219
 
1108
1220
  /** 库版本,与 packages/core/package.json 的 version 同步(发布前 `pnpm check:dist` 会核对) */
1109
- declare const REINS_VERSION = "0.16.0";
1221
+ declare const REINS_VERSION = "0.18.0";
1110
1222
 
1111
- export { AwaitingCall, BUILTIN_APPROVAL_POLICY, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CheckImageRefsContext, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, type DecodedToolArguments, type DefaultChainOptions, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type FoldedUserMedia, type ForkOptions, type HydrateImageRefsContext, IMAGE_REF_ID_MAX, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, type ImageRefCache, ImageRefPart, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, Interruption, LoopConfig, LoweringError, type LoweringErrorCode, MAX_TURNS_PAUSE_CODE, type MarkedContent, MemoryStore, ModelRef, OUTCOME_UNKNOWN_TEXT, PAUSE_CODE_RE, PauseReason, type ProjectOptions, ProjectionBudget, ProjectionContext, ProjectionResult, ProjectionStats, ProjectionStrategy, REINS_VERSION, RUN_MARKER_TYPES, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, RunLease, RunResult, RunStateError, type RunStateErrorCode, type RunStatus, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, SerializedRunState, type SocketPauseInterruption, type SocketPauseResolution, type StopTexts, StoreError, type StoreErrorCode, Stores, SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, TokenEstimator, Tool, ToolCallEvent, type ToolNamesDiff, ToolResult, ToolResultEvent, ToolSpec, type ToolsBoundEvent, Trust, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertRunStateShape, awaitingOf, blobUsableBy, budgetTruncate, bytesToBase64, checkImageRefs, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, foldedUserMedia, forkSession, hydrateImageRefs, imageRefNotFound, inputDrafts, isClientTool, isCompaction, isContentPart, isImageRef, isModelOutput, isPauseCode, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, keptBy, lastRunMarker, lastToolsBound, markUntrusted, markUntrustedText, mediaRefsOf, memoryStore, needsUntrustedMark, normalizeToolOutput, outcomeUnknownText, pauseDetailOf, pausedStateOf, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderFoldedUserMedia, renderToolChangeNote, replayTurns, resolveSocketContributions, resolveSocketPause, roughTokenEstimate, runLoop, runStatusOf, serializeRunState, signRunState, splitTurns, startedToolCallIds, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolStartedAt, toolsBoundDrafts, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter, withStartedAt };
1223
+ export { ApprovalDecisionInput, AwaitingCall, BUILTIN_APPROVAL_POLICY, BlobMeta, BlobStore, type BudgetTruncateOptions, BudgetUsagePayload, type CheckImageRefsContext, type CompactionEvent, ContentPart, type ContributionConfig, CoreEventDraft, CoreEventOf, DEFAULT_CUT_TO_RATIO, DEFAULT_MAX_TURNS, DEFAULT_MODEL_INVISIBLE_TYPES, DEFAULT_RESERVE_RATIO, type DecodedToolArguments, type DefaultChainOptions, ErrorPayload, Event, EventDraft, EventLog, EventSchemaRegistry, type FoldOptions, type FoldedToolResult, type FoldedToolResultOptions, type FoldedUserMedia, type ForkOptions, HANDOFF_PROVENANCE_SOURCE, HandoffIntent, type HydrateImageRefsContext, IMAGE_REF_ID_MAX, INPUT_DRAFT_TYPES, INTERRUPTED_IN_PROGRESS_TEXT, INTERRUPTED_NOT_EXECUTED_TEXT, type ImageRefCache, ImageRefPart, InMemoryBlobStore, InMemoryEventLog, InMemoryMemoryStore, InMemoryRunLease, Interruption, LoopConfig, LoweringError, type LoweringErrorCode, MAX_TURNS_PAUSE_CODE, MODEL_FAILED_NOT_EXECUTED_TEXT, MODEL_INTERRUPTED_NOT_EXECUTED_TEXT, type MarkedContent, MemoryStore, ModelRef, OUTCOME_UNKNOWN_TEXT, PAUSE_CODE_RE, PauseReason, type ProjectOptions, ProjectionBudget, ProjectionContext, ProjectionResult, ProjectionStats, ProjectionStrategy, REINS_VERSION, RUN_MARKER_TYPES, ReadOptions, type ReadTimelineOptions, type RenderManifestOptions, type ReplayOptions, type ReplayResult, type ReplayedTurn, type ResolvedContributions, RunLease, RunResult, RunStateError, type RunStateErrorCode, type RunStatus, RunStop, STOPPED_IN_PROGRESS_TEXT, STOPPED_NOTE, STOPPED_NOT_EXECUTED_TEXT, SUPPORTED_IMAGE_MIMES, SerializedRunState, type SocketPauseInterruption, type SocketPauseResolution, type StopTexts, StoreError, type StoreErrorCode, Stores, SubagentInterruption, type SubagentPause, type SubagentPauseDetail, type ThresholdSummarizer, TokenEstimator, Tool, ToolCallEvent, type ToolNamesDiff, ToolResult, ToolResultEvent, ToolSpec, type ToolsBoundEvent, Trust, UNTRUSTED_CLOSE_TAG, UNTRUSTED_TAG, type VisibilityFilterOptions, assertDecisionsAwaitApproval, assertRunStateShape, awaitingOf, blobUsableBy, budgetTruncate, bytesToBase64, checkImageRefs, computeConfigHash, computeModelDigest, computePendingDigest, computePendingToolsDigest, covers, decodeToolArgumentsText, defaultProjectionChain, defaultThresholdSummary, deferredToolSpecOf, defineTool, diffToolNames, digestArgs, errorMessageOf, escapeUntrustedText, estimateBudgetOf, estimateTextTokens, estimateTotal, foldCompactions, foldedToolResults, foldedUserMedia, forkSession, handoffOpeningDrafts, hydrateImageRefs, imageRefNotFound, inputDrafts, isClientTool, isCompaction, isContentPart, isImageRef, isModelInvisibleByDefault, isModelOutput, isPauseCode, isPinNote, isReplayable, isStopReason, isStopped, isSubagentPause, isSupportedImageMime, keptBy, lastRunMarker, lastToolsBound, markUntrusted, markUntrustedText, mediaRefsOf, memoryStore, needsUntrustedMark, normalizeToolOutput, outcomeUnknownText, pauseDetailOf, pausedStateOf, pendingToolCalls, project, readEvents, readTimeline, reinjectPins, renderFoldedToolResults, renderFoldedUserMedia, renderToolChangeNote, replayTurns, resolveReserveTokens, resolveSocketContributions, resolveSocketPause, roughTokenEstimate, runLoop, runStatusOf, serializeRunState, signRunState, splitTurns, startedToolCallIds, stopTextsOf, subagentPause, supersededIds, toolBatchOf, toolCallArgumentsMeta, toolResultTrust, toolSpecOf, toolStartedAt, toolsBoundDrafts, unsupportedImageText, untrustedOpenTag, untrustedSourceOf, unwrapToolArguments, uuidv7, validateResume, verifyRunState, visibilityFilter, withStartedAt };