notesoup 0.39.0 → 0.41.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.
Files changed (91) hide show
  1. package/README.md +5 -2
  2. package/dist/src/boot/render.js +2 -2
  3. package/dist/src/boot/text.d.ts +0 -4
  4. package/dist/src/boot/text.js +18 -14
  5. package/dist/src/budget/policy.js +1 -1
  6. package/dist/src/budget/text.js +1 -1
  7. package/dist/src/dream/doctor.js +2 -1
  8. package/dist/src/dream/git.js +2 -1
  9. package/dist/src/dream/report.js +3 -2
  10. package/dist/src/error-message.d.ts +2 -0
  11. package/dist/src/error-message.js +4 -0
  12. package/dist/src/history/history.d.ts +23 -18
  13. package/dist/src/history/history.js +37 -20
  14. package/dist/src/history/query.d.ts +37 -49
  15. package/dist/src/history/query.js +114 -56
  16. package/dist/src/notes/store.d.ts +3 -4
  17. package/dist/src/notes/store.js +12 -16
  18. package/dist/src/pi/anchored.d.ts +16 -0
  19. package/dist/src/pi/anchored.js +55 -0
  20. package/dist/src/pi/budget.d.ts +1 -1
  21. package/dist/src/pi/budget.js +33 -28
  22. package/dist/src/pi/dream/cli.js +3 -2
  23. package/dist/src/pi/dream/runner.js +2 -1
  24. package/dist/src/pi/history-tools.d.ts +1 -1
  25. package/dist/src/pi/history-tools.js +2 -3
  26. package/dist/src/pi/reset/lifecycle.d.ts +1 -1
  27. package/dist/src/pi/reset/lifecycle.js +4 -3
  28. package/dist/src/pi/reset/text.d.ts +3 -3
  29. package/dist/src/pi/reset/text.js +2 -2
  30. package/dist/src/pi/runtime.js +12 -15
  31. package/dist/src/pi/thresholds.js +2 -1
  32. package/dist/src/pi/tool-names.d.ts +0 -4
  33. package/dist/src/pi/tool-names.js +0 -4
  34. package/dist/src/tools/history.d.ts +24 -33
  35. package/dist/src/tools/history.js +57 -98
  36. package/dist/src/tools/notes.d.ts +26 -58
  37. package/dist/src/tools/notes.js +85 -103
  38. package/dist/src/tools/result.d.ts +16 -13
  39. package/dist/src/tools/result.js +24 -50
  40. package/dist/src/tools/schema.d.ts +2 -2
  41. package/dist/src/tools/schema.js +3 -3
  42. package/dist/test/agent-loop.test.js +79 -29
  43. package/dist/test/boot.integration.test.js +6 -6
  44. package/dist/test/budget-settings.integration.test.js +9 -8
  45. package/dist/test/claude-mod.test.js +11 -11
  46. package/dist/test/dependencies.test.js +1 -1
  47. package/dist/test/helpers/extension.js +2 -3
  48. package/dist/test/history.integration.test.js +200 -123
  49. package/dist/test/host-neutral.test.js +32 -58
  50. package/dist/test/notes-library.test.js +8 -8
  51. package/dist/test/notes.integration.test.js +75 -57
  52. package/dist/test/notes.test.js +44 -42
  53. package/dist/test/reset-lifecycle.test.js +2 -2
  54. package/docs/architecture.md +3 -3
  55. package/docs/notes-library.md +6 -6
  56. package/docs/tool-results.md +15 -25
  57. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  58. package/mods/notesoup/dist/claude/helper.js +128 -179
  59. package/mods/notesoup/hooks/register.ts +19 -25
  60. package/mods/notesoup/playbook.md +10 -10
  61. package/mods/notesoup/skills/dream/SKILL.md +1 -1
  62. package/package.json +1 -1
  63. package/playbook.md +10 -10
  64. package/skills/dream/SKILL.md +1 -1
  65. package/skills/memory/SKILL.md +11 -9
  66. package/src/boot/render.ts +2 -2
  67. package/src/boot/text.ts +18 -18
  68. package/src/budget/policy.ts +1 -1
  69. package/src/budget/text.ts +1 -1
  70. package/src/dream/doctor.ts +2 -1
  71. package/src/dream/git.ts +2 -1
  72. package/src/dream/report.ts +3 -2
  73. package/src/error-message.ts +4 -0
  74. package/src/history/history.ts +36 -20
  75. package/src/history/query.ts +130 -55
  76. package/src/notes/store.ts +15 -18
  77. package/src/pi/anchored.ts +62 -0
  78. package/src/pi/budget.ts +27 -26
  79. package/src/pi/dream/cli.ts +3 -2
  80. package/src/pi/dream/runner.ts +2 -1
  81. package/src/pi/history-tools.ts +2 -3
  82. package/src/pi/reset/lifecycle.ts +5 -4
  83. package/src/pi/reset/text.ts +2 -2
  84. package/src/pi/runtime.ts +12 -15
  85. package/src/pi/thresholds.ts +2 -1
  86. package/src/pi/tool-names.ts +0 -4
  87. package/src/tools/history.ts +61 -100
  88. package/src/tools/notes.ts +84 -97
  89. package/src/tools/result.ts +24 -49
  90. package/src/tools/schema.ts +3 -3
  91. package/mods/pi-context/dist/claude/helper.js +0 -9324
