@reinsjs/brain 0.9.0 → 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 CHANGED
@@ -1,5 +1,17 @@
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
+
3
15
  ## 0.9.0
4
16
 
5
17
  ### 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. 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 |
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`) |
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
  /**
@@ -225,6 +225,7 @@ declare function budget(opts: BudgetOptions): Socket;
225
225
  * 5. (E3c)被折叠的工具结果列成清单附在摘要之后(`seq N tool(arguments) — 大小`),模型之后可用 recall 按 seq 取回。
226
226
  * 摘要是模型的取舍,清单是"事实上还在的东西";两个模型族的实测都把复核过的字段值整理成了一句结论,
227
227
  * 清单让它至少知道去哪拿。脑子自己的工具(compact / pin / recall / fetch_blob 的回执)不列,只是噪音。
228
+ * (2026-11-24)被折叠用户消息里的图片 / 视频 / 音频另列一节,同样按 seq 用 recall 取回——否则贴过的截图一折就再也看不到。
228
229
  */
229
230
 
230
231
  interface CompactArgs {
@@ -237,6 +238,8 @@ declare function parseCompactArgs(raw: unknown): CompactArgs;
237
238
  /** 缺省不列进清单的工具:脑子自己的回执与切片,取回没有意义 */
238
239
  declare const MANIFEST_DEFAULT_EXCLUDE: ReadonlySet<string>;
239
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 })):";
240
243
  interface ManifestOptions {
241
244
  /** 最多列几条,其余折成一行。缺省 80 */
242
245
  maxItems?: number;
@@ -247,7 +250,7 @@ interface ManifestOptions {
247
250
  * 摘要正文 + 要点清单 + 被折叠工具结果清单,合成 compaction.summary。
248
251
  * 要点单列是为了模型(和 eval)一眼看到"什么被明确保留了";结果清单让它知道"什么还能拿回来"。
249
252
  */
250
- 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;
251
254
  type CompactPlan = {
252
255
  ok: true;
253
256
  payload: CompactionPayload;
@@ -259,6 +262,8 @@ type CompactPlan = {
259
262
  keptTurns: number;
260
263
  /** 列进摘要的被折叠工具结果(E3c) */
261
264
  manifest: FoldedToolResult[];
265
+ /** 列进摘要的被折叠用户消息媒体(2026-11-24) */
266
+ media: FoldedUserMedia[];
262
267
  } | {
263
268
  ok: false;
264
269
  reason: string;
@@ -444,7 +449,7 @@ declare function compact(opts?: CompactOptions): Socket;
444
449
  declare function isModelCompaction(e: Event): boolean;
445
450
 
446
451
  /**
447
- * recall —— 按 seq 逐字取回一条被折叠的工具结果(E3c,技术方案 §9.2)。
452
+ * recall —— 按 seq 逐字取回一条被折叠的工具结果或用户消息(E3c,技术方案 §9.2;用户消息 2026-11-24)。
448
453
  *
449
454
  * 为什么要有它:整理是模型自己的取舍,两个模型族的实测都把"复核过的字段值"整理成了"状态正常"一句结论,
450
455
  * 被问到时只能说"摘要里没留,可以重查"——而重查要宿主工具、且查到的是现在的值不是当时的值。原件本来就在
@@ -457,6 +462,10 @@ declare function isModelCompaction(e: Event): boolean;
457
462
  *
458
463
  * 取回的内容再次进入上下文,是模型有意识的花费;结果超过外溢上限时由 spill 模块照常处理(recall 不在它的排除名单里)。
459
464
  * 已外溢的原件事件里只剩预览,这里不复述预览,而是指向 blob 让模型用 fetch_blob 读全文。
465
+ *
466
+ * 用户消息(2026-11-24,AdRate 建议 17 第一步):用户贴的截图随旧轮被折叠后原本取不回。清单只列带媒体的用户消息,
467
+ * 但这里接受任何 user_message 的 seq——取回的是原话,拒绝纯文本消息没有意义。取回内容以 tool_result 进上下文,
468
+ * 缺省 untrusted:旧消息重读一遍是"看资料",不该被当成新指令再执行一次,这正是想要的。
460
469
  */
461
470
 
462
471
  declare const RECALL_INPUT_SCHEMA: {
@@ -465,7 +474,7 @@ declare const RECALL_INPUT_SCHEMA: {
465
474
  readonly seq: {
466
475
  readonly type: "integer";
467
476
  readonly minimum: 1;
468
- 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.";
469
478
  };
470
479
  };
471
480
  readonly required: readonly ["seq"];
@@ -504,7 +513,7 @@ declare const RECALL_TOOL_DESCRIPTION: string;
504
513
  * 所以 force: false 且没自定义 rules 时,模块用去掉这一行的版本——告诉模型的事框架必须兑现
505
514
  */
506
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.";
507
- 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.";
508
517
 
509
518
  /**
510
519
  * halt-on-failure —— 同批前一个调用失败时拦下后面的(2026-11-02,OnSet 建议 9)。
@@ -1600,4 +1609,4 @@ interface StopAfterOptions {
1600
1609
  }
1601
1610
  declare function stopAfter(opts: StopAfterOptions): Socket;
1602
1611
 
1603
- 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, 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
@@ -314,9 +314,11 @@ function compactNumber(n) {
314
314
  // src/compact/plan.ts
315
315
  import {
316
316
  foldedToolResults,
317
+ foldedUserMedia,
317
318
  isCompaction,
318
319
  isPinNote,
319
320
  renderFoldedToolResults,
321
+ renderFoldedUserMedia,
320
322
  splitTurns,
321
323
  supersededIds
322
324
  } from "@reinsjs/core";
@@ -365,12 +367,12 @@ var COMPACT_TOOL_DESCRIPTION = [
365
367
  "the originals stay in the session log but you will no longer see them.",
366
368
  "Earlier summaries inside the folded range are replaced too \u2014 carry forward whatever still matters.",
367
369
  "The most recent user message and pinned notes survive verbatim, so you need not repeat them.",
368
- `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}\`.`
369
371
  ].join(" ");
