notesoup 0.0.0-stage → 0.39.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +91 -2
  3. package/dist/src/boot/render.d.ts +16 -0
  4. package/dist/src/boot/render.js +95 -0
  5. package/dist/src/boot/snapshot.d.ts +32 -0
  6. package/dist/src/boot/snapshot.js +36 -0
  7. package/dist/src/boot/text.d.ts +21 -0
  8. package/dist/src/boot/text.js +52 -0
  9. package/dist/src/budget/constants.d.ts +9 -0
  10. package/dist/src/budget/constants.js +9 -0
  11. package/dist/src/budget/policy.d.ts +19 -0
  12. package/dist/src/budget/policy.js +36 -0
  13. package/dist/src/budget/text.d.ts +8 -0
  14. package/dist/src/budget/text.js +10 -0
  15. package/dist/src/claude/helper.d.ts +15 -0
  16. package/dist/src/claude/helper.js +87 -0
  17. package/dist/src/dream/doctor.d.ts +2 -0
  18. package/dist/src/dream/doctor.js +160 -0
  19. package/dist/src/dream/gates.d.ts +10 -0
  20. package/dist/src/dream/gates.js +26 -0
  21. package/dist/src/dream/git.d.ts +21 -0
  22. package/dist/src/dream/git.js +71 -0
  23. package/dist/src/dream/jail.d.ts +11 -0
  24. package/dist/src/dream/jail.js +71 -0
  25. package/dist/src/dream/lock.d.ts +31 -0
  26. package/dist/src/dream/lock.js +99 -0
  27. package/dist/src/dream/playbook.d.ts +1 -0
  28. package/dist/src/dream/playbook.js +2 -0
  29. package/dist/src/dream/report.d.ts +7 -0
  30. package/dist/src/dream/report.js +43 -0
  31. package/dist/src/dream/result.d.ts +9 -0
  32. package/dist/src/dream/result.js +1 -0
  33. package/dist/src/dream/settings.d.ts +10 -0
  34. package/dist/src/dream/settings.js +14 -0
  35. package/dist/src/history/history.d.ts +151 -0
  36. package/dist/src/history/history.js +195 -0
  37. package/dist/src/history/query.d.ts +75 -0
  38. package/dist/src/history/query.js +143 -0
  39. package/dist/src/index.d.ts +1 -0
  40. package/dist/src/index.js +1 -0
  41. package/dist/src/notes/address.d.ts +31 -0
  42. package/dist/src/notes/address.js +123 -0
  43. package/dist/src/notes/constants.d.ts +3 -0
  44. package/dist/src/notes/constants.js +3 -0
  45. package/dist/src/notes/errors.d.ts +11 -0
  46. package/dist/src/notes/errors.js +13 -0
  47. package/dist/src/notes/frontmatter.d.ts +44 -0
  48. package/dist/src/notes/frontmatter.js +145 -0
  49. package/dist/src/notes/fs-error.d.ts +2 -0
  50. package/dist/src/notes/fs-error.js +5 -0
  51. package/dist/src/notes/identity.d.ts +10 -0
  52. package/dist/src/notes/identity.js +33 -0
  53. package/dist/src/notes/index.d.ts +5 -0
  54. package/dist/src/notes/index.js +3 -0
  55. package/dist/src/notes/paths.d.ts +21 -0
  56. package/dist/src/notes/paths.js +113 -0
  57. package/dist/src/notes/store.d.ts +104 -0
  58. package/dist/src/notes/store.js +478 -0
  59. package/dist/src/pi/boot.d.ts +24 -0
  60. package/dist/src/pi/boot.js +56 -0
  61. package/dist/src/pi/budget.d.ts +13 -0
  62. package/dist/src/pi/budget.js +178 -0
  63. package/dist/src/pi/dream/cli.d.ts +10 -0
  64. package/dist/src/pi/dream/cli.js +140 -0
  65. package/dist/src/pi/dream/runner.d.ts +27 -0
  66. package/dist/src/pi/dream/runner.js +90 -0
  67. package/dist/src/pi/dream/settings.d.ts +7 -0
  68. package/dist/src/pi/dream/settings.js +17 -0
  69. package/dist/src/pi/entries.d.ts +7 -0
  70. package/dist/src/pi/entries.js +7 -0
  71. package/dist/src/pi/estimate.d.ts +16 -0
  72. package/dist/src/pi/estimate.js +99 -0
  73. package/dist/src/pi/extension.d.ts +10 -0
  74. package/dist/src/pi/extension.js +24 -0
  75. package/dist/src/pi/history-tools.d.ts +3 -0
  76. package/dist/src/pi/history-tools.js +10 -0
  77. package/dist/src/pi/history.d.ts +4 -0
  78. package/dist/src/pi/history.js +150 -0
  79. package/dist/src/pi/notes/adapter.d.ts +10 -0
  80. package/dist/src/pi/notes/adapter.js +27 -0
  81. package/dist/src/pi/notes/tools.d.ts +3 -0
  82. package/dist/src/pi/notes/tools.js +15 -0
  83. package/dist/src/pi/reset/artifacts.d.ts +24 -0
  84. package/dist/src/pi/reset/artifacts.js +84 -0
  85. package/dist/src/pi/reset/committed.d.ts +7 -0
  86. package/dist/src/pi/reset/committed.js +28 -0
  87. package/dist/src/pi/reset/lifecycle.d.ts +101 -0
  88. package/dist/src/pi/reset/lifecycle.js +277 -0
  89. package/dist/src/pi/reset/text.d.ts +5 -0
  90. package/dist/src/pi/reset/text.js +6 -0
  91. package/dist/src/pi/runtime.d.ts +3 -0
  92. package/dist/src/pi/runtime.js +206 -0
  93. package/dist/src/pi/session-reader.d.ts +5 -0
  94. package/dist/src/pi/session-reader.js +1 -0
  95. package/dist/src/pi/thresholds.d.ts +17 -0
  96. package/dist/src/pi/thresholds.js +33 -0
  97. package/dist/src/pi/tool-names.d.ts +11 -0
  98. package/dist/src/pi/tool-names.js +11 -0
  99. package/dist/src/pi/tool-result.d.ts +15 -0
  100. package/dist/src/pi/tool-result.js +29 -0
  101. package/dist/src/pi/window.d.ts +41 -0
  102. package/dist/src/pi/window.js +127 -0
  103. package/dist/src/settings.d.ts +9 -0
  104. package/dist/src/settings.js +18 -0
  105. package/dist/src/text-match.d.ts +5 -0
  106. package/dist/src/text-match.js +16 -0
  107. package/dist/src/tools/history.d.ts +67 -0
  108. package/dist/src/tools/history.js +251 -0
  109. package/dist/src/tools/notes.d.ts +282 -0
  110. package/dist/src/tools/notes.js +378 -0
  111. package/dist/src/tools/output.d.ts +23 -0
  112. package/dist/src/tools/output.js +39 -0
  113. package/dist/src/tools/result.d.ts +79 -0
  114. package/dist/src/tools/result.js +130 -0
  115. package/dist/src/tools/schema.d.ts +18 -0
  116. package/dist/src/tools/schema.js +31 -0
  117. package/dist/test/agent-loop.test.d.ts +1 -0
  118. package/dist/test/agent-loop.test.js +1497 -0
  119. package/dist/test/boot.integration.test.d.ts +1 -0
  120. package/dist/test/boot.integration.test.js +294 -0
  121. package/dist/test/budget-settings.integration.test.d.ts +1 -0
  122. package/dist/test/budget-settings.integration.test.js +144 -0
  123. package/dist/test/claude-mod.test.d.ts +1 -0
  124. package/dist/test/claude-mod.test.js +404 -0
  125. package/dist/test/dependencies.test.d.ts +1 -0
  126. package/dist/test/dependencies.test.js +101 -0
  127. package/dist/test/doctor.test.d.ts +1 -0
  128. package/dist/test/doctor.test.js +37 -0
  129. package/dist/test/dream-skill.test.d.ts +1 -0
  130. package/dist/test/dream-skill.test.js +72 -0
  131. package/dist/test/dream.test.d.ts +1 -0
  132. package/dist/test/dream.test.js +136 -0
  133. package/dist/test/helpers/dependency-graph.d.ts +5 -0
  134. package/dist/test/helpers/dependency-graph.js +73 -0
  135. package/dist/test/helpers/extension-test-environment.d.ts +1 -0
  136. package/dist/test/helpers/extension-test-environment.js +9 -0
  137. package/dist/test/helpers/extension.d.ts +119 -0
  138. package/dist/test/helpers/extension.js +368 -0
  139. package/dist/test/helpers/notes.d.ts +6 -0
  140. package/dist/test/helpers/notes.js +13 -0
  141. package/dist/test/history.integration.test.d.ts +1 -0
  142. package/dist/test/history.integration.test.js +556 -0
  143. package/dist/test/host-neutral.test.d.ts +1 -0
  144. package/dist/test/host-neutral.test.js +300 -0
  145. package/dist/test/notes-library.test.d.ts +1 -0
  146. package/dist/test/notes-library.test.js +214 -0
  147. package/dist/test/notes.integration.test.d.ts +1 -0
  148. package/dist/test/notes.integration.test.js +497 -0
  149. package/dist/test/notes.test.d.ts +1 -0
  150. package/dist/test/notes.test.js +528 -0
  151. package/dist/test/reset-lifecycle.test.d.ts +1 -0
  152. package/dist/test/reset-lifecycle.test.js +605 -0
  153. package/docs/architecture.md +63 -0
  154. package/docs/claude-code-mod.md +9 -0
  155. package/docs/notes-library.md +74 -0
  156. package/docs/reset-lifecycle.md +75 -0
  157. package/docs/sdk-integration.md +39 -0
  158. package/docs/skills.md +30 -0
  159. package/docs/tool-results.md +88 -0
  160. package/mods/notesoup/.claude-plugin/plugin.json +8 -0
  161. package/mods/notesoup/dist/claude/helper.js +9324 -0
  162. package/mods/notesoup/hooks/hooks.json +4 -0
  163. package/mods/notesoup/hooks/register.ts +241 -0
  164. package/mods/notesoup/playbook.md +34 -0
  165. package/mods/notesoup/skills/dream/SKILL.md +12 -0
  166. package/mods/pi-context/dist/claude/helper.js +9324 -0
  167. package/package.json +89 -5
  168. package/playbook.md +34 -0
  169. package/skills/dream/SKILL.md +12 -0
  170. package/skills/memory/SKILL.md +59 -0
  171. package/src/boot/render.ts +115 -0
  172. package/src/boot/snapshot.ts +46 -0
  173. package/src/boot/text.ts +66 -0
  174. package/src/budget/constants.ts +9 -0
  175. package/src/budget/policy.ts +36 -0
  176. package/src/budget/text.ts +11 -0
  177. package/src/claude/helper.ts +94 -0
  178. package/src/dream/doctor.ts +117 -0
  179. package/src/dream/gates.ts +26 -0
  180. package/src/dream/git.ts +73 -0
  181. package/src/dream/jail.ts +62 -0
  182. package/src/dream/lock.ts +82 -0
  183. package/src/dream/playbook.ts +3 -0
  184. package/src/dream/report.ts +36 -0
  185. package/src/dream/result.ts +2 -0
  186. package/src/dream/settings.ts +16 -0
  187. package/src/history/history.ts +270 -0
  188. package/src/history/query.ts +147 -0
  189. package/src/index.ts +1 -0
  190. package/src/notes/address.ts +110 -0
  191. package/src/notes/constants.ts +3 -0
  192. package/src/notes/errors.ts +15 -0
  193. package/src/notes/frontmatter.ts +166 -0
  194. package/src/notes/fs-error.ts +5 -0
  195. package/src/notes/identity.ts +40 -0
  196. package/src/notes/index.ts +24 -0
  197. package/src/notes/paths.ts +109 -0
  198. package/src/notes/store.ts +497 -0
  199. package/src/pi/boot.ts +88 -0
  200. package/src/pi/budget.ts +178 -0
  201. package/src/pi/dream/cli.ts +92 -0
  202. package/src/pi/dream/runner.ts +91 -0
  203. package/src/pi/dream/settings.ts +17 -0
  204. package/src/pi/entries.ts +7 -0
  205. package/src/pi/estimate.ts +116 -0
  206. package/src/pi/extension.ts +27 -0
  207. package/src/pi/history-tools.ts +12 -0
  208. package/src/pi/history.ts +162 -0
  209. package/src/pi/notes/adapter.ts +33 -0
  210. package/src/pi/notes/tools.ts +18 -0
  211. package/src/pi/reset/artifacts.ts +100 -0
  212. package/src/pi/reset/committed.ts +26 -0
  213. package/src/pi/reset/lifecycle.ts +342 -0
  214. package/src/pi/reset/text.ts +10 -0
  215. package/src/pi/runtime.ts +200 -0
  216. package/src/pi/session-reader.ts +6 -0
  217. package/src/pi/thresholds.ts +50 -0
  218. package/src/pi/tool-names.ts +13 -0
  219. package/src/pi/tool-result.ts +41 -0
  220. package/src/pi/window.ts +133 -0
  221. package/src/settings.ts +22 -0
  222. package/src/text-match.ts +14 -0
  223. package/src/tools/history.ts +273 -0
  224. package/src/tools/notes.ts +394 -0
  225. package/src/tools/output.ts +41 -0
  226. package/src/tools/result.ts +169 -0
  227. package/src/tools/schema.ts +31 -0