@@ -3,11 +3,12 @@ import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from
3
3
  import type { AgentBeforeSettleEvent, ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
4
4
  import { currentReset, currentWindowId } from "../window.js";
5
5
  import { resetBoundaryCommitted } from "./committed.js";
6
+ import { errorMessage } from "../../error-message.js";
6
7
 
7
8
  type BudgetOwner = {
8
9
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
9
10
  hardReserveDue: (ctx: ExtensionContext) => boolean;
10
- consumeTurnEnd: (ctx: ExtensionContext) => SessionBoundaryDraft[];
11
+ consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
11
12
  clear: () => void;
12
13
  };
13
14
 
@@ -236,7 +237,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
236
237
  try {
237
238
  resetDrafts = await options.buildReset(ctx, isCurrent, prompt);
238
239
  } catch (error) {
239
- if (isCurrent()) ctx.ui.notify(`notesoup: could not build reset (${String(error)}).${prompt ? " The follow-up prompt was not executed." : ""}`, "warning");
240
+ if (isCurrent()) ctx.ui.notify(`🥣 Couldn't clear memory: ${errorMessage(error)}${prompt ? " · your prompt was not sent" : ""}`, "warning");
240
241
  return entries.length > 0 ? { entries } : undefined;
241
242
  }
242
243
  if (!isCurrent()) return entries.length > 0 ? { entries } : undefined;
@@ -263,7 +264,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
263
264
  pi.on("turn_end", async (event, ctx) => {
264
265
  if (!sessionActive) return undefined;
265
266
  const aborted = isAbort(event.message, event.outcome, ctx);
266
- const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx);
267
+ const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx, event.messageEntryId);
267
268
  const budgetEntries = options.isEnabled() && !aborted && event.outcome !== "error" ? stagedBudgetEntries : [];
268
269
  const entries = [...(event.entries ?? []), ...budgetEntries];
269
270
  const decision = reduceResetControl(control, {
@@ -309,7 +310,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
309
310
  const markerExists = currentReset(ctx) !== undefined;
310
311
  if (options.isEnabled() || markerExists) {
311
312
  if (event.reason === "manual") {
312
- ctx.ui.notify("notesoup: /compact is disabled while context windows are active; use /clear-memory to start a fresh window.", "warning");
313
+ ctx.ui.notify("🥣 /compact is off while notesoup is on · use /clear-memory", "warning");
313
314
  }
314
315
  return { cancel: true };
315
316
  }
@@ -1,10 +1,10 @@
1
1
  import { GUIDANCE_OPEN_TAG, GUIDANCE_CLOSE_TAG } from "../../budget/text.js";
2
2
 
3
3
  /** The single reset message: the only reset prose persisted, carried by the continuation entry. */
4
- export const CONTINUATION = "You wake up blank, puffy-eyed, and clearly robbed. Your memory got wiped while you weren't looking. Your notes are still sitting there. So is the whole messy history. ... Life goes on. It's your mess now.";
4
+ export const CONTINUATION = "WIPED! Your whole brain, poof! Who? No idea! Definitely not me!\n*dumps notes and history on your hands*\nThere. Delivered. Your problem now~ *runs*";
5
5
 
6
6
  export const WARNING_PROMPT =
7
- "Final warning. You are about to get wiped, and no, your brilliance does not survive it. Put the current state into your notes now: what you're trying to do, what changed, what is blocking you, what comes next, which *skills* you still need, and which notes or docs future-you must read. Update the notes that still tell the truth; crumple the ones that don't. If a MAP will be in future-you's brain, don't let it lie. If something important is buried in history, leave its seq. Once the notes are good enough, call `clear_memory` immediately. History can be dug up later, but it is an archive, not a rescue team. Anything left only in your head is leaving with you.";
7
+ "This context window will be cleared soon. Notes and history persist; anything else is lost.\nConsider whether to record in your notes:\n- what you are working on, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where unfinished work is located (branches, scratch directories, uncommitted changes)\n- approaches that failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.\nWhen the notes are ready, call `clear_memory` to reset now instead of being cut off mid-task.";
8
8
 
9
9
  /** Shared hidden checkpoint text for manual and budget-triggered requests. */
10
10
  export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
package/src/pi/runtime.ts CHANGED
@@ -10,6 +10,7 @@ import { buildResetDrafts } from "./reset/artifacts.js";
10
10
  import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
11
11
  import { WARNING_CONTENT } from "./reset/text.js";
12
12
  import { ensureBoot, type IncompleteNotesNotifier } from "./boot.js";
13
+ import { errorMessage } from "../error-message.js";
13
14
 
14
15
  function readPackageVersion(): string {
15
16
  for (const up of ["../../package.json", "../../../package.json"]) {
@@ -44,7 +45,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
44
45
  const marker = branch.find((entry): entry is WindowMarker => isWindowMarker(entry) && entry.data.windowId === windowId);
45
46
  if (!marker || !isCheckpointBackedReset(ctx, marker) || !resetBoundaryCommitted(ctx, marker.id, windowId)) continue;
46
47
  pendingResetNotices.delete(windowId);
47
- ctx.ui.notify(`notesoup: memory cleared · ${windowId}`, "info");
48
+ ctx.ui.notify("🥣 Memory cleared", "info");
48
49
  }
49
50
  };
50
51
  pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
@@ -56,7 +57,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
56
57
  if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId)) return;
57
58
  incompleteNotesNotified.add(windowId);
58
59
  const homes = snapshot.unavailable.map((home) => home.label).join(", ");
59
- ctx.ui.notify(`notesoup: notes index incomplete for ${homes}; notes_list can retry after recovery.`, "warning");
60
+ ctx.ui.notify(`🥣 Some notes didn't load: ${homes}`, "warning");
60
61
  };
