@reinsjs/brain 0.4.0 → 0.5.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,19 @@
1
1
  # @reinsjs/brain
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0455c28: Deliver `compact`'s request as a directive and ask twice. `SystemNotePayload` gains an optional `directive: true` for notes that ask the model to act; `@reinsjs/lowering-fetch` (all three protocols) and `@reinsjs/lowering-pi` send those as a framed `<system_note>` user message even when the model accepts mid-conversation system messages, and record the landing as `lossy(user-role)`. Measured on a pooled DeepSeek relay, the same request was ignored 4 of 4 times as a mid-conversation system message and followed 5 of 6 times as a framed user note; the official DeepSeek endpoint followed it 6 of 6 either way. Other notes (perception, pins) keep their current landing, and notes already in a log keep theirs, so cached prefixes do not change on upgrade. `compact({ force })` now asks at two lines by default (`at: [0.75, 0.8]`; a single number still works), uses blunter wording on the second request (`CompactRequestInfo.attempt`), skips the turn right after a compaction until the model has acted, and marks requests as directives unless `force.directive` is `false`.
8
+ - 24ba407: Ask the model to compact before the mechanical fallback kicks in. When the real context passes a soft line (`compact({ force: { at } })`, default `0.75` of the window) and nothing has been compacted since the last request, `compact` appends one runtime note at the end asking the model to call `compact` before doing anything else. A compaction made after such a request is recorded as `decidedBy: "forced"` (new value on `CompactionPayload.decidedBy`: the harness picked the timing, the model wrote the summary). The request is made once per segment; if the model ignores it, threshold truncation still folds mechanically at `contextLimit - reserveTokens`. Appending at the end keeps the prompt cache intact, unlike forcing `tool_choice` or narrowing the tool list. Pass `force: false` to turn it off (the default rules then drop the sentence that promises the request); `force.render` customizes the wording. `@reinsjs/eval` counts the new value separately (`CompactionCounts.forced`). The default `COMPACT_RULES` text gains one line, so sessions paused under an older version see a config change on resume.
9
+
10
+ ### Patch Changes
11
+
12
+ - Updated dependencies [0455c28]
13
+ - Updated dependencies [24ba407]
14
+ - Updated dependencies [4a57a7a]
15
+ - @reinsjs/core@0.5.0
16
+
3
17
  ## 0.4.0
4
18
 
5
19
  ### Minor Changes
