notesoup 0.0.0-stage → 0.40.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 +94 -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 +17 -0
  8. package/dist/src/boot/text.js +48 -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 +156 -0
  36. package/dist/src/history/history.js +212 -0
  37. package/dist/src/history/query.d.ts +63 -0
  38. package/dist/src/history/query.js +201 -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 +103 -0
  58. package/dist/src/notes/store.js +474 -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 +9 -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 +7 -0
  98. package/dist/src/pi/tool-names.js +7 -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 +58 -0
  108. package/dist/src/tools/history.js +210 -0
  109. package/dist/src/tools/notes.d.ts +250 -0
  110. package/dist/src/tools/notes.js +360 -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 +82 -0
  114. package/dist/src/tools/result.js +104 -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 +367 -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 +633 -0
  143. package/dist/test/host-neutral.test.d.ts +1 -0
  144. package/dist/test/host-neutral.test.js +274 -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 +515 -0
  149. package/dist/test/notes.test.d.ts +1 -0
  150. package/dist/test/notes.test.js +530 -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 +78 -0
  160. package/mods/notesoup/.claude-plugin/plugin.json +8 -0
  161. package/mods/notesoup/dist/claude/helper.js +9265 -0
  162. package/mods/notesoup/hooks/hooks.json +4 -0
  163. package/mods/notesoup/hooks/register.ts +240 -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 +58 -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 +286 -0
  188. package/src/history/query.ts +222 -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 +494 -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 +11 -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 +9 -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 +234 -0
  224. package/src/tools/notes.ts +381 -0
  225. package/src/tools/output.ts +41 -0
  226. package/src/tools/result.ts +144 -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,234 @@
1
+ /** Host-neutral history operations: one bounded payload for text and structured results. */
2
+ import { Type, type Static } from "typebox";
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";
8
+
9
+ /** One read: identity, tool summary and a flat document slice. */
10
+ const HistoryReadDataSchema = Type.Object({
11
+ seq: Type.Integer({ minimum: 1 }),
12
+ window_id: Type.String(),
13
+ role: HistoryRoleSchema,
14
+ created_at: Type.Union([Type.String(), Type.Null()]),
15
+ ...ToolSummarySchema.properties,
16
+ nested_calls: Type.Optional(NestedCallSummarySchema),
17
+ ...TextWindowSchema.properties,
18
+ }, { additionalProperties: false });
19
+ type HistoryReadData = Static<typeof HistoryReadDataSchema>;
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
+ /* ------------------------------------------------------------------ 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_status?: string; output_truncated?: true; full_output_path?: string; nested_calls?: { call_count: number; complete: boolean } }): string | undefined {
40
+ if (item.role !== "tool") return undefined;
41
+ const parts = [`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(`[truncated; from offset ${item.offset_chars ?? 0}]`);
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 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}`;
65
+ }
66
+
67
+ function renderPage(page: HistoryPage): string {
68
+ // An empty selection has no anchors either, so it would otherwise render as nothing at all.
69
+ if (page.items.length === 0) return "no events match this selection";
70
+ const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
71
+ const cursors = [
72
+ page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
73
+ page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
74
+ ].filter((line) => line !== "");
75
+ return cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`;
76
+ }
77
+
78
+ function renderRead(data: HistoryReadData): string {
79
+ const tool = toolHeader(data);
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
+ 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 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
+ }
99
+
100
+ export const PREVIOUS_WINDOW = "@previous";
101
+
102
+ /** Resolve "@previous" against oldest-first windows; every other value passes through. */
103
+ function resolveWindowId(projection: HistoryProjection, windowId: string | undefined): { ok: true; window_id: string | undefined } | { ok: false; outcome: Outcome<never> } {
104
+ if (windowId !== PREVIOUS_WINDOW) return { ok: true, window_id: windowId };
105
+ const previous = projection.windows.at(-2);
106
+ if (previous !== undefined) return { ok: true, window_id: previous.windowId };
107
+ const known = projection.windows.map((current) => current.windowId);
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)}`) };
109
+ }
110
+
111
+ function badWindowId(projection: HistoryProjection, params: HistoryFilter): Outcome<never> | undefined {
112
+ const badWindow = unknownWindowId(projection, params);
113
+ if (!badWindow) return undefined;
114
+ return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}`);
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 this session's context windows, oldest first, with seq ranges.",
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 };
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 ?? "-"}`)];
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
+ 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
+ roles: historyRoles(),
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.` })),
166
+ }, { additionalProperties: false });
167
+
168
+ export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]> = {
169
+ name: "history_list",
170
+ label: "History list items",
171
+ description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
172
+ parameters: historyListParameters,
173
+ outputSchema: resultSchema(HistoryPageSchema),
174
+ async execute(params, projection) {
175
+ const resolved = resolveWindowId(projection, params.window_id);
176
+ if (!resolved.ok) return resolved.outcome;
177
+ const scoped = { ...params, window_id: resolved.window_id };
178
+ const badWindow = badWindowId(projection, scoped);
179
+ if (badWindow) return badWindow;
180
+ return selectPage(projection, scoped, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
181
+ },
182
+ render: (result) => renderOutcome(result, renderPage),
183
+ };
184
+
185
+ /* ------------------------------------------------------------------ history_read */
186
+
187
+ export const historyReadParameters = Type.Object({ seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`." }), ...TextWindowRequestSchema }, { additionalProperties: false });
188
+
189
+ export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection]> = {
190
+ name: "history_read",
191
+ label: "History read item",
192
+ description: "Read one event in full: tool arguments, output, and nested calls.",
193
+ parameters: historyReadParameters,
194
+ outputSchema: resultSchema(HistoryReadDataSchema),
195
+ async execute(params, projection) {
196
+ const item = allItems(projection).find((event) => event.seq === params.seq);
197
+ // Address checks run in one order: past the end of the file, off this branch, then
198
+ // consumed by a pairing. Only the last two can mention what is at the address.
199
+ if (item === undefined && params.seq > projection.highestSeq) {
200
+ return failure("unknown_seq", `unknown seq ${params.seq}: this session's items run 1..${projection.highestSeq}`);
201
+ }
202
+ if (!projection.branchSeqs.has(params.seq)) {
203
+ return failure("not_on_branch", `seq ${params.seq} is on another branch and is not readable here`);
204
+ }
205
+ if (item === undefined) {
206
+ const callSeq = projection.pairedResults.get(params.seq);
207
+ if (callSeq !== undefined) {
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`);
209
+ }
210
+ return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event`);
211
+ }
212
+ const document = eventDocument(item);
213
+ const totalChars = Array.from(document).length;
214
+ if (typeof params.offset_chars === "number" && params.offset_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)`);
216
+ }
217
+ return readTextWindow(
218
+ document,
219
+ params.offset_chars,
220
+ params.max_chars,
221
+ (window) => ({
222
+ seq: item.seq,
223
+ window_id: item.windowId,
224
+ role: item.role,
225
+ created_at: item.createdAt ?? null,
226
+ ...toolSummary(item),
227
+ ...nestedCallSummary(item),
228
+ ...window,
229
+ }),
230
+ (result) => renderOutcome(result, renderRead),
231
+ );
232
+ },
233
+ render: (result) => renderOutcome(result, renderRead),
234
+ };