@reinsjs/brain 0.2.1 → 0.4.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,28 @@
1
1
  # @reinsjs/brain
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 6b390d0: perception: the default render no longer reports session tokens used or unfolded turns (both stay in `meta.reading` and are available to a custom `render`). Session tokens counted cache reads, so a fresh session crossed several tiers within a few steps and each crossing appended another note the model could not act on. The compactions line keeps its "what was folded" note. compact: the default rules no longer name the perception note's title, so they hold when the host renders its own status notes or does not install perception.
8
+
9
+ ### Patch Changes
10
+
11
+ - fb032c1: core: the projection's threshold fallback now compares the calibrated context size — the estimate plus the fixed overhead the estimate cannot see (system prompt, tool definitions, thinking), measured from the last `budget_usage` — against `contextLimit - reserveTokens`. Before, it compared the raw estimate, so perception could report "≥85%, the harness auto-folds at 85%" while no fold happened, and a system prompt plus tool table larger than the reserve could overflow the window before the fallback ever fired. `contextOverheadOf` moves to core (brain still re-exports it) and returns 0 when the last usage record yields a non-finite value, so a malformed `budget_usage` cannot fail the run at start; `ProjectionStats.overheadTokens` is new; `project({ budget: { overheadTokens: 0 } })` restores the old comparison. The fallback now fires earlier by that overhead, and `reserveTokens` is effectively the output reserve.
12
+ - Updated dependencies [fb032c1]
13
+ - @reinsjs/core@0.4.0
14
+
15
+ ## 0.3.0
16
+
17
+ ### Minor Changes
18
+
19
+ - a3afbf9: `lazyTools()` builds its menu from every tool bound before it (`SocketSetup.tools`), not only the host's — so tools contributed by an earlier socket, such as `mcpTools({ override: (t, info) => info.annotations?.readOnlyHint ? { ...t, lazy: true } : false })`, are disclosed on demand too. Register `lazyTools()` after the sockets that feed it; `lazy` tools from sockets registered later are still never hidden, and the module now warns once naming them. The "already has a tool named tool_find" check likewise looks at everything bound before it. `lazyMenuOf()` keeps its signature (the parameter was renamed).
20
+
21
+ ### Patch Changes
22
+
23
+ - Updated dependencies [a3afbf9]
24
+ - @reinsjs/core@0.3.0
25
+
3
26
  ## 0.2.1
4
27
 
5
28
  ### Patch Changes