package/README.md CHANGED
@@ -35,7 +35,7 @@ const agent = createAgent({
35
35
  | module | what the model gets | what it costs you |
36
36
  | --- | --- | --- |
37
37
  | `perception()` | A `system_note` at the end of the timeline with context usage, history length and budget headroom, in coarse tiers so it does not change every turn (cache-friendly). Calibrated against the last real `budget_usage`. | nothing |
38
- | `compact()` | A `compact` tool: the model summarizes a range of old turns itself; the summary carries a manifest of the folded tool results and a `recall({ seq })` tool fetches any of them back verbatim. A threshold fallback folds the oldest turns when the projection would overflow. **Recommended on** since 2026-09-10: measured on DeepSeek and Claude, recall stayed at 100% while tokens went down. | a `BlobStore` is not required |
38
+ | `compact()` | A `compact` tool: the model summarizes a range of old turns itself; the summary carries a manifest of the folded tool results and a `recall({ seq })` tool fetches any of them back verbatim. When the window passes 75% and the model has not compacted since the last fold, it appends a note asking the model to compact first, and asks once more, more bluntly, at 80% (`decidedBy: "forced"`; `force: false` turns this off, `force: { at, render, directive }` tunes it — `at` takes one ratio or an ascending list). The request is marked as a directive, so lowerings deliver it as a tagged user note even where mid-conversation system messages are accepted: some upstreams accept those but do not act on instructions inside them. If the model still does not compact, a threshold fallback at 85% folds the oldest turns down to 60%. **Recommended on** since 2026-09-10: measured on DeepSeek and Claude, recall stayed at 100% while tokens went down. | a `BlobStore` is not required |
39
39
  | `pins()` | Host-declared constraints (static text or extracted from the conversation) plus a `pin` tool. Pinned notes survive compaction and are re-injected when they scroll out. | nothing |
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`) |
@@ -63,6 +63,6 @@ Any `MemoryStore` (in-memory, `@reinsjs/store-sqlite`, `@reinsjs/store-pg`) is a
63
63
 
64
64
  ## Documentation
65
65
 
66
- `docs/技术方案.md` §9 (module specs and measurements), `docs/模块盘点/brain.md` (file map), `docs/踩坑记录.md` (pitfalls) — in Chinese, at the repository root.
66
+ `docs/archive/implementation-plans/2026-09-08-技术方案v1.0.md` §9 (module specs and measurements), `docs/系统全景图_模块盘点/brain.md` (file map), `docs/踩坑记录.md` (pitfalls) — in Chinese, at the repository root.
67
67
 
68
68
  MIT © 2026 NewRate Limited.
package/dist/index.d.ts CHANGED
@@ -282,10 +282,71 @@ declare function segmentTimelineByTurn(timeline: readonly Event[]): Event[][];
282
282
  */
283
283
  declare function trailingCompactionRun(timeline: readonly Event[]): number;
284
284
 
285
+ /**
286
+ * 到线请模型整理(OPT-261030-3):用量过软线、本段还没请过时,在末尾追加一条说明请模型先 compact 再继续。
287
+ *
288
+ * 三层分工(宪法一):模型自决整理是默认路径;它没动、用量过软线 → 这里请它整理(时机框架定、摘要模型写,
289
+ * 记 decidedBy=forced);还不动、过触发线 → core 投影链机械裁剪。
290
+ *
291
+ * 为什么是"末尾追加说明"而不是 tool_choice 强制或收窄工具表(spikes/forced-compact/,两族实测):
292
+ * 追加只动末尾,缓存照命中(DeepSeek 98% / Haiku 5.5 99.3%),模型照做(6/6、3/3);DeepSeek thinking 模式拒绝
293
+ * 一切强制 tool_choice,Haiku 5.5 接受但缓存归零;换工具表两家缓存都崩。
294
+ *
295
+ * 全部判据从时间线读,没有跨轮状态:续跑、多 run 的长期会话都成立。
296
+ */
297
+
298
+ /**
299
+ * 请求整理的缺省各级软线(占 contextLimit 的比例,升序),都低于阈值兜底的缺省触发线 85%。
300
+ * 每段(上次整理之后)每级请一次:过 75% 请第一次,模型没理、过 80% 再请一次,仍不理才留给机械兜底(OPT-261031-1)
301
+ */
302
+ declare const DEFAULT_FORCE_AT: readonly number[];
303
+ interface CompactRequestInfo {
304
+ /** 本轮真实上下文占窗口的比例,如 "78%" */
305
+ usage: string;
306
+ /** 阈值兜底的触发点,如 "85%"(与感知报的 autoFoldAt 同一口径) */
307
+ autoFoldAt: string;
308
+ /** 本段第几次请求,从 1 起 */
309
+ attempt: number;
310
+ }
311
+ interface ForceOptions {
312
+ /**
313
+ * 软线:真实上下文 ≥ contextLimit × at 时请模型整理。一个数或严格升序的一组,每个取 (0, 1),缺省 [0.75, 0.8]:
314
+ * 每段每级请一次。不低于触发线的级永远不出现(投影先裁了);相邻两级的间隔小于一步能涨的量(spill 单个结果上限 16k)时,后一级可能被跨过
315
+ */
316
+ at?: number | readonly number[];
317
+ /**
318
+ * 请求说明是否标为指令(`SystemNotePayload.directive`),缺省 true:降级层以带标签的 user 文本送达。
319
+ * 实测号池中转站对中途 system 里的请求 0/4 照做、改成这样 5/6(踩坑 42);官方线路两种都照做
320
+ */
321
+ directive?: boolean;
322
+ /** 自定义措辞 / 语言;必须是纯函数 */
323
+ render?: (info: CompactRequestInfo) => string;
324
+ }
325
+ /** 缺省说明:明确命令,不是建议(onset-pause 证明"建议在收尾前整理"无效,forced-compact 证明命令有效);第二次起更直接 */
326
+ declare function renderCompactRequest(info: CompactRequestInfo): string;
327
+ /** 某条事件是不是本模块追加的整理请求 */
328
+ declare function isCompactRequest(e: Event): boolean;
329
+ /** 时间线里最后一次整理(任何 decidedBy)之后有没有整理请求 —— "本段已经请过" */
330
+ declare function compactRequestedSinceLastCompaction(timeline: readonly Event[]): boolean;
331
+ /** 最后一次整理之后的整理请求条数 = 本段已用掉几级 */
332
+ declare function compactRequestsSinceLastCompaction(timeline: readonly Event[]): number;
333
+ /**
334
+ * 最后一次整理之后模型有没有动过(正文或工具调用);从没整理过算动过。
335
+ * 刚整理完、折后仍在软线以上时,先让模型干一轮活再请,免得整理一结束就被追着连请、撞上连续整理上限
336
+ */
337
+ declare function modelActedSinceLastCompaction(timeline: readonly Event[]): boolean;
338
+ /**
339
+ * 截至此刻的时间线:本轮开始时的快照 + 本轮新增(投影新造的阈值 compaction、beforeModel 追加的说明)。
340
+ * 后者只在 ctx.events 里、不在 ctx.timeline 里,按 seq 大于快照末尾取出
341
+ */
342
+ declare function timelineSoFar(ctx: TurnContext): Event[];
343
+ /** 本轮真实上下文占窗口的比例:投影估算 + 校准出的固定开销,与感知读数、阈值兜底同一把尺 */
344
+ declare function contextUsageRatio(ctx: TurnContext): number;
345
+
285
346
  /**
286
347
  * compact —— 自主整理模块(技术方案 §9.2,B2)。
287
348
  *
288
- * 五件事:
349
+ * 六件事:
289
350
  * 1. **工具** `compact({ summary, keep, keepRecentTurns? })`:模型自己决定何时整理、留什么(宪法一)。
290
351
  * 工具本身是静态贡献(Socket.tools),整个 run 不变,续跑补齐 pending 时也在场。
291
352
  * 2. **规则提示**:静态 systemPrompt 片段(rules.ts),告诉模型什么时候该整理、什么时候别整理。
@@ -294,6 +355,8 @@ declare function trailingCompactionRun(timeline: readonly Event[]): number;
294
355
  * 宿主经 LoopConfig.projection.reserveTokens 调;perception 会把这个点告诉模型。
295
356
  * 4. **连续上限**:连着整理(模型自决 + 阈值兜底合计)达到 maxConsecutive 次仍没有一轮"正常"工作,
296
357
  * 说明卡死了(折叠后仍放不下、或模型在反复整理)→ onTurnEnd 返回 pause(budget) 交宿主处理。
358
+ * 6. **到线请整理**(OPT-261030-3 / OPT-261031-1):过软线(缺省 75%、80% 两级,每段每级一次)→ beforeModel 末尾追加一条
359
+ * 指令类说明(directive,降级层以带标签的 user 文本送达)请模型先整理,照做记 decidedBy=forced;两级都不理就留给第 3 条的机械兜底。见 request.ts。
297
360
  * 5. **取回**(E3c):摘要下面列出被折叠的每条工具结果(seq + 工具 + 入参),`recall({ seq })` 工具逐字取回一条。
298
361
  * 整理丢细节是机制的代价(模型按自己的重要性判断留东西),清单与取回让丢掉的东西有路可回,见 recall.ts。
299
362
  *
@@ -323,6 +386,12 @@ interface CompactOptions {
323
386
  manifest?: false | ManifestOptions;
324
387
  /** 是否给模型 recall 取回工具(E3c)。缺省 true;false 时清单照列,只是模型自己取不回(宿主另有读法时用) */
325
388
  recall?: boolean;
389
+ /**
390
+ * 到线请模型整理(OPT-261030-3 / OPT-261031-1):真实上下文过某一级软线(缺省 75%、80%)、且本段(上次整理之后)还没在这一级请过时,
391
+ * 在末尾追加一条指令类说明请模型先 compact 再继续;照做的整理记 decidedBy=forced。刚整理完模型还没动过不请;两级都不理就留给触发线的机械裁剪。
392
+ * 传 false 关闭;传对象调软线与措辞
393
+ */
394
+ force?: false | ForceOptions;
326
395
  }
327
396
  declare const COMPACT_SOCKET_NAME = "compact";
328
397
  declare const DEFAULT_MAX_CONSECUTIVE_COMPACTIONS = 3;
@@ -409,7 +478,12 @@ declare const COMPACT_TOOL_NAME = "compact";
409
478
  declare const RECALL_TOOL_NAME = "recall";
410
479
  declare const COMPACT_TOOL_DESCRIPTION: string;
411
480
  declare const RECALL_TOOL_DESCRIPTION: string;
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.";
481
+ /**
482
+ * 规则里讲"到线会请你整理"的那一行(OPT-261030-3)。只有开着 compact({ force }) 时才成立,
483
+ * 所以 force: false 且没自定义 rules 时,模块用去掉这一行的版本——告诉模型的事框架必须兑现
484
+ */
485
+ declare const COMPACT_REQUEST_RULE = "- If the window gets close to full and you have not compacted, the harness will ask you to. Compact then, before anything else: that is the point where your own summary still beats a mechanical one.";
486
+ 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 the window gets close to full and you have not compacted, the harness will ask you to. Compact then, before anything else: that is the point where your own summary still beats a mechanical one.\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.";
413
487
 
414
488
  /**
415
489
  * handoff —— 会话交接模块(技术方案 §9.5,B5)。
@@ -1409,4 +1483,4 @@ declare function parseFetchBlobArgs(raw: unknown): FetchBlobArgs;
1409
1483
  declare function isTextMime(mime: string): boolean;
1410
1484
  declare function spill(opts?: SpillOptions): Socket;
1411
1485
 
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 };
1486
+ 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_REQUEST_RULE, COMPACT_RULES, COMPACT_SOCKET_NAME, COMPACT_TOOL_DESCRIPTION, COMPACT_TOOL_NAME, type CompactArgs, type CompactOptions, type CompactPlan, type CompactRequestInfo, DEFAULT_FORCE_AT, 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, type ForceOptions, 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, compactRequestedSinceLastCompaction, compactRequestsSinceLastCompaction, composeHandoffNote, contextUsageRatio, countLines, countModelTurns, countTier, defaultBudgetNote, defaultSummary, defaultTextTokens, evaluatePolicy, executeMemoryCommand, findExpiredApproval, findModelPin, fmt, globToRegExp, handoff, humanSize, inlineSkills, isCompactRequest, isModelCompaction, isPinNoteEvent, isTextMime, isUnder, lastHostPin, lastVisiblePerceptionNote, lastVisibleUserMessage, lazyMenuOf, lazyTools, loadSkillMenu, measureText, memory, modelActedSinceLastCompaction, normalizeRule, parseCompactArgs, parseFetchBlobArgs, parseHandoffArgs, parseMemoryCommand, parsePinArgs, parseRecallArgs, parseSkillMarkdown, parseSkillReadInput, parseToolFindInput, percent, perception, pinInputSchema, pinMetaOf, pinToolDescription, pins, planCompaction, previewOf, rangeTier, readPerception, recallResult, recallTool, renderCompactRequest, renderCompactionSummary, renderLazyToolMenu, renderLoadedTool, renderPerception, renderSkillMenu, renderToolFindResult, resolveMemoryPath, revealedLazyTools, segmentTimelineByTurn, skills, spill, sumSessionTokens, summarizeTool, timelineSoFar, toolFindResultBound, toolReferenceOf, trailingCompactionRun, unfinishedHandoffArgs };
package/dist/index.js CHANGED
@@ -267,9 +267,47 @@ function budget(opts) {
267
267
 
268
268
  // src/compact/compact.ts
269
269
  import {
270
- isCompaction as isCompaction2
270
+ isCompaction as isCompaction3
271
271
  } from "@reinsjs/core";
272
272
 
273
+ // src/perception/tiers.ts
274
+ function assertAscending(name, bounds) {
275
+ for (let i = 0; i < bounds.length; i++) {
276
+ const cur = bounds[i];
277
+ const prev = bounds[i - 1];
278
+ if (cur === void 0 || !Number.isFinite(cur) || prev !== void 0 && cur <= prev) {
279
+ throw new RangeError(
280
+ `the tier bounds of ${name} must be strictly ascending finite numbers, got ${JSON.stringify(bounds)}`
281
+ );
282
+ }
283
+ }
284
+ }
285
+ function rangeTier(value, bounds, fmt2) {
286
+ let level = 0;
287
+ while (level < bounds.length && value >= bounds[level]) level++;
288
+ const lo = bounds[level - 1];
289
+ const hi = bounds[level];
290
+ if (lo === void 0) return { level, label: `<${fmt2(hi)}` };
291
+ if (hi === void 0) return { level, label: `\u2265${fmt2(lo)}` };
292
+ return { level, label: `${fmt2(lo)}\u2013${fmt2(hi)}` };
293
+ }
294
+ function countTier(value, bounds) {
295
+ let level = 0;
296
+ while (level < bounds.length && value > bounds[level]) level++;
297
+ const lo = bounds[level - 1];
298
+ const hi = bounds[level];
299
+ if (lo === void 0) return { level, label: `\u2264${hi}` };
300
+ if (hi === void 0) return { level, label: `>${lo}` };
301
+ return { level, label: lo + 1 === hi ? `${hi}` : `${lo + 1}\u2013${hi}` };
302
+ }
303
+ var percent = (ratio) => `${Math.round(ratio * 100)}%`;
304
+ function compactNumber(n) {
305
+ const trim = (x) => String(Number(x.toFixed(1)));
306
+ if (n >= 1e6) return `${trim(n / 1e6)}M`;
307
+ if (n >= 1e3) return `${trim(n / 1e3)}k`;
308
+ return String(n);
309
+ }
310
+
273
311
  // src/compact/plan.ts
274
312
  import {
275
313
  foldedToolResults,
@@ -332,6 +370,7 @@ var RECALL_TOOL_DESCRIPTION = [
332
370
  "The original output is returned exactly as the tool produced it (large outputs are stored as blobs and read with fetch_blob instead).",
333
371
  "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
372
  ].join(" ");
373
+ var COMPACT_REQUEST_RULE = "- If the window gets close to full and you have not compacted, the harness will ask you to. Compact then, before anything else: that is the point where your own summary still beats a mechanical one.";
335
374
  var COMPACT_RULES = `## Managing your context window
336
375
  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
376
  - 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.
@@ -339,6 +378,7 @@ You have a \`${COMPACT_TOOL_NAME}\` tool that folds earlier conversation into a
339
378
  - 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.
340
379
  - 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.
341
380
  - Nothing folded is lost for good: under each summary the harness lists the folded tool results as \`seq N tool(arguments)\`, and \`${RECALL_TOOL_NAME}({ 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.
381
+ ${COMPACT_REQUEST_RULE}
342
382
  - 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.`;
343
383
 
344
384
  // src/compact/plan.ts
@@ -589,6 +629,52 @@ function recallTool() {
589
629
  };
590
630
  }
591
631
 
632
+ // src/compact/request.ts
633
+ import {
634
+ contextOverheadOf,
635
+ isCompaction as isCompaction2
636
+ } from "@reinsjs/core";
637
+ var DEFAULT_FORCE_AT = [0.75, 0.8];
638
+ function renderCompactRequest(info) {
639
+ if (info.attempt > 1) {
640
+ return `Context window is now ${info.usage} full and you were already asked to compact. This is the last request: your next action must be a \`${COMPACT_TOOL_NAME}\` call, before any reply or other tool. At ${info.autoFoldAt} the harness cuts the oldest turns mechanically and keeps only a rough list instead of your summary.`;
641
+ }
642
+ return `Context window is ${info.usage} full; the harness folds the oldest turns mechanically at ${info.autoFoldAt}. Before doing anything else, call \`${COMPACT_TOOL_NAME}\` now to fold the conversation so far into your own summary (use keepRecentTurns to keep the turns you are actively working from), then continue the task.`;
643
+ }
644
+ function isCompactRequest(e) {
645
+ const n = e;
646
+ return n.type === "core.system_note" && n.payload.meta?.compactRequest !== void 0;
647
+ }
648
+ function compactRequestedSinceLastCompaction(timeline) {
649
+ return compactRequestsSinceLastCompaction(timeline) > 0;
650
+ }
651
+ function compactRequestsSinceLastCompaction(timeline) {
652
+ let n = 0;
653
+ for (let i = timeline.length - 1; i >= 0; i--) {
654
+ const e = timeline[i];
655
+ if (!e || isCompaction2(e)) break;
656
+ if (isCompactRequest(e)) n++;
657
+ }
658
+ return n;
659
+ }
660
+ function modelActedSinceLastCompaction(timeline) {
661
+ for (let i = timeline.length - 1; i >= 0; i--) {
662
+ const e = timeline[i];
663
+ if (!e) continue;
664
+ if (isCompaction2(e)) return false;
665
+ if (e.type === "core.model_text" || e.type === "core.tool_call") return true;
666
+ }
667
+ return true;
668
+ }
669
+ function timelineSoFar(ctx) {
670
+ const end = ctx.timeline.at(-1)?.seq ?? 0;
671
+ const fresh = ctx.events.filter((e) => e.seq > end).sort((a, b) => a.seq - b.seq);
672
+ return [...ctx.timeline, ...fresh];
673
+ }
674
+ function contextUsageRatio(ctx) {
675
+ return (ctx.budget.used + contextOverheadOf(ctx.timeline)) / ctx.budget.contextLimit;
676
+ }
677
+
592
678
  // src/compact/compact.ts
593
679
  var COMPACT_SOCKET_NAME = "compact";
594
680
  var DEFAULT_MAX_CONSECUTIVE_COMPACTIONS = 3;
@@ -642,6 +728,15 @@ function compact(opts = {}) {
642
728
  throw new RangeError(`compact.maxConsecutive must be an integer >= 1, got ${String(maxConsecutive)}`);
643
729
  }
644
730
  const withRecall = opts.recall ?? true;
731
+ const force = opts.force === false ? void 0 : opts.force ?? {};
732
+ const forceAt = typeof force?.at === "number" ? [force.at] : force?.at ?? DEFAULT_FORCE_AT;
733
+ if (force && (forceAt.length === 0 || forceAt.some((at, i) => !(at > 0 && at < 1) || i > 0 && at <= (forceAt[i - 1] ?? 0)))) {
734
+ throw new RangeError(
735
+ `compact.force.at must be a number in (0, 1) or a strictly ascending non-empty list of them, got ${JSON.stringify(force.at)}`
736
+ );
737
+ }
738
+ const directive = force?.directive ?? true;
739
+ const renderRequest = force?.render ?? renderCompactRequest;
645
740
  const records = /* @__PURE__ */ new WeakMap();
646
741
  const recordOf = (ctx) => {
647
742
  let r = records.get(ctx);
@@ -662,6 +757,30 @@ function compact(opts = {}) {
662
757
  const socket = {
663
758
  name: COMPACT_SOCKET_NAME,
664
759
  tools: withRecall ? [tool, recallTool()] : [tool],
760
+ beforeModel(ctx) {
761
+ if (!force) return void 0;
762
+ const timeline = timelineSoFar(ctx);
763
+ const used = compactRequestsSinceLastCompaction(timeline);
764
+ const at = forceAt[used];
765
+ const usage = contextUsageRatio(ctx);
766
+ if (at === void 0 || usage < at || !modelActedSinceLastCompaction(timeline)) return void 0;
767
+ const info = {
768
+ usage: percent(usage),
769
+ autoFoldAt: percent(ctx.budget.targetTokens / ctx.budget.contextLimit),
770
+ attempt: used + 1
771
+ };
772
+ ctx.emit({
773
+ type: "core.system_note",
774
+ actor: "system",
775
+ payload: {
776
+ kind: "budget",
777
+ text: renderRequest(info),
778
+ meta: { compactRequest: { ...info, at } },
779
+ ...directive ? { directive: true } : {}
780
+ }
781
+ });
782
+ return void 0;
783
+ },
665
784
  afterModel(ctx, events) {
666
785
  recordOf(ctx).hadToolCall = events.some((e) => e.type === "core.tool_call");
667
786
  },
@@ -678,7 +797,10 @@ function compact(opts = {}) {
678
797
  return replaceResult(result, err instanceof Error ? err.message : String(err), true);
679
798
  }
680
799
  if (!plan.ok) return replaceResult(result, plan.reason, true);
681
- const payload = plan.payload;
800
+ const payload = {
801
+ ...plan.payload,
802
+ decidedBy: compactRequestedSinceLastCompaction(timelineSoFar(ctx)) ? "forced" : "model"
803
+ };
682
804
  ctx.emit({
683
805
  type: "core.compaction",
684
806
  actor: "model",
@@ -693,7 +815,7 @@ function compact(opts = {}) {
693
815
  const record = records.get(ctx);
694
816
  if (!record?.hadToolCall) return void 0;
695
817
  const snapshotEnd = ctx.timeline.at(-1)?.seq ?? 0;
696
- const thresholdThisTurn = ctx.events.filter((e) => isCompaction2(e) && e.seq > snapshotEnd).length;
818
+ const thresholdThisTurn = ctx.events.filter((e) => isCompaction3(e) && e.seq > snapshotEnd).length;
697
819
  const thisTurn = record.compactions + thresholdThisTurn;
698
820
  if (thisTurn === 0) return void 0;
699
821
  const total = thisTurn + trailingCompactionRun(ctx.timeline);
@@ -706,11 +828,14 @@ function compact(opts = {}) {
706
828
  };
707
829
  }
708
830
  };
709
- if (opts.rules !== false) socket.systemPrompt = opts.rules ?? COMPACT_RULES;
831
+ if (opts.rules !== false) {
832
+ socket.systemPrompt = opts.rules ?? (force ? COMPACT_RULES : COMPACT_RULES.replace(`${COMPACT_REQUEST_RULE}
833
+ `, ""));
834
+ }
710
835
  return socket;
711
836
  }
712
837
  function isModelCompaction(e) {
713
- return isCompaction2(e) && e.payload.decidedBy === "model";
838
+ return isCompaction3(e) && e.payload.decidedBy === "model";
714
839
  }
715
840
 
716
841
  // src/handoff/handoff.ts
@@ -1687,47 +1812,7 @@ function memory(opts = {}) {
1687
1812
  }
1688
1813
 
1689
1814
  // src/perception/reading.ts
1690
- import { contextOverheadOf } from "@reinsjs/core";
1691
-
1692
- // src/perception/tiers.ts
1693
- function assertAscending(name, bounds) {
1694
- for (let i = 0; i < bounds.length; i++) {
1695
- const cur = bounds[i];
1696
- const prev = bounds[i - 1];
1697
- if (cur === void 0 || !Number.isFinite(cur) || prev !== void 0 && cur <= prev) {
1698
- throw new RangeError(
1699
- `the tier bounds of ${name} must be strictly ascending finite numbers, got ${JSON.stringify(bounds)}`
1700
- );
1701
- }
1702
- }
1703
- }
1704
- function rangeTier(value, bounds, fmt2) {
1705
- let level = 0;
1706
- while (level < bounds.length && value >= bounds[level]) level++;
1707
- const lo = bounds[level - 1];
1708
- const hi = bounds[level];
1709
- if (lo === void 0) return { level, label: `<${fmt2(hi)}` };
1710
- if (hi === void 0) return { level, label: `\u2265${fmt2(lo)}` };
1711
- return { level, label: `${fmt2(lo)}\u2013${fmt2(hi)}` };
1712
- }
1713
- function countTier(value, bounds) {
1714
- let level = 0;
1715
- while (level < bounds.length && value > bounds[level]) level++;
1716
- const lo = bounds[level - 1];
1717
- const hi = bounds[level];
1718
- if (lo === void 0) return { level, label: `\u2264${hi}` };
1719
- if (hi === void 0) return { level, label: `>${lo}` };
1720
- return { level, label: lo + 1 === hi ? `${hi}` : `${lo + 1}\u2013${hi}` };
1721
- }
1722
- var percent = (ratio) => `${Math.round(ratio * 100)}%`;
1723
- function compactNumber(n) {
1724
- const trim = (x) => String(Number(x.toFixed(1)));
1725
- if (n >= 1e6) return `${trim(n / 1e6)}M`;
1726
- if (n >= 1e3) return `${trim(n / 1e3)}k`;
1727
- return String(n);
1728
- }
1729
-
1730
- // src/perception/reading.ts
1815
+ import { contextOverheadOf as contextOverheadOf2 } from "@reinsjs/core";
1731
1816
  var ASSISTANT_TYPES2 = /* @__PURE__ */ new Set([
1732
1817
  "core.model_thinking",
1733
1818
  "core.model_text",
@@ -1772,7 +1857,7 @@ function remainingOf(budget2, contextTokens, limits) {
1772
1857
  }
1773
1858
  function readPerception(ctx, thresholds, limits, opts = {}) {
1774
1859
  const { budget: budget2 } = ctx;
1775
- const contextOverhead = opts.calibrate === false ? 0 : contextOverheadOf(ctx.timeline);
1860
+ const contextOverhead = opts.calibrate === false ? 0 : contextOverheadOf2(ctx.timeline);
1776
1861
  const contextTokens = budget2.used + contextOverhead;
1777
1862
  const spilled = ctx.events.filter(
1778
1863
  (e) => e.type === "core.tool_result" && e.payload.spilled
@@ -2675,10 +2760,12 @@ export {
2675
2760
  APPROVAL_SOCKET_NAME,
2676
2761
  BUDGET_SOCKET_NAME,
2677
2762
  COMPACT_INPUT_SCHEMA,
2763
+ COMPACT_REQUEST_RULE,
2678
2764
  COMPACT_RULES,
2679
2765
  COMPACT_SOCKET_NAME,
2680
2766
  COMPACT_TOOL_DESCRIPTION,
2681
2767
  COMPACT_TOOL_NAME,
2768
+ DEFAULT_FORCE_AT,
2682
2769
  DEFAULT_HANDOFF_REASON,
2683
2770
  DEFAULT_LAZY_SUMMARY_CHARS,
2684
2771
  DEFAULT_MAX_CONSECUTIVE_COMPACTIONS,
@@ -2750,8 +2837,11 @@ export {
2750
2837
  clipEndByTokens,
2751
2838
  compact,
2752
2839
  compactNumber,
2840
+ compactRequestedSinceLastCompaction,
2841
+ compactRequestsSinceLastCompaction,
2753
2842
  composeHandoffNote,
2754
- contextOverheadOf,
2843
+ contextOverheadOf2 as contextOverheadOf,
2844
+ contextUsageRatio,
2755
2845
  countLines,
2756
2846
  countModelTurns,
2757
2847
  countTier,
@@ -2767,6 +2857,7 @@ export {
2767
2857
  handoff,
2768
2858
  humanSize,
2769
2859
  inlineSkills,
2860
+ isCompactRequest,
2770
2861
  isModelCompaction,
2771
2862
  isPinNoteEvent,
2772
2863
  isTextMime,
@@ -2779,6 +2870,7 @@ export {
2779
2870
  loadSkillMenu,
2780
2871
  measureText,
2781
2872
  memory,
2873
+ modelActedSinceLastCompaction,
2782
2874
  normalizeRule,
2783
2875
  parseCompactArgs,
2784
2876
  parseFetchBlobArgs,
@@ -2801,6 +2893,7 @@ export {
2801
2893
  readPerception,
2802
2894
  recallResult,
2803
2895
  recallTool,
2896
+ renderCompactRequest,
2804
2897
  renderCompactionSummary,
2805
2898
  renderLazyToolMenu,
2806
2899
  renderLoadedTool,
@@ -2814,6 +2907,7 @@ export {
2814
2907
  spill,
2815
2908
  sumSessionTokens,
2816
2909
  summarizeTool,
2910
+ timelineSoFar,
2817
2911
  toolFindResultBound,
2818
2912
  toolReferenceOf,
2819
2913
  trailingCompactionRun,