@reinsjs/brain 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,1247 @@
1
+ import { Tool, TurnContext, MaybePromise, Socket, CompactionPayload, Event, FoldedToolResult, ToolContext, ContentPart, EventDraft, MemoryStore, CoreEventOf, SkillSource } from '@reinsjs/core';
2
+
3
+ /**
4
+ * approval —— 审批与权限模块(技术方案 §9.7,B7)。
5
+ *
6
+ * 循环本身只有一处兜底:工具声明 `needsApproval` 且没有 Socket 做主时转审批暂停(P1)。本模块把"谁可以不问就跑、
7
+ * 谁要先问人、谁一律不许"做成宿主可配的 **Policy 管线**,在 `beforeTool` 里跑:
8
+ *
9
+ * 未知工具 → deny | deny 段 → ask 段(规则,再看工具自己的 needsApproval)→ allow 段 → 三段都没命中按 `unmatched`
10
+ *
11
+ * 每段内首个命中的规则即定;段与段的先后就是"deny 不可被 allow 覆盖"的落点。三种结论怎么落到时间线:
12
+ * - **deny**:emit 一条 `approval_decision(approved=false, by=规则 id, reason)`,再返回 `{ block }`,循环把留痕排在
13
+ * `tool_result(isError)` 之前 —— 谁拒的、为什么,日志里有据可查;模型看到的是带策略名的错误结果。
14
+ * - **ask**:返回 `{ defer: { policyId, summary } }`,循环 append `approval_request` 并以 paused(approval) 返回,
15
+ * 宿主批完用 `decisions` 续跑(T10)。宿主已批准的调用再次经过管线时 defer 会被循环略过、直接执行,deny 仍然生效。
16
+ * - **allow**:返回 "proceed",不留事件 —— 时间线里 tool_call → tool_result 已经是完整记录,每次放行都多记一条只会撑大日志。
17
+ *
18
+ * fail-closed:任何规则求值抛错、`needsApproval` 函数抛错,都按 deny 处理(by = 出错的规则 id),并经 `warn` 告警。
19
+ *
20
+ * 位置:管线跑在哪一步由 Socket 注册顺序决定。**建议放在 sockets 末尾**(至少放在会 rewrite 入参的钩子之后):
21
+ * 这样判定的是真正要执行的入参;前面的钩子只可能收紧(block / defer),不存在"钩子放行绕过策略"的路径。
22
+ */
23
+
24
+ /** 规则看到的一次调用 */
25
+ interface PolicyCall {
26
+ toolCallId: string;
27
+ name: string;
28
+ /** 经前面钩子改写后的入参(循环保证后续钩子看到的是最终入参) */
29
+ args: unknown;
30
+ /** 工具定义;未知工具为 undefined(管线在规则之前就拒了,规则里见不到) */
31
+ tool: Tool | undefined;
32
+ }
33
+ interface PolicyRule {
34
+ /** 策略标识:ask 时进 `approval_request.policyId`,deny 时进 `approval_decision.by` */
35
+ id: string;
36
+ /** 是否命中。抛错按 fail-closed 记 deny */
37
+ match(call: PolicyCall, ctx: TurnContext): MaybePromise<boolean>;
38
+ /** ask 时给审批人看的一句话摘要;缺省 `name(入参 JSON)`(按 maxSummaryChars 截断) */
39
+ summary?(call: PolicyCall): string;
40
+ /** deny 时给模型的说明;缺省 "策略 <id> 不允许调用 <name>" */
41
+ reason?: string;
42
+ }
43
+ /** 规则的简写:字符串即工具名 glob(`*` 匹配任意字符),id 为 `name:<pattern>` */
44
+ type PolicyRuleSpec = PolicyRule | string;
45
+ type PolicyVerdict = "deny" | "ask" | "allow";
46
+ interface ApprovalOptions {
47
+ /** 一律不许(首匹配即定) */
48
+ deny?: readonly PolicyRuleSpec[];
49
+ /** 先问人 */
50
+ ask?: readonly PolicyRuleSpec[];
51
+ /** 不问就跑 */
52
+ allow?: readonly PolicyRuleSpec[];
53
+ /**
54
+ * 三段都没命中时怎么办。缺省 "byRisk":按工具声明的 risk —— low → allow;medium / high / 未声明 → ask
55
+ * (只读工具放行、写与副作用先问人,§14)。"ask" / "deny" 则一律如此。
56
+ */
57
+ unmatched?: "byRisk" | "ask" | "deny";
58
+ /** 审批摘要里入参 JSON 的最大字符数,超出截断并加省略号。缺省 200 */
59
+ maxSummaryChars?: number;
60
+ /** 规则提示:缺省内置英文文案;传字符串替换;false 则不碰系统提示 */
61
+ rules?: string | false;
62
+ /** 策略求值异常(fail-closed 记 deny)的告警出口。缺省 console.warn */
63
+ warn?: (message: string) => void;
64
+ }
65
+ declare const APPROVAL_SOCKET_NAME = "approval";
66
+ declare const DEFAULT_MAX_SUMMARY_CHARS = 200;
67
+ /** 管线自带结论的策略标识(进 approval_request.policyId / approval_decision.by) */
68
+ declare const APPROVAL_POLICY_IDS: {
69
+ /** 模型调了工具表里没有的工具 */
70
+ readonly unknownTool: "approval.unknown_tool";
71
+ /** 三段都没命中、unmatched="deny" */
72
+ readonly unmatched: "approval.unmatched";
73
+ /** 三段都没命中、按 risk 兜底:`approval.risk.<low|medium|high|undeclared>` */
74
+ readonly risk: (level: Tool["risk"]) => string;
75
+ /** 入参没过工具自己的 validate:不问人、放行给循环以"入参不合法"拒掉(执行不会发生) */
76
+ readonly invalidArgs: "approval.invalid_args";
77
+ };
78
+ /** 管线的一次结论(导出供测试与宿主自己的 Socket 复用) */
79
+ type PolicyOutcome = {
80
+ verdict: "allow";
81
+ policyId: string;
82
+ } | {
83
+ verdict: "ask";
84
+ policyId: string;
85
+ summary: string;
86
+ } | {
87
+ verdict: "deny";
88
+ policyId: string;
89
+ reason: string;
90
+ };
91
+ /** 工具名 glob → 正则:只认 `*`,其余字符按字面匹配,整串匹配 */
92
+ declare function globToRegExp(pattern: string): RegExp;
93
+ /** 把简写规范成规则 */
94
+ declare function normalizeRule(spec: PolicyRuleSpec): PolicyRule;
95
+ /** 缺省摘要:`name(入参 JSON)`,入参过长截断 */
96
+ declare function defaultSummary(call: PolicyCall, maxChars: number): string;
97
+ interface Stages {
98
+ deny: readonly PolicyRule[];
99
+ ask: readonly PolicyRule[];
100
+ allow: readonly PolicyRule[];
101
+ }
102
+ /**
103
+ * 跑一遍管线,得到结论。纯函数(不碰时间线),便于单测与宿主在别处复用。
104
+ * 任何规则抛错 → deny(fail-closed),by 为出错规则的 id,原因带上错误信息;出错会经 onError 通知一次。
105
+ */
106
+ declare function evaluatePolicy(call: PolicyCall, ctx: TurnContext, stages: Stages, opts: {
107
+ unmatched: NonNullable<ApprovalOptions["unmatched"]>;
108
+ maxSummaryChars: number;
109
+ onError?: (rule: string, err: unknown) => void;
110
+ }): Promise<PolicyOutcome>;
111
+ /** 审批模块:deny → ask → allow 管线 + 规则提示。建议放在 sockets 末尾 */
112
+ declare function approval(options?: ApprovalOptions): Socket;
113
+
114
+ /**
115
+ * approval 模块给模型的规则提示(技术方案 §9.7)。
116
+ *
117
+ * 只说模型需要知道的两件事:有些调用要等人批(run 会暂停,不是出错);被拒的调用不要换个写法再试。
118
+ * 英文:与其他模块的规则片段一致,规则提示对英语模型最稳;宿主可用 `rules` 选项替换或关闭。
119
+ */
120
+ declare const APPROVAL_RULES = "Tool permissions:\n- Some tool calls require human approval before they run. When that happens the run pauses until a person decides; this is normal, not an error. Do not repeat the call while it is waiting.\n- A call may be denied by policy. A denied call returns an error naming the policy; do not retry it with the same or a disguised input. Explain what you were trying to do and ask the user how to proceed.";
121
+
122
+ /**
123
+ * budget —— 预算模块(技术方案 §9.8,B8)。
124
+ *
125
+ * 循环自己只有一条粗兜底(轮数 `maxTurns`),每轮记一条 `budget_usage`。本模块把宿主关心的五维上限做成边界:
126
+ * contextTokens(单次请求送进模型的上下文大小)、totalTokens(本次 run 累计输入 + 输出)、turns、toolCalls、wallMs。
127
+ *
128
+ * 做法:`onTurnEnd` 里对照 `ctx.budget`(循环在模型调用后已更新 tokensSpent / wallMs / lastUsage),任一维 **用量 ≥ 上限**
129
+ * 即返回 `{ pause: { reason: "budget", note } }`,循环 append `run_paused(reason=budget)` 并以 paused 返回,note 进
130
+ * `Interruption` 给宿主看。只在模型本轮还要继续(有工具调用)时拦:模型已经收尾作答的轮,循环本来就要停,
131
+ * 把一个自然结束的 run 改成"暂停"只会让宿主续跑一个没事可做的会话。
132
+ *
133
+ * 上限是**每次 run** 的:宿主续跑(同一 sessionId 再起 runLoop)即视为再批一份预算,`ctx.budget` 从零计。
134
+ * 会话级 / 用户级配额由宿主聚合 `budget_usage` 事件自己做(§9.8:库不做配额);要"整个会话不超过 X"就把 X 减去
135
+ * 已用量再传进来。模型在触顶前收到的提醒来自 perception 模块(同一份 limits 传给它,它按最紧一维报余量档位)。
136
+ *
137
+ * 注册顺序:onTurnEnd 第一个给意见的 Socket 说了算。本模块应排在 handoff 之后(模型已决定交接就让它交接,
138
+ * 新会话由宿主再起时照样受限),其余位置不敏感 —— compact 的暂停同样是 budget 原因。
139
+ */
140
+
141
+ /** 五维上限;给了哪几维就只查哪几维。与 perception 的 limits 是同一个形状 */
142
+ interface BudgetLimits {
143
+ /** 单次请求送进模型的上下文大小(input + cacheRead + cacheWrite),按最近一次请求的真实用量 */
144
+ contextTokens?: number;
145
+ /** 本次 run 累计 token(输入 + 输出,不含缓存读写 —— 与 TurnContext.budget.tokensSpent 同口径) */
146
+ totalTokens?: number;
147
+ /** 本次 run 的模型轮数 */
148
+ turns?: number;
149
+ /** 本次 run 真正执行过的工具调用数 */
150
+ toolCalls?: number;
151
+ /** 距 run 开始的毫秒数 */
152
+ wallMs?: number;
153
+ }
154
+ type BudgetDimension = keyof BudgetLimits;
155
+ interface BudgetHit {
156
+ dimension: BudgetDimension;
157
+ used: number;
158
+ limit: number;
159
+ }
160
+ interface BudgetOptions {
161
+ limits: BudgetLimits;
162
+ /** 暂停说明(给宿主看,进 Interruption.note);缺省英文一句话列出触顶的维度 */
163
+ note?: (hits: readonly BudgetHit[]) => string;
164
+ }
165
+ declare const BUDGET_SOCKET_NAME = "budget";
166
+ /** 上限必须是正的有限数;构造期就拒绝,免得跑起来才发现"0 上限"把一切都拦了 */
167
+ declare function assertLimits(limits: BudgetLimits): void;
168
+ /** 各维当前用量;contextTokens 没有真实用量(还没请求过)时为 undefined */
169
+ declare function budgetUsedOf(budget: TurnContext["budget"]): Record<BudgetDimension, number | undefined>;
170
+ /** 触顶的维度(用量 ≥ 上限),按 BudgetLimits 字段顺序。纯函数 */
171
+ declare function checkBudget(budget: TurnContext["budget"], limits: BudgetLimits): BudgetHit[];
172
+ declare function defaultBudgetNote(hits: readonly BudgetHit[]): string;
173
+ declare function budget(opts: BudgetOptions): Socket;
174
+
175
+ /**
176
+ * 从"模型本轮看到的视图 + 模型给的入参"算出一条 compaction 事件的内容。纯函数,无副作用,可单测、可回放。
177
+ *
178
+ * 切点规则与投影裁剪(core/projection/truncate.ts)同一口径,否则降级层会产出厂商拒收的请求:
179
+ * 1. 只在模型轮的边界切:`keepRecentTurns = n` 表示保留视图里最后 n 个模型轮(含各自之后的工具结果、用户消息、说明),
180
+ * n = 0 即折叠本轮之前可见的一切。当前正在执行的这一轮不在视图里,天然完整保留 ——
181
+ * Anthropic 要求带 tool_use 的 assistant 轮连同 thinking 一起原样回放,拆开就是 400。
182
+ * 2. seq 封闭:被覆盖的 seq 区间不能碰到保留部分。视图里唯一可能破坏它的是旧 compaction(它的 seq 大于自己覆盖的范围,
183
+ * 位置却排在前面)。这种旧摘要不并入本次范围,留在视图里继续可见;只有保留部分为空(全部折叠)时才把它们一起吸收。
184
+ * 3. 被覆盖事件里的 pin 说明与旧 compaction 已保留的事件继续幸存,记进 pinsKept —— 与 fold / truncate 的幸存定义一致;
185
+ * 被后来说明 `supersedes` 取代的不幸存(B3:模型替换过的 pin、宿主抽取式 pin 的旧值)。
186
+ * 4. 被折叠范围内**最近的一条用户消息**缺省也幸存。真模型实测(spikes/b2-compact-live):用户说"先整理,然后做 X",
187
+ * 模型先整理、把这条消息也折了进去,摘要里只写"接着做第二部分",整理完反问"第二部分要做什么"。模型没法复述
188
+ * 它还没开始处理的指令,所以这条由库保住;长任务里它就是原始任务陈述,留着只多一条消息。
189
+ * 5. (E3c)被折叠的工具结果列成清单附在摘要之后(`seq N tool(arguments) — 大小`),模型之后可用 recall 按 seq 取回。
190
+ * 摘要是模型的取舍,清单是"事实上还在的东西";两个模型族的实测都把复核过的字段值整理成了一句结论,
191
+ * 清单让它至少知道去哪拿。脑子自己的工具(compact / pin / recall / fetch_blob 的回执)不列,只是噪音。
192
+ */
193
+
194
+ interface CompactArgs {
195
+ summary: string;
196
+ keep: string[];
197
+ keepRecentTurns: number;
198
+ }
199
+ /** 模型入参 → 规范形态;不合法抛 RangeError(循环会把它作为 isError 的结果告知模型) */
200
+ declare function parseCompactArgs(raw: unknown): CompactArgs;
201
+ /** 缺省不列进清单的工具:脑子自己的回执与切片,取回没有意义 */
202
+ declare const MANIFEST_DEFAULT_EXCLUDE: ReadonlySet<string>;
203
+ declare const MANIFEST_HEADING = "Folded tool results (bring one back verbatim with recall({ seq })):";
204
+ interface ManifestOptions {
205
+ /** 最多列几条,其余折成一行。缺省 80 */
206
+ maxItems?: number;
207
+ /** 不列的工具名;缺省 MANIFEST_DEFAULT_EXCLUDE */
208
+ exclude?: ReadonlySet<string>;
209
+ }
210
+ /**
211
+ * 摘要正文 + 要点清单 + 被折叠工具结果清单,合成 compaction.summary。
212
+ * 要点单列是为了模型(和 eval)一眼看到"什么被明确保留了";结果清单让它知道"什么还能拿回来"。
213
+ */
214
+ declare function renderCompactionSummary(args: Pick<CompactArgs, "summary" | "keep">, folded?: readonly FoldedToolResult[], manifest?: ManifestOptions): string;
215
+ type CompactPlan = {
216
+ ok: true;
217
+ payload: CompactionPayload;
218
+ /** 被折叠的原事件(不含旧 compaction) */
219
+ folded: Event[];
220
+ /** 一并吸收的旧摘要 */
221
+ absorbed: Event[];
222
+ /** 保留在视图里的最近模型轮数(可能比请求的多) */
223
+ keptTurns: number;
224
+ /** 列进摘要的被折叠工具结果(E3c) */
225
+ manifest: FoldedToolResult[];
226
+ } | {
227
+ ok: false;
228
+ reason: string;
229
+ };
230
+ interface PlanOptions {
231
+ /**
232
+ * 发起本次整理的 tool_call 事件 id。正常路径下它还不在视图里(本轮的模型输出在视图快照之后);
233
+ * 续跑补齐 pending 调用时它**在**视图里 —— 那一轮必须整个保留,否则 tool_call 被折掉、稍后 append 的
234
+ * tool_result 成了孤儿,厂商拒收。
235
+ */
236
+ protectCallId?: string;
237
+ /** 被折叠范围内最近的一条用户消息原样幸存(进 pinsKept)。缺省 true,见文件头第 4 条 */
238
+ keepLatestUserMessage?: boolean;
239
+ /** 完整时间线:取代关系(system_note.supersedes)在这里找,取代者可能已不在视图里。缺省只看视图 */
240
+ timeline?: readonly Event[];
241
+ /** 被折叠工具结果清单:false 不列;对象调条数与排除名单。缺省列、上限 80 条 */
242
+ manifest?: false | ManifestOptions;
243
+ }
244
+ declare function planCompaction(visible: readonly Event[], args: CompactArgs, opts?: PlanOptions): CompactPlan;
245
+ /**
246
+ * 按轮切分完整时间线:一轮 = 开轮时追加的兜底 compaction / 说明 + 模型输出 + 之后到下一轮之前的一切(工具结果、
247
+ * 模型自决的 compaction、用量、用户插话)。第一轮模型输出之前的开场事件(用户消息等)单独成一段。
248
+ * 与投影的 splitTurns 不同:那是给视图切轮边界用的,这里要的是"每一轮期间发生了什么"。
249
+ */
250
+ declare function segmentTimelineByTurn(timeline: readonly Event[]): Event[][];
251
+ /**
252
+ * 连续整理计数:从最近一轮往前,连续每轮都含 compaction(模型自决或阈值兜底)的这些轮里 compaction 的总数;
253
+ * 遇到第一轮没有 compaction 的就停。传入的是本轮开始时的时间线快照,所以数的是"之前的轮",本轮的另算。
254
+ */
255
+ declare function trailingCompactionRun(timeline: readonly Event[]): number;
256
+
257
+ /**
258
+ * compact —— 自主整理模块(技术方案 §9.2,B2)。
259
+ *
260
+ * 五件事:
261
+ * 1. **工具** `compact({ summary, keep, keepRecentTurns? })`:模型自己决定何时整理、留什么(宪法一)。
262
+ * 工具本身是静态贡献(Socket.tools),整个 run 不变,续跑补齐 pending 时也在场。
263
+ * 2. **规则提示**:静态 systemPrompt 片段(rules.ts),告诉模型什么时候该整理、什么时候别整理。
264
+ * 3. **阈值兜底**:模型没整理、上下文超过裁剪目标时,core 投影链的 budgetTruncate 会机械折叠最旧的轮并记
265
+ * `compaction(decidedBy=threshold)`;本模块不重复实现,只把它算进连续计数。触发点 = contextLimit − reserveTokens,
266
+ * 宿主经 LoopConfig.projection.reserveTokens 调;perception 会把这个点告诉模型。
267
+ * 4. **连续上限**:连着整理(模型自决 + 阈值兜底合计)达到 maxConsecutive 次仍没有一轮"正常"工作,
268
+ * 说明卡死了(折叠后仍放不下、或模型在反复整理)→ onTurnEnd 返回 pause(budget) 交宿主处理。
269
+ * 5. **取回**(E3c):摘要下面列出被折叠的每条工具结果(seq + 工具 + 入参),`recall({ seq })` 工具逐字取回一条。
270
+ * 整理丢细节是机制的代价(模型按自己的重要性判断留东西),清单与取回让丢掉的东西有路可回,见 recall.ts。
271
+ *
272
+ * 为什么真正的工作在 afterTool 而不在工具的 execute 里:算覆盖范围需要"模型本轮看到的视图"(ctx.events)与
273
+ * 完整时间线,这些只有 TurnContext 有、ToolContext 没有;工具自己 readTimeline 又会绕开宿主的注册表(ext.* 事件会读不出)。
274
+ * 所以 execute 只占位,afterTool 拿着 ctx 算出 compaction、emit 进日志(循环在 tool_result 之前 append),再把结果换成回执。
275
+ * 这样模块没有跨轮状态:本轮的临时记录挂在 WeakMap<TurnContext> 上,轮结束即随 ctx 回收,两个并发 run 也互不干扰。
276
+ *
277
+ * 日志顺序:… tool_call(compact) → compaction → tool_result(回执)。compaction 的 seq 大于它覆盖的一切,
278
+ * 所以下一轮投影的折叠策略会把范围内的事件盖掉、摘要放到原位置。这也是唯一被允许打掉 prompt cache 的动作(§9.1 约束 5)。
279
+ */
280
+
281
+ interface CompactOptions {
282
+ /**
283
+ * 连续整理次数上限(模型自决 + 阈值兜底合计),达到即 pause(budget)。缺省 3。
284
+ * 只在模型本轮还要继续(有工具调用)时生效:模型已经收尾作答的轮不拦。
285
+ */
286
+ maxConsecutive?: number;
287
+ /**
288
+ * 规则提示:缺省用内置英文文案;传字符串替换;传 false 则本模块不碰系统提示(宿主自己把 COMPACT_RULES 放进去)。
289
+ */
290
+ rules?: string | false;
291
+ /**
292
+ * 被折叠工具结果清单(E3c):缺省列在摘要之后、最多 80 条;传 false 不列;传对象调条数与排除名单。
293
+ * 关掉清单时缺省文案里关于清单的说法就不成立了,宿主应一并换 rules。
294
+ */
295
+ manifest?: false | ManifestOptions;
296
+ /** 是否给模型 recall 取回工具(E3c)。缺省 true;false 时清单照列,只是模型自己取不回(宿主另有读法时用) */
297
+ recall?: boolean;
298
+ }
299
+ declare const COMPACT_SOCKET_NAME = "compact";
300
+ declare const DEFAULT_MAX_CONSECUTIVE_COMPACTIONS = 3;
301
+ declare const COMPACT_INPUT_SCHEMA: {
302
+ readonly type: "object";
303
+ readonly properties: {
304
+ readonly summary: {
305
+ readonly type: "string";
306
+ readonly description: "Your summary of the folded conversation: goals and constraints, decisions and why, current state, next steps.";
307
+ };
308
+ readonly keep: {
309
+ readonly type: "array";
310
+ readonly items: {
311
+ readonly type: "string";
312
+ };
313
+ readonly description: "Facts that must survive verbatim (identifiers, numbers, user constraints). Empty if none.";
314
+ };
315
+ readonly keepRecentTurns: {
316
+ readonly type: "integer";
317
+ readonly minimum: 0;
318
+ readonly description: "How many of the most recent model turns (with their tool results) to leave unfolded. Default 0 = fold everything before the current turn.";
319
+ };
320
+ };
321
+ readonly required: readonly ["summary", "keep"];
322
+ readonly additionalProperties: false;
323
+ };
324
+ declare function compact(opts?: CompactOptions): Socket;
325
+ /** 给宿主或测试:某条事件是不是模型自决的整理 */
326
+ declare function isModelCompaction(e: Event): boolean;
327
+
328
+ /**
329
+ * recall —— 按 seq 逐字取回一条被折叠的工具结果(E3c,技术方案 §9.2)。
330
+ *
331
+ * 为什么要有它:整理是模型自己的取舍,两个模型族的实测都把"复核过的字段值"整理成了"状态正常"一句结论,
332
+ * 被问到时只能说"摘要里没留,可以重查"——而重查要宿主工具、且查到的是现在的值不是当时的值。原件本来就在
333
+ * 日志里(宪法二),缺的只是一条读回去的路。compact 的摘要下面列出被折叠的每条结果(`seq N tool(arguments)`),
334
+ * 这个工具把其中一条原样拿回来,与 spill 的 fetch_blob 是同一个思路:让模型看见、给它能力,不替它决定。
335
+ *
336
+ * 读的是**本会话**的日志(ctx.log.read(ctx.sessionId)),别的会话一律当不存在。fork 出的会话(eval 探针)复制了
337
+ * 事件且保留 seq,所以摘要里的 seq 在子会话照样有效。原始读取不过注册表:只看 core 稳定字段(type / seq / payload),
338
+ * 与 spill.referencedHere 同一理由。
339
+ *
340
+ * 取回的内容再次进入上下文,是模型有意识的花费;结果超过外溢上限时由 spill 模块照常处理(recall 不在它的排除名单里)。
341
+ * 已外溢的原件事件里只剩预览,这里不复述预览,而是指向 blob 让模型用 fetch_blob 读全文。
342
+ */
343
+
344
+ declare const RECALL_INPUT_SCHEMA: {
345
+ readonly type: "object";
346
+ readonly properties: {
347
+ readonly seq: {
348
+ readonly type: "integer";
349
+ readonly minimum: 1;
350
+ readonly description: "The `seq` shown next to the folded tool result in a summary's list.";
351
+ };
352
+ };
353
+ readonly required: readonly ["seq"];
354
+ readonly additionalProperties: false;
355
+ };
356
+ interface RecallArgs {
357
+ seq: number;
358
+ }
359
+ declare function parseRecallArgs(raw: unknown): RecallArgs;
360
+ declare function recallResult(args: RecallArgs, ctx: ToolContext): Promise<{
361
+ content: ContentPart[];
362
+ isError: boolean;
363
+ }>;
364
+ declare function recallTool(): Tool;
365
+
366
+ /**
367
+ * compact 模块给模型看的文字(技术方案 §9.2):工具说明与规则提示。
368
+ *
369
+ * 规则提示是"一等交付物":什么时候整理、什么时候别整理,是模型判断,但判断需要经验 —— 这段话就是经验。
370
+ * 它作为 Socket 的静态 systemPrompt 片段追加在宿主系统提示之后,整个 run 逐字不变(prompt cache 约束 3);
371
+ * 每轮变化的读数(上下文用了多少)由 perception 模块以 system_note 追加在末尾,两者分工不重叠。
372
+ *
373
+ * 用英文写:进的是模型上下文,不是给人看的日志。宿主要换措辞,传 compact({ rules }) 或 rules: false 自己放。
374
+ */
375
+ declare const COMPACT_TOOL_NAME = "compact";
376
+ /**
377
+ * 取回工具(E3c)。整理会丢细节是机制本身的代价(两个模型族都把"复核过的字段值"整理成了"状态正常"这一句结论);
378
+ * 与其教模型该留什么,不如让它知道**什么还能拿回来**:摘要下面列出被折叠的每条工具结果,`recall({ seq })` 逐字取回。
379
+ * 原件本来就在日志里(宪法二),这只是给模型一条读回去的路,与 spill 的 fetch_blob 同理。
380
+ */
381
+ declare const RECALL_TOOL_NAME = "recall";
382
+ declare const COMPACT_TOOL_DESCRIPTION: string;
383
+ declare const RECALL_TOOL_DESCRIPTION: string;
384
+ declare const COMPACT_RULES = "## Managing your context window\nYou have a `compact` tool that folds earlier conversation into a summary you write. Runtime notes titled \"Runtime context status\" tell you how full the window is.\n- Compact when a sub-task is finished or the trajectory has converged and the folded details are no longer needed verbatim. Do it at a natural pause, not while acting on something.\n- Do not compact in the middle of a derivation, while a problem is still unresolved, or when you feel stuck: you would lose exactly the details you still need.\n- The summary replaces everything it folds, including earlier summaries. Carry forward the user's goals and constraints, decisions made and why, the current state, and what comes next. List each fact that must survive in `keep`. The most recent user message and pinned notes survive verbatim on their own; check the pins still say what you need.\n- Keep exact values, not just conclusions: identifiers, status and enum fields you verified, numbers, dates, error codes. \"Checked, all ENABLE\" loses the field values themselves.\n- Nothing folded is lost for good: under each summary the harness lists the folded tool results as `seq N tool(arguments)`, and `recall({ seq })` brings one back verbatim. When asked about a detail your summary did not keep, recall the result that contained it instead of guessing or saying it is gone.\n- If you never compact, the harness folds the oldest turns mechanically once the window nears its limit. Its summary is worse than yours, but it lists the folded tool results the same way.";
385
+
386
+ /**
387
+ * handoff —— 会话交接模块(技术方案 §9.5,B5)。
388
+ *
389
+ * 交接的机械部分在 core 循环里(T9):`onTurnEnd` 返回 `{ handoff }` → 旧会话 append `core.handoff`,
390
+ * 新会话 seq 1 = `system_note(kind=host, 摘要)`、之后是脑子带来的开场事件、最后 `user_message(触发消息)`,
391
+ * 调 `cfg.onHandoff(from, to)`,返回 `handoff` 态;续跑新会话由宿主再起一次 runLoop。本模块只让模型能用它(宪法一):
392
+ *
393
+ * 1. **工具** `handoff({ summary, nextSteps, triggerMessage?, reason? })`,静态贡献 + 规则提示 `HANDOFF_RULES`。
394
+ * 工作在 afterTool:解析入参、把意图记在本轮(WeakMap<TurnContext>,轮结束即回收),把结果换成回执;
395
+ * 本轮其余工具调用照常执行,onTurnEnd 时才真正交接 —— 交接只能在轮次边界发生,且不该打断同轮的其他工作。
396
+ * 2. **开场说明**由本模块排版:摘要 + 编号的下一步。`handoff.summary` 与新会话 seq 1 的文字是同一段,
397
+ * 回放旧会话就能看到新会话拿到了什么。
398
+ * 3. **pin 跟着走**:模型当前可见、未被取代的 `system_note(kind=pin)`(宿主的和模型的)原样复制成新会话的开场事件
399
+ * (`HandoffIntent.opening`,保留 meta.pin 与 actor,provenance 指回旧事件),在新会话里仍是 pin:穿越那边的折叠,
400
+ * pins() Socket 见同名同文的宿主 pin 也不会再注入一条。方案里"首条 system_note 携带 summary 与 pins"落成
401
+ * "摘要一条 + pin 各一条",因为 pin 塞进摘要正文就不再是 pin 了。
402
+ * 4. **触发消息**缺省取模型当前可见的最后一条用户消息:长任务里那通常就是原始任务陈述;模型可以显式给别的。
403
+ *
404
+ * 注意注册顺序:onTurnEnd 第一个给意见的 Socket 说了算,本模块应排在 compact 等可能返回 pause 的 Socket 之前,
405
+ * 否则模型调了 handoff、拿到了回执,本轮却被别的模块暂停 —— 回执会撒谎。
406
+ *
407
+ * 不带走的:外溢到 BlobStore 的结果(fetch_blob 按会话隔离,见 §17)、旧会话的其他历史。规则提示里已告知模型。
408
+ */
409
+
410
+ interface HandoffOptions {
411
+ /** 是否把当前可见、未被取代的 pin 复制到新会话开头。缺省 true */
412
+ carryPins?: boolean;
413
+ /** 规则提示:缺省内置英文文案;传字符串替换;false 则不碰系统提示 */
414
+ rules?: string | false;
415
+ }
416
+ declare const HANDOFF_SOCKET_NAME = "handoff";
417
+ /** 模型没给 reason 时记在 handoff 事件里的值 */
418
+ declare const DEFAULT_HANDOFF_REASON = "model_decision";
419
+ declare const HANDOFF_INPUT_SCHEMA: {
420
+ readonly type: "object";
421
+ readonly properties: {
422
+ readonly summary: {
423
+ readonly type: "string";
424
+ readonly description: "Everything the next session must know, written for someone who has not seen this conversation: goal in the user's words, what is done, decisions and why, exact state of unfinished work, identifiers it will need.";
425
+ };
426
+ readonly nextSteps: {
427
+ readonly type: "array";
428
+ readonly items: {
429
+ readonly type: "string";
430
+ };
431
+ readonly description: "Concrete actions for the next session, in order. One action per item.";
432
+ };
433
+ readonly triggerMessage: {
434
+ readonly type: "string";
435
+ readonly description: "The message the new session should act on. Omit to reuse the latest user message from this session.";
436
+ };
437
+ readonly reason: {
438
+ readonly type: "string";
439
+ readonly description: "Why you are handing off (e.g. context_pressure, phase_boundary). Recorded in the timeline.";
440
+ };
441
+ };
442
+ readonly required: readonly ["summary", "nextSteps"];
443
+ readonly additionalProperties: false;
444
+ };
445
+ interface HandoffArgs {
446
+ summary: string;
447
+ nextSteps: string[];
448
+ triggerMessage?: string;
449
+ reason?: string;
450
+ }
451
+ declare function parseHandoffArgs(raw: unknown): HandoffArgs;
452
+ /** 新会话 seq 1 的文字(也是旧会话 handoff.summary):摘要 + 编号的下一步 */
453
+ declare function composeHandoffNote(args: Pick<HandoffArgs, "summary" | "nextSteps">): string;
454
+ /** 模型当前可见、未被取代的 pin,按可见顺序复制成新会话的开场草稿 */
455
+ declare function carriedPins(ctx: TurnContext): EventDraft[];
456
+ /** 模型当前可见的最后一条用户消息的文字;没有则 undefined */
457
+ declare function lastVisibleUserMessage(events: readonly Event[]): string | undefined;
458
+ /**
459
+ * 上一次 run 里模型调了 handoff、拿到了"已安排交接"的回执,但那一轮被打断(审批暂停、宿主中止),
460
+ * 没能走到 onTurnEnd,内存里的意图随之丢失(R2)。续跑补齐 pending 后循环会再调 onTurnEnd,
461
+ * 这里从日志把入参找回来:最后一条成功的 handoff 回执之后,既没有 `core.handoff`(说明还没交接),
462
+ * 也没有新的模型输出(说明没有开新的一轮、旧意图仍然有效)。任一不满足即 undefined。
463
+ */
464
+ declare function unfinishedHandoffArgs(timeline: readonly Event[]): HandoffArgs | undefined;
465
+ declare function handoff(opts?: HandoffOptions): Socket;
466
+
467
+ /**
468
+ * handoff 模块给模型看的文字(技术方案 §9.5):工具说明与规则提示。
469
+ *
470
+ * 经验不是指令:什么时候该换一个新会话继续,判断在模型。作为 Socket 的静态 systemPrompt 片段
471
+ * 追加在宿主提示之后,整个 run 逐字不变(§9.1 约束 3)。英文:进的是模型上下文。
472
+ */
473
+ declare const HANDOFF_TOOL_NAME = "handoff";
474
+ declare const HANDOFF_TOOL_DESCRIPTION: string;
475
+ declare const HANDOFF_RULES = "## Handing off to a new session\nYou have a `handoff` tool that ends this session and starts a fresh one carrying only your summary, next steps, and the pinned notes.\n- Hand off when the history is mostly spent context rather than useful memory: a long task has reached a clean phase boundary, or compaction has already happened several times and the summaries are what you actually work from. Prefer compacting while the current context is still worth keeping.\n- Do not hand off in the middle of a step, with tool results you have not read yet, or when the user is waiting for an answer to a direct question. Answer first.\n- The summary is the whole memory of the next session: state the goal in the user's words, what is done and what was decided and why, the exact state of anything half-finished, and identifiers (paths, ids, numbers) the next session will need. Put one concrete action per item in `nextSteps`.\n- Outputs stored as blobs in this session are not readable from the new one; copy what matters into the summary.";
476
+
477
+ /**
478
+ * 带行号的文件视图(memory 的 `view` 与 skills 的 `skill_read` 共用,S1 抽出):
479
+ * 行号格式对齐 Anthropic memory 工具参考实现(6 位右对齐 + 制表符);模型没指定范围时按字符上限**按行**截断,
480
+ * 并提示用范围续读。
481
+ *
482
+ * 两种上限语义(`enforceLimit`):
483
+ * - memory(缺省 false):截断只在模型没指定范围时做——指定了范围就是它自己在分页;单行超长也整行给
484
+ * - skills(true):`maxChars` 是硬上限。带范围也照样截、提示下一段从哪续;单行超过上限的按字符切开并说明。
485
+ * 硬上限才能让 `skill_read` 对 spill 声明一个可证明的 token 上界(发前审查:`range: [1, -1]` 与单行 200k 字符都能绕过软上限)
486
+ */
487
+ declare const byteLength: (s: string) => number;
488
+ /** 人读的大小:与参考实现一致用 K / M,1024 进制 */
489
+ declare function humanSize(bytes: number): string;
490
+
491
+ /**
492
+ * memory 工具的六个 command:入参解析 + 在 MemoryStore 上执行(技术方案 §9.6)。
493
+ *
494
+ * 形状与返回文案对齐 Anthropic `memory_20250818` 的参考实现(platform.claude.com/docs/.../memory-tool),
495
+ * 让模型已有的使用习惯直接迁移;差异只在几处更诚实或更安全的地方:
496
+ * - `create` 对已存在的文件是**覆盖**(工具说明本来就写"creates or overwrites"),回执里说明替换了旧内容
497
+ * - `view` 超长文件按字符上限截断并提示用 `view_range` 续读;写类操作有单文件大小上限
498
+ * - 目录在 KV 式存储里是隐含的(有以它为前缀的文件就算存在),所以 `create` 到目录路径、对目录 `str_replace` 都报错
499
+ *
500
+ * 全部是纯的存储操作,不知道 Socket / 事件 / 命名空间:命名空间由 memory.ts 用 `bindMemoryFs` 包一层。
501
+ * `rename` 目录与 `delete` 目录不是原子的(MemoryStore 没有事务);顺序都是"先写后删",中途失败最多多出重复,不会丢。
502
+ */
503
+
504
+ type MemoryOp = "view" | "create" | "str_replace" | "insert" | "delete" | "rename";
505
+ type MemoryCommand = {
506
+ command: "view";
507
+ path: string;
508
+ viewRange?: [number, number];
509
+ } | {
510
+ command: "create";
511
+ path: string;
512
+ fileText: string;
513
+ } | {
514
+ command: "str_replace";
515
+ path: string;
516
+ oldStr: string;
517
+ newStr: string;
518
+ } | {
519
+ command: "insert";
520
+ path: string;
521
+ insertLine: number;
522
+ insertText: string;
523
+ } | {
524
+ command: "delete";
525
+ path: string;
526
+ } | {
527
+ command: "rename";
528
+ oldPath: string;
529
+ newPath: string;
530
+ };
531
+ declare const MEMORY_COMMANDS: readonly MemoryOp[];
532
+ declare const MEMORY_INPUT_SCHEMA: {
533
+ readonly type: "object";
534
+ readonly properties: {
535
+ readonly command: {
536
+ readonly type: "string";
537
+ readonly enum: readonly MemoryOp[];
538
+ readonly description: "The operation to perform.";
539
+ };
540
+ readonly path: {
541
+ readonly type: "string";
542
+ readonly description: "Absolute path under /memories. Used by every command except rename.";
543
+ };
544
+ readonly view_range: {
545
+ readonly type: "array";
546
+ readonly items: {
547
+ readonly type: "integer";
548
+ };
549
+ readonly minItems: 2;
550
+ readonly maxItems: 2;
551
+ readonly description: "view only: [start_line, end_line], 1-indexed and inclusive; end_line -1 means to the end of the file.";
552
+ };
553
+ readonly file_text: {
554
+ readonly type: "string";
555
+ readonly description: "create: the full content of the file.";
556
+ };
557
+ readonly old_str: {
558
+ readonly type: "string";
559
+ readonly description: "str_replace: the exact text to replace; it must occur exactly once in the file.";
560
+ };
561
+ readonly new_str: {
562
+ readonly type: "string";
563
+ readonly description: "str_replace: the replacement text. Omit to delete old_str.";
564
+ };
565
+ readonly insert_line: {
566
+ readonly type: "integer";
567
+ readonly minimum: 0;
568
+ readonly description: "insert: insert after this line number; 0 inserts at the top of the file.";
569
+ };
570
+ readonly insert_text: {
571
+ readonly type: "string";
572
+ readonly description: "insert: the text to insert.";
573
+ };
574
+ readonly old_path: {
575
+ readonly type: "string";
576
+ readonly description: "rename: the current path.";
577
+ };
578
+ readonly new_path: {
579
+ readonly type: "string";
580
+ readonly description: "rename: the new path; it must not exist yet.";
581
+ };
582
+ };
583
+ readonly required: readonly ["command"];
584
+ readonly additionalProperties: false;
585
+ };
586
+ /** 解析并校验模型给的入参:路径在这里就规范化(防穿越),字段缺失或类型不对抛 RangeError */
587
+ declare function parseMemoryCommand(raw: unknown): MemoryCommand;
588
+ /** 命令执行看到的存储:路径都是模型可见形态(/memories/...),命名空间在这层之下 */
589
+ interface MemoryFs {
590
+ read(path: string): Promise<string | null>;
591
+ write(path: string, content: string): Promise<void>;
592
+ delete(path: string): Promise<void>;
593
+ /** 目录下任意深度的全部文件路径,字典序 */
594
+ listUnder(dir: string): Promise<string[]>;
595
+ }
596
+ /**
597
+ * 把 MemoryStore 绑到一个命名空间前缀上:存储里的键 = prefix + 模型可见路径。
598
+ * 多用户宿主用它给每个 principal 一块独立的 /memories(`memory({ namespace })`)。
599
+ */
600
+ declare function bindMemoryFs(store: MemoryStore, prefix?: string): MemoryFs;
601
+ interface MemoryLimits {
602
+ /** 单文件上限(UTF-8 字节):create / str_replace / insert 写出的结果超过即拒绝 */
603
+ maxFileBytes: number;
604
+ /** view 单次最多返回的字符数(正文部分);超过按行截断并提示用 view_range 续读 */
605
+ maxViewChars: number;
606
+ }
607
+ interface MemoryOutcome {
608
+ /** 给模型看的文字 */
609
+ text: string;
610
+ isError: boolean;
611
+ /** 成功时的留痕要素(memory_op 载荷);失败为 undefined */
612
+ op?: {
613
+ op: MemoryOp;
614
+ path: string;
615
+ toPath?: string;
616
+ bytes?: number;
617
+ };
618
+ }
619
+ declare function executeMemoryCommand(fs: MemoryFs, cmd: MemoryCommand, limits: MemoryLimits): Promise<MemoryOutcome>;
620
+
621
+ /**
622
+ * memory —— 记忆模块(技术方案 §9.6,B6)。
623
+ *
624
+ * 给模型一个 `memory` 工具:形状与 Anthropic `memory_20250818` 对齐(view / create / str_replace / insert / delete / rename,
625
+ * 路径限定在 `/memories`),后端是宿主实现的 MemoryStore(core §5)。库只做三件事(宪法一):
626
+ * - **给它能力**:六个 command 在 MemoryStore 上执行(commands.ts),文案对齐参考实现,模型已有的习惯直接迁移
627
+ * - **给它边界**:每个路径先规范化再碰存储(paths.ts,拒绝 `..` / 反斜杠 / 百分号编码,只认 `/memories` 之下);
628
+ * 单文件大小与单次 view 的字符上限;宿主可用 `namespace` 给每个 principal 一块独立的 /memories
629
+ * - **给它记录**:每次成功的读写留一条 `memory_op` 事件(模型不可见,见投影过滤),供配额统计、回放、eval
630
+ * 记什么、什么时候记,判断在模型;规则提示只给经验(rules.ts)。
631
+ *
632
+ * 为什么是自定义工具而不是 Anthropic 的原生 `memory_20250818` 类型:降级层 pi-ai 不支持 provider-defined 工具,
633
+ * 且 reins 要跨模型族;同名同义的 JSON Schema 已足够让模型认出这是它熟悉的工具。
634
+ *
635
+ * 没有 MemoryStore 时按 §5"缺则不注册":静态贡献是按运行环境算一次的函数(core `StaticContribution`),
636
+ * 工具与规则都不出现,并告警一次 —— 而不是注册一个一用就报错的工具,那会让模型每轮都撞墙。
637
+ */
638
+
639
+ interface MemoryOptions {
640
+ /**
641
+ * 命名空间:返回加在存储键前面的前缀,模型看到的路径不变。多用户宿主用它隔离:
642
+ * `namespace: (ctx) => \`/users/${ctx.principal?.id ?? "anonymous"}\``。缺省无前缀(全体共享一块 /memories)
643
+ */
644
+ namespace?: (ctx: ToolContext) => string;
645
+ /** 单文件上限(UTF-8 字节)。缺省 64 KiB:记忆是给未来的自己看的摘记,不是数据仓库 */
646
+ maxFileBytes?: number;
647
+ /** view 单次最多返回的字符数(正文部分),超过按行截断并提示用 view_range 续读。缺省 16000(与 Anthropic 工具说明一致) */
648
+ maxViewChars?: number;
649
+ /** 规则提示:缺省内置英文文案;传字符串替换;false 则不碰系统提示 */
650
+ rules?: string | false;
651
+ /** 没有 MemoryStore 时的告警出口(每个 memory() 实例只告警一次)。缺省 console.warn */
652
+ warn?: (message: string) => void;
653
+ }
654
+ declare const MEMORY_SOCKET_NAME = "memory";
655
+ declare const DEFAULT_MAX_FILE_BYTES: number;
656
+ declare const DEFAULT_MAX_VIEW_CHARS = 16000;
657
+ declare function memory(opts?: MemoryOptions): Socket;
658
+
659
+ /** 目录 a 是否包含路径 b(b 在 a 之下,不含相等) */
660
+ declare function isUnder(dir: string, path: string): boolean;
661
+
662
+ declare const MEMORY_ROOT = "/memories";
663
+ /** 路径长度上限:防止把整段内容当路径塞进来 */
664
+ declare const MAX_MEMORY_PATH_LENGTH = 1024;
665
+ /**
666
+ * 把模型给的路径规范化成 `/memories[/segment...]`;不合法则抛 RangeError(消息面向模型,会以 isError 结果返回)。
667
+ * @param field 出错时提示的入参名(rename 有 old_path / new_path 两个)
668
+ */
669
+ declare function resolveMemoryPath(raw: unknown, field?: string): string;
670
+
671
+ /**
672
+ * memory 模块给模型看的文字(技术方案 §9.6):工具说明与规则提示。
673
+ *
674
+ * 工具名与六个 command 与 Anthropic 的 `memory_20250818` 同名同义,模型对这个形状已有训练:
675
+ * 先看 /memories、把进展写进去、假定随时会被打断。规则提示按 §9.6 的三句经验写:任务开始先查记忆;
676
+ * 只记未来有用的;不记能从代码或文档推出的。这是"经验"不是"指令":记什么、什么时候记,判断在模型。
677
+ * 作为 Socket 的静态 systemPrompt 片段追加在宿主提示之后,整个 run 逐字不变(§9.1 约束 3)。英文:进的是模型上下文。
678
+ */
679
+ declare const MEMORY_TOOL_NAME = "memory";
680
+ declare const MEMORY_TOOL_DESCRIPTION: string;
681
+ declare const MEMORY_RULES = "## Memory\nYou have a `memory` tool: a directory `/memories` that persists across sessions, while everything else in this conversation is forgotten when it ends.\n- Before starting a task, `view` `/memories` and read the files that look relevant. Earlier sessions may have left progress, decisions, or lessons there.\n- Record what a future session would need and could not re-derive: the goal in the user's words, decisions and the reasons behind them, open questions, lessons from mistakes, where things are. Do not store what can be read from the code or documents, transient state, or secrets and credentials.\n- Assume interruption: your context may be reset at any moment. Update memory as you make progress, not only at the end.\n- Keep it organized: small files with clear names, rewrite a fact when it changes instead of appending a second version, delete what is no longer true.";
682
+
683
+ /**
684
+ * 档位离散化。感知说明里的每个数字都先落到一个档位再给模型看,理由(技术方案 §9.1):
685
+ * 精确值每轮都变,会让每轮都多一条说明;档位一段会话只变三四次,说明条数与 token 都可控。
686
+ */
687
+ interface Tier {
688
+ /** 档位序号,0 起;eval 与回放按它对比,不必解析标签 */
689
+ level: number;
690
+ /** 给模型看的标签 */
691
+ label: string;
692
+ }
693
+ /** 边界必须严格升序,否则档位没有意义;在构造期就拒绝 */
694
+ declare function assertAscending(name: string, bounds: readonly number[]): void;
695
+ /**
696
+ * 连续量(比例、token 数):<b0 | b0–b1 | … | ≥bn。
697
+ * 值恰在边界上归入上一档(≥),与"85%+ 才算高"直觉一致。
698
+ */
699
+ declare function rangeTier(value: number, bounds: readonly number[], fmt: (n: number) => string): Tier;
700
+ /** 计数量(轮数、条数):≤b0 | b0+1–b1 | … | >bn */
701
+ declare function countTier(value: number, bounds: readonly number[]): Tier;
702
+ declare const percent: (ratio: number) => string;
703
+ /** 10000 → 10k,1500000 → 1.5M;小于 1000 原样 */
704
+ declare function compactNumber(n: number): string;
705
+
706
+ /**
707
+ * 从本轮上下文算出感知读数(技术方案 §9.1 列的几项)。纯函数:同一 TurnContext 同一读数。
708
+ *
709
+ * 数据来源刻意区分两处:
710
+ * - `ctx.events`(模型本轮将看到的投影):算"未折叠历史有多长"、"有几条外溢结果可取"—— 这些是模型视角的量;
711
+ * - `ctx.timeline`(完整日志):算"整理过几次"、"本会话累计花了多少 token"—— 这些是会话全局的量。
712
+ */
713
+
714
+ /** 预算上限:与 budget 模块(§9.8)同一个形状,宿主把同一份 limits 传给两个模块。给了哪几维就只按那几维算余量 */
715
+ type PerceptionLimits = BudgetLimits;
716
+ type LimitDimension = BudgetDimension;
717
+ interface PerceptionReading {
718
+ /** 上下文窗口使用率档位(校准后的本轮上下文估算 / contextLimit,见 contextOverheadOf) */
719
+ contextUsage: Tier;
720
+ /**
721
+ * 校准用的固定开销(token):上一次请求的真实上下文 − 当时的投影估算,即系统提示、工具表、thinking 等估算不含的部分。
722
+ * 没有可对照的请求时为 0。精确值,只进 meta 不进文字
723
+ */
724
+ contextOverhead: number;
725
+ /** 阈值兜底的触发点(裁剪目标 / contextLimit),如 "85%"。配置不变它就不变 */
726
+ autoFoldAt: string;
727
+ /** 当前可见、未被折叠的模型轮数档位(一轮 = 连续的 thinking / text / tool_call) */
728
+ unfoldedTurns: Tier;
729
+ /** 本会话至今的整理次数(模型自决 + 阈值兜底)。只在整理时变,而整理本身已经改了前缀 */
730
+ compactions: number;
731
+ /** 本会话累计消耗 token(输入 + 缓存读写 + 输出,按 budget_usage 事件累加)档位 */
732
+ sessionTokens: Tier;
733
+ /** 可见的外溢工具结果条数档位;level 0 即没有 */
734
+ spilledResults: Tier;
735
+ /** 配置了上限时:最紧的那一维的剩余比例档位 */
736
+ budgetRemaining?: Tier & {
737
+ tightest: LimitDimension;
738
+ };
739
+ }
740
+ interface ReadingThresholds {
741
+ usage: readonly number[];
742
+ turns: readonly number[];
743
+ tokens: readonly number[];
744
+ spills: readonly number[];
745
+ remaining: readonly number[];
746
+ }
747
+ /** 与投影裁剪同一口径:连续的模型输出算一轮 */
748
+ declare function countModelTurns(events: readonly Event[]): number;
749
+ /** 累加 budget_usage:输入、缓存读、缓存写、输出全算,反映的是"花了多少",不是"上下文多大" */
750
+ declare function sumSessionTokens(timeline: readonly Event[]): number;
751
+ /**
752
+ * 估算与真实之间的固定开销(B8,关闭 §17 的 B2 实测发现)。
753
+ *
754
+ * 投影只数模型可见事件的正文,系统提示、工具表、thinking 签名块等都不在内,真实 input 可高出一倍。
755
+ * 这些多出来的部分在一个 run 里基本是常量(系统提示与工具表整轮不变),所以用**加法**校准而不是比例:
756
+ * 比例会随历史变长把误差放大(100k 时翻倍成 200k),加法只补那块固定的开销。
757
+ * 数据来自日志最后一条同时带 tokens 与 contextEstimate 的 budget_usage:真实上下文 = input + cacheRead + cacheWrite。
758
+ */
759
+ declare function contextOverheadOf(timeline: readonly Event[]): number;
760
+ interface ReadingOptions {
761
+ /** 用上一请求的真实用量校准上下文估算。缺省 true;关掉则只按投影估算(偏低) */
762
+ calibrate?: boolean;
763
+ }
764
+ declare function readPerception(ctx: TurnContext, thresholds: ReadingThresholds, limits?: PerceptionLimits, opts?: ReadingOptions): PerceptionReading;
765
+
766
+ /**
767
+ * perception —— 感知模块(技术方案 §9.1,B1)。
768
+ *
769
+ * 做法:beforeModel 里算一份档位读数,渲染成文字;若模型当前可见的最后一条感知说明与之逐字相同就什么都不做,
770
+ * 否则 emit 一条 `system_note(kind=perception)`。循环把它 append 到时间线末尾并让模型本轮看到。
771
+ *
772
+ * prompt cache 的五条约束在这里的落实:
773
+ * 1. 只追加在末尾:emit 走循环的 append,seq 在最新 user 消息之后、模型回答之前;前面的历史一字不改。
774
+ * 2. 旧说明不删不隐藏:本模块从不改投影;旧说明随历史留着,整理时一起折叠。
775
+ * 3. 系统提示与工具表稳定:beforeModel 永远返回 undefined,不动 systemPrompt / tools。
776
+ * 4. 断点不自造:靠 pi-ai 的既有断点;降级层负责在改写 system_note 时保住它(lowering-pi/system-note.ts)。
777
+ * 5. 唯一改前缀的是 compaction,那是 compact 模块(B2)的事。
778
+ *
779
+ * "每档只变一次":所有数值先离散成档位,读数不变 → 文字不变 → 不追加。判重比较的是文字而非读数,
780
+ * 因为宿主自定义 render 后,只要模型看到的东西没变就没必要多一条。
781
+ */
782
+
783
+ interface PerceptionOptions {
784
+ /** 上下文使用率档位边界(占窗口比例)。缺省 [0.5, 0.7, 0.85] → <50% / 50%–70% / 70%–85% / ≥85% */
785
+ usageTiers?: readonly number[];
786
+ /** 未折叠模型轮数档位边界。缺省 [5, 15, 40] → ≤5 / 6–15 / 16–40 / >40 */
787
+ turnTiers?: readonly number[];
788
+ /** 会话累计 token 档位边界。缺省 [1e4, 5e4, 2e5, 1e6] */
789
+ tokenTiers?: readonly number[];
790
+ /** 外溢结果条数档位边界(0 单独一档)。缺省 [3, 10] → 0 / 1–3 / 4–10 / >10 */
791
+ spillTiers?: readonly number[];
792
+ /** 预算余量比例档位边界。缺省 [0.05, 0.2, 0.5] → <5% / 5%–20% / 20%–50% / ≥50% */
793
+ remainingTiers?: readonly number[];
794
+ /** 本次 run 的上限;给了才报"余量"。与 budget 模块(B8)传同一份 */
795
+ limits?: PerceptionLimits;
796
+ /** 用上一请求的真实用量校准上下文使用率(B8)。缺省 true */
797
+ calibrate?: boolean;
798
+ /** 自定义措辞 / 语言;必须是纯函数(同一读数同一文字),否则每轮都会追加 */
799
+ render?: (reading: PerceptionReading) => string;
800
+ }
801
+ declare const DEFAULT_PERCEPTION_THRESHOLDS: ReadingThresholds;
802
+ declare const PERCEPTION_SOCKET_NAME = "perception";
803
+ type PerceptionNote = CoreEventOf<"core.system_note">;
804
+ /** 模型当前可见的最后一条感知说明;没有(从未注入或已被折叠)返回 undefined */
805
+ declare function lastVisiblePerceptionNote(visible: readonly Event[]): PerceptionNote | undefined;
806
+ declare function perception(opts?: PerceptionOptions): Socket;
807
+
808
+ /**
809
+ * 读数 → 给模型看的文字。只陈述事实,不下指令:什么时候整理、要不要交接是模型的判断(宪法一),
810
+ * 规则提示属于 compact 模块(B2)且放在稳定的系统提示里,不在这条每次变档才出现的说明里。
811
+ *
812
+ * 用英文写:这段话进的是模型上下文而不是给人看的日志,英文 token 更省,且各家模型都熟。
813
+ * 宿主要换措辞或语言,给 perception() 传自己的 render。
814
+ */
815
+
816
+ declare function renderPerception(r: PerceptionReading): string;
817
+
818
+ /**
819
+ * pins —— 幸存契约模块(技术方案 §9.3,B3)。
820
+ *
821
+ * 幸存契约本身在 core:`system_note(kind=pin)` 穿越折叠与阈值裁剪自动幸存、重排到覆盖它的摘要之后,
822
+ * `compaction.pinsKept` 记录每次整理保住了谁(fold.ts / pins.ts / truncate.ts,T6)。本模块只做两件事,让契约有人用:
823
+ *
824
+ * 1. **宿主声明** `pins: PinSpec[]`:静态文本("不要动生产库")或从时间线抽取的函数("最近一条带'必须'的用户消息")。
825
+ * beforeModel 里算出每条的文字,与模型**当前可见**的同名 pin 逐字比对:相同什么都不做;不同(首轮、内容变了、
826
+ * 或被折叠掉了)就 emit 一条新的 `system_note(kind=pin, actor=system)` 追加到末尾,并用 `supersedes` 指向该 spec
827
+ * 在完整时间线里的上一条 —— 旧值到下一次折叠时不再幸存,否则抽取式 pin 每变一次就永久多一条。
828
+ * 永不返回补丁:只追加、不改前缀(§9.1 prompt cache 约束)。
829
+ * 2. **模型工具** `pin({ text, replaces? })`:模型自己决定什么值得钉(宪法一)。工作在 afterTool 里做(要视图判重与找被替换者,
830
+ * ToolContext 没有视图),emit `system_note(kind=pin, actor=model, parentId=tool_call)`,再把结果换成回执。
831
+ * `replaces` 只能指向模型自己钉的(meta.pin.source = "model"):宿主钉的是宿主的约束,模型动不了。
832
+ *
833
+ * 说明的 `meta.pin` 记来源与 spec 名(不进模型上下文),判重与 supersede 靠它,回放 / eval 也靠它分辨谁钉的。
834
+ * 没有 unpin:append-only 日志里"撤销"只能表达为"被新说明取代",模型要撤销就钉一条当前有效的说法去替换旧的。
835
+ */
836
+
837
+ /**
838
+ * 宿主声明的一条 pin:
839
+ * - 字符串:静态文本,名字就是文本本身
840
+ * - `{ name, text }`:静态文本,命名(换措辞时名字不变,旧文字会被取代而不是并存)
841
+ * - `{ name, extract }`:每轮从上下文抽取;返回 undefined / 空串表示"这轮没新说法",上一条继续生效
842
+ */
843
+ type PinSpec = string | {
844
+ name: string;
845
+ text: string;
846
+ } | {
847
+ name: string;
848
+ extract: (ctx: TurnContext) => string | undefined;
849
+ };
850
+ interface PinsOptions {
851
+ /** 宿主声明的 pin。名字必须唯一 */
852
+ pins?: readonly PinSpec[];
853
+ /** 是否给模型 `pin` 工具。缺省 true */
854
+ tool?: boolean;
855
+ /** 单条 pin 的最大字数(写进工具说明与 schema 的"声明上限")。缺省 500:pin 是永久占用,长内容该进摘要或记忆 */
856
+ maxTextLength?: number;
857
+ /**
858
+ * 校验时在声明上限之上再放的容差比例,缺省 0.2(声明 500 → 实际 600 才拒)。
859
+ * E3c 实测:上限写进说明与 schema 后,Sonnet 5 仍写出 502 / 545 / 558 字符 —— 模型瞄着上限写、数不准自己的字数,
860
+ * 差几个字就拒掉只是白费一轮。声明值仍是 500,模型照旧往 500 以内凑;容差只吃掉数错的那一点。传 0 则严格按声明值。
861
+ */
862
+ overshootTolerance?: number;
863
+ /** 规则提示:缺省内置英文文案;传字符串替换;false 则不碰系统提示 */
864
+ rules?: string | false;
865
+ }
866
+ declare const PINS_SOCKET_NAME = "pins";
867
+ declare const DEFAULT_MAX_PIN_TEXT_LENGTH = 500;
868
+ declare const DEFAULT_PIN_OVERSHOOT_TOLERANCE = 0.2;
869
+ /** system_note.meta.pin 的形状:谁钉的、宿主 spec 名 */
870
+ interface PinMeta {
871
+ source: "host" | "model";
872
+ spec?: string;
873
+ }
874
+ type PinNote = CoreEventOf<"core.system_note">;
875
+ /** 入参 schema;`maxLength` 随 maxTextLength 变,模型下笔前就看得到上限(E3c) */
876
+ declare function pinInputSchema(maxTextLength: number): {
877
+ readonly type: "object";
878
+ readonly properties: {
879
+ readonly text: {
880
+ readonly type: "string";
881
+ readonly maxLength: number;
882
+ readonly description: `The note to pin, one or two sentences (at most ${number} characters). It will be shown verbatim after every future summary.`;
883
+ };
884
+ readonly replaces: {
885
+ readonly type: "string";
886
+ readonly description: "Exact text of one of your earlier pinned notes that this one supersedes. Omit to add a new note.";
887
+ };
888
+ };
889
+ readonly required: readonly ["text"];
890
+ readonly additionalProperties: false;
891
+ };
892
+ declare const PIN_INPUT_SCHEMA: {
893
+ readonly type: "object";
894
+ readonly properties: {
895
+ readonly text: {
896
+ readonly type: "string";
897
+ readonly description: "The note to pin, one or two sentences. It will be shown verbatim after every future summary.";
898
+ };
899
+ readonly replaces: {
900
+ readonly type: "string";
901
+ readonly description: "Exact text of one of your earlier pinned notes that this one supersedes. Omit to add a new note.";
902
+ };
903
+ };
904
+ readonly required: readonly ["text"];
905
+ readonly additionalProperties: false;
906
+ };
907
+ interface PinArgs {
908
+ text: string;
909
+ replaces?: string;
910
+ }
911
+ declare function parsePinArgs(raw: unknown, maxTextLength?: number, overshootTolerance?: number): PinArgs;
912
+ declare function isPinNoteEvent(e: Event): e is PinNote;
913
+ declare function pinMetaOf(e: PinNote): PinMeta | undefined;
914
+ /** 某个宿主 spec 最后一条 pin(从后往前找) */
915
+ declare function lastHostPin(events: readonly Event[], spec: string): PinNote | undefined;
916
+ /** 模型钉的、文字完全相同的一条(从后往前找) */
917
+ declare function findModelPin(events: readonly Event[], text: string): PinNote | undefined;
918
+ declare function pins(opts?: PinsOptions): Socket;
919
+
920
+ /**
921
+ * pins 模块给模型看的文字(技术方案 §9.3):工具说明与规则提示。
922
+ *
923
+ * 与 compact 的规则一样,这是"经验"不是"指令":什么值得钉、什么不值得,判断在模型。
924
+ * 作为 Socket 的静态 systemPrompt 片段追加在宿主提示之后,整个 run 逐字不变(prompt cache 约束 3)。
925
+ * 用英文写:进的是模型上下文。宿主要换措辞,传 pins({ rules }) 或 rules: false 自己放。
926
+ */
927
+ declare const PIN_TOOL_NAME = "pin";
928
+ /**
929
+ * 工具说明带上单条上限(E3c):Sonnet 5 在 5/9 格把长清单塞进 pin、撞 500 字符被拒后再重试,白费一轮。
930
+ * 上限写在说明与 schema 的 maxLength 里,模型下笔前就知道;分条的办法也一并说明。
931
+ */
932
+ declare function pinToolDescription(maxTextLength: number): string;
933
+ /** 缺省上限(500)下的说明文字 */
934
+ declare const PIN_TOOL_DESCRIPTION: string;
935
+ declare const PIN_RULES = "## Pinned notes\nNotes marked kind=\"pin\" survive compaction verbatim and reappear right after each summary, so the pins are what you can rely on after folding. You have a `pin` tool to add one.\n- Pin what must not drift: the user's explicit constraints, the goal in the user's words, identifiers and numbers you will need later. One or two sentences each.\n- Do not pin what you can re-derive, large content, or the current step. Every pin costs context on every turn until it is replaced.\n- When a pinned fact changes, pin the new version with `replaces` set to the old note's exact text instead of adding a second note. Notes pinned by the host are the host's constraints and cannot be replaced.\n- Before compacting, check the pins still say what you need; whatever is not pinned or in your summary is only reachable by recalling the folded tool result it came from.";
936
+
937
+ /**
938
+ * skills 模块的字面常量,单独成文件、零依赖:`@reinsjs/brain/node` 的 fsSkillSource 也要用同一份 `/skills`,
939
+ * 而它不能把整个 skills 模块拖进 `dist/node.js`("同一个值在两处必须同一份",踩坑记录)。
940
+ */
941
+ /** 载体里技能的键前缀缺省值:`${root}/<name>/SKILL.md` */
942
+ declare const DEFAULT_SKILLS_ROOT = "/skills";
943
+ /** 每个技能目录里的入口文件名(Agent Skills 规范固定,不可配) */
944
+ declare const SKILL_FILE_NAME = "SKILL.md";
945
+ /** 技能名:小写字母 / 数字 / 连字符,64 字符内,须与目录名一致(Agent Skills 规范) */
946
+ declare const SKILL_NAME_RE: RegExp;
947
+
948
+ declare const MAX_SKILL_DESCRIPTION_CHARS = 1024;
949
+ interface SkillFrontmatter {
950
+ name: string;
951
+ description: string;
952
+ /** 头部之后的正文(不含分隔线) */
953
+ body: string;
954
+ }
955
+ type ParsedSkill = {
956
+ ok: true;
957
+ skill: SkillFrontmatter;
958
+ } | {
959
+ ok: false;
960
+ reason: string;
961
+ };
962
+ /**
963
+ * 解析一份 SKILL.md。头部必须以 `---` 起、以 `---` 收(各占一行,允许 CRLF)。
964
+ */
965
+ declare function parseSkillMarkdown(content: string): ParsedSkill;
966
+
967
+ /**
968
+ * 内联技能载体:把 SKILL.md(与附件)以字符串预填成一个只读 `SkillSource`(技术方案 §9.9)。
969
+ *
970
+ * 给两种宿主用:
971
+ * - 没有文件系统的运行时(Workers):构建期把 SKILL.md bundle 成字符串
972
+ * - 技能正文来自别处(如 AdRate CLI 的 `skills read` 输出):拼好头部后直接喂进来
973
+ * 键的布局与其它载体一致:`${root}/<name>/SKILL.md`、`${root}/<name>/<附件相对路径>`。零依赖、无 I/O。
974
+ *
975
+ * 对象键就是技能目录名,必须匹配技能名规范且与 SKILL.md 头部的 `name` 一致——不合规的键在这里就抛错,
976
+ * 而不是拼出一个菜单正则永远匹配不上的键让技能静默消失(发前审查抓到 `"a/b"` / `""` / `"../x"` 三种都会无声丢失)。
977
+ */
978
+
979
+ /** 一个技能:直接给 SKILL.md 全文,或给 `{ "SKILL.md": ..., "reference.md": ... }` 一组文件 */
980
+ type InlineSkill = string | Readonly<Record<string, string>>;
981
+ interface InlineSkillsOptions {
982
+ /** 键前缀,须与 `skills({ root })` 一致;缺省 `/skills` */
983
+ root?: string;
984
+ }
985
+ declare function inlineSkills(skills: Readonly<Record<string, InlineSkill>>, opts?: InlineSkillsOptions): SkillSource;
986
+
987
+ /**
988
+ * skills 模块给模型看的文字(技术方案 §9.9):工具说明、规则提示、菜单排版。
989
+ *
990
+ * 渐进式披露的两层:系统提示里只有菜单(每个技能的 name + description),正文要模型自己用 `skill_read` 翻——
991
+ * 读哪份、什么时候读是模型的判断(宪法一),规则只给经验:有相关技能先读再动手、读过的不重读、附件按需读。
992
+ * 作为 Socket 的静态 systemPrompt 片段追加在宿主提示之后,整个 run 逐字不变(§9.1 约束 3)。英文:进的是模型上下文。
993
+ */
994
+ declare const SKILL_READ_TOOL_NAME = "skill_read";
995
+ declare const SKILL_READ_TOOL_DESCRIPTION: string;
996
+ /** 规则提示的经验部分;菜单由 renderSkillMenu 排在其后 */
997
+ declare const SKILL_RULES = "## Skills\nSkills are instruction documents the host wrote for specific kinds of work. Each entry below is only a name and a one-line description; the instructions themselves are not loaded until you read them.\n- Before starting on a task a skill covers, read it with `skill_read({ name })` and follow it. Read a skill's supporting files (`path`) only when the skill points you to them.\n- A skill you have already read in this conversation stays in your context; do not read it again unless it has been folded away.\n- Do not guess what an unread skill says. If no skill fits the task, proceed without one.";
998
+ interface SkillMenuEntry {
999
+ name: string;
1000
+ description: string;
1001
+ }
1002
+ /** 菜单:每项一行 `- name: description`(description 里的换行折成空格,菜单保持一行一项) */
1003
+ declare function renderSkillMenu(entries: readonly SkillMenuEntry[]): string;
1004
+ declare const SKILL_READ_INPUT_SCHEMA: {
1005
+ readonly type: "object";
1006
+ readonly properties: {
1007
+ readonly name: {
1008
+ readonly type: "string";
1009
+ readonly description: "The skill's name, exactly as listed under Skills.";
1010
+ };
1011
+ readonly path: {
1012
+ readonly type: "string";
1013
+ readonly description: "File to read inside the skill's folder, relative to it. Default SKILL.md.";
1014
+ };
1015
+ readonly range: {
1016
+ readonly type: "array";
1017
+ readonly items: {
1018
+ readonly type: "integer";
1019
+ };
1020
+ readonly minItems: 2;
1021
+ readonly maxItems: 2;
1022
+ readonly description: "[start_line, end_line], 1-indexed and inclusive; end_line -1 means to the end of the file.";
1023
+ };
1024
+ };
1025
+ readonly required: readonly ["name"];
1026
+ readonly additionalProperties: false;
1027
+ };
1028
+
1029
+ /**
1030
+ * skills —— 技能模块(技术方案 §9.9,S1):Agent Skills(SKILL.md)的加载与渐进式披露。
1031
+ *
1032
+ * 库只做两件事(宪法一):
1033
+ * - **让它看见**:系统提示里一份菜单(每个技能的 name + description),run 起步从 `SkillSource` 读一次、run 内不变。
1034
+ * 菜单进 configHash:暂停期间技能的 **name / description** 变了,续跑按配置漂移处理(与工具表同规则);
1035
+ * 只改 SKILL.md **正文**不动菜单、不进 hash,续跑照常,模型下次 `skill_read` 读到的是新正文
1036
+ * - **给它能力**:`skill_read({ name, path?, range? })` 翻书,正文以 `tool_result` 进时间线而不塞 system——
1037
+ * compact 折叠、`recall` 取回、spill 外溢零改动自动适用(宪法二)
1038
+ * 读哪份、什么时候读是模型的判断;规则提示只给经验(rules.ts)。
1039
+ *
1040
+ * 载体接口不新造:`SkillSource = Pick<MemoryStore, "list" | "read">`,任何 MemoryStore 都是数据库载体,
1041
+ * 文件系统载体 `fsSkillSource(dir)` 在 `@reinsjs/brain/node`,字符串预填用 `inlineSkills({...})`。
1042
+ * 布局 `${root}/<name>/SKILL.md` + 同目录附件,`root` 缺省 `/skills`;同一个 MemoryStore 同时给 memory(/memories)
1043
+ * 与本模块(/skills)时,模型的 memory 工具够不到技能——技能对模型天然只读、对宿主可写。
1044
+ * 因此 `root` **不得**与 `/memories` 相同或互为前缀(构造期拒绝):否则模型用 memory 工具写一份 SKILL.md,下一 run 就进了
1045
+ * 系统提示、读出来还是 system 信任——正是下面禁止的事。
1046
+ *
1047
+ * trust 模型:技能是宿主配置的说明书,视同系统提示可信,`skill_read` 声明 `resultTrust: "system"`,结果不套 untrusted 标记。
1048
+ * 这条豁免的代价由宿主承担——技能正文来自哪(本地目录、数据库、AdRate 这样的网络 CLI)就信谁;宿主若给模型任何能写进
1049
+ * 技能载体的工具,等于让模型给自己写 system 信任的说明书。第三期若允许模型写技能,模型写的必须回到 untrusted。
1050
+ * 同一份正文被 compact 折叠后经 `recall` 取回、或被 spill 外溢后经 `fetch_blob` 取回时是 untrusted(那两个工具没有豁免)——
1051
+ * 方向保守,不是 bug;正常装法下 skill_read 的结果不会被 spill 外溢(见 resultPolicy)。
1052
+ *
1053
+ * 缺 source、source 下没有一份合规的 SKILL.md、或宿主自己的工具表里已有同名 `skill_read`:按 §5"缺则不注册"——
1054
+ * 工具与菜单都不出现,告警一次;注册一个空菜单加一个一用就"不存在"的工具、或让菜单指向宿主的另一个同名工具,
1055
+ * 都只会让模型撞墙。不合规的技能单独跳过并告警一次,不拖垮整个菜单。
1056
+ * 不做:脚本执行(子进程越硬约束,技能要的动作宿主用普通 Tool 暴露)、热刷新、`allowed-tools` 等私有字段。
1057
+ */
1058
+
1059
+ interface SkillsOptions {
1060
+ /**
1061
+ * 技能载体。不给(或按环境算出 undefined)则模块不注册任何东西并告警一次——
1062
+ * 宿主按"这个环境有没有技能库"条件装配时可以直接透传可能为 undefined 的值
1063
+ */
1064
+ source?: SkillSource | undefined;
1065
+ /** 载体里技能的键前缀,缺省 `/skills`;须是 `/` 起、不以 `/` 收、不含 `.` / `..` 段的规范路径,且不能与 `/memories` 重叠 */
1066
+ root?: string;
1067
+ /**
1068
+ * `skill_read` 单次最多返回的字符数(正文部分,硬上限:带 range 也截、超长单行切开)。缺省 40000:
1069
+ * Agent Skills 规范建议 SKILL.md 不超过 500 行(约 40k 字符),而两族真模型实测都不会按截断提示续读一份"动手前先读"的说明书
1070
+ * (2026-09-13 AdRate 24.5k 字符的 SKILL.md 在 16k 上限下被截掉 110 行,DeepSeek 与 Claude 都直接开工),
1071
+ * 所以缺省要让规范内的技能一次读完;比 memory view 的 16000 大是有意的
1072
+ */
1073
+ maxReadChars?: number;
1074
+ /**
1075
+ * 规则提示的经验部分:缺省内置英文 `SKILL_RULES`;传字符串替换(菜单仍自动排在其后);
1076
+ * false 则完全不碰系统提示——工具仍注册,菜单由宿主自己排(`renderSkillMenu` / `loadSkillMenu` 可用)。
1077
+ * 代价:菜单不在本模块的贡献里就不进 configHash,暂停期间技能表变化续跑察觉不到;宿主自己排的菜单进了宿主 systemPrompt 才算
1078
+ */
1079
+ rules?: string | false;
1080
+ /** 告警出口(缺 source、无合规技能、某份 SKILL.md 不合规、载体读失败),每个 skills() 实例对每个原因只告警一次。缺省 console.warn */
1081
+ warn?: (message: string) => void;
1082
+ }
1083
+ declare const SKILLS_SOCKET_NAME = "skills";
1084
+ declare const DEFAULT_SKILL_READ_CHARS = 40000;
1085
+ /** 菜单里的一项:合规的技能 */
1086
+ interface LoadedSkill extends SkillMenuEntry {
1087
+ /** SKILL.md 在载体里的键 */
1088
+ path: string;
1089
+ }
1090
+ interface SkillMenu {
1091
+ skills: LoadedSkill[];
1092
+ /** 被跳过的 SKILL.md:键 → 原因 */
1093
+ rejected: {
1094
+ path: string;
1095
+ reason: string;
1096
+ }[];
1097
+ }
1098
+ /**
1099
+ * 从载体读菜单:`${root}/<name>/SKILL.md` 每份整个读出来解析头部(MemoryStore 只有整读),`name` 须与目录名一致。
1100
+ * 纯函数(只读载体),菜单与测试共用。结果按 name 排序,与载体返回顺序无关——菜单进 configHash,顺序抖动会误判配置漂移。
1101
+ * 载体抛错原样上抛:run 起步失败、日志零事件(fail-closed,宿主看到的是 runLoop 抛错而不是一个没技能的 run)。
1102
+ */
1103
+ declare function loadSkillMenu(source: SkillSource, root?: string): Promise<SkillMenu>;
1104
+ interface SkillReadInput {
1105
+ name: string;
1106
+ /** 相对技能目录的文件路径,已规范化(如 `SKILL.md`、`reference/api.md`) */
1107
+ path: string;
1108
+ range?: [number, number];
1109
+ }
1110
+ /** 解析并校验模型给的入参:name 按规范正则,path 经共用的路径规范化(拒绝 `..` 等穿越),range 同 memory view */
1111
+ declare function parseSkillReadInput(raw: unknown, root?: string): SkillReadInput;
1112
+ /** root 必须是规范的绝对路径(`/a/b`,无空段、无 `.`/`..`),且不能与记忆根相同或互为前缀 */
1113
+ declare function assertSkillsRoot(root: string): void;
1114
+ declare function skills(opts?: SkillsOptions): Socket;
1115
+
1116
+ /** 文本 token 估算器;缺省用 core 的粗估(ASCII 4 字一 token、非 ASCII 一字一 token),宿主可注入精确 tokenizer */
1117
+ type TextTokenEstimator = (text: string) => number;
1118
+ declare const defaultTextTokens: TextTokenEstimator;
1119
+ interface TextMeasure {
1120
+ chars: number;
1121
+ lines: number;
1122
+ tokens: number;
1123
+ }
1124
+ declare function measureText(text: string, estimate?: TextTokenEstimator): TextMeasure;
1125
+ /** 行数:空串算 0 行,其余按换行符数 +1(末尾换行不多算一行) */
1126
+ declare function countLines(text: string): number;
1127
+ /**
1128
+ * 从 text 开头取不超过 maxTokens 的一段(按 core 粗估的口径逐字累加:ASCII 4 字一 token、非 ASCII 一字一 token)。
1129
+ * 只在缺省估算器下精确;宿主注入了别的 estimate 时仍按这个口径裁,估算器只决定"要不要裁"。
1130
+ * 返回裁到的字符位置(== text.length 表示不用裁)。
1131
+ */
1132
+ declare function clipEndByTokens(text: string, maxTokens: number): number;
1133
+ interface PreviewOptions {
1134
+ /** 首尾各取多少行 */
1135
+ lines: number;
1136
+ /** 首尾各最多多少字符(防单行超长,比如一行 JSON) */
1137
+ chars: number;
1138
+ }
1139
+ interface Preview {
1140
+ head: string;
1141
+ /** 空串表示 head 已是全文(没有被省略的中段) */
1142
+ tail: string;
1143
+ omitted: {
1144
+ chars: number;
1145
+ lines: number;
1146
+ };
1147
+ }
1148
+ /**
1149
+ * 首尾预览:头 `lines` 行与尾 `lines` 行,各不超过 `chars` 字符。
1150
+ * 头尾在文本里重叠(文本本来就短)时 head 即全文、tail 为空;否则中段被省略并记下省略量。确定性纯函数。
1151
+ */
1152
+ declare function previewOf(text: string, opts: PreviewOptions): Preview;
1153
+ /** 千分位,给模型看的数字更好读 */
1154
+ declare function fmt(n: number): string;
1155
+
1156
+ /**
1157
+ * spill 模块给模型看的文字(技术方案 §9.4):fetch_blob 工具说明与规则提示。
1158
+ *
1159
+ * 与 compact / pins 一样,这是"经验"不是"指令":大结果该不该分页读、读哪段,判断在模型。
1160
+ * 作为 Socket 的静态 systemPrompt 片段追加在宿主提示之后,整个 run 逐字不变(§9.1 约束 3)。
1161
+ * 用英文写:进的是模型上下文。宿主要换措辞,传 spill({ rules }) 或 rules: false 自己放。
1162
+ */
1163
+ declare const FETCH_BLOB_TOOL_NAME = "fetch_blob";
1164
+ declare const FETCH_BLOB_TOOL_DESCRIPTION: string;
1165
+ declare const SPILL_RULES = "## Large tool outputs\nWhen a tool returns more than fits inline, you see a preview (the first and last lines) and a blob id instead of the full output; nothing is lost, the complete output is stored verbatim. You have a `fetch_blob` tool to read it by character offsets.\n- Read the preview first: often the head and tail already answer the question, or show that the call should be narrowed (a filter, a smaller page, a specific file) rather than paged through.\n- Fetch only the ranges you need. Each fetch costs context on every later turn; paging through a huge output end to end is rarely worth it.\n- The header of each fetch tells you the total size and where to continue; the offsets are characters, not lines.\n- A blob id stays valid for the whole session, including after compaction, so you can note the id in your summary and come back to it.";
1166
+
1167
+ /**
1168
+ * spill —— 结果外溢模块(技术方案 §9.4,B4)。
1169
+ *
1170
+ * 工具偶尔会吐回一大坨(整页搜索结果、几千行日志、一个大 JSON)。硬塞进上下文既贵又挤掉别的东西,
1171
+ * 直接截断又等于替模型决定"后面的不重要"。本模块的做法:
1172
+ *
1173
+ * 1. **afterTool 外溢**:结果的文本部分超过 `maxResultTokens`(缺省 16k,工具可用 `resultPolicy.maxTokens` 单独配)
1174
+ * → 全文原样写进 BlobStore,模型看到的结果换成 `[说明 + 首尾各 N 行预览]`,并在 `tool_result.spilled` 记下
1175
+ * `{ blobId, summary }`。全文一个字都没丢,只是搬到了旁边;决定读不读、读哪段的仍是模型(宪法一)。
1176
+ * 工具声明 `resultPolicy.overflow = "truncate"` 时不存 blob、只留预览并明说中段不可恢复 —— 这是宿主对该工具的显式选择。
1177
+ * 没有 BlobStore 则外溢自动关闭(结果原样通过)并告警一次;声明了 truncate 的工具照常截断(截断不需要存储)。
1178
+ * 2. **工具 `fetch_blob({ id, start?, end? })`**:按字符偏移分段取回,每次最多给 `maxResultTokens` 那么多,
1179
+ * 头部说明总长与下一段从哪开始。只能读本会话的 blob(越权当不存在),只读文本类 mime。
1180
+ * 它的结果本身不再外溢(已经按上限裁过),否则会自己咬自己。
1181
+ *
1182
+ * 为什么在 afterTool 而不是包装工具的 execute:宿主的工具不必知道 reins 的存在(P3),也让 MCP / OpenAPI 来源的工具
1183
+ * 同样受益;afterTool 拿到的是尚未 append 的草稿,返回即替换,日志里只有一条 tool_result(T9 决策)。
1184
+ * `spilled` 字段是给 UI / 回放 / 感知看的(perception 统计"可见外溢结果数"就靠它),降级层不翻译它。
1185
+ *
1186
+ * 图片片段不度量也不外溢(一张图对模型是固定开销,没有"分页读"的意义),原样保留在预览之后。
1187
+ */
1188
+
1189
+ interface SpillOptions {
1190
+ /** 结果文本超过多少 token 就外溢;也是 fetch_blob 单次返回的上限。工具的 `resultPolicy.maxTokens` 优先。缺省 16000(E3 定) */
1191
+ maxResultTokens?: number;
1192
+ /** 预览首尾各取多少行。缺省 20 */
1193
+ previewLines?: number;
1194
+ /** 预览首尾各最多多少字符(防单行超长)。缺省 min(2000, maxResultTokens / 4),保证预览本身远低于上限 */
1195
+ previewChars?: number;
1196
+ /** 文本 token 估算器;缺省 core 粗估。宿主有精确 tokenizer 时注入 */
1197
+ estimate?: TextTokenEstimator;
1198
+ /** 是否给模型 fetch_blob 工具。缺省 true;false 时外溢仍发生,只是模型取不回(宿主自己提供读法时用) */
1199
+ tool?: boolean;
1200
+ /** 规则提示:缺省内置英文文案;传字符串替换;false 则不碰系统提示 */
1201
+ rules?: string | false;
1202
+ /** 没有 BlobStore 时的告警出口(每个 spill() 实例只告警一次)。缺省 console.warn */
1203
+ warn?: (message: string) => void;
1204
+ }
1205
+ declare const SPILL_SOCKET_NAME = "spill";
1206
+ /**
1207
+ * 缺省外溢阈值。E3 对照(2026-09-09,DeepSeek v4 flash,AdRate 巡检):6k 阈值把模型必须整读的 10k token 计划列表外溢出去,
1208
+ * 模型再用 fetch_blob 分两三次取回,平白多两三轮、总 token 翻倍而完成度不变;16k 时同一任务 4 轮做完。
1209
+ * 外溢是给"模型不需要全读"的巨量结果准备的安全网,阈值要高于常见的"整表读完"体量。
1210
+ */
1211
+ declare const DEFAULT_MAX_RESULT_TOKENS = 16000;
1212
+ declare const DEFAULT_PREVIEW_LINES = 20;
1213
+ declare const DEFAULT_PREVIEW_CHARS = 2000;
1214
+ /** 外溢正文的 mime;BlobStore 按 UTF-8 存字符串 */
1215
+ declare const SPILL_BLOB_MIME = "text/plain; charset=utf-8";
1216
+ declare const FETCH_BLOB_INPUT_SCHEMA: {
1217
+ readonly type: "object";
1218
+ readonly properties: {
1219
+ readonly id: {
1220
+ readonly type: "string";
1221
+ readonly description: "The blob id shown in the tool result preview.";
1222
+ };
1223
+ readonly start: {
1224
+ readonly type: "integer";
1225
+ readonly minimum: 0;
1226
+ readonly description: "0-based character offset to start from. Omit to start at the beginning.";
1227
+ };
1228
+ readonly end: {
1229
+ readonly type: "integer";
1230
+ readonly minimum: 1;
1231
+ readonly description: "Character offset to stop before (exclusive). Omit to read as much as fits.";
1232
+ };
1233
+ };
1234
+ readonly required: readonly ["id"];
1235
+ readonly additionalProperties: false;
1236
+ };
1237
+ interface FetchBlobArgs {
1238
+ id: string;
1239
+ start?: number;
1240
+ end?: number;
1241
+ }
1242
+ declare function parseFetchBlobArgs(raw: unknown): FetchBlobArgs;
1243
+ /** 能当文本给模型看的 mime:text/*、JSON / XML / YAML / JS 及其 +json / +xml 变体 */
1244
+ declare function isTextMime(mime: string): boolean;
1245
+ declare function spill(opts?: SpillOptions): Socket;
1246
+
1247
+ export { APPROVAL_POLICY_IDS, APPROVAL_RULES, APPROVAL_SOCKET_NAME, type ApprovalOptions, BUDGET_SOCKET_NAME, type BudgetDimension, type BudgetHit, type BudgetLimits, type BudgetOptions, COMPACT_INPUT_SCHEMA, COMPACT_RULES, COMPACT_SOCKET_NAME, COMPACT_TOOL_DESCRIPTION, COMPACT_TOOL_NAME, type CompactArgs, type CompactOptions, type CompactPlan, DEFAULT_HANDOFF_REASON, DEFAULT_MAX_CONSECUTIVE_COMPACTIONS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MAX_PIN_TEXT_LENGTH, DEFAULT_MAX_RESULT_TOKENS, DEFAULT_MAX_SUMMARY_CHARS, DEFAULT_MAX_VIEW_CHARS, DEFAULT_PERCEPTION_THRESHOLDS, DEFAULT_PIN_OVERSHOOT_TOLERANCE, DEFAULT_PREVIEW_CHARS, DEFAULT_PREVIEW_LINES, DEFAULT_SKILLS_ROOT, DEFAULT_SKILL_READ_CHARS, FETCH_BLOB_INPUT_SCHEMA, FETCH_BLOB_TOOL_DESCRIPTION, FETCH_BLOB_TOOL_NAME, type FetchBlobArgs, HANDOFF_INPUT_SCHEMA, HANDOFF_RULES, HANDOFF_SOCKET_NAME, HANDOFF_TOOL_DESCRIPTION, HANDOFF_TOOL_NAME, type HandoffArgs, type HandoffOptions, type InlineSkill, type InlineSkillsOptions, type LimitDimension, type LoadedSkill, MANIFEST_DEFAULT_EXCLUDE, MANIFEST_HEADING, MAX_MEMORY_PATH_LENGTH, MAX_SKILL_DESCRIPTION_CHARS, MEMORY_COMMANDS, MEMORY_INPUT_SCHEMA, MEMORY_ROOT, MEMORY_RULES, MEMORY_SOCKET_NAME, MEMORY_TOOL_DESCRIPTION, MEMORY_TOOL_NAME, type ManifestOptions, type MemoryCommand, type MemoryFs, type MemoryLimits, type MemoryOp, type MemoryOptions, type MemoryOutcome, PERCEPTION_SOCKET_NAME, PINS_SOCKET_NAME, PIN_INPUT_SCHEMA, PIN_RULES, PIN_TOOL_DESCRIPTION, PIN_TOOL_NAME, type ParsedSkill, type PerceptionLimits, type PerceptionOptions, type PerceptionReading, type PinArgs, type PinMeta, type PinNote, type PinSpec, type PinsOptions, type PlanOptions, type PolicyCall, type PolicyOutcome, type PolicyRule, type PolicyRuleSpec, type PolicyVerdict, type Preview, type PreviewOptions, RECALL_INPUT_SCHEMA, RECALL_TOOL_DESCRIPTION, RECALL_TOOL_NAME, type ReadingOptions, type ReadingThresholds, type RecallArgs, SKILLS_SOCKET_NAME, SKILL_FILE_NAME, SKILL_NAME_RE, SKILL_READ_INPUT_SCHEMA, SKILL_READ_TOOL_DESCRIPTION, SKILL_READ_TOOL_NAME, SKILL_RULES, SPILL_BLOB_MIME, SPILL_RULES, SPILL_SOCKET_NAME, type SkillFrontmatter, type SkillMenu, type SkillMenuEntry, type SkillReadInput, type SkillsOptions, type SpillOptions, type TextMeasure, type TextTokenEstimator, type Tier, approval, assertAscending, assertLimits, assertSkillsRoot, bindMemoryFs, budget, budgetUsedOf, byteLength, carriedPins, checkBudget, clipEndByTokens, compact, compactNumber, composeHandoffNote, contextOverheadOf, countLines, countModelTurns, countTier, defaultBudgetNote, defaultSummary, defaultTextTokens, evaluatePolicy, executeMemoryCommand, findModelPin, fmt, globToRegExp, handoff, humanSize, inlineSkills, isModelCompaction, isPinNoteEvent, isTextMime, isUnder, lastHostPin, lastVisiblePerceptionNote, lastVisibleUserMessage, loadSkillMenu, measureText, memory, normalizeRule, parseCompactArgs, parseFetchBlobArgs, parseHandoffArgs, parseMemoryCommand, parsePinArgs, parseRecallArgs, parseSkillMarkdown, parseSkillReadInput, percent, perception, pinInputSchema, pinMetaOf, pinToolDescription, pins, planCompaction, previewOf, rangeTier, readPerception, recallResult, recallTool, renderCompactionSummary, renderPerception, renderSkillMenu, resolveMemoryPath, segmentTimelineByTurn, skills, spill, sumSessionTokens, trailingCompactionRun, unfinishedHandoffArgs };