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,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,58 @@
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
+ /** One read: identity, tool summary and a flat document slice. */
7
+ declare const HistoryReadDataSchema: Type.TObject<{
8
+ text: Type.TString;
9
+ total_chars: Type.TInteger;
10
+ next_offset_chars: Type.TUnion<[Type.TInteger, Type.TNull]>;
11
+ nested_calls: Type.TOptional<Type.TObject<{
12
+ call_count: Type.TInteger;
13
+ complete: Type.TBoolean;
14
+ }>>;
15
+ tool: Type.TOptional<Type.TString>;
16
+ tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
17
+ output_truncated: Type.TOptional<Type.TLiteral<true>>;
18
+ full_output_path: Type.TOptional<Type.TString>;
19
+ seq: Type.TInteger;
20
+ window_id: Type.TString;
21
+ role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
22
+ created_at: Type.TUnion<[Type.TString, Type.TNull]>;
23
+ }>;
24
+ type HistoryReadData = Static<typeof HistoryReadDataSchema>;
25
+ declare const HistoryWindowsDataSchema: Type.TObject<{
26
+ session_id: Type.TString;
27
+ windows: Type.TArray<Type.TObject<{
28
+ window_id: Type.TString;
29
+ created_at: Type.TUnion<[Type.TString, Type.TNull]>;
30
+ first_seq: Type.TUnion<[Type.TInteger, Type.TNull]>;
31
+ last_seq: Type.TUnion<[Type.TInteger, Type.TNull]>;
32
+ }>>;
33
+ more: Type.TInteger;
34
+ }>;
35
+ type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
36
+ export declare const PREVIOUS_WINDOW = "@previous";
37
+ export declare const historyWindowsParameters: Type.TObject<{}>;
38
+ export declare const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string]>;
39
+ export declare const historyListParameters: Type.TObject<{
40
+ query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
41
+ roles: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
42
+ before_seq: Type.TOptional<Type.TInteger>;
43
+ after_seq: Type.TOptional<Type.TInteger>;
44
+ since: Type.TOptional<Type.TString>;
45
+ until: Type.TOptional<Type.TString>;
46
+ from: Type.TOptional<Type.TUnion<[Type.TLiteral<"newest">, Type.TLiteral<"oldest">]>>;
47
+ window_id: Type.TOptional<Type.TString>;
48
+ limit: Type.TOptional<Type.TInteger>;
49
+ max_chars_per_item: Type.TOptional<Type.TInteger>;
50
+ }>;
51
+ export declare const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]>;
52
+ export declare const historyReadParameters: Type.TObject<{
53
+ offset_chars: Type.TOptional<Type.TInteger>;
54
+ max_chars: Type.TOptional<Type.TInteger>;
55
+ seq: Type.TInteger;
56
+ }>;
57
+ export declare const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection]>;
58
+ export {};
@@ -0,0 +1,210 @@
1
+ /** Host-neutral history operations: one bounded payload for text and structured results. */
2
+ import { Type } from "typebox";
3
+ import { HISTORY_PREVIEW_CHARS } from "./output.js";
4
+ import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
5
+ import { historyRoles, searchQuery } from "./schema.js";
6
+ import { HistoryPageSchema, selectPage } from "../history/query.js";
7
+ import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, unknownWindowId } from "../history/history.js";
8
+ /** One read: identity, tool summary and a flat document slice. */
9
+ const HistoryReadDataSchema = Type.Object({
10
+ seq: Type.Integer({ minimum: 1 }),
11
+ window_id: Type.String(),
12
+ role: HistoryRoleSchema,
13
+ created_at: Type.Union([Type.String(), Type.Null()]),
14
+ ...ToolSummarySchema.properties,
15
+ nested_calls: Type.Optional(NestedCallSummarySchema),
16
+ ...TextWindowSchema.properties,
17
+ }, { additionalProperties: false });
18
+ const HistoryWindowsDataSchema = Type.Object({
19
+ session_id: Type.String(),
20
+ windows: Type.Array(Type.Object({
21
+ window_id: Type.String(),
22
+ created_at: Type.Union([Type.String(), Type.Null()]),
23
+ first_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
24
+ last_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
25
+ }, { additionalProperties: false })),
26
+ more: Type.Integer({ minimum: 0, description: "How many more were left out." }),
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 = [`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(`[truncated; from offset ${item.offset_chars ?? 0}]`);
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 expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
57
+ return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
58
+ }
59
+ function renderPage(page) {
60
+ // An empty selection has no anchors either, so it would otherwise render as nothing at all.
61
+ if (page.items.length === 0)
62
+ return "no events match this selection";
63
+ const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
64
+ const cursors = [
65
+ page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
66
+ page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
67
+ ].filter((line) => line !== "");
68
+ return cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`;
69
+ }
70
+ function renderRead(data) {
71
+ const tool = toolHeader(data);
72
+ const afterSeq = data.seq - 10;
73
+ const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: 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 in the refusal message itself, never as a second listing.
82
+ const MAX_REPORTED_WINDOWS = 5;
83
+ /** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
84
+ function knownWindowSuffix(known) {
85
+ return known.length === 0 ? "" : `; known: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
86
+ }
87
+ export const PREVIOUS_WINDOW = "@previous";
88
+ /** Resolve "@previous" against oldest-first windows; every other value passes through. */
89
+ function resolveWindowId(projection, windowId) {
90
+ if (windowId !== PREVIOUS_WINDOW)
91
+ return { ok: true, window_id: windowId };
92
+ const previous = projection.windows.at(-2);
93
+ if (previous !== undefined)
94
+ return { ok: true, window_id: previous.windowId };
95
+ const known = projection.windows.map((current) => current.windowId);
96
+ return { ok: false, outcome: failure("unknown_window_id", `unknown window_id "${PREVIOUS_WINDOW}": this session has no window before the current one${knownWindowSuffix(known)}`) };
97
+ }
98
+ function badWindowId(projection, params) {
99
+ const badWindow = unknownWindowId(projection, params);
100
+ if (!badWindow)
101
+ return undefined;
102
+ return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}`);
103
+ }
104
+ /* ------------------------------------------------------------------ history_windows */
105
+ export const historyWindowsParameters = Type.Object({}, { additionalProperties: false });
106
+ export const historyWindows = {
107
+ name: "history_windows",
108
+ label: "History list windows",
109
+ description: "List this session's context windows, oldest first, with seq ranges.",
110
+ parameters: historyWindowsParameters,
111
+ outputSchema: resultSchema(HistoryWindowsDataSchema),
112
+ async execute(_params, projection, sessionId) {
113
+ const data = { session_id: sessionId, windows: [], more: projection.windows.length };
114
+ const fits = (candidate) => fitsResult(success(candidate), (result) => renderOutcome(result, renderWindows));
115
+ for (const window of projection.windows) {
116
+ let first = null;
117
+ let last = null;
118
+ for (const event of window.items) {
119
+ first = first === null ? event.seq : Math.min(first, event.seq);
120
+ last = last === null ? event.seq : Math.max(last, event.seq);
121
+ }
122
+ const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last };
123
+ if (!fits({ ...data, windows: [...data.windows, row], more: data.more - 1 }))
124
+ break;
125
+ data.windows.push(row);
126
+ data.more--;
127
+ }
128
+ return fits(data) ? success(data) : failure("output_too_large", "The session identity does not fit one `history_windows` response.");
129
+ },
130
+ render: (result) => renderOutcome(result, renderWindows),
131
+ };
132
+ function renderWindows(data) {
133
+ const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
134
+ if (data.more > 0)
135
+ lines.push(`${data.more} more windows not shown; \`history_list\` also reports window ids on events`);
136
+ return lines.join("\n");
137
+ }
138
+ /* ------------------------------------------------------------------ history_list */
139
+ export const historyListParameters = Type.Object({
140
+ query: Type.Optional(searchQuery("(optional) Text, or a list of texts (any match). Searches every role, tool arguments and output included; returns only hits.")),
141
+ roles: historyRoles(),
142
+ before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
143
+ after_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq above this." })),
144
+ since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
145
+ until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
146
+ 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." })),
147
+ 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.` })),
148
+ limit: Type.Optional(Type.Integer({ description: "(optional, default 20) Max events per page; folded rows don't count." })),
149
+ max_chars_per_item: Type.Optional(Type.Integer({ description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
150
+ }, { additionalProperties: false });
151
+ export const historyList = {
152
+ name: "history_list",
153
+ label: "History list items",
154
+ description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
155
+ parameters: historyListParameters,
156
+ outputSchema: resultSchema(HistoryPageSchema),
157
+ async execute(params, projection) {
158
+ const resolved = resolveWindowId(projection, params.window_id);
159
+ if (!resolved.ok)
160
+ return resolved.outcome;
161
+ const scoped = { ...params, window_id: resolved.window_id };
162
+ const badWindow = badWindowId(projection, scoped);
163
+ if (badWindow)
164
+ return badWindow;
165
+ return selectPage(projection, scoped, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
166
+ },
167
+ render: (result) => renderOutcome(result, renderPage),
168
+ };
169
+ /* ------------------------------------------------------------------ history_read */
170
+ export const historyReadParameters = Type.Object({ seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`." }), ...TextWindowRequestSchema }, { additionalProperties: false });
171
+ export const historyRead = {
172
+ name: "history_read",
173
+ label: "History read item",
174
+ description: "Read one event in full: tool arguments, output, and nested calls.",
175
+ parameters: historyReadParameters,
176
+ outputSchema: resultSchema(HistoryReadDataSchema),
177
+ async execute(params, projection) {
178
+ const item = allItems(projection).find((event) => event.seq === params.seq);
179
+ // Address checks run in one order: past the end of the file, off this branch, then
180
+ // consumed by a pairing. Only the last two can mention what is at the address.
181
+ if (item === undefined && params.seq > projection.highestSeq) {
182
+ return failure("unknown_seq", `unknown seq ${params.seq}: this session's items run 1..${projection.highestSeq}`);
183
+ }
184
+ if (!projection.branchSeqs.has(params.seq)) {
185
+ return failure("not_on_branch", `seq ${params.seq} is on another branch and is not readable here`);
186
+ }
187
+ if (item === undefined) {
188
+ const callSeq = projection.pairedResults.get(params.seq);
189
+ if (callSeq !== undefined) {
190
+ return failure("not_an_event", `seq ${params.seq} is a tool result already shown inside the call at seq ${callSeq}; read that seq instead`);
191
+ }
192
+ return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event`);
193
+ }
194
+ const document = eventDocument(item);
195
+ const totalChars = Array.from(document).length;
196
+ if (typeof params.offset_chars === "number" && params.offset_chars > totalChars) {
197
+ 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)`);
198
+ }
199
+ return readTextWindow(document, params.offset_chars, params.max_chars, (window) => ({
200
+ seq: item.seq,
201
+ window_id: item.windowId,
202
+ role: item.role,
203
+ created_at: item.createdAt ?? null,
204
+ ...toolSummary(item),
205
+ ...nestedCallSummary(item),
206
+ ...window,
207
+ }), (result) => renderOutcome(result, renderRead));
208
+ },
209
+ render: (result) => renderOutcome(result, renderRead),
210
+ };