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,41 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import { type CustomEntry, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { SessionReader } from "./session-reader.js";
4
+ export type WindowMarker = CustomEntry<{
5
+ windowId: string;
6
+ }> & {
7
+ data: {
8
+ windowId: string;
9
+ };
10
+ };
11
+ export declare function isWindowMarker(entry: SessionEntry): entry is WindowMarker;
12
+ /** Only the active branch can supply a window boundary. */
13
+ export declare function currentReset(ctx: SessionReader): WindowMarker | undefined;
14
+ /** A reset is checkpoint-backed only when its marker directly follows a native compaction. */
15
+ export declare function isCheckpointBackedReset(ctx: SessionReader, marker?: WindowMarker | undefined): boolean;
16
+ /** Mint the durable identity of a session's root history window. */
17
+ export declare function rootWindowId(sessionId: string): string;
18
+ /** Persisted messages in the active window, excluding earlier windows on this branch. */
19
+ export declare function hasWindowMessage(ctx: SessionReader, customType: string): boolean;
20
+ /** The root or latest durable marker on the active branch. */
21
+ export declare function currentWindowId(ctx: SessionReader): string;
22
+ /** The durable window active just before the marker: the last earlier marker, else the root window. */
23
+ export declare function previousWindowId(ctx: SessionReader, markerId: string): string;
24
+ /** Match a provider-facing boot message, optionally by window identity. */
25
+ export declare function isWindowBoot(message: AgentMessage, windowId?: string): boolean;
26
+ /** Match a persisted boot entry by raw identity, even when a later edit hides it from projection. */
27
+ export declare function isWindowBootEntry(entry: SessionEntry, windowId: string): boolean;
28
+ /**
29
+ * The durable marker selects a boot message by identity, never by wall-clock time.
30
+ * The boot is the first conversation message of the window. Folding only its prefix
31
+ * preserves later prompt/tool patches in place, including their cacheable ordering.
32
+ */
33
+ export declare function projectWindow(messages: AgentMessage[], windowId: string): AgentMessage[];
34
+ /**
35
+ * Root windows are not reset boundaries. A forked session can copy a root boot whose
36
+ * details name the source session; refresh that boot in-place in the provider projection
37
+ * while retaining every user/assistant/tool message from the copied root transcript.
38
+ */
39
+ export declare function projectRootWindow(messages: AgentMessage[], windowId: string): AgentMessage[];
40
+ /** Usage for the selected window, excluding provider usage recorded before its marker. */
41
+ export declare function windowUsage(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model">): import("@earendil-works/pi-coding-agent").ContextUsage | undefined;
@@ -0,0 +1,127 @@
1
+ import { getCurrentSystemMessage } from "@earendil-works/pi-ai";
2
+ import { estimateContextTokens } from "./estimate.js";
3
+ import { convertToLlm } from "@earendil-works/pi-coding-agent";
4
+ import { BOOT_TYPE, RESET_MARKER_TYPE } from "./entries.js";
5
+ export function isWindowMarker(entry) {
6
+ return entry.type === "custom" && entry.customType === RESET_MARKER_TYPE &&
7
+ typeof entry.data === "object" && entry.data !== null &&
8
+ typeof entry.data.windowId === "string" &&
9
+ entry.data.windowId.length > 0;
10
+ }
11
+ /** Only the active branch can supply a window boundary. */
12
+ export function currentReset(ctx) {
13
+ const branch = ctx.sessionManager.getBranch();
14
+ for (let i = branch.length - 1; i >= 0; i--) {
15
+ const entry = branch[i];
16
+ if (entry && isWindowMarker(entry))
17
+ return entry;
18
+ }
19
+ return undefined;
20
+ }
21
+ /** A reset is checkpoint-backed only when its marker directly follows a native compaction. */
22
+ export function isCheckpointBackedReset(ctx, marker = currentReset(ctx)) {
23
+ if (!marker?.parentId)
24
+ return false;
25
+ const branch = ctx.sessionManager.getBranch();
26
+ const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
27
+ const checkpoint = branch[markerIndex - 1];
28
+ return markerIndex > 0 && checkpoint?.id === marker.parentId && checkpoint.type === "compaction" &&
29
+ checkpoint.summary === "" && checkpoint.firstKeptEntryId === checkpoint.id;
30
+ }
31
+ /** Mint the durable identity of a session's root history window. */
32
+ export function rootWindowId(sessionId) {
33
+ return `pcw:${sessionId.slice(0, 8)}:root`;
34
+ }
35
+ /** Persisted messages in the active window, excluding earlier windows on this branch. */
36
+ export function hasWindowMessage(ctx, customType) {
37
+ const branch = ctx.sessionManager.getBranch();
38
+ for (let i = branch.length - 1; i >= 0; i--) {
39
+ const entry = branch[i];
40
+ if (isWindowMarker(entry))
41
+ break;
42
+ if (entry.type === "custom_message" && entry.customType === customType)
43
+ return true;
44
+ }
45
+ return false;
46
+ }
47
+ /** The root or latest durable marker on the active branch. */
48
+ export function currentWindowId(ctx) {
49
+ return currentReset(ctx)?.data.windowId ?? rootWindowId(ctx.sessionManager.getSessionId());
50
+ }
51
+ /** The durable window active just before the marker: the last earlier marker, else the root window. */
52
+ export function previousWindowId(ctx, markerId) {
53
+ let previousId = rootWindowId(ctx.sessionManager.getSessionId());
54
+ for (const entry of ctx.sessionManager.getBranch()) {
55
+ if (entry.id === markerId)
56
+ break;
57
+ if (isWindowMarker(entry))
58
+ previousId = entry.data.windowId;
59
+ }
60
+ return previousId;
61
+ }
62
+ function hasWindowId(details, windowId) {
63
+ return typeof details === "object" && details !== null &&
64
+ typeof details.windowId === "string" &&
65
+ details.windowId === windowId;
66
+ }
67
+ /** Match a provider-facing boot message, optionally by window identity. */
68
+ export function isWindowBoot(message, windowId) {
69
+ return message.role === "custom" && message.customType === BOOT_TYPE && (windowId === undefined || hasWindowId(message.details, windowId));
70
+ }
71
+ /** Match a persisted boot entry by raw identity, even when a later edit hides it from projection. */
72
+ export function isWindowBootEntry(entry, windowId) {
73
+ return entry.type === "custom_message" && entry.customType === BOOT_TYPE && hasWindowId(entry.details, windowId);
74
+ }
75
+ /**
76
+ * The durable marker selects a boot message by identity, never by wall-clock time.
77
+ * The boot is the first conversation message of the window. Folding only its prefix
78
+ * preserves later prompt/tool patches in place, including their cacheable ordering.
79
+ */
80
+ export function projectWindow(messages, windowId) {
81
+ const cut = messages.findIndex((message) => isWindowBoot(message, windowId));
82
+ if (cut < 0)
83
+ throw new Error(`Missing boot for context window ${windowId}`);
84
+ const head = getCurrentSystemMessage(messages.slice(0, cut));
85
+ const suffix = messages.slice(cut);
86
+ return head ? [head, ...suffix] : suffix;
87
+ }
88
+ /**
89
+ * Root windows are not reset boundaries. A forked session can copy a root boot whose
90
+ * details name the source session; refresh that boot in-place in the provider projection
91
+ * while retaining every user/assistant/tool message from the copied root transcript.
92
+ */
93
+ export function projectRootWindow(messages, windowId) {
94
+ const matching = messages.filter((message) => isWindowBoot(message, windowId));
95
+ if (matching.length === 0)
96
+ return messages;
97
+ const activeBoot = matching[matching.length - 1];
98
+ const firstBoot = messages.findIndex((message) => isWindowBoot(message));
99
+ const withoutBoots = messages.filter((message) => !isWindowBoot(message));
100
+ return [...withoutBoots.slice(0, firstBoot), activeBoot, ...withoutBoots.slice(firstBoot)];
101
+ }
102
+ /** Usage for the selected window, excluding provider usage recorded before its marker. */
103
+ export function windowUsage(ctx) {
104
+ const reset = currentReset(ctx);
105
+ if (!reset)
106
+ return ctx.getContextUsage();
107
+ const contextWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
108
+ if (!contextWindow)
109
+ return undefined;
110
+ const windowId = reset.data.windowId;
111
+ try {
112
+ const canonicalMessages = ctx.sessionManager.buildSessionProjection().messages;
113
+ // New resets already cut the durable Pi projection. Marker slicing is retained only
114
+ // for sessions written before native reset checkpoints existed.
115
+ const messages = isCheckpointBackedReset(ctx, reset)
116
+ ? canonicalMessages
117
+ : projectWindow(canonicalMessages, windowId);
118
+ const { tokens } = estimateContextTokens(convertToLlm(messages));
119
+ return { tokens, contextWindow, percent: tokens / contextWindow * 100 };
120
+ }
121
+ catch {
122
+ // A marker can be durable before its boot when a process stops between the two
123
+ // public writes. Startup/tree repair will append the missing boot; until then the
124
+ // budget hook must not turn a recoverable partial append into a swallowed error.
125
+ return undefined;
126
+ }
127
+ }
@@ -0,0 +1,9 @@
1
+ export declare const NOTESOUP_SETTINGS_KEY = "notesoup";
2
+ /** Nested under "notesoup": the default dreamer model pattern, overridden by CLI --dreamer. */
3
+ export declare const NOTESOUP_DREAMER_KEY = "dreamer";
4
+ export type NotesoupSettings = {
5
+ reminderMarginTokens?: unknown;
6
+ dreamer?: unknown;
7
+ };
8
+ /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
9
+ export declare function mergeNotesoupSettings(globalSettings: unknown, projectSettings: unknown): NotesoupSettings;
@@ -0,0 +1,18 @@
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
+ function isSettingsObject(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ /** Read the raw "notesoup" object from one parsed settings scope. */
8
+ function notesoupSettings(settings) {
9
+ if (!isSettingsObject(settings))
10
+ return {};
11
+ const value = settings[NOTESOUP_SETTINGS_KEY];
12
+ return isSettingsObject(value) ? value : {};
13
+ }
14
+ /** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
15
+ export function mergeNotesoupSettings(globalSettings, projectSettings) {
16
+ const merged = { ...notesoupSettings(globalSettings), ...notesoupSettings(projectSettings) };
17
+ return { reminderMarginTokens: merged.reminderMarginTokens, dreamer: merged.dreamer };
18
+ }
@@ -0,0 +1,5 @@
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 declare function earliestMatchOffsetChars(text: string, queries: string[]): number;
@@ -0,0 +1,16 @@
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, queries) {
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)
11
+ continue;
12
+ if (earliest < 0 || index < earliest)
13
+ earliest = index;
14
+ }
15
+ return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
16
+ }
@@ -0,0 +1,67 @@
1
+ /** Host-neutral history operations: one bounded payload for text and structured results. */
2
+ import { Type, type Static } from "typebox";
3
+ import { type Operation } from "./result.js";
4
+ import { type HistoryPage } from "../history/query.js";
5
+ import { type HistoryProjection } from "../history/history.js";
6
+ declare const HistoryWindowsDataSchema: Type.TObject<{
7
+ session_id: Type.TString;
8
+ windows: Type.TArray<Type.TObject<{
9
+ window_id: Type.TString;
10
+ created_at: Type.TUnion<[Type.TString, Type.TNull]>;
11
+ first_seq: Type.TUnion<[Type.TInteger, Type.TNull]>;
12
+ last_seq: Type.TUnion<[Type.TInteger, Type.TNull]>;
13
+ item_count: Type.TInteger;
14
+ }>>;
15
+ more: Type.TInteger;
16
+ }>;
17
+ type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
18
+ /** One read: identity, tool summary and a flat document slice. */
19
+ declare const HistoryReadDataSchema: Type.TObject<{
20
+ text: Type.TString;
21
+ offset_chars: Type.TInteger;
22
+ total_chars: Type.TInteger;
23
+ next_offset_chars: Type.TUnion<[Type.TInteger, Type.TNull]>;
24
+ limited_by: Type.TUnion<[Type.TLiteral<"limit">, Type.TLiteral<"bytes">, Type.TNull]>;
25
+ tool: Type.TOptional<Type.TString>;
26
+ tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
27
+ output_truncated: Type.TOptional<Type.TBoolean>;
28
+ full_output_path: Type.TOptional<Type.TString>;
29
+ nested_calls: Type.TOptional<Type.TObject<{
30
+ call_count: Type.TInteger;
31
+ complete: Type.TBoolean;
32
+ }>>;
33
+ seq: Type.TInteger;
34
+ window_id: Type.TString;
35
+ role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
36
+ created_at: Type.TUnion<[Type.TString, Type.TNull]>;
37
+ }>;
38
+ type HistoryReadData = Static<typeof HistoryReadDataSchema>;
39
+ export declare const PREVIOUS_WINDOW = "@previous";
40
+ export declare const historyWindowsParameters: Type.TObject<{}>;
41
+ export declare const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string]>;
42
+ export declare const historyListParameters: Type.TObject<{
43
+ limit: Type.TOptional<Type.TInteger>;
44
+ roles: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
45
+ before: Type.TOptional<Type.TInteger>;
46
+ after: Type.TOptional<Type.TInteger>;
47
+ window_id: Type.TOptional<Type.TString>;
48
+ max_chars_per_item: Type.TOptional<Type.TInteger>;
49
+ }>;
50
+ export declare const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]>;
51
+ export declare const historyReadParameters: Type.TObject<{
52
+ seq: Type.TInteger;
53
+ offset_chars: Type.TOptional<Type.TInteger>;
54
+ limit_chars: Type.TOptional<Type.TInteger>;
55
+ }>;
56
+ export declare const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection]>;
57
+ export declare const historySearchParameters: Type.TObject<{
58
+ query: Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>;
59
+ limit: Type.TOptional<Type.TInteger>;
60
+ roles: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
61
+ before: Type.TOptional<Type.TInteger>;
62
+ after: Type.TOptional<Type.TInteger>;
63
+ window_id: Type.TOptional<Type.TString>;
64
+ max_chars_per_item: Type.TOptional<Type.TInteger>;
65
+ }>;
66
+ export declare const historySearch: Operation<typeof historySearchParameters, HistoryPage, [HistoryProjection]>;
67
+ export {};
@@ -0,0 +1,251 @@
1
+ /** Host-neutral history operations: one bounded payload for text and structured results. */
2
+ import { Type } 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 } from "./result.js";
5
+ import { historyRoles, InvalidQueryError, searchQueries, searchQuery } from "./schema.js";
6
+ import { HistoryPageSchema, HistorySearchPageSchema, isConversationView, selectPage } from "../history/query.js";
7
+ import { allItems, eventDocument, toolSummary, filteredItems, HistoryRoleSchema, ToolSummarySchema, unknownWindowId } from "../history/history.js";
8
+ const HistoryWindowsDataSchema = Type.Object({
9
+ session_id: Type.String(),
10
+ windows: Type.Array(Type.Object({
11
+ window_id: Type.String(),
12
+ created_at: Type.Union([Type.String(), Type.Null()]),
13
+ first_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
14
+ last_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
15
+ item_count: Type.Integer({ minimum: 0 }),
16
+ }, { additionalProperties: false }), { description: "Oldest first." }),
17
+ more: Type.Integer({ minimum: 0, description: "Omitted windows; history_list also supplies window ids." }),
18
+ }, { additionalProperties: false });
19
+ /** One read: identity, tool summary and a flat document slice. */
20
+ const HistoryReadDataSchema = Type.Object({
21
+ seq: Type.Integer({ minimum: 1 }),
22
+ window_id: Type.String(),
23
+ role: HistoryRoleSchema,
24
+ created_at: Type.Union([Type.String(), Type.Null()]),
25
+ ...ToolSummarySchema.properties,
26
+ ...TextWindowSchema.properties,
27
+ }, { additionalProperties: false });
28
+ /* ------------------------------------------------------------------ rendering */
29
+ function header(item) {
30
+ return `seq ${item.seq} | window ${item.window_id} | ${item.role}`;
31
+ }
32
+ function toolHeader(item) {
33
+ if (item.role !== "tool")
34
+ return undefined;
35
+ const parts = [item.tool_name_omitted ? "tool name omitted" : `tool ${item.tool}`, `status ${item.tool_status}`];
36
+ if (item.output_truncated)
37
+ parts.push(`output truncated${item.full_output_path ? `, full text at ${item.full_output_path}` : ""}`);
38
+ if (item.nested_calls) {
39
+ parts.push(`nested calls ${item.nested_calls.call_count} recorded, ${item.nested_calls.complete ? "complete" : "incomplete"}`);
40
+ }
41
+ return parts.join(" | ");
42
+ }
43
+ function renderPageItem(item) {
44
+ const tool = toolHeader(item);
45
+ const lines = tool === undefined ? [header(item)] : [header(item), tool];
46
+ if (item.truncated)
47
+ lines.push(`[preview of ${item.total_chars} chars from offset ${item.offset_chars ?? 0}; read this seq for the rest]`);
48
+ lines.push(item.content);
49
+ return lines.join("\n");
50
+ }
51
+ function isFoldedRow(item) {
52
+ return "folded" in item;
53
+ }
54
+ function renderFoldedRow(row) {
55
+ const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
56
+ const omitted = row.omitted_tools ? ` | ${row.omitted_tools} distinct tool names omitted` : "";
57
+ const expand = `\n\t→ expand: {"after":${row.first_seq - 1},"before":${row.last_seq + 1},"roles":["tool","context"]}`;
58
+ return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${omitted}${expand}`;
59
+ }
60
+ function renderPage(page) {
61
+ // An empty selection has no anchors either, so it would otherwise render as nothing at all.
62
+ if (page.items.length === 0)
63
+ return "no events match this selection";
64
+ const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
65
+ const cursors = [
66
+ page.older_before === null ? "" : `→ older: {"before":${page.older_before}}`,
67
+ page.newer_after === null ? "" : `→ newer: {"after":${page.newer_after}}`,
68
+ ].filter((line) => line !== "");
69
+ return cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`;
70
+ }
71
+ function renderRead(data) {
72
+ const tool = toolHeader(data);
73
+ const neighborhood = `neighborhood → history_list({"after":${Math.max(0, data.seq - 10)},"before":${data.seq + 10}})`;
74
+ return [header(data), ...(tool ? [tool] : []), neighborhood, "", renderTextWindow(data)].join("\n");
75
+ }
76
+ /* ------------------------------------------------------------------ shared bounding */
77
+ /** Include rendering and cursors in the budget, not just row contents. */
78
+ function pageFits(page) {
79
+ return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
80
+ }
81
+ // Sample known ids on errors without turning the refusal into a second listing.
82
+ const MAX_REPORTED_WINDOWS = 25;
83
+ export const PREVIOUS_WINDOW = "@previous";
84
+ /** Resolve "@previous" against oldest-first windows; every other value passes through. */
85
+ function resolveWindowId(projection, windowId) {
86
+ if (windowId !== PREVIOUS_WINDOW)
87
+ return { ok: true, window_id: windowId };
88
+ const previous = projection.windows.at(-2);
89
+ if (previous !== undefined)
90
+ return { ok: true, window_id: previous.windowId };
91
+ const known = projection.windows.map((current) => current.windowId);
92
+ 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) }) };
93
+ }
94
+ function badWindowId(projection, params) {
95
+ const badWindow = unknownWindowId(projection, params);
96
+ if (!badWindow)
97
+ return undefined;
98
+ const known = badWindow.known;
99
+ return failure("unknown_window_id", badWindow.message, {
100
+ window_id: params.window_id,
101
+ known_windows: known.slice(0, MAX_REPORTED_WINDOWS),
102
+ ...(known.length > MAX_REPORTED_WINDOWS ? { known_windows_omitted: known.length - MAX_REPORTED_WINDOWS } : {}),
103
+ });
104
+ }
105
+ /* ------------------------------------------------------------------ history_windows */
106
+ export const historyWindowsParameters = Type.Object({}, { additionalProperties: false });
107
+ export const historyWindows = {
108
+ name: "history_windows",
109
+ label: "History list windows",
110
+ description: "List session-history windows oldest first, with seq ranges. A fork has its own session_id.",
111
+ parameters: historyWindowsParameters,
112
+ outputSchema: resultSchema(HistoryWindowsDataSchema),
113
+ async execute(_params, projection, sessionId) {
114
+ const data = { session_id: sessionId, windows: [], more: projection.windows.length };
115
+ const fits = (candidate) => fitsResult(success(candidate), (result) => renderOutcome(result, renderWindows));
116
+ for (const window of projection.windows) {
117
+ let first = null;
118
+ let last = null;
119
+ for (const event of window.items) {
120
+ first = first === null ? event.seq : Math.min(first, event.seq);
121
+ last = last === null ? event.seq : Math.max(last, event.seq);
122
+ }
123
+ const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last, item_count: window.items.length };
124
+ if (!fits({ ...data, windows: [...data.windows, row], more: data.more - 1 }))
125
+ break;
126
+ data.windows.push(row);
127
+ data.more--;
128
+ }
129
+ return fits(data) ? success(data) : failure("output_too_large", "The session identity does not fit one history_windows response.");
130
+ },
131
+ render: (result) => renderOutcome(result, renderWindows),
132
+ };
133
+ function renderWindows(data) {
134
+ 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`)];
135
+ if (data.more > 0)
136
+ lines.push(`${data.more} more windows not shown; history_list also reports window ids on events`);
137
+ return lines.join("\n");
138
+ }
139
+ /* ------------------------------------------------------------------ history_list */
140
+ export const historyListParameters = Type.Object({
141
+ limit: Type.Optional(Type.Integer({ description: "Optional. Maximum visible items per page; folded rows do not count. Default 20." })),
142
+ roles: historyRoles(),
143
+ 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." })),
144
+ 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." })),
145
+ 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.` })),
146
+ 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.` })),
147
+ }, { additionalProperties: false });
148
+ export const historyList = {
149
+ name: "history_list",
150
+ label: "History list items",
151
+ 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.",
152
+ parameters: historyListParameters,
153
+ outputSchema: resultSchema(HistoryPageSchema),
154
+ async execute(params, projection) {
155
+ const resolved = resolveWindowId(projection, params.window_id);
156
+ if (!resolved.ok)
157
+ return resolved.outcome;
158
+ const scoped = { ...params, window_id: resolved.window_id };
159
+ const badWindow = badWindowId(projection, scoped);
160
+ if (badWindow)
161
+ return badWindow;
162
+ const items = filteredItems(projection, scoped, "list");
163
+ return selectPage(projection, scoped, items.map((event) => ({ event })), isConversationView(scoped), pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
164
+ },
165
+ render: (result) => renderOutcome(result, renderPage),
166
+ };
167
+ /* ------------------------------------------------------------------ history_read */
168
+ export const historyReadParameters = Type.Object({
169
+ seq: Type.Integer({ minimum: 1, description: "Event address from history_list/search." }),
170
+ offset_chars: Type.Optional(Type.Integer({ description: "Code-point offset (default 0); negative counts from EOF." })),
171
+ 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.` })),
172
+ }, { additionalProperties: false });
173
+ export const historyRead = {
174
+ name: "history_read",
175
+ label: "History read item",
176
+ 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.",
177
+ parameters: historyReadParameters,
178
+ outputSchema: resultSchema(HistoryReadDataSchema),
179
+ async execute(params, projection) {
180
+ const item = allItems(projection).find((event) => event.seq === params.seq);
181
+ // Address checks run in one order: past the end of the file, off this branch, then
182
+ // consumed by a pairing. Only the last two can mention what is at the address.
183
+ if (item === undefined && params.seq > projection.highestSeq) {
184
+ return failure("unknown_seq", `unknown seq ${params.seq}: this session's items run 1..${projection.highestSeq}`, { seq: params.seq, highest_seq: projection.highestSeq });
185
+ }
186
+ if (!projection.branchSeqs.has(params.seq)) {
187
+ return failure("not_on_branch", `seq ${params.seq} is on another branch and is not readable here`, { seq: params.seq });
188
+ }
189
+ if (item === undefined) {
190
+ const callSeq = projection.pairedResults.get(params.seq);
191
+ if (callSeq !== undefined) {
192
+ 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 });
193
+ }
194
+ return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event`, { seq: params.seq });
195
+ }
196
+ const document = eventDocument(item);
197
+ const totalChars = Array.from(document).length;
198
+ if (typeof params.offset_chars === "number" && params.offset_chars > totalChars) {
199
+ 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 });
200
+ }
201
+ return readTextWindow(document, params.offset_chars, params.limit_chars, (window) => ({
202
+ seq: item.seq,
203
+ window_id: item.windowId,
204
+ role: item.role,
205
+ created_at: item.createdAt ?? null,
206
+ ...toolSummary(item),
207
+ ...window,
208
+ }), (result) => renderOutcome(result, renderRead));
209
+ },
210
+ render: (result) => renderOutcome(result, renderRead),
211
+ };
212
+ /* ------------------------------------------------------------------ history_search */
213
+ export const historySearchParameters = Type.Object({
214
+ query: searchQuery(),
215
+ limit: Type.Optional(Type.Integer({ description: "Optional. Maximum matching items returned." })),
216
+ roles: historyRoles(),
217
+ 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." })),
218
+ 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." })),
219
+ 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.` })),
220
+ 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.` })),
221
+ }, { additionalProperties: false });
222
+ export const historySearch = {
223
+ name: "history_search",
224
+ label: "History search",
225
+ 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.",
226
+ parameters: historySearchParameters,
227
+ outputSchema: resultSchema(HistorySearchPageSchema),
228
+ async execute(params, projection) {
229
+ const resolved = resolveWindowId(projection, params.window_id);
230
+ if (!resolved.ok)
231
+ return resolved.outcome;
232
+ const scoped = { ...params, window_id: resolved.window_id };
233
+ const badWindow = badWindowId(projection, scoped);
234
+ if (badWindow)
235
+ return badWindow;
236
+ let queries;
237
+ try {
238
+ queries = searchQueries(scoped.query);
239
+ }
240
+ catch (error) {
241
+ if (error instanceof InvalidQueryError)
242
+ return failure("invalid_query", error.message);
243
+ throw error;
244
+ }
245
+ const matches = filteredItems(projection, scoped, "search")
246
+ .map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), queries) }))
247
+ .filter((candidate) => candidate.matchOffset >= 0);
248
+ return selectPage(projection, scoped, matches, false, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
249
+ },
250
+ render: (result) => renderOutcome(result, renderPage),
251
+ };