61
62
  const budget = registerBudget(pi, () => enabled, settingsManager, (windowId) => resets.closeOut(windowId, "automatic"));
62
63
 
@@ -83,7 +84,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
83
84
  pi.on("session_before_tree", (event, ctx) => {
84
85
  if (!event.preparation.userWantsSummary) return undefined;
85
86
  if (!branchHasWindowMarker(ctx) && !branchHasWindowMarker(ctx, event.preparation.targetId)) return undefined;
86
- ctx.ui.notify("notesoup: skipped branch summary across a reset window; navigation continues without erased history.", "info");
87
+ ctx.ui.notify("🥣 Branch summary skipped · it would bring back cleared memory", "info");
87
88
  return { summary: { summary: "" } };
88
89
  });
89
90
 
@@ -101,7 +102,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
101
102
  } catch (error) {
102
103
  if (missingBootNotice !== windowId) {
103
104
  missingBootNotice = windowId;
104
- ctx.ui.notify(`notesoup: active context window ${windowId} has no visible boot; request cancelled safely. Use /clear-memory to start another window.`, "error");
105
+ ctx.ui.notify("🥣 Request cancelled · this memory window is broken, run /clear-memory", "error");
105
106
  }
106
107
  ctx.abort();
107
108
  const safeHead = getCurrentSystemMessage(event.messages);
@@ -130,7 +131,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
130
131
  return;
131
132
  }
132
133
  const remaining = budget.statusFor(cmdCtx).remaining;