370
372
  var RECALL_TOOL_DESCRIPTION = [
371
- "Bring back, verbatim, a tool result that was folded away by a compaction.",
372
- "Each summary lists its folded tool results as `seq N tool(arguments)`; pass that `seq`.",
373
- "The original output is returned exactly as the tool produced it (large outputs are stored as blobs and read with fetch_blob instead).",
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).",
374
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."
375
377
  ].join(" ");
376
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.";
@@ -380,7 +382,7 @@ You have a \`${COMPACT_TOOL_NAME}\` tool that folds earlier conversation into a
380
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.
381
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.
382
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.
383
- - 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.
384
386
  ${COMPACT_REQUEST_RULE}
385
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.`;
386
388
 
@@ -408,13 +410,19 @@ var MANIFEST_DEFAULT_EXCLUDE = /* @__PURE__ */ new Set([
408
410
  FETCH_BLOB_TOOL_NAME
409
411
  ]);
410
412
  var MANIFEST_HEADING = `Folded tool results (bring one back verbatim with ${RECALL_TOOL_NAME}({ seq })):`;
411
- function renderCompactionSummary(args, folded = [], manifest = {}) {
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 = []) {
412
415
  const parts = [args.summary];
413
416
  if (args.keep.length > 0)
414
417
  parts.push(`Key facts carried forward:
415
418
  ${args.keep.map((k) => `- ${k}`).join("\n")}`);
416
419
  const list = renderFoldedToolResults(folded, { heading: MANIFEST_HEADING, ...manifest });
417
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);
418
426
  return parts.join("\n\n");
419
427
  }