package/README.md CHANGED
@@ -43,7 +43,7 @@ const agent = createAgent({
43
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
+ | `lazyTools()` | Tool discovery for large tool tables — the consumer of `Tool.lazy`. 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`. The menu is built from the tools bound *before* this socket — the host's and those of sockets registered earlier, e.g. `mcpTools({ override: (t, info) => info.annotations?.readOnlyHint ? { ...t, lazy: true } : false })` — so register `lazyTools()` last; `lazy` tools from later sockets are never hidden, one warning names them. No `lazy` tool bound before it, or a 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` |
47
47
 
48
48
  ### Skills from a database
49
49
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Tool, TurnContext, MaybePromise, Socket, Event, CompactionPayload, FoldedToolResult, ToolContext, ContentPart, EventDraft, ToolReferencePart, MemoryStore, CoreEventOf, SkillSource } from '@reinsjs/core';
2
+ export { contextOverheadOf } from '@reinsjs/core';
2
3
 
3
4
  /**
4
5
  * approval —— 审批与权限模块(技术方案 §9.7,B7)。
@@ -408,7 +409,7 @@ declare const COMPACT_TOOL_NAME = "compact";
408
409
  declare const RECALL_TOOL_NAME = "recall";
409
410
  declare const COMPACT_TOOL_DESCRIPTION: string;
410
411
  declare const RECALL_TOOL_DESCRIPTION: string;
411
- 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.";
412
+ declare const COMPACT_RULES = "## Managing your context window\nYou have a `compact` tool that folds earlier conversation into a summary you write. Status notes from the harness, if present, 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.";
412
413
 
413
414
  /**
414
415
  * handoff —— 会话交接模块(技术方案 §9.5,B5)。
@@ -552,7 +553,7 @@ declare function renderToolFindResult(input: {
552
553
  * lazy-tools —— 工具懒发现(技术方案 §9.10,D1):大工具表的渐进式披露,`Tool.lazy` 的消费者。
553
554
  *
554
555
  * 库只做两件事(宪法一):
555
- * - **让它看见**:系统提示里一份菜单(每件 `lazy: true` 的宿主工具的 name + 一行摘要),run 起步算一次、run 内不变、进 configHash。
556
+ * - **让它看见**:系统提示里一份菜单(每件 `lazy: true` 的工具的 name + 一行摘要),run 起步算一次、run 内不变、进 configHash。
556
557
  * - **给它能力**:`tool_find({ names })` 取回几件工具的完整 description + inputSchema;从下一轮起那几件出现在请求的工具表里。
557
558
  * 取哪几件、什么时候取是模型的判断;规则提示只给经验(rules.ts)。
558
559
  *
@@ -568,18 +569,20 @@ declare function renderToolFindResult(input: {
568
569
  * - **过滤路径**(其余降级层):本轮工具表 = 非 lazy + 已取回的 lazy;取回后的第一个请求缓存前缀重算一次(Anthropic 文档:工具表
569
570
  * 变动使三段缓存全失效),所以规则文案要求一次把要用的都取回;实测数字见 `spikes/d1-lazy-tools-cache/`。
570
571
  *
571
- * 作用范围只有**宿主工具**(`SocketSetup.hostTools`):静态贡献阶段各 Socket 互不可见,Socket 贡献的工具(如 MCP 经 `override`
572
- * 标了 lazy)不进菜单——菜单上没有的工具若被藏起来就等于消失,所以也不藏。模块用对象同一性(WeakSet)记住"哪些工具是菜单工具",
573
- * 同一个 Socket 实例给多个 agent 定义共用也不会串。
572
+ * 作用范围是**注册在本模块之前已并入的工具**(`SocketSetup.tools`:宿主工具 + 排在前面的 Socket 贡献,2026-09-22 起):MCP 经
573
+ * `override` 标了 lazy 的工具也进菜单,前提是 `lazyTools()` 注册在 `mcpTools()` 之后——静态贡献按注册顺序依次解析,后面的看得见前面的,
574
+ * 反过来不行。注册在本模块之后的 Socket 贡献的 lazy 工具不进菜单也不藏(菜单上没有的工具若被藏起来就等于消失),`beforeModel`
575
+ * 见到这样的工具告警一次指出顺序。模块用对象同一性(WeakSet)记住"哪些工具是菜单工具",同一个 Socket 实例给多个 agent 定义共用也不会串。
574
576
  *
575
577
  * 模型没取回就直接调菜单里的工具:`beforeTool` 回 `block` 并指向 `tool_find`——不拦的话循环回"未知工具",模型会以为工具不存在;
576
578
  * 也不放行,因为请求里没给 schema 的调用入参多半不对(原生路径同样拦:厂商知道这件工具、模型只凭菜单摘要就能报出名字)。
577
579
  * 续跑补齐 pending 时没有 beforeModel、表是全表,隐藏工具照常执行。
578
580
  *
579
581
  * trust:工具说明与 schema 是宿主配置,视同系统提示可信,`tool_find` 声明 `resultTrust: "system"`(与 `skill_read` 同一条理由)。
582
+ * MCP 工具的说明来自服务器,但它本就直接进请求的 tools 块、与系统提示同一信任层级,经 `tool_find` 取回不另降级。
580
583
  * `resultPolicy.maxTokens` 按"最大的 maxPerCall 件条目估算之和 + 256"在 setup 时算出:spill 永不把 schema 换成 untrusted 预览。
581
584
  *
582
- * 缺则不注册:宿主没有一件 `lazy: true` 的工具、或宿主自己已有同名 `tool_find` → 工具与菜单都不出现,告警一次(同 skills)。
585
+ * 缺则不注册:此前并入的工具里没有一件 `lazy: true`、或已有同名 `tool_find` → 工具与菜单都不出现,告警一次(同 skills)。
583
586
  * 不做:关键词搜索(菜单就是搜索空间,200 行约 4k token 且逐轮不变)、按 provider 原生 deferred-tools 下发(降级层的优化,另立任务)。
584
587
  */
585
588
 
@@ -614,10 +617,10 @@ interface LazyToolMenu {
614
617
  byName: Map<string, Tool>;
615
618
  }
616
619
  /**
617
- * 从宿主工具表挑出 `lazy: true` 的做菜单。纯函数,菜单与测试共用。
618
- * 按 name 排序,与宿主给的顺序无关——菜单进 configHash,顺序抖动会误判配置漂移。
620
+ * 从一张工具表挑出 `lazy: true` 的做菜单。纯函数,菜单与测试共用;模块传的是 `SocketSetup.tools`(到本模块为止已并入的表)。
621
+ * 按 name 排序,与给的顺序无关——菜单进 configHash,顺序抖动会误判配置漂移。
619
622
  */
620
- declare function lazyMenuOf(hostTools: readonly Tool[], summarize?: (tool: Tool) => string): LazyToolMenu;
623
+ declare function lazyMenuOf(tools: readonly Tool[], summarize?: (tool: Tool) => string): LazyToolMenu;
621
624
  interface ToolFindInput {
622
625
  /** 去重后的名字,保持模型给的顺序 */
623
626
  names: string[];
@@ -911,17 +914,12 @@ interface ReadingThresholds {
911
914
  declare function countModelTurns(events: readonly Event[]): number;
912
915
  /** 累加 budget_usage:输入、缓存读、缓存写、输出全算,反映的是"花了多少",不是"上下文多大" */
913
916
  declare function sumSessionTokens(timeline: readonly Event[]): number;
914
- /**
915
- * 估算与真实之间的固定开销(B8,关闭 §17 的 B2 实测发现)。
916
- *
917
- * 投影只数模型可见事件的正文,系统提示、工具表、thinking 签名块等都不在内,真实 input 可高出一倍。
918
- * 这些多出来的部分在一个 run 里基本是常量(系统提示与工具表整轮不变),所以用**加法**校准而不是比例:
919
- * 比例会随历史变长把误差放大(100k 时翻倍成 200k),加法只补那块固定的开销。
920
- * 数据来自日志最后一条同时带 tokens 与 contextEstimate 的 budget_usage:真实上下文 = input + cacheRead + cacheWrite。
921
- */
922
- declare function contextOverheadOf(timeline: readonly Event[]): number;
917
+
923
918
  interface ReadingOptions {
924
- /** 用上一请求的真实用量校准上下文估算。缺省 true;关掉则只按投影估算(偏低) */
919
+ /**
920
+ * 用上一请求的真实用量校准上下文估算。缺省 true,与 core 阈值兜底同一口径;
921
+ * 关掉则只按投影估算(偏低),此时读数会比兜底实际触发点低一截
922
+ */
925
923
  calibrate?: boolean;
926
924
  }
927
925
  declare function readPerception(ctx: TurnContext, thresholds: ReadingThresholds, limits?: PerceptionLimits, opts?: ReadingOptions): PerceptionReading;
@@ -946,9 +944,9 @@ declare function readPerception(ctx: TurnContext, thresholds: ReadingThresholds,
946
944
  interface PerceptionOptions {
947
945
  /** 上下文使用率档位边界(占窗口比例)。缺省 [0.5, 0.7, 0.85] → <50% / 50%–70% / 70%–85% / ≥85% */
948
946
  usageTiers?: readonly number[];
949
- /** 未折叠模型轮数档位边界。缺省 [5, 15, 40] → ≤5 / 6–15 / 16–40 / >40 */
947
+ /** 未折叠模型轮数档位边界。缺省 [5, 15, 40] → ≤5 / 6–15 / 16–40 / >40。只进读数,缺省 render 不报 */
950
948
  turnTiers?: readonly number[];
951
- /** 会话累计 token 档位边界。缺省 [1e4, 5e4, 2e5, 1e6] */
949
+ /** 会话累计 token 档位边界。缺省 [1e4, 5e4, 2e5, 1e6]。只进读数,缺省 render 不报 */
952
950
  tokenTiers?: readonly number[];
953
951
  /** 外溢结果条数档位边界(0 单独一档)。缺省 [3, 10] → 0 / 1–3 / 4–10 / >10 */
954
952
  spillTiers?: readonly number[];
@@ -972,6 +970,10 @@ declare function perception(opts?: PerceptionOptions): Socket;
972
970
  * 读数 → 给模型看的文字。只陈述事实,不下指令:什么时候整理、要不要交接是模型的判断(宪法一),
973
971
  * 规则提示属于 compact 模块(B2)且放在稳定的系统提示里,不在这条每次变档才出现的说明里。
974
972
  *
973
+ * 只报对模型做决定有用的量。"会话累计 token"与"未折叠轮数"留在读数里(meta 与自定义 render 可用),缺省文字不报
974
+ * (2026-10-30 OnSet 反馈):累计 token 含缓存读,上下文一大每步都加一整份,新会话几步就连跨几档;轮数档位开头也连跳。
975
+ * 每跨一档文字就变、就多一条说明,而模型拿这两个数做不了任何判断 —— 上下文多满看使用率,花了多少看预算余量。
976
+ *
975
977
  * 用英文写:这段话进的是模型上下文而不是给人看的日志,英文 token 更省,且各家模型都熟。
976
978
  * 宿主要换措辞或语言,给 perception() 传自己的 render。
977
979
  */
@@ -1407,4 +1409,4 @@ declare function parseFetchBlobArgs(raw: unknown): FetchBlobArgs;
1407
1409
  declare function isTextMime(mime: string): boolean;
1408
1410
  declare function spill(opts?: SpillOptions): Socket;
1409
1411
 
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 };
1412
+ 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, 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 };
package/dist/index.js CHANGED
@@ -333,7 +333,7 @@ var RECALL_TOOL_DESCRIPTION = [
333
333
  "Use it when you need a value that the summary only mentioned or left out; each recall costs a turn and stays in context afterwards."
334
334
  ].join(" ");
335
335
  var COMPACT_RULES = `## Managing your context window
336
- You have a \`${COMPACT_TOOL_NAME}\` tool that folds earlier conversation into a summary you write. Runtime notes titled "Runtime context status" tell you how full the window is.
336
+ You have a \`${COMPACT_TOOL_NAME}\` tool that folds earlier conversation into a summary you write. Status notes from the harness, if present, tell you how full the window is.
337
337
  - 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.
338
338
  - 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.
339
339
  - 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.
@@ -992,10 +992,10 @@ function summarizeTool(tool, maxChars = DEFAULT_LAZY_SUMMARY_CHARS) {
992
992
  if (flat.length <= maxChars) return flat;
993
993
  return `${flat.slice(0, Math.max(0, maxChars - 1)).trimEnd()}\u2026`;
994
994
  }
995
- function lazyMenuOf(hostTools, summarize = (t) => summarizeTool(t)) {
996
- const tools = hostTools.filter((t) => t.lazy === true).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
997
- const entries = tools.map((t) => ({ name: t.name, summary: summarize(t).replace(/\s*\n\s*/g, " ") }));
998
- return { tools, entries, byName: new Map(tools.map((t) => [t.name, t])) };
995
+ function lazyMenuOf(tools, summarize = (t) => summarizeTool(t)) {
996
+ const picked = tools.filter((t) => t.lazy === true).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
997
+ const entries = picked.map((t) => ({ name: t.name, summary: summarize(t).replace(/\s*\n\s*/g, " ") }));
998
+ return { tools: picked, entries, byName: new Map(picked.map((t) => [t.name, t])) };
999
999
  }
1000
1000
  function parseToolFindInput(raw, maxPerCall = DEFAULT_TOOL_FIND_MAX) {
1001
1001
  if (typeof raw !== "object" || raw === null || !Array.isArray(raw.names)) {
@@ -1065,17 +1065,17 @@ function lazyTools(opts = {}) {
1065
1065
  const resolveFor = (setup) => {
1066
1066
  if (resolved.has(setup)) return resolved.get(setup);
1067
1067
  let out;
1068
- if (setup.hostTools.some((t) => t.name === TOOL_FIND_TOOL_NAME)) {
1068
+ if (setup.tools.some((t) => t.name === TOOL_FIND_TOOL_NAME)) {
1069
1069
  warnOnce(
1070
1070
  "host-tool",
1071
- `[reins/lazy-tools] The host tool table already has a tool named ${TOOL_FIND_TOOL_NAME}, so this module's tool and menu are not registered. Rename the host tool to enable them.`
1071
+ `[reins/lazy-tools] The tool table already has a tool named ${TOOL_FIND_TOOL_NAME} (from the host or a socket registered before lazyTools()), so this module's tool and menu are not registered. Rename that tool to enable them.`
1072
1072
  );
1073
1073
  } else {
1074
- const menu = lazyMenuOf(setup.hostTools, summarize);
1074
+ const menu = lazyMenuOf(setup.tools, summarize);
1075
1075
  if (menu.tools.length === 0) {
1076
1076
  warnOnce(
1077
1077
  "no-lazy",
1078
- "[reins/lazy-tools] No host tool is marked lazy: true, so tool_find and the menu are not registered. Mark the tools you want disclosed on demand with lazy: true to enable them."
1078
+ "[reins/lazy-tools] No tool bound before lazyTools() is marked lazy: true, so tool_find and the menu are not registered. Mark the tools you want disclosed on demand with lazy: true, and register lazyTools() after the sockets (such as mcpTools()) that contribute them."
1079
1079
  );
1080
1080
  } else {
1081
1081
  for (const t of menu.tools) menuTools.add(t);
@@ -1094,7 +1094,18 @@ function lazyTools(opts = {}) {
1094
1094
  },
1095
1095
  beforeModel(ctx) {
1096
1096
  const menuNames = /* @__PURE__ */ new Set();
1097
- for (const t of ctx.tools) if (t.lazy === true && menuTools.has(t)) menuNames.add(t.name);
1097
+ const late = [];
1098
+ for (const t of ctx.tools) {
1099
+ if (t.lazy !== true) continue;
1100
+ if (menuTools.has(t)) menuNames.add(t.name);
1101
+ else late.push(t.name);
1102
+ }
1103
+ if (late.length > 0) {
1104
+ warnOnce(
1105
+ "late",
1106
+ `[reins/lazy-tools] ${late.length} tool(s) marked lazy: true are not on the menu because their socket is registered after lazyTools(): ${late.sort().join(", ")}. They are sent in full every turn. Register lazyTools() after the sockets that contribute them.`
1107
+ );
1108
+ }
1098
1109
  if (menuNames.size === 0) return void 0;
1099
1110
  const revealed = revealedLazyTools(ctx.timeline, menuNames);
1100
1111
  const hidden = /* @__PURE__ */ new Map();
@@ -1676,7 +1687,7 @@ function memory(opts = {}) {
1676
1687
  }
1677
1688
 
1678
1689
  // src/perception/reading.ts
1679
- import { contextTokensOf as contextTokensOf2 } from "@reinsjs/core";
1690
+ import { contextOverheadOf } from "@reinsjs/core";
1680
1691
 
1681
1692
  // src/perception/tiers.ts
1682
1693
  function assertAscending(name, bounds) {
@@ -1742,14 +1753,6 @@ function sumSessionTokens(timeline) {
1742
1753
  }
1743
1754
  return n;
1744
1755
  }
1745
- function contextOverheadOf(timeline) {
1746
- for (let i = timeline.length - 1; i >= 0; i--) {
1747
- const e = timeline[i];
1748
- if (e?.type !== "core.budget_usage" || e.payload.contextEstimate === void 0) continue;
1749
- return Math.max(0, contextTokensOf2(e.payload.tokens) - e.payload.contextEstimate);
1750
- }
1751
- return 0;
1752
- }
1753
1756
  function remainingOf(budget2, contextTokens, limits) {
1754
1757
  const used = {
1755
1758
  contextTokens,
@@ -1809,8 +1812,7 @@ function renderPerception(r) {
1809
1812
  const lines = [
1810
1813
  "Runtime context status (from the harness, not from the user):",
1811
1814
  `- Context window used: ${r.contextUsage.label} (the harness auto-folds the oldest turns at ${r.autoFoldAt})`,
1812
- `- Unfolded history: ${r.unfoldedTurns.label} turns; compactions so far: ${r.compactions} ${foldedNote(r.compactions)}`,
1813
- `- Session tokens used: ${r.sessionTokens.label}`
1815
+ `- Compactions so far: ${r.compactions} ${foldedNote(r.compactions)}`
1814
1816
  ];
1815
1817
  if (r.budgetRemaining) {
1816
1818
  lines.push(`- Run budget remaining: ${r.budgetRemaining.label} (tightest: ${r.budgetRemaining.tightest})`);