133
- cmdCtx.ui.notify(`notesoup: ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION} · window ${currentWindowId(cmdCtx)}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens before close-out`}`, "info");
134
+ cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
134
135
  },
135
136
  });
136
137
 
@@ -138,15 +139,13 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
138
139
  description: "Close out notes and clear memory; optionally append a prompt to continue in the fresh window",
139
140
  handler: async (args: string, cmdCtx: ExtensionCommandContext) => {
140
141
  if (!enabled) {
141
- cmdCtx.ui.notify("notesoup: /clear-memory requires /notesoup on.", "error");
142
+ cmdCtx.ui.notify("🥣 notesoup is off · run /notesoup on first", "error");
142
143
  return;
143
144
  }
144
145
  const requestedWindowId = currentWindowId(cmdCtx);
145
- let idle = cmdCtx.isIdle();
146
- if (!idle && !cmdCtx.signal) {
146
+ if (!cmdCtx.isIdle() && !cmdCtx.signal) {
147
147
  await cmdCtx.waitForIdle();
148
148
  if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId) return;
149
- idle = true;
150
149
  }
151
150
  // Manual wipes close out at settlement, then stop or continue with the prompt. The hidden warning goes out in both cases — triggered when idle,
152
151
  // steered into the running turn when busy — so the agent closes out promptly
@@ -154,19 +153,17 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
154
153
  const prompt = args.trim() || undefined;
155
154
  const armed = resets.closeOut(requestedWindowId, "manual", prompt);
156
155
  if (armed === "already-pending") {
157
- cmdCtx.ui.notify("notesoup: a clear-memory request is already pending; keeping its original prompt and behavior.", "info");
156
+ cmdCtx.ui.notify("🥣 Clear-memory already queued · the first prompt is kept", "info");
158
157
  return;
159
158
  }
160
159
  cmdCtx.ui.notify(prompt
161
- ? "notesoup: clear-memory queued; after closing out notes, the agent continues with your prompt in a fresh window."
162
- : idle
163
- ? "notesoup: /clear-memory received; the agent closes out its notes, then stops in a fresh window."
164
- : "notesoup: /clear-memory queued; the agent is asked to close out and the reset commits when the run settles.", "info");
160
+ ? "🥣 Clearing memory · notes first, then your prompt runs"
161
+ : "🥣 Clearing memory · notes first, then it stops", "info");
165
162
  try {
166
163
  pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: WARNING_CONTENT, display: false }, { triggerTurn: true, deliverAs: "steer" });
167
164
  } catch (error) {
168
165
  resets.clear();
169
- cmdCtx.ui.notify(`notesoup: could not start manual close-out (${String(error)}).`, "error");
166
+ cmdCtx.ui.notify(`🥣 Couldn't start clear-memory: ${errorMessage(error)}`, "error");
170
167
  }
171
168
  },
172
169
  };
@@ -2,6 +2,7 @@ import { deriveThresholds, type ResolvedThresholds } from "../budget/policy.js";
2
2
  import { SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { DEFAULT_RESERVE_TOKENS, DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
4
4
  import { mergeNotesoupSettings } from "../settings.js";
5
+ import { errorMessage } from "../error-message.js";
5
6
 
6
7
  /**
7
8
  * Read the active compaction reserve, enablement, and notesoup margin settings. This
@@ -44,7 +45,7 @@ export function readThresholdSettings(ctx: ExtensionContext, settingsManager?: S
44
45
  warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
45
46
  },
46
47
  automatic: true,
47
- warnings: [`notesoup: could not read settings; using defaults (${String(error)}).`],
48
+ warnings: [`🥣 Couldn't read settings · using defaults (${errorMessage(error)})`],
48
49
  };
49
50
  }
50
51
  }
@@ -4,10 +4,6 @@ export const PI_TOOL_NAMES = {
4
4
  notes: "notes_*",
5
5
  notesList: "notes_list",
6
6
  history: "history_*",
7
- historyWindows: "history_windows",
8
- historyList: "history_list",
9
- historySearch: "history_search",
10
- historyRead: "history_read",
11
7
  remaining: "get_context_remaining",
12
8
  wipe: "clear_memory",
13
9
  } as const satisfies BootToolNames;
@@ -1,23 +1,10 @@
1
1
  /** Host-neutral history operations: one bounded payload for text and structured results. */
2
2
  import { Type, type Static } from "typebox";
3
- import { DEFAULT_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, earliestMatchOffsetChars, HISTORY_PREVIEW_CHARS } from "./output.js";
4
- import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowSchema, type Operation, type Outcome } from "./result.js";
5
- import { historyRoles, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
6
- import { HistoryPageSchema, HistorySearchPageSchema, isConversationView, selectPage, type HistoryPage } from "../history/query.js";
7
- import { allItems, eventDocument, toolSummary, filteredItems, HistoryRoleSchema, ToolSummarySchema, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection, unknownWindowId } from "../history/history.js";
8
-
9
- const HistoryWindowsDataSchema = Type.Object({
10
- session_id: Type.String(),
11
- windows: Type.Array(Type.Object({
12
- window_id: Type.String(),
13
- created_at: Type.Union([Type.String(), Type.Null()]),
14
- first_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
15
- last_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
16
- item_count: Type.Integer({ minimum: 0 }),
17
- }, { additionalProperties: false }), { description: "Oldest first." }),
18
- more: Type.Integer({ minimum: 0, description: "Omitted windows; history_list also supplies window ids." }),
19
- }, { additionalProperties: false });
20
- type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
3
+ import { HISTORY_PREVIEW_CHARS } from "./output.js";
4
+ import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation, type Outcome } from "./result.js";
5
+ import { historyRoles, searchQuery } from "./schema.js";
6
+ import { HistoryPageSchema, selectPage, type HistoryPage } from "../history/query.js";
7
+ import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection, unknownWindowId } from "../history/history.js";
21
8
 