420
428
  var ASSISTANT_TYPES = /* @__PURE__ */ new Set([
@@ -479,6 +487,7 @@ function planCompaction(visible, args, opts = {}) {
479
487
  const survivorIds = new Set(survivors.map((e) => e.id));
480
488
  const manifestOpts = opts.manifest === false ? void 0 : { exclude: MANIFEST_DEFAULT_EXCLUDE, ...opts.manifest };
481
489
  let manifest = [];
490
+ let media = [];
482
491
  if (manifestOpts) {
483
492
  const listed = new Set(folded.map((e) => e.id));
484
493
  const scope = folded.filter((e) => !survivorIds.has(e.id));
@@ -498,6 +507,7 @@ function planCompaction(visible, args, opts = {}) {
498
507
  lookup: opts.timeline ?? visible,
499
508
  exclude: manifestOpts.exclude ?? MANIFEST_DEFAULT_EXCLUDE
500
509
  });
510
+ media = foldedUserMedia(scope);
501
511
  }
502
512
  const from = Math.min(
503
513
  minSeq(folded),
@@ -508,14 +518,15 @@ function planCompaction(visible, args, opts = {}) {
508
518
  ok: true,
509
519
  payload: {
510
520
  coversSeq: [from, to],
511
- summary: renderCompactionSummary(args, manifest, manifestOpts ?? {}),
521
+ summary: renderCompactionSummary(args, manifest, manifestOpts ?? {}, media),
512
522
  decidedBy: "model",
513
523
  pinsKept: survivors.map((e) => e.id)
514
524
  },
515
525
  folded,
516
526
  absorbed,
517
527
  keptTurns: args.keepRecentTurns,
518
- manifest
528
+ manifest,
529
+ media
519
530
  };
520
531
  }
521
532
  function isPreModelEvent(e) {
@@ -558,7 +569,7 @@ var RECALL_INPUT_SCHEMA = {
558
569
  seq: {
559
570
  type: "integer",
560
571
  minimum: 1,
561
- 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."
562
573
  }
563
574
  },
564
575
  required: ["seq"],
@@ -585,6 +596,7 @@ function digest(args, max = 200) {
585
596
  }
586
597
  async function locate(ctx, seq) {
587
598
  let result;
599
+ let user;
588
600
  let foundType;
589
601
  const calls = /* @__PURE__ */ new Map();
590
602
  for await (const e of ctx.log.read(ctx.sessionId)) {
@@ -592,6 +604,10 @@ async function locate(ctx, seq) {
592
604
  if (e.seq === seq) {
593
605
  foundType = e.type;
594
606
  if (e.type === "core.tool_result") result = e;
607
+ if (e.type === "core.user_message") {
608
+ user = e;
609
+ break;
610
+ }
595
611
  }
596
612
  if (result && calls.has(result.payload.toolCallId)) break;
597
613
  }
@@ -601,14 +617,19 @@ async function locate(ctx, seq) {
601
617
  const call = calls.get(result.payload.toolCallId);
602
618
  if (call) out.call = call;
603
619
  }
620
+ if (user) out.user = user;
604
621
  if (foundType) out.foundType = foundType;
605
622
  return out;
606
623
  }
607
624
  async function recallResult(args, ctx) {
608
- 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
+ }
609
630
  if (!result) {
610
631
  return fail(
611
- foundType ? `seq ${args.seq} is a ${foundType.replace(/^core\./, "")} event, not a tool result. Pass a seq from a summary's "Folded tool results" list.` : `No event with seq ${args.seq} in this session.`
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.`
612
633
  );
613
634
  }
614
635
  const { name, spilled, isError, content } = result.payload;
@@ -738,6 +759,11 @@ function receipt(plan, withRecall) {
738
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 })` : ""}.`
739
760
  );
740
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
+ }
741
767
  if (plan.payload.pinsKept.length > 0)
742
768
  parts.push(
743
769
  `${plan.payload.pinsKept.length} item(s) carried over verbatim (pinned notes and the latest user message).`
@@ -3008,6 +3034,7 @@ export {
3008
3034
  MANIFEST_HEADING,
3009
3035
  MAX_MEMORY_PATH_LENGTH,
3010
3036
  MAX_SKILL_DESCRIPTION_CHARS,
3037
+ MEDIA_MANIFEST_HEADING,
3011
3038
  MEMORY_COMMANDS,
3012
3039
  MEMORY_INPUT_SCHEMA,
3013
3040
  MEMORY_ROOT,