@@ -0,0 +1,133 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import { getCurrentSystemMessage } from "@earendil-works/pi-ai";
3
+ import { estimateContextTokens } from "./estimate.js";
4
+ import { convertToLlm, type CustomEntry, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
5
+ import { BOOT_TYPE, RESET_MARKER_TYPE } from "./entries.js";
6
+ import type { SessionReader } from "./session-reader.js";
7
+
8
+ export type WindowMarker = CustomEntry<{ windowId: string }> & { data: { windowId: string } };
9
+
10
+ export function isWindowMarker(entry: SessionEntry): entry is WindowMarker {
11
+ return entry.type === "custom" && entry.customType === RESET_MARKER_TYPE &&
12
+ typeof entry.data === "object" && entry.data !== null &&
13
+ typeof (entry.data as { windowId?: unknown }).windowId === "string" &&
14
+ (entry.data as { windowId: string }).windowId.length > 0;
15
+ }
16
+
17
+ /** Only the active branch can supply a window boundary. */
18
+ export function currentReset(ctx: SessionReader): WindowMarker | undefined {
19
+ const branch = ctx.sessionManager.getBranch();
20
+ for (let i = branch.length - 1; i >= 0; i--) {
21
+ const entry = branch[i];
22
+ if (entry && isWindowMarker(entry)) return entry;
23
+ }
24
+ return undefined;
25
+ }
26
+
27
+ /** A reset is checkpoint-backed only when its marker directly follows a native compaction. */
28
+ export function isCheckpointBackedReset(ctx: SessionReader, marker = currentReset(ctx)): boolean {
29
+ if (!marker?.parentId) return false;
30
+ const branch = ctx.sessionManager.getBranch();
31
+ const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
32
+ const checkpoint = branch[markerIndex - 1];
33
+ return markerIndex > 0 && checkpoint?.id === marker.parentId && checkpoint.type === "compaction" &&
34
+ checkpoint.summary === "" && checkpoint.firstKeptEntryId === checkpoint.id;
35
+ }
36
+
37
+ /** Mint the durable identity of a session's root history window. */
38
+ export function rootWindowId(sessionId: string): string {
39
+ return `pcw:${sessionId.slice(0, 8)}:root`;
40
+ }
41
+
42
+ /** Persisted messages in the active window, excluding earlier windows on this branch. */
43
+ export function hasWindowMessage(ctx: SessionReader, customType: string): boolean {
44
+ const branch = ctx.sessionManager.getBranch();
45
+ for (let i = branch.length - 1; i >= 0; i--) {
46
+ const entry = branch[i];
47
+ if (isWindowMarker(entry)) break;
48
+ if (entry.type === "custom_message" && entry.customType === customType) return true;
49
+ }
50
+ return false;
51
+ }
52
+
53
+ /** The root or latest durable marker on the active branch. */
54
+ export function currentWindowId(ctx: SessionReader): string {
55
+ return currentReset(ctx)?.data.windowId ?? rootWindowId(ctx.sessionManager.getSessionId());
56
+ }
57
+
58
+ /** The durable window active just before the marker: the last earlier marker, else the root window. */
59
+ export function previousWindowId(ctx: SessionReader, markerId: string): string {
60
+ let previousId = rootWindowId(ctx.sessionManager.getSessionId());
61
+ for (const entry of ctx.sessionManager.getBranch()) {
62
+ if (entry.id === markerId) break;
63
+ if (isWindowMarker(entry)) previousId = entry.data.windowId;
64
+ }
65
+ return previousId;
66
+ }
67
+
68
+ function hasWindowId(details: unknown, windowId: string): boolean {
69
+ return typeof details === "object" && details !== null &&
70
+ typeof (details as { windowId?: unknown }).windowId === "string" &&
71
+ (details as { windowId: string }).windowId === windowId;
72
+ }
73
+
74
+ /** Match a provider-facing boot message, optionally by window identity. */
75
+ export function isWindowBoot(message: AgentMessage, windowId?: string): boolean {
76
+ return message.role === "custom" && message.customType === BOOT_TYPE && (windowId === undefined || hasWindowId(message.details, windowId));
77
+ }
78
+
79
+ /** Match a persisted boot entry by raw identity, even when a later edit hides it from projection. */
80
+ export function isWindowBootEntry(entry: SessionEntry, windowId: string): boolean {
81
+ return entry.type === "custom_message" && entry.customType === BOOT_TYPE && hasWindowId(entry.details, windowId);
82
+ }
83
+
84
+ /**
85
+ * The durable marker selects a boot message by identity, never by wall-clock time.
86
+ * The boot is the first conversation message of the window. Folding only its prefix
87
+ * preserves later prompt/tool patches in place, including their cacheable ordering.
88
+ */
89
+ export function projectWindow(messages: AgentMessage[], windowId: string): AgentMessage[] {
90
+ const cut = messages.findIndex((message) => isWindowBoot(message, windowId));
91
+ if (cut < 0) throw new Error(`Missing boot for context window ${windowId}`);
92
+ const head = getCurrentSystemMessage(messages.slice(0, cut));
93
+ const suffix = messages.slice(cut);
94
+ return head ? [head, ...suffix] : suffix;
95
+ }
96
+
97
+ /**
98
+ * Root windows are not reset boundaries. A forked session can copy a root boot whose
99
+ * details name the source session; refresh that boot in-place in the provider projection
100
+ * while retaining every user/assistant/tool message from the copied root transcript.
101
+ */
102
+ export function projectRootWindow(messages: AgentMessage[], windowId: string): AgentMessage[] {
103
+ const matching = messages.filter((message) => isWindowBoot(message, windowId));
104
+ if (matching.length === 0) return messages;
105
+ const activeBoot = matching[matching.length - 1];
106
+ const firstBoot = messages.findIndex((message) => isWindowBoot(message));
107
+ const withoutBoots = messages.filter((message) => !isWindowBoot(message));
108
+ return [...withoutBoots.slice(0, firstBoot), activeBoot, ...withoutBoots.slice(firstBoot)];
109
+ }
110
+
111
+ /** Usage for the selected window, excluding provider usage recorded before its marker. */
112
+ export function windowUsage(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model">) {
113
+ const reset = currentReset(ctx);
114
+ if (!reset) return ctx.getContextUsage();
115
+ const contextWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
116
+ if (!contextWindow) return undefined;
117
+ const windowId = reset.data.windowId;
118
+ try {
119
+ const canonicalMessages = ctx.sessionManager.buildSessionProjection().messages;
120
+ // New resets already cut the durable Pi projection. Marker slicing is retained only
121
+ // for sessions written before native reset checkpoints existed.
122
+ const messages: AgentMessage[] = isCheckpointBackedReset(ctx, reset)
123
+ ? canonicalMessages
124
+ : projectWindow(canonicalMessages, windowId);
125
+ const { tokens } = estimateContextTokens(convertToLlm(messages));
126
+ return { tokens, contextWindow, percent: tokens / contextWindow * 100 };
127
+ } catch {
128
+ // A marker can be durable before its boot when a process stops between the two
129
+ // public writes. Startup/tree repair will append the missing boot; until then the
130
+ // budget hook must not turn a recoverable partial append into a swallowed error.
131
+ return undefined;
132
+ }
133
+ }
@@ -0,0 +1,22 @@
1
+ export const NOTESOUP_SETTINGS_KEY = "notesoup";
2
+ /** Nested under "notesoup": the default dreamer model pattern, overridden by CLI --dreamer. */
3
+ export const NOTESOUP_DREAMER_KEY = "dreamer";
4
+
5
+ export type NotesoupSettings = { reminderMarginTokens?: unknown; dreamer?: unknown };
6
+
7
+ function isSettingsObject(value: unknown): value is Record<string, unknown> {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9
+ }
10
+
11
+ /** Read the raw "notesoup" object from one parsed settings scope. */
12
+ function notesoupSettings(settings: unknown): Record<string, unknown> {
13
+ if (!isSettingsObject(settings)) return {};
14
+ const value = settings[NOTESOUP_SETTINGS_KEY];
15
+ return isSettingsObject(value) ? value : {};
16
+ }
17
+
18
+ /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
19
+ export function mergeNotesoupSettings(globalSettings: unknown, projectSettings: unknown): NotesoupSettings {
20
+ const merged = { ...notesoupSettings(globalSettings), ...notesoupSettings(projectSettings) };
21
+ return { reminderMarginTokens: merged.reminderMarginTokens, dreamer: merged.dreamer };
22
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Code-point offset of the earliest case-insensitive literal match, or -1 when
3
+ * none occurs. Match against the original text so Unicode casing cannot shift offsets.
4
+ */
5
+ export function earliestMatchOffsetChars(text: string, queries: string[]): number {
6
+ let earliest = -1;
7
+ for (const query of queries) {
8
+ const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9
+ const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
10
+ if (index < 0) continue;
11
+ if (earliest < 0 || index < earliest) earliest = index;
12
+ }
13
+ return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
14
+ }
@@ -0,0 +1,273 @@
1
+ /** Host-neutral history operations: one bounded payload for text and structured results. */
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>;
21
+
22
+ /** One read: identity, tool summary and a flat document slice. */
23
+ const HistoryReadDataSchema = Type.Object({
24
+ seq: Type.Integer({ minimum: 1 }),
25
+ window_id: Type.String(),
26
+ role: HistoryRoleSchema,
27
+ created_at: Type.Union([Type.String(), Type.Null()]),
28
+ ...ToolSummarySchema.properties,
29
+ ...TextWindowSchema.properties,
30
+ }, { additionalProperties: false });
31
+ type HistoryReadData = Static<typeof HistoryReadDataSchema>;
32
+
33
+ /* ------------------------------------------------------------------ rendering */
34
+
35
+ function header(item: { seq: number; window_id: string; role: string }): string {
36
+ return `seq ${item.seq} | window ${item.window_id} | ${item.role}`;
37
+ }
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 {
40
+ if (item.role !== "tool") return undefined;
41
+ const parts = [item.tool_name_omitted ? "tool name omitted" : `tool ${item.tool}`, `status ${item.tool_status}`];
42
+ if (item.output_truncated) parts.push(`output truncated${item.full_output_path ? `, full text at ${item.full_output_path}` : ""}`);
43
+ if (item.nested_calls) {
44
+ parts.push(`nested calls ${item.nested_calls.call_count} recorded, ${item.nested_calls.complete ? "complete" : "incomplete"}`);
45
+ }
46
+ return parts.join(" | ");
47
+ }
48
+
49
+ function renderPageItem(item: HistoryPageItem): string {
50
+ const tool = toolHeader(item);
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]`);
53
+ lines.push(item.content);
54
+ return lines.join("\n");
55
+ }
56
+
57
+ function isFoldedRow(item: HistoryPageItem | HistoryFoldedRow): item is HistoryFoldedRow {
58
+ return "folded" in item;
59
+ }
60
+
61
+ function renderFoldedRow(row: HistoryFoldedRow): string {
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}`;
66
+ }
67
+
68
+ function renderPage(page: HistoryPage): string {
69
+ // An empty selection has no anchors either, so it would otherwise render as nothing at all.
70
+ if (page.items.length === 0) return "no events match this selection";
71
+ const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
72
+ const cursors = [
73
+ page.older_before === null ? "" : `→ older: {"before":${page.older_before}}`,
74
+ page.newer_after === null ? "" : `→ newer: {"after":${page.newer_after}}`,
75
+ ].filter((line) => line !== "");
76
+ return cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`;
77
+ }
78
+
79
+ function renderRead(data: HistoryReadData): string {
80
+ const tool = toolHeader(data);
81
+ const neighborhood = `neighborhood → history_list({"after":${Math.max(0, data.seq - 10)},"before":${data.seq + 10}})`;
82
+ return [header(data), ...(tool ? [tool] : []), neighborhood, "", renderTextWindow(data)].join("\n");
83
+ }
84
+
85
+ /* ------------------------------------------------------------------ shared bounding */
86
+
87
+ /** Include rendering and cursors in the budget, not just row contents. */
88
+ function pageFits(page: HistoryPage): boolean {
89
+ return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
90
+ }
91
+
92
+ // Sample known ids on errors without turning the refusal into a second listing.
93
+ const MAX_REPORTED_WINDOWS = 25;
94
+
95
+ export const PREVIOUS_WINDOW = "@previous";
96
+
97
+ /** Resolve "@previous" against oldest-first windows; every other value passes through. */
98
+ function resolveWindowId(projection: HistoryProjection, windowId: string | undefined): { ok: true; window_id: string | undefined } | { ok: false; outcome: Outcome<never> } {
99
+ if (windowId !== PREVIOUS_WINDOW) return { ok: true, window_id: windowId };
100
+ const previous = projection.windows.at(-2);
101
+ if (previous !== undefined) return { ok: true, window_id: previous.windowId };
102
+ 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) }) };
104
+ }
105
+
106
+ function badWindowId(projection: HistoryProjection, params: HistoryFilter): Outcome<never> | undefined {
107
+ const badWindow = unknownWindowId(projection, params);
108
+ 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
+ });
115
+ }
116
+
117
+ /* ------------------------------------------------------------------ history_windows */
118
+
119
+ export const historyWindowsParameters = Type.Object({}, { additionalProperties: false });
120
+
121
+ export const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string]> = {
122
+ name: "history_windows",
123
+ label: "History list windows",
124
+ description: "List session-history windows oldest first, with seq ranges. A fork has its own session_id.",
125
+ parameters: historyWindowsParameters,
126
+ outputSchema: resultSchema(HistoryWindowsDataSchema),
127
+ async execute(_params, projection, sessionId) {
128
+ const data: HistoryWindowsData = { session_id: sessionId, windows: [], more: projection.windows.length };
129
+ const fits = (candidate: HistoryWindowsData) => fitsResult(success(candidate), (result) => renderOutcome(result, renderWindows));
130
+ for (const window of projection.windows) {
131
+ let first: number | null = null;
132
+ let last: number | null = null;
133
+ for (const event of window.items) {
134
+ first = first === null ? event.seq : Math.min(first, event.seq);
135
+ last = last === null ? event.seq : Math.max(last, event.seq);
136
+ }
137
+ const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last, item_count: window.items.length };
138
+ if (!fits({ ...data, windows: [...data.windows, row], more: data.more - 1 })) break;
139
+ data.windows.push(row);
140
+ data.more--;
141
+ }
142
+ return fits(data) ? success(data) : failure("output_too_large", "The session identity does not fit one history_windows response.");
143
+ },
144
+ render: (result) => renderOutcome(result, renderWindows),
145
+ };
146
+
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`);
150
+ return lines.join("\n");
151
+ }
152
+
153
+ /* ------------------------------------------------------------------ history_list */
154
+
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." })),
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.` })),
162
+ }, { additionalProperties: false });
163
+
164
+ export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]> = {
165
+ name: "history_list",
166
+ 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.",
168
+ parameters: historyListParameters,
169
+ outputSchema: resultSchema(HistoryPageSchema),
170
+ async execute(params, projection) {
171
+ const resolved = resolveWindowId(projection, params.window_id);
172
+ if (!resolved.ok) return resolved.outcome;
173
+ const scoped = { ...params, window_id: resolved.window_id };
174
+ const badWindow = badWindowId(projection, scoped);
175
+ 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);
178
+ },
179
+ render: (result) => renderOutcome(result, renderPage),
180
+ };
181
+
182
+ /* ------------------------------------------------------------------ history_read */
183
+
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 });
189
+
190
+ export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection]> = {
191
+ name: "history_read",
192
+ 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.",
194
+ parameters: historyReadParameters,
195
+ outputSchema: resultSchema(HistoryReadDataSchema),
196
+ async execute(params, projection) {
197
+ const item = allItems(projection).find((event) => event.seq === params.seq);
198
+ // Address checks run in one order: past the end of the file, off this branch, then
199
+ // consumed by a pairing. Only the last two can mention what is at the address.
200
+ 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 });
202
+ }
203
+ 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 });
205
+ }
206
+ if (item === undefined) {
207
+ const callSeq = projection.pairedResults.get(params.seq);
208
+ 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 });
210
+ }
211
+ return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event`, { seq: params.seq });
212
+ }
213
+ const document = eventDocument(item);
214
+ const totalChars = Array.from(document).length;
215
+ 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 });
217
+ }
218
+ return readTextWindow(
219
+ document,
220
+ params.offset_chars,
221
+ params.limit_chars,
222
+ (window) => ({
223
+ seq: item.seq,
224
+ window_id: item.windowId,
225
+ role: item.role,
226
+ created_at: item.createdAt ?? null,
227
+ ...toolSummary(item),
228
+ ...window,
229
+ }),
230
+ (result) => renderOutcome(result, renderRead),
231
+ );
232
+ },
233
+ render: (result) => renderOutcome(result, renderRead),
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
+ };