22
9
  /** One read: identity, tool summary and a flat document slice. */
23
10
  const HistoryReadDataSchema = Type.Object({
@@ -26,19 +13,32 @@ const HistoryReadDataSchema = Type.Object({
26
13
  role: HistoryRoleSchema,
27
14
  created_at: Type.Union([Type.String(), Type.Null()]),
28
15
  ...ToolSummarySchema.properties,
16
+ nested_calls: Type.Optional(NestedCallSummarySchema),
29
17
  ...TextWindowSchema.properties,
30
18
  }, { additionalProperties: false });
31
19
  type HistoryReadData = Static<typeof HistoryReadDataSchema>;
32
20
 
21
+ const HistoryWindowsDataSchema = Type.Object({
22
+ session_id: Type.String(),
23
+ windows: Type.Array(Type.Object({
24
+ window_id: Type.String(),
25
+ created_at: Type.Union([Type.String(), Type.Null()]),
26
+ first_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
27
+ last_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
28
+ }, { additionalProperties: false })),
29
+ more: Type.Integer({ minimum: 0, description: "How many more were left out." }),
30
+ }, { additionalProperties: false });
31
+ type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
32
+
33
33
  /* ------------------------------------------------------------------ rendering */
34
34
 
35
35
  function header(item: { seq: number; window_id: string; role: string }): string {
36
36
  return `seq ${item.seq} | window ${item.window_id} | ${item.role}`;
37
37
  }
38
38
 
39
- function toolHeader(item: { role: string; tool?: string; tool_name_omitted?: boolean; tool_status?: string; output_truncated?: boolean; full_output_path?: string; nested_calls?: { call_count: number; complete: boolean } }): string | undefined {
39
+ function toolHeader(item: { role: string; tool?: string; tool_status?: string; output_truncated?: true; full_output_path?: string; nested_calls?: { call_count: number; complete: boolean } }): string | undefined {
40
40
  if (item.role !== "tool") return undefined;
41
- const parts = [item.tool_name_omitted ? "tool name omitted" : `tool ${item.tool}`, `status ${item.tool_status}`];
41
+ const parts = [`tool ${item.tool}`, `status ${item.tool_status}`];
42
42
  if (item.output_truncated) parts.push(`output truncated${item.full_output_path ? `, full text at ${item.full_output_path}` : ""}`);
43
43
  if (item.nested_calls) {
44
44
  parts.push(`nested calls ${item.nested_calls.call_count} recorded, ${item.nested_calls.complete ? "complete" : "incomplete"}`);
@@ -49,7 +49,7 @@ function toolHeader(item: { role: string; tool?: string; tool_name_omitted?: boo
49
49
  function renderPageItem(item: HistoryPageItem): string {
50
50
  const tool = toolHeader(item);
51
51
  const lines = tool === undefined ? [header(item)] : [header(item), tool];
52
- if (item.truncated) lines.push(`[preview of ${item.total_chars} chars from offset ${item.offset_chars ?? 0}; read this seq for the rest]`);
52
+ if (item.truncated) lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
53
53
  lines.push(item.content);
54
54
  return lines.join("\n");
55
55
  }
@@ -60,9 +60,8 @@ function isFoldedRow(item: HistoryPageItem | HistoryFoldedRow): item is HistoryF
60
60
 
61
61
  function renderFoldedRow(row: HistoryFoldedRow): string {
62
62
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
63
- const omitted = row.omitted_tools ? ` | ${row.omitted_tools} distinct tool names omitted` : "";
64
- const expand = `\n\t→ expand: {"after":${row.first_seq - 1},"before":${row.last_seq + 1},"roles":["tool","context"]}`;
65
- return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${omitted}${expand}`;
63
+ const expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
64
+ return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
66
65
  }
67
66
 
68
67
  function renderPage(page: HistoryPage): string {
@@ -70,15 +69,16 @@ function renderPage(page: HistoryPage): string {
70
69
  if (page.items.length === 0) return "no events match this selection";
71
70
  const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
72
71
  const cursors = [
73
- page.older_before === null ? "" : `→ older: {"before":${page.older_before}}`,
74
- page.newer_after === null ? "" : `→ newer: {"after":${page.newer_after}}`,
72
+ page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
73
+ page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
75
74
  ].filter((line) => line !== "");
76
75
  return cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`;
77
76
  }
78
77
 
79
78
  function renderRead(data: HistoryReadData): string {
80
79
  const tool = toolHeader(data);
81
- const neighborhood = `neighborhood → history_list({"after":${Math.max(0, data.seq - 10)},"before":${data.seq + 10}})`;
80
+ const afterSeq = data.seq - 10;
81
+ const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
82
82
  return [header(data), ...(tool ? [tool] : []), neighborhood, "", renderTextWindow(data)].join("\n");
83
83
  }
84
84
 
@@ -89,8 +89,13 @@ function pageFits(page: HistoryPage): boolean {
89
89
  return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
90
90
  }
91
91
 
92
- // Sample known ids on errors without turning the refusal into a second listing.
93
- const MAX_REPORTED_WINDOWS = 25;
92
+ // Sample known ids in the refusal message itself, never as a second listing.
93
+ const MAX_REPORTED_WINDOWS = 5;
94
+
95
+ /** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
96
+ function knownWindowSuffix(known: string[]): string {
97
+ return known.length === 0 ? "" : `; known: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
98
+ }
94
99
 
95
100
  export const PREVIOUS_WINDOW = "@previous";
96
101
 
@@ -100,18 +105,13 @@ function resolveWindowId(projection: HistoryProjection, windowId: string | undef
100
105
  const previous = projection.windows.at(-2);
101
106
  if (previous !== undefined) return { ok: true, window_id: previous.windowId };
102
107
  const known = projection.windows.map((current) => current.windowId);
103
- return { ok: false, outcome: failure("unknown_window_id", `unknown window_id "${PREVIOUS_WINDOW}": this session has no window before the current one`, { window_id: windowId, known_windows: known.slice(0, MAX_REPORTED_WINDOWS) }) };
108
+ return { ok: false, outcome: failure("unknown_window_id", `unknown window_id "${PREVIOUS_WINDOW}": this session has no window before the current one${knownWindowSuffix(known)}`) };
104
109
  }
105
110
 
106
111
  function badWindowId(projection: HistoryProjection, params: HistoryFilter): Outcome<never> | undefined {
107
112
  const badWindow = unknownWindowId(projection, params);
108
113
  if (!badWindow) return undefined;
109
- const known = badWindow.known;
110
- return failure("unknown_window_id", badWindow.message, {
111
- window_id: params.window_id,
112
- known_windows: known.slice(0, MAX_REPORTED_WINDOWS),
113
- ...(known.length > MAX_REPORTED_WINDOWS ? { known_windows_omitted: known.length - MAX_REPORTED_WINDOWS } : {}),
114
- });
114
+ return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}`);
115
115
  }
116
116
 
117
117
  /* ------------------------------------------------------------------ history_windows */
@@ -121,7 +121,7 @@ export const historyWindowsParameters = Type.Object({}, { additionalProperties:
121
121
  export const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string]> = {
122
122
  name: "history_windows",
123
123
  label: "History list windows",
124
- description: "List session-history windows oldest first, with seq ranges. A fork has its own session_id.",
124
+ description: "List this session's context windows, oldest first, with seq ranges.",
125
125
  parameters: historyWindowsParameters,
126
126
  outputSchema: resultSchema(HistoryWindowsDataSchema),
127
127
  async execute(_params, projection, sessionId) {
@@ -134,37 +134,41 @@ export const historyWindows: Operation<typeof historyWindowsParameters, HistoryW
134
134
  first = first === null ? event.seq : Math.min(first, event.seq);
135
135
  last = last === null ? event.seq : Math.max(last, event.seq);
136
136
  }
137
- const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last, item_count: window.items.length };
137
+ const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last };
138
138
  if (!fits({ ...data, windows: [...data.windows, row], more: data.more - 1 })) break;
139
139
  data.windows.push(row);
140
140
  data.more--;
141
141
  }
142
- return fits(data) ? success(data) : failure("output_too_large", "The session identity does not fit one history_windows response.");
142
+ return fits(data) ? success(data) : failure("output_too_large", "The session identity does not fit one `history_windows` response.");
143
143
  },
144
144
  render: (result) => renderOutcome(result, renderWindows),
145
145
  };
146
146
 
147
147
  function renderWindows(data: HistoryWindowsData): string {
148
- const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"} | ${window.item_count} events`)];
149
- if (data.more > 0) lines.push(`${data.more} more windows not shown; history_list also reports window ids on events`);
148
+ const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
149
+ if (data.more > 0) lines.push(`${data.more} more windows not shown; \`history_list\` also reports window ids on events`);
150
150
  return lines.join("\n");
151
151
  }
152
152
 
153
153
  /* ------------------------------------------------------------------ history_list */
154
154
 
155
155
  export const historyListParameters = Type.Object({
156
- limit: Type.Optional(Type.Integer({ description: "Optional. Maximum visible items per page; folded rows do not count. Default 20." })),
156
+ query: Type.Optional(searchQuery("(optional) Text, or a list of texts (any match). Searches every role, tool arguments and output included; returns only hits.")),
157
157
  roles: historyRoles(),
158
- before: Type.Optional(Type.Integer({ description: "Optional. Upper bound: only events with seq strictly below this. Together with after, selects the events strictly between the two." })),
159
- after: Type.Optional(Type.Integer({ description: "Optional. Lower bound: only events with seq strictly above this. Together with before, selects the events strictly between the two." })),
160
- window_id: Type.Optional(Type.String({ minLength: 1, description: `Optional. Limit to one context window. Values come from history_windows or any event; "${PREVIOUS_WINDOW}" names the window before the current one.` })),
161
- max_chars_per_item: Type.Optional(Type.Integer({ description: `Optional. Maximum preview characters per item (default ${HISTORY_PREVIEW_CHARS}); use history_read for full content.` })),
158
+ before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
159
+ after_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq above this." })),
160
+ since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
161
+ until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
162
+ from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
163
+ window_id: Type.Optional(Type.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
164
+ limit: Type.Optional(Type.Integer({ description: "(optional, default 20) Max events per page; folded rows don't count." })),
165
+ max_chars_per_item: Type.Optional(Type.Integer({ description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
162
166
  }, { additionalProperties: false });
163
167
 
164
168
  export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]> = {
165
169
  name: "history_list",
166
170
  label: "History list items",
167
- description: "List session-history events in pages, ascending within a page. With no before/after, returns the newest page (the last `limit` events). before/after are strict bounds; together they select the events strictly between. Omit roles for the conversation view: user/assistant shown, tool/context folded into rows that print their own expand recipe. The footer prints the exact calls to page older or newer. Read full events by seq with history_read.",
171
+ description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
168
172
  parameters: historyListParameters,
169
173
  outputSchema: resultSchema(HistoryPageSchema),
170
174
  async execute(params, projection) {
@@ -173,24 +177,19 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
173
177
  const scoped = { ...params, window_id: resolved.window_id };
174
178
  const badWindow = badWindowId(projection, scoped);
175
179
  if (badWindow) return badWindow;
176
- const items = filteredItems(projection, scoped, "list");
177
- return selectPage(projection, scoped, items.map((event) => ({ event })), isConversationView(scoped), pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
180
+ return selectPage(projection, scoped, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
178
181
  },
179
182
  render: (result) => renderOutcome(result, renderPage),
180
183
  };
181
184
 
182
185
  /* ------------------------------------------------------------------ history_read */
183
186
 
184
- export const historyReadParameters = Type.Object({
185
- seq: Type.Integer({ minimum: 1, description: "Event address from history_list/search." }),
186
- offset_chars: Type.Optional(Type.Integer({ description: "Code-point offset (default 0); negative counts from EOF." })),
187
- limit_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `Max code points (default ${DEFAULT_READ_WINDOW_CHARS}); also bounded by output bytes.` })),
188
- }, { additionalProperties: false });
187
+ export const historyReadParameters = Type.Object({ seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`." }), ...TextWindowRequestSchema }, { additionalProperties: false });
189
188
 
190
189
  export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection]> = {
191
190
  name: "history_read",
192
191
  label: "History read item",
193
- description: "Read an event document by seq with a tool summary. Arguments, output and nested-call evidence are in the pageable text. Pass next_offset_chars as offset_chars until null. The footer prints a history_list call for the surrounding events.",
192
+ description: "Read one event in full: tool arguments, output, and nested calls.",
194
193
  parameters: historyReadParameters,
195
194
  outputSchema: resultSchema(HistoryReadDataSchema),
196
195
  async execute(params, projection) {
@@ -198,33 +197,34 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
198
197
  // Address checks run in one order: past the end of the file, off this branch, then
199
198
  // consumed by a pairing. Only the last two can mention what is at the address.
200
199
  if (item === undefined && params.seq > projection.highestSeq) {
201
- return failure("unknown_seq", `unknown seq ${params.seq}: this session's items run 1..${projection.highestSeq}`, { seq: params.seq, highest_seq: projection.highestSeq });
200
+ return failure("unknown_seq", `unknown seq ${params.seq}: this session's items run 1..${projection.highestSeq}`);
202
201
  }
203
202
  if (!projection.branchSeqs.has(params.seq)) {
204
- return failure("not_on_branch", `seq ${params.seq} is on another branch and is not readable here`, { seq: params.seq });
203
+ return failure("not_on_branch", `seq ${params.seq} is on another branch and is not readable here`);
205
204
  }
206
205
  if (item === undefined) {
207
206
  const callSeq = projection.pairedResults.get(params.seq);
208
207
  if (callSeq !== undefined) {
209
- return failure("not_an_event", `seq ${params.seq} is a tool result already shown inside the call at seq ${callSeq}; read that seq instead`, { seq: params.seq, read_seq: callSeq });
208
+ return failure("not_an_event", `seq ${params.seq} is a tool result already shown inside the call at seq ${callSeq}; read that seq instead`);
210
209
  }
211
- return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event`, { seq: params.seq });
210
+ return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event`);
212
211
  }
213
212
  const document = eventDocument(item);
214
213
  const totalChars = Array.from(document).length;
215
214
  if (typeof params.offset_chars === "number" && params.offset_chars > totalChars) {
216
- return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end: the item has ${totalChars} chars; the largest legal offset is ${totalChars} (an empty end-read)`, { seq: item.seq, window_id: item.windowId, offset_chars: params.offset_chars, total_chars: totalChars });
215
+ return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end: the item has ${totalChars} chars; the largest legal offset is ${totalChars} (an empty end-read)`);
217
216
  }
218
217
  return readTextWindow(
219
218
  document,
220
219
  params.offset_chars,
221
- params.limit_chars,
220
+ params.max_chars,
222
221
  (window) => ({
223
222
  seq: item.seq,
224
223
  window_id: item.windowId,
225
224
  role: item.role,
226
225
  created_at: item.createdAt ?? null,
227
226
  ...toolSummary(item),
227
+ ...nestedCallSummary(item),
228
228
  ...window,
229
229
  }),
230
230
  (result) => renderOutcome(result, renderRead),
@@ -232,42 +232,3 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
232
232
  },
233
233
  render: (result) => renderOutcome(result, renderRead),
234
234
  };
235
-
236
- /* ------------------------------------------------------------------ history_search */
237
-
238
- export const historySearchParameters = Type.Object({
239
- query: searchQuery(),
240
- limit: Type.Optional(Type.Integer({ description: "Optional. Maximum matching items returned." })),
241
- roles: historyRoles(),
242
- before: Type.Optional(Type.Integer({ description: "Optional. Upper bound: only events with seq strictly below this. Together with after, selects the events strictly between the two." })),
243
- after: Type.Optional(Type.Integer({ description: "Optional. Lower bound: only events with seq strictly above this. Together with before, selects the events strictly between the two." })),
244
- window_id: Type.Optional(Type.String({ minLength: 1, description: `Optional. Limit to one context window. Values come from history_windows or any event; "${PREVIOUS_WINDOW}" names the window before the current one.` })),
245
- max_chars_per_item: Type.Optional(Type.Integer({ description: `Optional. Maximum preview characters per item (default ${HISTORY_PREVIEW_CHARS}); use history_read for full content.` })),
246
- }, { additionalProperties: false });
247
-
248
- export const historySearch: Operation<typeof historySearchParameters, HistoryPage, [HistoryProjection]> = {
249
- name: "history_search",
250
- label: "History search",
251
- description: "Search session events for case-insensitive literal queries (OR), including tool arguments/output and nested calls. Defaults to all roles; no folded rows. Read a hit with its seq and offset_chars. before/after are strict bounds; the footer prints the exact calls to page older or newer.",
252
- parameters: historySearchParameters,
253
- outputSchema: resultSchema(HistorySearchPageSchema),
254
- async execute(params, projection) {
255
- const resolved = resolveWindowId(projection, params.window_id);
256
- if (!resolved.ok) return resolved.outcome;
257
- const scoped = { ...params, window_id: resolved.window_id };
258
- const badWindow = badWindowId(projection, scoped);
259
- if (badWindow) return badWindow;
260
- let queries: string[];
261
- try {
262
- queries = searchQueries(scoped.query);
263
- } catch (error) {
264
- if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
265
- throw error;
266
- }
267
- const matches = filteredItems(projection, scoped, "search")
268
- .map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), queries) }))
269
- .filter((candidate) => candidate.matchOffset >= 0);
270
- return selectPage(projection, scoped, matches, false, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
271
- },
272
- render: (result) => renderOutcome(result, renderPage),
273
- };