@reinsjs/brain 0.8.8 → 0.10.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 +23 -0
- package/README.md +2 -2
- package/dist/index.d.ts +27 -8
- package/dist/index.js +46 -12
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# @reinsjs/brain
|
|
2
2
|
|
|
3
|
+
## 0.10.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 12d9343: `recall({ seq })` also brings back a folded user message verbatim, media included, so a screenshot the user pasted earlier is no longer lost once `compact` folds it. A compaction summary gets a second list (`MEDIA_MANIFEST_HEADING`) of folded user messages that carried images, video or audio, the receipt counts them, and the `compact` / `recall` tool descriptions and rules text mention them. The recalled message comes back as a tool result and is therefore `untrusted`. Summaries without media are unchanged; `manifest: false` turns the new list off as well. The rules text and tool descriptions changed, so the config hash of runs using `compact()` changes too.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [c47e62b]
|
|
12
|
+
- Updated dependencies [12d9343]
|
|
13
|
+
- @reinsjs/core@0.16.0
|
|
14
|
+
|
|
15
|
+
## 0.9.0
|
|
16
|
+
|
|
17
|
+
### Minor Changes
|
|
18
|
+
|
|
19
|
+
- f8a3550: `budget()` pauses with `code: "reins.budget"` (`BUDGET_PAUSE_CODE`; pass `code: (hits) => string` to compute your own; pause codes are lowercase, so lowercase a dimension name before using it) and `compact()` pauses on its consecutive-compaction limit with `code: "reins.compact_stalled"` (`COMPACT_STALLED_PAUSE_CODE`). Both still use `reason: "budget"`; the code is what tells them apart afterwards.
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- Updated dependencies [f8a3550]
|
|
24
|
+
- @reinsjs/core@0.15.0
|
|
25
|
+
|
|
3
26
|
## 0.8.8
|
|
4
27
|
|
|
5
28
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -35,13 +35,13 @@ 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. 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 |
|
|
38
|
+
| `compact()` | A `compact` tool: the model summarizes a range of old turns itself; the summary carries a manifest of the folded tool results, plus a second list of folded user messages that carried images, video or audio, and a `recall({ seq })` tool fetches any of them back verbatim (a recalled user message comes back as an `untrusted` tool result, media included). 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%. Compacting `maxConsecutive` (default 3) times in a row without a turn of progress pauses the run with `reason: "budget"` and `code: "reins.compact_stalled"`. **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. A host spec can also be a **resident snapshot** (`{ name, snapshot }`, sync or async): taken at the start of each segment — the session's first turn and the first turn after every compaction — and appended only when it differs from the copy in view, so an index of the model's memory stays at hand without being rewritten mid-task (see below). | 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`) |
|
|
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. If your store routes memory into layers (`/memories/personal`, `/memories/project`, …), declare them as `directories` so an empty layer views as an empty directory instead of "does not exist", and shows up when the model views `/memories`. **Off by default.** | a `MemoryStore` |
|
|
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
|
-
| `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"
|
|
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"` and `code: "reins.budget"` (pass `code: (hits) => string` to compute your own — pause codes are lowercase, so lowercase a dimension name before using it); 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
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
|
| `haltOnFailure()` | Models put several calls in one reply to save round trips, and the order is often a dependency: update the item, *then* tell the team it is ready. The model cannot make the second call conditional on the first — it does not see results inside one reply. With this module, once a call in the batch has failed (or is still waiting for approval or a client result), the calls after it are not run: each gets an error result naming the earlier call and asking the model to handle it first. Tool call ids stay one-to-one, nothing is executed, nothing counts toward the `toolCalls` budget. `counts(result)` picks which failures matter, `applies(call, tool)` which later calls to hold back (e.g. let `risk: "low"` reads run). Register it **first**. **Opt-in.** | nothing |
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Tool, TurnContext, MaybePromise, Socket, Event, CompactionPayload, FoldedToolResult, ToolContext, ContentPart, ToolResultEvent, ToolCallEvent, EventDraft, ToolReferencePart, MemoryStore, CoreEventOf, SkillSource } from '@reinsjs/core';
|
|
1
|
+
import { Tool, TurnContext, MaybePromise, Socket, Event, CompactionPayload, FoldedToolResult, FoldedUserMedia, ToolContext, ContentPart, ToolResultEvent, ToolCallEvent, EventDraft, ToolReferencePart, MemoryStore, CoreEventOf, SkillSource } from '@reinsjs/core';
|
|
2
2
|
export { contextOverheadOf } from '@reinsjs/core';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -154,8 +154,8 @@ declare const APPROVAL_EXPIRY_RULE = "- An approval can expire if it arrives too
|
|
|
154
154
|
* contextTokens(单次请求送进模型的上下文大小)、totalTokens(本次 run 累计输入 + 输出)、turns、toolCalls、wallMs。
|
|
155
155
|
*
|
|
156
156
|
* 做法:`onTurnEnd` 里对照 `ctx.budget`(循环在模型调用后已更新 tokensSpent / wallMs / lastUsage),任一维 **用量 ≥ 上限**
|
|
157
|
-
* 即返回 `{ pause: { reason: "budget", note } }`,循环 append `run_paused(reason=budget)` 并以 paused 返回,note 进
|
|
158
|
-
* `Interruption`
|
|
157
|
+
* 即返回 `{ pause: { reason: "budget", code, note } }`,循环 append `run_paused(reason=budget)` 并以 paused 返回,note 进
|
|
158
|
+
* `Interruption` 给宿主看;原因码 `code`(缺省 `BUDGET_PAUSE_CODE`)随暂停落库,事后与"连续整理失败""宿主自己的配额"分得开。只在模型本轮还要继续(有工具调用)时拦:模型已经收尾作答的轮,循环本来就要停,
|
|
159
159
|
* 把一个自然结束的 run 改成"暂停"只会让宿主续跑一个没事可做的会话。
|
|
160
160
|
*
|
|
161
161
|
* 上限是**每次 run** 的:宿主续跑(同一 sessionId 再起 runLoop)即视为再批一份预算,`ctx.budget` 从零计。
|
|
@@ -189,8 +189,16 @@ interface BudgetOptions {
|
|
|
189
189
|
limits: BudgetLimits;
|
|
190
190
|
/** 暂停说明(给宿主看,进 Interruption.note);缺省英文一句话列出触顶的维度 */
|
|
191
191
|
note?: (hits: readonly BudgetHit[]) => string;
|
|
192
|
+
/**
|
|
193
|
+
* 暂停原因码(AdRate 建议 16),缺省恒为 `BUDGET_PAUSE_CODE`。缺省不把维度编进码里:可能多维同时触顶,一个码装不下;
|
|
194
|
+
* 要按维度区分的宿主在这里自己算(如 `(hits) => \`acme.budget.${hits[0].dimension.toLowerCase()}\``——维度名带大写,要先转小写)。
|
|
195
|
+
* 返回值须满足 core 的 `PAUSE_CODE_RE`(只收小写),否则码被丢掉、记一条非终结 `core.error`,暂停照常
|
|
196
|
+
*/
|
|
197
|
+
code?: (hits: readonly BudgetHit[]) => string;
|
|
192
198
|
}
|
|
193
199
|
declare const BUDGET_SOCKET_NAME = "budget";
|
|
200
|
+
/** 本模块暂停时的缺省原因码(`reins.` 前缀留给内置来源) */
|
|
201
|
+
declare const BUDGET_PAUSE_CODE = "reins.budget";
|
|
194
202
|
/** 上限必须是正的有限数;构造期就拒绝,免得跑起来才发现"0 上限"把一切都拦了 */
|
|
195
203
|
declare function assertLimits(limits: BudgetLimits): void;
|
|
196
204
|
/** 各维当前用量;contextTokens 没有真实用量(还没请求过)时为 undefined */
|
|
@@ -217,6 +225,7 @@ declare function budget(opts: BudgetOptions): Socket;
|
|
|
217
225
|
* 5. (E3c)被折叠的工具结果列成清单附在摘要之后(`seq N tool(arguments) — 大小`),模型之后可用 recall 按 seq 取回。
|
|
218
226
|
* 摘要是模型的取舍,清单是"事实上还在的东西";两个模型族的实测都把复核过的字段值整理成了一句结论,
|
|
219
227
|
* 清单让它至少知道去哪拿。脑子自己的工具(compact / pin / recall / fetch_blob 的回执)不列,只是噪音。
|
|
228
|
+
* (2026-11-24)被折叠用户消息里的图片 / 视频 / 音频另列一节,同样按 seq 用 recall 取回——否则贴过的截图一折就再也看不到。
|
|
220
229
|
*/
|
|
221
230
|
|
|
222
231
|
interface CompactArgs {
|
|
@@ -229,6 +238,8 @@ declare function parseCompactArgs(raw: unknown): CompactArgs;
|
|
|
229
238
|
/** 缺省不列进清单的工具:脑子自己的回执与切片,取回没有意义 */
|
|
230
239
|
declare const MANIFEST_DEFAULT_EXCLUDE: ReadonlySet<string>;
|
|
231
240
|
declare const MANIFEST_HEADING = "Folded tool results (bring one back verbatim with recall({ seq })):";
|
|
241
|
+
/** 被折叠用户消息里媒体的清单标题;与工具结果清单分开,没有媒体时摘要逐字不变 */
|
|
242
|
+
declare const MEDIA_MANIFEST_HEADING = "Images, video or audio in folded user messages (bring the message back verbatim with recall({ seq })):";
|
|
232
243
|
interface ManifestOptions {
|
|
233
244
|
/** 最多列几条,其余折成一行。缺省 80 */
|
|
234
245
|
maxItems?: number;
|
|
@@ -239,7 +250,7 @@ interface ManifestOptions {
|
|
|
239
250
|
* 摘要正文 + 要点清单 + 被折叠工具结果清单,合成 compaction.summary。
|
|
240
251
|
* 要点单列是为了模型(和 eval)一眼看到"什么被明确保留了";结果清单让它知道"什么还能拿回来"。
|
|
241
252
|
*/
|
|
242
|
-
declare function renderCompactionSummary(args: Pick<CompactArgs, "summary" | "keep">, folded?: readonly FoldedToolResult[], manifest?: ManifestOptions): string;
|
|
253
|
+
declare function renderCompactionSummary(args: Pick<CompactArgs, "summary" | "keep">, folded?: readonly FoldedToolResult[], manifest?: ManifestOptions, media?: readonly FoldedUserMedia[]): string;
|
|
243
254
|
type CompactPlan = {
|
|
244
255
|
ok: true;
|
|
245
256
|
payload: CompactionPayload;
|
|
@@ -251,6 +262,8 @@ type CompactPlan = {
|
|
|
251
262
|
keptTurns: number;
|
|
252
263
|
/** 列进摘要的被折叠工具结果(E3c) */
|
|
253
264
|
manifest: FoldedToolResult[];
|
|
265
|
+
/** 列进摘要的被折叠用户消息媒体(2026-11-24) */
|
|
266
|
+
media: FoldedUserMedia[];
|
|
254
267
|
} | {
|
|
255
268
|
ok: false;
|
|
256
269
|
reason: string;
|
|
@@ -406,6 +419,8 @@ interface CompactOptions {
|
|
|
406
419
|
}
|
|
407
420
|
declare const COMPACT_SOCKET_NAME = "compact";
|
|
408
421
|
declare const DEFAULT_MAX_CONSECUTIVE_COMPACTIONS = 3;
|
|
422
|
+
/** 连续整理达到上限而暂停时的原因码(AdRate 建议 16):reason 仍是 budget,靠它与预算触顶分开 */
|
|
423
|
+
declare const COMPACT_STALLED_PAUSE_CODE = "reins.compact_stalled";
|
|
409
424
|
declare const COMPACT_INPUT_SCHEMA: {
|
|
410
425
|
readonly type: "object";
|
|
411
426
|
readonly properties: {
|
|
@@ -434,7 +449,7 @@ declare function compact(opts?: CompactOptions): Socket;
|
|
|
434
449
|
declare function isModelCompaction(e: Event): boolean;
|
|
435
450
|
|
|
436
451
|
/**
|
|
437
|
-
* recall —— 按 seq
|
|
452
|
+
* recall —— 按 seq 逐字取回一条被折叠的工具结果或用户消息(E3c,技术方案 §9.2;用户消息 2026-11-24)。
|
|
438
453
|
*
|
|
439
454
|
* 为什么要有它:整理是模型自己的取舍,两个模型族的实测都把"复核过的字段值"整理成了"状态正常"一句结论,
|
|
440
455
|
* 被问到时只能说"摘要里没留,可以重查"——而重查要宿主工具、且查到的是现在的值不是当时的值。原件本来就在
|
|
@@ -447,6 +462,10 @@ declare function isModelCompaction(e: Event): boolean;
|
|
|
447
462
|
*
|
|
448
463
|
* 取回的内容再次进入上下文,是模型有意识的花费;结果超过外溢上限时由 spill 模块照常处理(recall 不在它的排除名单里)。
|
|
449
464
|
* 已外溢的原件事件里只剩预览,这里不复述预览,而是指向 blob 让模型用 fetch_blob 读全文。
|
|
465
|
+
*
|
|
466
|
+
* 用户消息(2026-11-24,AdRate 建议 17 第一步):用户贴的截图随旧轮被折叠后原本取不回。清单只列带媒体的用户消息,
|
|
467
|
+
* 但这里接受任何 user_message 的 seq——取回的是原话,拒绝纯文本消息没有意义。取回内容以 tool_result 进上下文,
|
|
468
|
+
* 缺省 untrusted:旧消息重读一遍是"看资料",不该被当成新指令再执行一次,这正是想要的。
|
|
450
469
|
*/
|
|
451
470
|
|
|
452
471
|
declare const RECALL_INPUT_SCHEMA: {
|
|
@@ -455,7 +474,7 @@ declare const RECALL_INPUT_SCHEMA: {
|
|
|
455
474
|
readonly seq: {
|
|
456
475
|
readonly type: "integer";
|
|
457
476
|
readonly minimum: 1;
|
|
458
|
-
readonly description: "The `seq` shown next to the folded tool result in a summary's list.";
|
|
477
|
+
readonly description: "The `seq` shown next to the folded tool result or user message in a summary's list.";
|
|
459
478
|
};
|
|
460
479
|
};
|
|
461
480
|
readonly required: readonly ["seq"];
|
|
@@ -494,7 +513,7 @@ declare const RECALL_TOOL_DESCRIPTION: string;
|
|
|
494
513
|
* 所以 force: false 且没自定义 rules 时,模块用去掉这一行的版本——告诉模型的事框架必须兑现
|
|
495
514
|
*/
|
|
496
515
|
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.";
|
|
497
|
-
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.";
|
|
516
|
+
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 folded user messages with images, video or audio as `seq N user message`, 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.";
|
|
498
517
|
|
|
499
518
|
/**
|
|
500
519
|
* halt-on-failure —— 同批前一个调用失败时拦下后面的(2026-11-02,OnSet 建议 9)。
|
|
@@ -1590,4 +1609,4 @@ interface StopAfterOptions {
|
|
|
1590
1609
|
}
|
|
1591
1610
|
declare function stopAfter(opts: StopAfterOptions): Socket;
|
|
1592
1611
|
|
|
1593
|
-
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, HALT_ON_FAILURE_SOCKET_NAME, HANDOFF_INPUT_SCHEMA, HANDOFF_RULES, HANDOFF_SOCKET_NAME, HANDOFF_TOOL_DESCRIPTION, HANDOFF_TOOL_NAME, type HaltOnFailureOptions, 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, STOP_AFTER_SOCKET_NAME, type SkillFrontmatter, type SkillMenu, type SkillMenuEntry, type SkillReadInput, type SkillsOptions, type SpillOptions, type StopAfterOptions, 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, expandMemoryDirectories, findExpiredApproval, findModelPin, fmt, globToRegExp, haltOnFailure, haltedText, handoff, humanSize, inlineSkills, isCompactRequest, isModelCompaction, isPinNoteEvent, isSnapshotPin, 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, stopAfter, sumSessionTokens, summarizeTool, timelineSoFar, toolFindResultBound, toolReferenceOf, trailingCompactionRun, unfinishedHandoffArgs };
|
|
1612
|
+
export { APPROVAL_EXPIRY_RULE, APPROVAL_POLICY_IDS, APPROVAL_RULES, APPROVAL_SOCKET_NAME, type ApprovalOptions, BUDGET_PAUSE_CODE, BUDGET_SOCKET_NAME, type BudgetDimension, type BudgetHit, type BudgetLimits, type BudgetOptions, COMPACT_INPUT_SCHEMA, COMPACT_REQUEST_RULE, COMPACT_RULES, COMPACT_SOCKET_NAME, COMPACT_STALLED_PAUSE_CODE, 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, HALT_ON_FAILURE_SOCKET_NAME, HANDOFF_INPUT_SCHEMA, HANDOFF_RULES, HANDOFF_SOCKET_NAME, HANDOFF_TOOL_DESCRIPTION, HANDOFF_TOOL_NAME, type HaltOnFailureOptions, 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, MEDIA_MANIFEST_HEADING, 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, STOP_AFTER_SOCKET_NAME, type SkillFrontmatter, type SkillMenu, type SkillMenuEntry, type SkillReadInput, type SkillsOptions, type SpillOptions, type StopAfterOptions, 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, expandMemoryDirectories, findExpiredApproval, findModelPin, fmt, globToRegExp, haltOnFailure, haltedText, handoff, humanSize, inlineSkills, isCompactRequest, isModelCompaction, isPinNoteEvent, isSnapshotPin, 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, stopAfter, sumSessionTokens, summarizeTool, timelineSoFar, toolFindResultBound, toolReferenceOf, trailingCompactionRun, unfinishedHandoffArgs };
|
package/dist/index.js
CHANGED
|
@@ -210,6 +210,7 @@ ${APPROVAL_EXPIRY_RULE}` : options.rules;
|
|
|
210
210
|
// src/budget/budget.ts
|
|
211
211
|
import { contextTokensOf } from "@reinsjs/core";
|
|
212
212
|
var BUDGET_SOCKET_NAME = "budget";
|
|
213
|
+
var BUDGET_PAUSE_CODE = "reins.budget";
|
|
213
214
|
function assertLimits(limits) {
|
|
214
215
|
for (const [dimension, limit] of Object.entries(limits)) {
|
|
215
216
|
if (limit === void 0) continue;
|
|
@@ -260,7 +261,9 @@ function budget(opts) {
|
|
|
260
261
|
if (!continuing.get(ctx)) return void 0;
|
|
261
262
|
const hits = checkBudget(ctx.budget, opts.limits);
|
|
262
263
|
if (hits.length === 0) return void 0;
|
|
263
|
-
return {
|
|
264
|
+
return {
|
|
265
|
+
pause: { reason: "budget", code: opts.code ? opts.code(hits) : BUDGET_PAUSE_CODE, note: note(hits) }
|
|
266
|
+
};
|
|
264
267
|
}
|
|
265
268
|
};
|
|
266
269
|
}
|
|
@@ -311,9 +314,11 @@ function compactNumber(n) {
|
|
|
311
314
|
// src/compact/plan.ts
|
|
312
315
|
import {
|
|
313
316
|
foldedToolResults,
|
|
317
|
+
foldedUserMedia,
|
|
314
318
|
isCompaction,
|
|
315
319
|
isPinNote,
|
|
316
320
|
renderFoldedToolResults,
|
|
321
|
+
renderFoldedUserMedia,
|
|
317
322
|
splitTurns,
|
|
318
323
|
supersededIds
|
|
319
324
|
} from "@reinsjs/core";
|
|
@@ -362,12 +367,12 @@ var COMPACT_TOOL_DESCRIPTION = [
|
|
|
362
367
|
"the originals stay in the session log but you will no longer see them.",
|
|
363
368
|
"Earlier summaries inside the folded range are replaced too \u2014 carry forward whatever still matters.",
|
|
364
369
|
"The most recent user message and pinned notes survive verbatim, so you need not repeat them.",
|
|
365
|
-
`Under your summary the harness lists every folded tool result (seq, tool, arguments); any of them can be brought back verbatim later with \`${RECALL_TOOL_NAME}\`.`
|
|
370
|
+
`Under your summary the harness lists every folded tool result (seq, tool, arguments) and every folded user message that carried images, video or audio; any of them can be brought back verbatim later with \`${RECALL_TOOL_NAME}\`.`
|
|
366
371
|
].join(" ");
|
|
367
372
|
var RECALL_TOOL_DESCRIPTION = [
|
|
368
|
-
"Bring back, verbatim, a tool result that was folded away by a compaction.",
|
|
369
|
-
"Each summary lists its folded tool results as `seq N tool(arguments)`; pass that `seq`.",
|
|
370
|
-
"The original
|
|
373
|
+
"Bring back, verbatim, a tool result or user message that was folded away by a compaction.",
|
|
374
|
+
"Each summary lists its folded tool results as `seq N tool(arguments)`, and folded user messages that carried images, video or audio as `seq N user message`; pass that `seq`.",
|
|
375
|
+
"The original is returned exactly as it was logged, media included (large tool outputs are stored as blobs and read with fetch_blob instead).",
|
|
371
376
|
"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."
|
|
372
377
|
].join(" ");
|
|
373
378
|
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.";
|
|
@@ -377,7 +382,7 @@ You have a \`${COMPACT_TOOL_NAME}\` tool that folds earlier conversation into a
|
|
|
377
382
|
- 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.
|
|
378
383
|
- 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.
|
|
379
384
|
- 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.
|
|
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.
|
|
385
|
+
- Nothing folded is lost for good: under each summary the harness lists the folded tool results as \`seq N tool(arguments)\` and folded user messages with images, video or audio as \`seq N user message\`, 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
386
|
${COMPACT_REQUEST_RULE}
|
|
382
387
|
- 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.`;
|
|
383
388
|
|
|
@@ -405,13 +410,19 @@ var MANIFEST_DEFAULT_EXCLUDE = /* @__PURE__ */ new Set([
|
|
|
405
410
|
FETCH_BLOB_TOOL_NAME
|
|
406
411
|
]);
|
|
407
412
|
var MANIFEST_HEADING = `Folded tool results (bring one back verbatim with ${RECALL_TOOL_NAME}({ seq })):`;
|
|
408
|
-
|
|
413
|
+
var MEDIA_MANIFEST_HEADING = `Images, video or audio in folded user messages (bring the message back verbatim with ${RECALL_TOOL_NAME}({ seq })):`;
|
|
414
|
+
function renderCompactionSummary(args, folded = [], manifest = {}, media = []) {
|
|
409
415
|
const parts = [args.summary];
|
|
410
416
|
if (args.keep.length > 0)
|
|
411
417
|
parts.push(`Key facts carried forward:
|
|
412
418
|
${args.keep.map((k) => `- ${k}`).join("\n")}`);
|
|
413
419
|
const list = renderFoldedToolResults(folded, { heading: MANIFEST_HEADING, ...manifest });
|
|
414
420
|
if (list) parts.push(list);
|
|
421
|
+
const mediaList = renderFoldedUserMedia(media, {
|
|
422
|
+
heading: MEDIA_MANIFEST_HEADING,
|
|
423
|
+
...manifest.maxItems !== void 0 ? { maxItems: manifest.maxItems } : {}
|
|
424
|
+
});
|
|
425
|
+
if (mediaList) parts.push(mediaList);
|
|
415
426
|
return parts.join("\n\n");
|
|
416
427
|
}
|
|
417
428
|
var ASSISTANT_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -476,6 +487,7 @@ function planCompaction(visible, args, opts = {}) {
|
|
|
476
487
|
const survivorIds = new Set(survivors.map((e) => e.id));
|
|
477
488
|
const manifestOpts = opts.manifest === false ? void 0 : { exclude: MANIFEST_DEFAULT_EXCLUDE, ...opts.manifest };
|
|
478
489
|
let manifest = [];
|
|
490
|
+
let media = [];
|
|
479
491
|
if (manifestOpts) {
|
|
480
492
|
const listed = new Set(folded.map((e) => e.id));
|
|
481
493
|
const scope = folded.filter((e) => !survivorIds.has(e.id));
|
|
@@ -495,6 +507,7 @@ function planCompaction(visible, args, opts = {}) {
|
|
|
495
507
|
lookup: opts.timeline ?? visible,
|
|
496
508
|
exclude: manifestOpts.exclude ?? MANIFEST_DEFAULT_EXCLUDE
|
|
497
509
|
});
|
|
510
|
+
media = foldedUserMedia(scope);
|
|
498
511
|
}
|
|
499
512
|
const from = Math.min(
|
|
500
513
|
minSeq(folded),
|
|
@@ -505,14 +518,15 @@ function planCompaction(visible, args, opts = {}) {
|
|
|
505
518
|
ok: true,
|
|
506
519
|
payload: {
|
|
507
520
|
coversSeq: [from, to],
|
|
508
|
-
summary: renderCompactionSummary(args, manifest, manifestOpts ?? {}),
|
|
521
|
+
summary: renderCompactionSummary(args, manifest, manifestOpts ?? {}, media),
|
|
509
522
|
decidedBy: "model",
|
|
510
523
|
pinsKept: survivors.map((e) => e.id)
|
|
511
524
|
},
|
|
512
525
|
folded,
|
|
513
526
|
absorbed,
|
|
514
527
|
keptTurns: args.keepRecentTurns,
|
|
515
|
-
manifest
|
|
528
|
+
manifest,
|
|
529
|
+
media
|
|
516
530
|
};
|
|
517
531
|
}
|
|
518
532
|
function isPreModelEvent(e) {
|
|
@@ -555,7 +569,7 @@ var RECALL_INPUT_SCHEMA = {
|
|
|
555
569
|
seq: {
|
|
556
570
|
type: "integer",
|
|
557
571
|
minimum: 1,
|
|
558
|
-
description: "The `seq` shown next to the folded tool result in a summary's list."
|
|
572
|
+
description: "The `seq` shown next to the folded tool result or user message in a summary's list."
|
|
559
573
|
}
|
|
560
574
|
},
|
|
561
575
|
required: ["seq"],
|
|
@@ -582,6 +596,7 @@ function digest(args, max = 200) {
|
|
|
582
596
|
}
|
|
583
597
|
async function locate(ctx, seq) {
|
|
584
598
|
let result;
|
|
599
|
+
let user;
|
|
585
600
|
let foundType;
|
|
586
601
|
const calls = /* @__PURE__ */ new Map();
|
|
587
602
|
for await (const e of ctx.log.read(ctx.sessionId)) {
|
|
@@ -589,6 +604,10 @@ async function locate(ctx, seq) {
|
|
|
589
604
|
if (e.seq === seq) {
|
|
590
605
|
foundType = e.type;
|
|
591
606
|
if (e.type === "core.tool_result") result = e;
|
|
607
|
+
if (e.type === "core.user_message") {
|
|
608
|
+
user = e;
|
|
609
|
+
break;
|
|
610
|
+
}
|
|
592
611
|
}
|
|
593
612
|
if (result && calls.has(result.payload.toolCallId)) break;
|
|
594
613
|
}
|
|
@@ -598,14 +617,19 @@ async function locate(ctx, seq) {
|
|
|
598
617
|
const call = calls.get(result.payload.toolCallId);
|
|
599
618
|
if (call) out.call = call;
|
|
600
619
|
}
|
|
620
|
+
if (user) out.user = user;
|
|
601
621
|
if (foundType) out.foundType = foundType;
|
|
602
622
|
return out;
|
|
603
623
|
}
|
|
604
624
|
async function recallResult(args, ctx) {
|
|
605
|
-
const { result, call, foundType } = await locate(ctx, args.seq);
|
|
625
|
+
const { result, call, user, foundType } = await locate(ctx, args.seq);
|
|
626
|
+
if (user) {
|
|
627
|
+
const header2 = `[Recalled user message seq ${args.seq}. Original content follows verbatim.]`;
|
|
628
|
+
return { content: [{ type: "text", text: header2 }, ...user.payload.content], isError: false };
|
|
629
|
+
}
|
|
606
630
|
if (!result) {
|
|
607
631
|
return fail(
|
|
608
|
-
foundType ? `seq ${args.seq} is a ${foundType.replace(/^core\./, "")} event, not a tool result. Pass a seq from a summary's
|
|
632
|
+
foundType ? `seq ${args.seq} is a ${foundType.replace(/^core\./, "")} event, not a tool result or user message. Pass a seq from a summary's list.` : `No event with seq ${args.seq} in this session.`
|
|
609
633
|
);
|
|
610
634
|
}
|
|
611
635
|
const { name, spilled, isError, content } = result.payload;
|
|
@@ -700,6 +724,7 @@ function contextUsageRatio(ctx) {
|
|
|
700
724
|
// src/compact/compact.ts
|
|
701
725
|
var COMPACT_SOCKET_NAME = "compact";
|
|
702
726
|
var DEFAULT_MAX_CONSECUTIVE_COMPACTIONS = 3;
|
|
727
|
+
var COMPACT_STALLED_PAUSE_CODE = "reins.compact_stalled";
|
|
703
728
|
var COMPACT_INPUT_SCHEMA = {
|
|
704
729
|
type: "object",
|
|
705
730
|
properties: {
|
|
@@ -734,6 +759,11 @@ function receipt(plan, withRecall) {
|
|
|
734
759
|
`${plan.manifest.length} folded tool result(s) are listed under the summary${withRecall ? ` and can be brought back verbatim with ${RECALL_TOOL_NAME}({ seq })` : ""}.`
|
|
735
760
|
);
|
|
736
761
|
}
|
|
762
|
+
if (plan.media.length > 0) {
|
|
763
|
+
parts.push(
|
|
764
|
+
`${plan.media.length} folded user message(s) with images, video or audio are listed under the summary${withRecall ? ` and can be brought back verbatim with ${RECALL_TOOL_NAME}({ seq })` : ""}.`
|
|
765
|
+
);
|
|
766
|
+
}
|
|
737
767
|
if (plan.payload.pinsKept.length > 0)
|
|
738
768
|
parts.push(
|
|
739
769
|
`${plan.payload.pinsKept.length} item(s) carried over verbatim (pinned notes and the latest user message).`
|
|
@@ -845,6 +875,7 @@ function compact(opts = {}) {
|
|
|
845
875
|
return {
|
|
846
876
|
pause: {
|
|
847
877
|
reason: "budget",
|
|
878
|
+
code: COMPACT_STALLED_PAUSE_CODE,
|
|
848
879
|
note: `Context was compacted ${total} times in a row without a turn of progress in between (limit ${maxConsecutive}). Either the window is still too small after folding, or the model is looping on compact. Paused for the host to inspect.`
|
|
849
880
|
}
|
|
850
881
|
};
|
|
@@ -2963,11 +2994,13 @@ export {
|
|
|
2963
2994
|
APPROVAL_POLICY_IDS,
|
|
2964
2995
|
APPROVAL_RULES,
|
|
2965
2996
|
APPROVAL_SOCKET_NAME,
|
|
2997
|
+
BUDGET_PAUSE_CODE,
|
|
2966
2998
|
BUDGET_SOCKET_NAME,
|
|
2967
2999
|
COMPACT_INPUT_SCHEMA,
|
|
2968
3000
|
COMPACT_REQUEST_RULE,
|
|
2969
3001
|
COMPACT_RULES,
|
|
2970
3002
|
COMPACT_SOCKET_NAME,
|
|
3003
|
+
COMPACT_STALLED_PAUSE_CODE,
|
|
2971
3004
|
COMPACT_TOOL_DESCRIPTION,
|
|
2972
3005
|
COMPACT_TOOL_NAME,
|
|
2973
3006
|
DEFAULT_FORCE_AT,
|
|
@@ -3001,6 +3034,7 @@ export {
|
|
|
3001
3034
|
MANIFEST_HEADING,
|
|
3002
3035
|
MAX_MEMORY_PATH_LENGTH,
|
|
3003
3036
|
MAX_SKILL_DESCRIPTION_CHARS,
|
|
3037
|
+
MEDIA_MANIFEST_HEADING,
|
|
3004
3038
|
MEMORY_COMMANDS,
|
|
3005
3039
|
MEMORY_INPUT_SCHEMA,
|
|
3006
3040
|
MEMORY_ROOT,
|