@reinsjs/brain 0.1.1 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @reinsjs/brain
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 19e9820: New module `lazyTools()` — tool discovery for large host tool tables (the consumer of `Tool.lazy`). Host tools marked `lazy: true` appear in the system prompt only as a menu (name + one-line summary); the model loads the ones a task needs with `tool_find({ names })`, which returns their full description and input schema, and from the next turn on those tools are part of the request's tool list. Which tools are loaded is rebuilt from the session timeline (the `tool_find` calls and their non-error results), so pause / resume, later runs on the same session and process restarts all agree; the bound tool table (`tools_bound`, config hash) still holds every tool. Calling a listed-but-unloaded tool is blocked with a message pointing at `tool_find`. Only host tools are affected; tools contributed by other sockets are never hidden. Opt-in: install the socket; with no `lazy` host tool (or a host tool already named `tool_find`) nothing is registered and one warning is emitted.
8
+ - bfb49b3: `approval({ ttlMs })` — approvals can now expire. When the host's approval arrives later than `ttlMs` after the `approval_request` (both read from the timeline, not the wall clock), the call is not run: the module appends `approval_decision(approved: false, by: "approval.expired")` and the model receives an error explaining that it may re-issue the call to request a fresh approval. Only calls the policy pipeline would have asked about are affected; calls the policy allows never needed the approval. With the default `rules` text a line about expiry is appended to the system prompt. Unset, behaviour is unchanged.
9
+ - 14345eb: Every user-facing runtime string is now English. This covers thrown error messages (construction-time validation, store and registry errors, HTTP 4xx bodies), `warn()` output from the brain modules and the server, the text the model sees in error tool results (`Unknown tool: …`, `Tool call blocked: …`, `Invalid arguments: …`, `Approval denied…`, `Approval expired…`), the `note` / `when` fields of every lowering loss matrix and landing, the placeholder text for content a wire protocol cannot carry, the conformance suites exported from `@reinsjs/core/testing`, and the `@reinsjs/eval` report and gate output. Previously these were Chinese while the READMEs and model-facing prompts were English, which left a non-Chinese-speaking host with unreadable diagnostics.
10
+
11
+ Nothing changes structurally: same errors, same codes, same warning points, same landing kinds. Hosts that match on the text of a message or a landing note (rather than on its error code or `landing` value) need to update those matches.
12
+
13
+ - a082a0c: `lazyTools()` no longer costs a cache rewrite on lowerings that support deferred tools. When `capabilities.deferredTools` is true (`@reinsjs/lowering-fetch` on official Anthropic models) the socket sends the whole tool table on every request and marks the menu tools as deferred, so the tool list never changes; the `tool_find` result now carries one `tool_reference` content part per loaded tool (plus a one-line note and the not-listed names as text) which the provider expands in place. A tool whose loading turn has been compacted out of the current view is sent un-deferred so the model keeps seeing it. On other lowerings the behaviour is unchanged (the tool appears in the next request's list); `renderLoadedTool` now renders the reference through core's `renderToolReference`. Calling a listed-but-unloaded tool is still blocked, on both paths. Public interface of `lazyTools()` unchanged.
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [49d5dea]
18
+ - Updated dependencies [c16e3ea]
19
+ - Updated dependencies [14345eb]
20
+ - Updated dependencies [a082a0c]
21
+ - @reinsjs/core@0.2.0
22
+
3
23
  ## 0.1.1
4
24
 
5
25
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @reinsjs/brain
2
2
 
3
- Pre-packaged driving experience for [reins](../../README.md) agents: nine `Socket` modules that make a model good at long tasks — seeing its own context, tidying it, keeping constraints, spilling large results, handing off, remembering, asking before dangerous actions, stopping at a budget, and reading the host's skills when a task calls for them. Each module is optional, individually configurable, and only depends on the contracts in `@reinsjs/core`. None of them decides *for* the model; they let it see, give it means, set bounds, and leave a record.
3
+ Pre-packaged driving experience for [reins](../../README.md) agents: ten `Socket` modules that make a model good at long tasks — seeing its own context, tidying it, keeping constraints, spilling large results, handing off, remembering, asking before dangerous actions, stopping at a budget, reading the host's skills when a task calls for them, and loading tools from a large table only when it needs them. Each module is optional, individually configurable, and only depends on the contracts in `@reinsjs/core`. None of them decides *for* the model; they let it see, give it means, set bounds, and leave a record.
4
4
 
5
5
  ```bash
6
6
  pnpm add @reinsjs/brain
@@ -40,9 +40,10 @@ const agent = createAgent({
40
40
  | `spill()` | Tool results above a size limit are stored whole in the `BlobStore`; the model sees head + tail + a blob id and pages through with `fetch_blob`. Without a `BlobStore` the module warns once and passes results through unchanged (no silent truncation). | a `BlobStore` |
41
41
  | `handoff()` | A `handoff` tool: the model writes a summary and next steps and moves to a fresh session; visible pins travel along. The mechanics (new session, opening note) are in the core loop. **Off by default** — turn it on when tasks routinely outlive one context window. | host must rebind the UI to the new session (`onHandoff`) |
42
42
  | `memory()` | A `memory` tool shaped like Anthropic's `memory_20250818` (view / create / str_replace / insert / delete / rename under `/memories`). Every operation leaves a `memory_op` event. Isolation is by `namespace`, invisible to the model. **Off by default.** | a `MemoryStore` |
43
- | `approval()` | A deny → ask → allow policy pipeline in `beforeTool`. `deny` leaves an `approval_decision` and blocks; `ask` pauses the run for a human; `allow` leaves no event. Default policy `byRisk`: tools without a declared `risk` are treated as medium and **ask** — mark read-only tools `risk: "low"`. Policy evaluation errors deny (fail-closed). | nothing |
43
+ | `approval()` | A deny → ask → allow policy pipeline in `beforeTool`. `deny` leaves an `approval_decision` and blocks; `ask` pauses the run for a human; `allow` leaves no event. Default policy `byRisk`: tools without a declared `risk` are treated as medium and **ask** — mark read-only tools `risk: "low"`. Policy evaluation errors deny (fail-closed). `ttlMs` gives approvals a lifetime: one that arrives later than that (measured between the `approval_request` and the host's `approval_decision` on the timeline) is not honoured — the call is denied with `by: "approval.expired"` and a message telling the model it may re-issue the call for a fresh approval. | nothing |
44
44
  | `budget()` | Five limits — `contextTokens`, `totalTokens`, `turns`, `toolCalls`, `wallMs` — checked in `onTurnEnd`. Hitting one while the model wants to continue pauses the run with `reason: "budget"`; resuming starts a fresh run budget. `totalTokens` includes what sub-agents spent through `asTool`. | nothing |
45
45
  | `skills()` | [Agent Skills](https://agentskills.io) with progressive disclosure: the system prompt carries only a menu (each `SKILL.md`'s `name` + `description`); the model reads a skill, or one of its supporting files, with `skill_read({ name, path?, range? })`, and the text lands in the timeline as a `tool_result` — so compaction, `recall` and spill apply to it unchanged. Skills are host-authored, so `skill_read` results are trusted like the system prompt (no `<untrusted>` marker). Skills that fail the spec (bad `name`, missing `description`) are skipped with one warning; no `source`, no valid skill, or a host tool already named `skill_read` means nothing is registered (one warning). **Opt-in**: give it a `source`. | a `SkillSource` — the read-only half of any `MemoryStore` (see below), `fsSkillSource(dir)` from `@reinsjs/brain/node` for a folder of `<name>/SKILL.md`, or `inlineSkills({ "code-review": "---\nname: code-review\ndescription: How we review PRs.\n---\n\n1. …" })` for bundled strings (Workers) — the object key must equal the frontmatter `name` |
46
+ | `lazyTools()` | Tool discovery for large host tool tables — the consumer of `Tool.lazy`. Host tools marked `lazy: true` appear in the system prompt only as a menu (`name: one-line summary`, first line of the description by default); the model loads the ones a task needs with `tool_find({ names })`, which returns each tool's full description and input schema, and from the next turn on those tools are in the request's tool list. Which tools are loaded is rebuilt from the timeline (the `tool_find` calls and their non-error results), so pause / resume, later runs on the same session and process restarts agree. Calling a listed-but-unloaded tool is blocked with a pointer to `tool_find`. Only host tools are affected — tools contributed by other sockets (MCP) are never hidden. No `lazy` host tool, or a host tool already named `tool_find`: nothing registered, one warning. **Opt-in**: install it. | `summarize(tool)` to replace the default summary, `summaryChars` (160), `maxPerCall` (20), `rules`, `warn` |
46
47
 
47
48
  ### Skills from a database
48
49
 
@@ -56,6 +57,7 @@ Any `MemoryStore` (in-memory, `@reinsjs/store-sqlite`, `@reinsjs/store-pg`) is a
56
57
  - **Skills are read, not executed.** A skill's `scripts/` are not run by the library — a child process would break the zero-Node-builtins rule of `@reinsjs/brain` — expose what a skill needs as ordinary tools. Only `@reinsjs/brain/node` touches the file system.
57
58
  - **The skill menu is part of the run's config hash.** The menu is read once when a run starts and stays fixed for that run. Adding, removing or renaming a skill (or editing its `description`) while a run is paused makes the resume fail as config drift — editing a skill's *body* does not. Deploy skill changes between runs, or pass `allowConfigDrift`. With `rules: false` the menu is not contributed at all, so this protection is gone unless your own system prompt carries the menu.
58
59
  - **Skills are trusted because you wrote them.** `skill_read` results carry `trust: "system"` and skip the `<untrusted>` marker, so whatever fills the source (a folder you deploy, a database row, a CLI's `skills read` output) is trusted like your system prompt. Do not give the model a tool that can write into the skill source. A skill body brought back later by `recall` or `fetch_blob` is `untrusted` again — deliberate, conservative.
60
+ - **Loading a tool keeps the prompt cache on Anthropic (native path), re-warms it once elsewhere.** When the lowering layer reports `capabilities.deferredTools` (`@reinsjs/lowering-fetch` on official Anthropic models, Haiku 4.5 and later), `lazyTools()` sends the whole tool table on every request with the menu tools marked `defer_loading: true`; the `tool_find` result carries `tool_reference` parts that the provider expands in place, so the tool list never changes and the cache prefix survives (measured: the request after a `tool_find` reads 8.5k cached tokens on Haiku 4.5 instead of rewriting them; `spikes/l1-deferred-tools/`). Without that capability the request's tool list changes on the turn after a `tool_find`, which invalidates the tools / system / messages prefix once — the rules text asks the model to load everything a task needs in one call; numbers in `spikes/d1-lazy-tools-cache/`. `tool_find` results are trusted like the system prompt (`trust: "system"`): tool descriptions and schemas are host configuration, and only system-trusted results are translated into native `tool_reference` blocks.
59
61
  - **Exports beyond this table** (`loadSkillMenu`, `parseSkillMarkdown`, `parseMemoryCommand`, `previewOf`, …) exist for hosts that replace a module's prompt or tool. They follow semver but are documented only in the type declarations.
60
62
  - **Compaction never makes information unreachable.** Early runs showed models refusing to answer once they saw "this was summarized", even when the detail was still visible. Attaching the manifest and giving them `recall` fixed it; removing the manifest requires rewriting the rules text too, or the prompt lies.
61
63
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Tool, TurnContext, MaybePromise, Socket, CompactionPayload, Event, FoldedToolResult, ToolContext, ContentPart, EventDraft, MemoryStore, CoreEventOf, SkillSource } from '@reinsjs/core';
1
+ import { Tool, TurnContext, MaybePromise, Socket, Event, CompactionPayload, FoldedToolResult, ToolContext, ContentPart, EventDraft, ToolReferencePart, MemoryStore, CoreEventOf, SkillSource } from '@reinsjs/core';
2
2
 
3
3
  /**
4
4
  * approval —— 审批与权限模块(技术方案 §9.7,B7)。
@@ -17,6 +17,11 @@ import { Tool, TurnContext, MaybePromise, Socket, CompactionPayload, Event, Fold
17
17
  *
18
18
  * fail-closed:任何规则求值抛错、`needsApproval` 函数抛错,都按 deny 处理(by = 出错的规则 id),并经 `warn` 告警。
19
19
  *
20
+ * 批准有效期(D3,`ttlMs`):宿主的批准到得太晚(批准事件的 `at` 减去 `approval_request` 的 `at` 超过 ttl)就不算数——
21
+ * 留一条 `approval_decision(approved=false, by="approval.expired")` 再 block,模型拿到带说明的错误结果,想做就再调一次、
22
+ * 重新发起审批。只对"管线本该问人、放行靠的是宿主批准"的调用生效:管线判 allow 的调用本来就不需要批准,过不过期无关。
23
+ * 时间全部取自时间线上的事件(循环时钟),不读墙钟——同一条日志在哪台机器上回放结论都一样。
24
+ *
20
25
  * 位置:管线跑在哪一步由 Socket 注册顺序决定。**建议放在 sockets 末尾**(至少放在会 rewrite 入参的钩子之后):
21
26
  * 这样判定的是真正要执行的入参;前面的钩子只可能收紧(block / defer),不存在"钩子放行绕过策略"的路径。
22
27
  */
@@ -57,7 +62,13 @@ interface ApprovalOptions {
57
62
  unmatched?: "byRisk" | "ask" | "deny";
58
63
  /** 审批摘要里入参 JSON 的最大字符数,超出截断并加省略号。缺省 200 */
59
64
  maxSummaryChars?: number;
60
- /** 规则提示:缺省内置英文文案;传字符串替换;false 则不碰系统提示 */
65
+ /**
66
+ * 批准的有效期(毫秒)。宿主的批准到达时距 `approval_request` 超过它就视为过期:不执行,留一条
67
+ * `approval_decision(approved=false, by="approval.expired", reason)` 并给模型带说明的错误结果,模型可再调一次重新发起审批。
68
+ * 比对的是两条事件的 `at`(循环时钟),不读墙钟。缺省不限期。必须是正的有限数。
69
+ */
70
+ ttlMs?: number;
71
+ /** 规则提示:缺省内置英文文案(设了 ttlMs 时追加一句过期说明);传字符串替换(不追加);false 则不碰系统提示 */
61
72
  rules?: string | false;
62
73
  /** 策略求值异常(fail-closed 记 deny)的告警出口。缺省 console.warn */
63
74
  warn?: (message: string) => void;
@@ -72,9 +83,23 @@ declare const APPROVAL_POLICY_IDS: {
72
83
  readonly unmatched: "approval.unmatched";
73
84
  /** 三段都没命中、按 risk 兜底:`approval.risk.<low|medium|high|undeclared>` */
74
85
  readonly risk: (level: Tool["risk"]) => string;
75
- /** 入参没过工具自己的 validate:不问人、放行给循环以"入参不合法"拒掉(执行不会发生) */
86
+ /** 入参没过工具自己的 validate:不问人、放行给循环以"Invalid arguments"拒掉(执行不会发生) */
76
87
  readonly invalidArgs: "approval.invalid_args";
88
+ /** 宿主的批准到得太晚(超过 `ttlMs`),按拒绝处理 */
89
+ readonly expired: "approval.expired";
77
90
  };
91
+ /** 一次过期的批准:请求何时发出、批准何时到、隔了多久 */
92
+ interface ExpiredApproval {
93
+ requestedAt: number;
94
+ decidedAt: number;
95
+ ageMs: number;
96
+ }
97
+ /**
98
+ * 在时间线里找这次调用的批准是否过期(纯函数):取最后一条 `approval_request(toolCallId)`,再取它之后最后一条
99
+ * `approval_decision(toolCallId, approved=true)`,两者 `at` 之差超过 ttl 即过期。缺任何一条都不算过期——
100
+ * 没有请求就没有起点,没有批准则循环根本不会走到执行这一步。
101
+ */
102
+ declare function findExpiredApproval(timeline: readonly Event[], toolCallId: string, ttlMs: number): ExpiredApproval | undefined;
78
103
  /** 管线的一次结论(导出供测试与宿主自己的 Socket 复用) */
79
104
  type PolicyOutcome = {
80
105
  verdict: "allow";
@@ -118,6 +143,8 @@ declare function approval(options?: ApprovalOptions): Socket;
118
143
  * 英文:与其他模块的规则片段一致,规则提示对英语模型最稳;宿主可用 `rules` 选项替换或关闭。
119
144
  */
120
145
  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.";
146
+ /** 设了 `ttlMs` 时追加:过期的批准会被拒,模型可以再调一次重新发起审批(与"被拒别重试"区分开) */
147
+ declare const APPROVAL_EXPIRY_RULE = "- An approval can expire if it arrives too late. The call is then not run and the error says so; unlike a policy denial, you may make the same call again to request a fresh approval.";
121
148
 
122
149
  /**
123
150
  * budget —— 预算模块(技术方案 §9.8,B8)。
@@ -474,6 +501,142 @@ declare const HANDOFF_TOOL_NAME = "handoff";
474
501
  declare const HANDOFF_TOOL_DESCRIPTION: string;
475
502
  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
503
 
504
+ /**
505
+ * lazy-tools 模块给模型看的文字(技术方案 §9.10):工具说明、规则提示、菜单排版、取回结果排版。
506
+ *
507
+ * 渐进式披露的两层(与 skills 同形):系统提示里只有菜单(每件工具的 name + 一行摘要),完整 schema 要模型自己用
508
+ * `tool_find` 取回——取哪几件、什么时候取是模型的判断(宪法一),规则只给经验:动手前先取、一次取全、只取任务要的。
509
+ * 作为 Socket 的静态 systemPrompt 片段追加在宿主提示之后,整个 run 逐字不变(§9.1 约束 3)。英文:进的是模型上下文。
510
+ */
511
+
512
+ declare const TOOL_FIND_TOOL_NAME = "tool_find";
513
+ declare const TOOL_FIND_TOOL_DESCRIPTION: string;
514
+ /** 规则提示的经验部分;菜单由 renderLazyToolMenu 排在其后 */
515
+ declare const LAZY_TOOL_RULES = "## Tools available on request\nThe tools listed below are bound to this session but not loaded yet: only a name and a one-line summary are shown, and they cannot be called until loaded.\n- Before starting work that needs one of them, call `tool_find({ names: [...] })` with every listed tool the task will need, in one call where possible. Each loaded tool then appears in your tool list from the next turn on, with its full input schema.\n- Load only what the task needs. A tool loaded earlier in this conversation stays loaded; do not load it again.\n- Do not guess a listed tool's parameters from its summary; load it first.";
516
+ interface LazyToolMenuEntry {
517
+ name: string;
518
+ summary: string;
519
+ }
520
+ /** 菜单:每项一行 `- name: summary` */
521
+ declare function renderLazyToolMenu(entries: readonly LazyToolMenuEntry[]): string;
522
+ declare const TOOL_FIND_INPUT_SCHEMA: {
523
+ readonly type: "object";
524
+ readonly properties: {
525
+ readonly names: {
526
+ readonly type: "array";
527
+ readonly items: {
528
+ readonly type: "string";
529
+ };
530
+ readonly minItems: 1;
531
+ readonly description: "Tool names to load, exactly as listed under \"Tools available on request\".";
532
+ };
533
+ };
534
+ readonly required: readonly ["names"];
535
+ readonly additionalProperties: false;
536
+ };
537
+ /** 一件工具的定义引用段(L1):取回结果里每件工具一段,带完整定义快照(日志自足),降级层按能力位翻成原生块或文本 */
538
+ declare function toolReferenceOf(tool: Tool): ToolReferencePart;
539
+ /** 一件工具展开成文本的样子(无原生落点的线上模型看到的、也是估算上界用的):core `renderToolReference` 的同一份写法 */
540
+ declare function renderLoadedTool(tool: Tool): string;
541
+ /**
542
+ * 取回结果的内容段。`loaded` 是这次取回的菜单工具,每件一个引用段;`notListed` 是模型点了名但不在菜单上的——点名而不是静默忽略,
543
+ * 模型才知道自己记错了名字(或者它本来就在工具表里,直接调即可;本模块看不到别的 Socket 的工具,不替它判断是哪种)。
544
+ * 文本段与引用段分开放:Anthropic 原生路径上引用块进 tool_result、文本段跟在这批结果之后(tool_result 内不能混放);其余线全展开成文本。
545
+ */
546
+ declare function renderToolFindResult(input: {
547
+ loaded: readonly Tool[];
548
+ notListed: readonly string[];
549
+ }): ContentPart[];
550
+
551
+ /**
552
+ * lazy-tools —— 工具懒发现(技术方案 §9.10,D1):大工具表的渐进式披露,`Tool.lazy` 的消费者。
553
+ *
554
+ * 库只做两件事(宪法一):
555
+ * - **让它看见**:系统提示里一份菜单(每件 `lazy: true` 的宿主工具的 name + 一行摘要),run 起步算一次、run 内不变、进 configHash。
556
+ * - **给它能力**:`tool_find({ names })` 取回几件工具的完整 description + inputSchema;从下一轮起那几件出现在请求的工具表里。
557
+ * 取哪几件、什么时候取是模型的判断;规则提示只给经验(rules.ts)。
558
+ *
559
+ * "哪些已取回"**从时间线重建**(宪法二):本会话所有 `tool_find` 的 tool_call 与其非 isError 的 tool_result 按 toolCallId 配对,
560
+ * 取 `args.names ∩ 当前菜单`。不加新事件类型、不留内存状态——审批暂停后换进程续跑、同一会话下一次 run、compact 折叠掉那段历史,
561
+ * 已取回集合都不变;handoff 到新会话即重置(新时间线,新菜单)。
562
+ *
563
+ * 绑定表不变:`tools_bound` 与 configHash 仍含全部工具、run 内固定(§9.1 约束 3 约束的是绑定表)。每轮请求暴露什么按降级层能力分两路(L1):
564
+ * - **原生路径**(`ctx.capabilities.deferredTools`,Anthropic 官方 `defer_loading`):工具表全表下发,菜单工具标 `deferredTools`——
565
+ * 厂商知道它们、模型看不见,`tool_find` 结果里的 `tool_reference` 段由厂商就地展开成定义。工具表整段不变,取回不再打掉缓存前缀
566
+ * (spikes/l1-deferred-tools:取回后第 2 请求 cacheRead 8488 vs 老路子 0)。已取回、但取回那轮已被 compact 折出本轮视图的工具
567
+ * 例外——历史里没有引用块可展开,就不再延迟、让定义进 tools 块(折叠本就重写了前缀,这一下不多花钱)。
568
+ * - **过滤路径**(其余降级层):本轮工具表 = 非 lazy + 已取回的 lazy;取回后的第一个请求缓存前缀重算一次(Anthropic 文档:工具表
569
+ * 变动使三段缓存全失效),所以规则文案要求一次把要用的都取回;实测数字见 `spikes/d1-lazy-tools-cache/`。
570
+ *
571
+ * 作用范围只有**宿主工具**(`SocketSetup.hostTools`):静态贡献阶段各 Socket 互不可见,Socket 贡献的工具(如 MCP 经 `override`
572
+ * 标了 lazy)不进菜单——菜单上没有的工具若被藏起来就等于消失,所以也不藏。模块用对象同一性(WeakSet)记住"哪些工具是菜单工具",
573
+ * 同一个 Socket 实例给多个 agent 定义共用也不会串。
574
+ *
575
+ * 模型没取回就直接调菜单里的工具:`beforeTool` 回 `block` 并指向 `tool_find`——不拦的话循环回"未知工具",模型会以为工具不存在;
576
+ * 也不放行,因为请求里没给 schema 的调用入参多半不对(原生路径同样拦:厂商知道这件工具、模型只凭菜单摘要就能报出名字)。
577
+ * 续跑补齐 pending 时没有 beforeModel、表是全表,隐藏工具照常执行。
578
+ *
579
+ * trust:工具说明与 schema 是宿主配置,视同系统提示可信,`tool_find` 声明 `resultTrust: "system"`(与 `skill_read` 同一条理由)。
580
+ * `resultPolicy.maxTokens` 按"最大的 maxPerCall 件条目估算之和 + 256"在 setup 时算出:spill 永不把 schema 换成 untrusted 预览。
581
+ *
582
+ * 缺则不注册:宿主没有一件 `lazy: true` 的工具、或宿主自己已有同名 `tool_find` → 工具与菜单都不出现,告警一次(同 skills)。
583
+ * 不做:关键词搜索(菜单就是搜索空间,200 行约 4k token 且逐轮不变)、按 provider 原生 deferred-tools 下发(降级层的优化,另立任务)。
584
+ */
585
+
586
+ interface LazyToolsOptions {
587
+ /**
588
+ * 菜单每项的一行摘要,缺省取 description 的首个非空行、空白折成一个空格、超 `summaryChars` 截断加 "…"。
589
+ * 宿主的 description 首行不适合当摘要时(如以参数表开头)用它换
590
+ */
591
+ summarize?: (tool: Tool) => string;
592
+ /** 缺省摘要的字符上限,缺省 160;只对缺省 summarize 生效 */
593
+ summaryChars?: number;
594
+ /** 一次 `tool_find` 最多取回几件,缺省 20;同时决定 resultPolicy.maxTokens 的上界 */
595
+ maxPerCall?: number;
596
+ /**
597
+ * 规则提示的经验部分:缺省内置英文 `LAZY_TOOL_RULES`;传字符串替换(菜单仍自动排在其后);
598
+ * false 则完全不碰系统提示——工具与过滤仍生效,菜单由宿主自己排(`lazyMenuOf` / `renderLazyToolMenu` 可用)。
599
+ * 代价:菜单不在本模块的贡献里就不进 configHash,暂停期间工具摘要变化续跑察觉不到(工具名本就在 configHash 里)
600
+ */
601
+ rules?: string | false;
602
+ /** 告警出口(没有 lazy 工具、宿主同名工具),每个 lazyTools() 实例对每个原因只告警一次。缺省 console.warn */
603
+ warn?: (message: string) => void;
604
+ }
605
+ declare const LAZY_TOOLS_SOCKET_NAME = "lazy-tools";
606
+ declare const DEFAULT_LAZY_SUMMARY_CHARS = 160;
607
+ declare const DEFAULT_TOOL_FIND_MAX = 20;
608
+ /** 缺省摘要:description 首个非空行,空白折叠,超长截断;没有正文就用工具名 */
609
+ declare function summarizeTool(tool: Tool, maxChars?: number): string;
610
+ interface LazyToolMenu {
611
+ /** 菜单工具,按 name 排序 */
612
+ tools: Tool[];
613
+ entries: LazyToolMenuEntry[];
614
+ byName: Map<string, Tool>;
615
+ }
616
+ /**
617
+ * 从宿主工具表挑出 `lazy: true` 的做菜单。纯函数,菜单与测试共用。
618
+ * 按 name 排序,与宿主给的顺序无关——菜单进 configHash,顺序抖动会误判配置漂移。
619
+ */
620
+ declare function lazyMenuOf(hostTools: readonly Tool[], summarize?: (tool: Tool) => string): LazyToolMenu;
621
+ interface ToolFindInput {
622
+ /** 去重后的名字,保持模型给的顺序 */
623
+ names: string[];
624
+ }
625
+ /** 解析并校验模型给的入参:非空字符串数组、去重、不超过 maxPerCall。是否在菜单上不在这里判——不在的名字由结果点名 */
626
+ declare function parseToolFindInput(raw: unknown, maxPerCall?: number): ToolFindInput;
627
+ /**
628
+ * 从时间线重建"已取回"的菜单工具名:`tool_find` 的 tool_call 与其**非 isError** 的 tool_result 按 toolCallId 配对,
629
+ * 取 `args.names ∩ menuNames`。入参按事件里的原样解析(去重前的原文),坏形状的条目跳过。
630
+ * 只认非 isError 的结果:被审批策略拦下("工具调用被拦截")或入参不合法的调用没有取回任何东西。
631
+ */
632
+ declare function revealedLazyTools(timeline: readonly Event[], menuNames: ReadonlySet<string>): Set<string>;
633
+ /**
634
+ * 一次取回最多返回多大:菜单里条目估算最大的 maxPerCall 件之和,加表头与分隔余量。
635
+ * 用它做 `resultPolicy.maxTokens`,spill 的按工具限额永远放行——schema 换成预览 + fetch_blob 取回来是 untrusted,等于白取
636
+ */
637
+ declare function toolFindResultBound(menu: LazyToolMenu, maxPerCall: number): number;
638
+ declare function lazyTools(opts?: LazyToolsOptions): Socket;
639
+
477
640
  /**
478
641
  * 带行号的文件视图(memory 的 `view` 与 skills 的 `skill_read` 共用,S1 抽出):
479
642
  * 行号格式对齐 Anthropic memory 工具参考实现(6 位右对齐 + 制表符);模型没指定范围时按字符上限**按行**截断,
@@ -1244,4 +1407,4 @@ declare function parseFetchBlobArgs(raw: unknown): FetchBlobArgs;
1244
1407
  declare function isTextMime(mime: string): boolean;
1245
1408
  declare function spill(opts?: SpillOptions): Socket;
1246
1409
 
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 };
1410
+ export { APPROVAL_EXPIRY_RULE, 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_LAZY_SUMMARY_CHARS, 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, DEFAULT_TOOL_FIND_MAX, type ExpiredApproval, 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, LAZY_TOOLS_SOCKET_NAME, LAZY_TOOL_RULES, type LazyToolMenu, type LazyToolMenuEntry, type LazyToolsOptions, 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, TOOL_FIND_INPUT_SCHEMA, TOOL_FIND_TOOL_DESCRIPTION, TOOL_FIND_TOOL_NAME, type TextMeasure, type TextTokenEstimator, type Tier, type ToolFindInput, approval, assertAscending, assertLimits, assertSkillsRoot, bindMemoryFs, budget, budgetUsedOf, byteLength, carriedPins, checkBudget, clipEndByTokens, compact, compactNumber, composeHandoffNote, contextOverheadOf, countLines, countModelTurns, countTier, defaultBudgetNote, defaultSummary, defaultTextTokens, evaluatePolicy, executeMemoryCommand, findExpiredApproval, findModelPin, fmt, globToRegExp, handoff, humanSize, inlineSkills, isModelCompaction, isPinNoteEvent, isTextMime, isUnder, lastHostPin, lastVisiblePerceptionNote, lastVisibleUserMessage, lazyMenuOf, lazyTools, loadSkillMenu, measureText, memory, normalizeRule, parseCompactArgs, parseFetchBlobArgs, parseHandoffArgs, parseMemoryCommand, parsePinArgs, parseRecallArgs, parseSkillMarkdown, parseSkillReadInput, parseToolFindInput, percent, perception, pinInputSchema, pinMetaOf, pinToolDescription, pins, planCompaction, previewOf, rangeTier, readPerception, recallResult, recallTool, renderCompactionSummary, renderLazyToolMenu, renderLoadedTool, renderPerception, renderSkillMenu, renderToolFindResult, resolveMemoryPath, revealedLazyTools, segmentTimelineByTurn, skills, spill, sumSessionTokens, summarizeTool, toolFindResultBound, toolReferenceOf, trailingCompactionRun, unfinishedHandoffArgs };