notesoup 0.61.0 → 0.63.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 (210) hide show
  1. package/.agents/plugins/marketplace.json +15 -0
  2. package/README.md +14 -11
  3. package/dist/plugins/antigravity/src/cli.d.ts +1 -0
  4. package/dist/plugins/antigravity/src/cli.js +23 -0
  5. package/dist/plugins/antigravity/src/hooks.d.ts +18 -0
  6. package/dist/plugins/antigravity/src/hooks.js +53 -0
  7. package/dist/plugins/antigravity/src/identity.d.ts +26 -0
  8. package/dist/plugins/antigravity/src/identity.js +129 -0
  9. package/dist/plugins/claude/src/helper.js +24 -5
  10. package/dist/plugins/claude/src/text.d.ts +7 -0
  11. package/dist/plugins/claude/src/text.js +12 -1
  12. package/dist/plugins/codex/src/hooks.js +1 -0
  13. package/dist/plugins/codex/src/identity.d.ts +6 -1
  14. package/dist/plugins/codex/src/identity.js +13 -1
  15. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  16. package/dist/plugins/codex/src/mcp.js +26 -88
  17. package/dist/plugins/codex/src/text.js +3 -3
  18. package/dist/plugins/dsh/tools.js +8 -4
  19. package/dist/plugins/mcp/operations.d.ts +15 -0
  20. package/dist/plugins/mcp/operations.js +43 -0
  21. package/dist/plugins/mcp/server.d.ts +14 -0
  22. package/dist/plugins/mcp/server.js +13 -0
  23. package/dist/plugins/pi/budget.d.ts +4 -1
  24. package/dist/plugins/pi/budget.js +35 -8
  25. package/dist/plugins/pi/entries.d.ts +2 -0
  26. package/dist/plugins/pi/entries.js +2 -0
  27. package/dist/plugins/pi/history-tools.js +2 -1
  28. package/dist/plugins/pi/history.js +18 -1
  29. package/dist/plugins/pi/notes/tools.js +7 -3
  30. package/dist/plugins/pi/render.d.ts +7 -1
  31. package/dist/plugins/pi/render.js +2 -2
  32. package/dist/plugins/pi/reset/artifacts.d.ts +1 -1
  33. package/dist/plugins/pi/reset/artifacts.js +4 -4
  34. package/dist/plugins/pi/reset/lifecycle.d.ts +9 -2
  35. package/dist/plugins/pi/reset/lifecycle.js +109 -31
  36. package/dist/plugins/pi/runtime.js +104 -63
  37. package/dist/plugins/pi/tool-result.js +7 -7
  38. package/dist/plugins/pi/window.d.ts +25 -3
  39. package/dist/plugins/pi/window.js +219 -9
  40. package/dist/src/boot/render.js +18 -15
  41. package/dist/src/boot/text.d.ts +3 -1
  42. package/dist/src/boot/text.js +22 -20
  43. package/dist/src/budget/text.d.ts +7 -3
  44. package/dist/src/budget/text.js +24 -15
  45. package/dist/src/history/claude.d.ts +2 -0
  46. package/dist/src/history/claude.js +46 -0
  47. package/dist/src/history/codex-transcript.js +7 -5
  48. package/dist/src/history/codex.js +3 -0
  49. package/dist/src/history/corpus.d.ts +28 -1
  50. package/dist/src/history/corpus.js +40 -0
  51. package/dist/src/history/history.d.ts +37 -46
  52. package/dist/src/history/history.js +21 -40
  53. package/dist/src/history/local.js +67 -32
  54. package/dist/src/history/pi.d.ts +2 -1
  55. package/dist/src/history/pi.js +122 -48
  56. package/dist/src/history/prefilter.js +76 -19
  57. package/dist/src/history/query.d.ts +28 -49
  58. package/dist/src/history/query.js +83 -68
  59. package/dist/src/history/summary-cache.d.ts +8 -1
  60. package/dist/src/history/summary-cache.js +138 -12
  61. package/dist/src/index.d.ts +2 -2
  62. package/dist/src/index.js +1 -1
  63. package/dist/src/notes/errors.d.ts +1 -1
  64. package/dist/src/notes/frontmatter.d.ts +0 -2
  65. package/dist/src/notes/frontmatter.js +0 -2
  66. package/dist/src/notes/index.d.ts +1 -1
  67. package/dist/src/notes/index.js +1 -1
  68. package/dist/src/notes/policy.d.ts +15 -1
  69. package/dist/src/notes/policy.js +46 -5
  70. package/dist/src/notes/store.d.ts +12 -0
  71. package/dist/src/notes/store.js +16 -20
  72. package/dist/src/text-match.d.ts +10 -1
  73. package/dist/src/text-match.js +42 -3
  74. package/dist/src/tools/dream.d.ts +22 -93
  75. package/dist/src/tools/dream.js +30 -27
  76. package/dist/src/tools/history.d.ts +33 -26
  77. package/dist/src/tools/history.js +257 -163
  78. package/dist/src/tools/notes.d.ts +51 -163
  79. package/dist/src/tools/notes.js +146 -100
  80. package/dist/src/tools/output.d.ts +2 -1
  81. package/dist/src/tools/output.js +2 -1
  82. package/dist/src/tools/result.d.ts +4 -7
  83. package/dist/src/tools/result.js +8 -9
  84. package/dist/src/tools/schema.d.ts +4 -1
  85. package/dist/src/tools/schema.js +25 -1
  86. package/dist/test/agent-loop.test.js +394 -56
  87. package/dist/test/antigravity-live.test.d.ts +1 -0
  88. package/dist/test/antigravity-live.test.js +142 -0
  89. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  90. package/dist/test/antigravity-plugin.test.js +101 -0
  91. package/dist/test/boot.integration.test.js +156 -15
  92. package/dist/test/budget-settings.integration.test.js +4 -4
  93. package/dist/test/claude-history.test.js +14 -13
  94. package/dist/test/claude-mod.test.js +199 -16
  95. package/dist/test/claude-validation.test.js +69 -2
  96. package/dist/test/codex-history.test.js +15 -3
  97. package/dist/test/codex-plugin.test.js +76 -38
  98. package/dist/test/dependencies.test.js +7 -3
  99. package/dist/test/dream-skill.test.js +3 -3
  100. package/dist/test/dream-tools.test.js +101 -56
  101. package/dist/test/dsh.test.js +34 -19
  102. package/dist/test/helpers/dependency-graph.js +2 -2
  103. package/dist/test/helpers/extension.d.ts +68 -3
  104. package/dist/test/helpers/extension.js +74 -5
  105. package/dist/test/history-corpus.test.js +79 -77
  106. package/dist/test/history-summary-cache.test.js +97 -9
  107. package/dist/test/history.integration.test.js +234 -168
  108. package/dist/test/host-neutral.test.js +69 -19
  109. package/dist/test/marker.test.js +1 -1
  110. package/dist/test/model-facing-text.test.js +13 -3
  111. package/dist/test/note-policy.test.js +96 -77
  112. package/dist/test/notes.integration.test.js +212 -94
  113. package/dist/test/notes.test.js +184 -113
  114. package/dist/test/pi-render.test.js +20 -12
  115. package/dist/test/project-namespace.test.js +3 -2
  116. package/dist/test/reset-lifecycle.test.js +12 -2
  117. package/docs/antigravity.md +44 -0
  118. package/docs/architecture.md +6 -4
  119. package/docs/claude-code-mod.md +7 -7
  120. package/docs/codex.md +36 -38
  121. package/docs/dsh.md +3 -3
  122. package/docs/history-sessions.md +28 -50
  123. package/docs/notes-library.md +4 -4
  124. package/docs/reset-lifecycle.md +1 -1
  125. package/docs/skills.md +3 -3
  126. package/docs/tool-results.md +47 -28
  127. package/package.json +3 -2
  128. package/playbook.md +1 -1
  129. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  130. package/plugins/antigravity/hooks.json +7 -0
  131. package/plugins/antigravity/mcp_config.json +8 -0
  132. package/plugins/antigravity/plugin.json +6 -0
  133. package/plugins/antigravity/src/cli.ts +22 -0
  134. package/plugins/antigravity/src/hooks.ts +51 -0
  135. package/plugins/antigravity/src/identity.ts +127 -0
  136. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  137. package/plugins/claude/dist/claude/helper.js +1108 -539
  138. package/plugins/claude/hooks/register.ts +202 -62
  139. package/plugins/claude/playbook.md +1 -1
  140. package/plugins/claude/skills/dream/SKILL.md +1 -1
  141. package/plugins/claude/skills/notesoup-guide/SKILL.md +92 -0
  142. package/plugins/claude/src/helper.ts +24 -5
  143. package/plugins/claude/src/text.ts +14 -1
  144. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  145. package/plugins/codex/.mcp.json +11 -0
  146. package/plugins/codex/README.md +5 -21
  147. package/plugins/codex/dist/codex/notesoup.js +18480 -17946
  148. package/plugins/codex/src/hooks.ts +1 -0
  149. package/plugins/codex/src/identity.ts +14 -1
  150. package/plugins/codex/src/mcp.ts +28 -98
  151. package/plugins/codex/src/text.ts +3 -3
  152. package/plugins/dsh/tools.ts +8 -4
  153. package/plugins/mcp/operations.ts +50 -0
  154. package/plugins/mcp/server.ts +23 -0
  155. package/plugins/paseo/README.md +5 -10
  156. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  157. package/plugins/paseo/client/markdown.tsx +50 -38
  158. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  159. package/plugins/paseo/client/paper-card.tsx +6 -5
  160. package/plugins/paseo/client/paper-palette.ts +2 -9
  161. package/plugins/paseo/client/sticky-card.tsx +2 -2
  162. package/plugins/paseo/client/tool-result.ts +7 -14
  163. package/plugins/paseo/package-lock.json +3406 -0
  164. package/plugins/paseo/package.json +1 -0
  165. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  166. package/plugins/pi/budget.ts +31 -8
  167. package/plugins/pi/entries.ts +2 -0
  168. package/plugins/pi/history-tools.ts +2 -1
  169. package/plugins/pi/history.ts +30 -1
  170. package/plugins/pi/notes/tools.ts +7 -3
  171. package/plugins/pi/render.ts +6 -6
  172. package/plugins/pi/reset/artifacts.ts +4 -3
  173. package/plugins/pi/reset/lifecycle.ts +125 -32
  174. package/plugins/pi/runtime.ts +98 -62
  175. package/plugins/pi/tool-result.ts +8 -8
  176. package/plugins/pi/window.ts +210 -10
  177. package/skills/dream/SKILL.md +1 -1
  178. package/skills/notesoup-guide/SKILL.md +92 -0
  179. package/src/boot/render.ts +18 -15
  180. package/src/boot/text.ts +23 -19
  181. package/src/budget/text.ts +27 -15
  182. package/src/history/claude.ts +41 -0
  183. package/src/history/codex-transcript.ts +6 -4
  184. package/src/history/codex.ts +2 -0
  185. package/src/history/corpus.ts +51 -2
  186. package/src/history/history.ts +35 -44
  187. package/src/history/local.ts +67 -27
  188. package/src/history/pi.ts +113 -35
  189. package/src/history/prefilter.ts +73 -15
  190. package/src/history/query.ts +93 -73
  191. package/src/history/summary-cache.ts +142 -17
  192. package/src/index.ts +2 -2
  193. package/src/notes/errors.ts +1 -1
  194. package/src/notes/frontmatter.ts +0 -3
  195. package/src/notes/index.ts +1 -1
  196. package/src/notes/policy.ts +44 -5
  197. package/src/notes/store.ts +17 -20
  198. package/src/text-match.ts +46 -4
  199. package/src/tools/dream.ts +29 -31
  200. package/src/tools/history.ts +249 -142
  201. package/src/tools/notes.ts +145 -113
  202. package/src/tools/output.ts +2 -1
  203. package/src/tools/result.ts +12 -11
  204. package/src/tools/schema.ts +24 -1
  205. package/plugins/claude/skills/memory/SKILL.md +0 -69
  206. package/plugins/codex/mcp.json +0 -10
  207. package/plugins/codex/plugin.json +0 -6
  208. package/plugins/paseo/client/markdown-core.tsx +0 -189
  209. package/plugins/paseo/client/typography.ts +0 -24
  210. package/skills/memory/SKILL.md +0 -69
package/src/history/pi.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  /** Pi's persisted entry/message wire format, independent of the Pi SDK. */
2
+ import { createReadStream } from "node:fs";
3
+ import { readFile, stat } from "node:fs/promises";
4
+ import { StringDecoder } from "node:string_decoder";
2
5
  import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection, type RecordedNestedCalls, type ToolCallStatus } from "./history.js";
3
6
 
7
+ const STREAM_FILE_BYTES = 64 * 1024 * 1024;
8
+
4
9
  type ToolCall = { type: "toolCall"; id: string; name: string; arguments: Record<string, unknown> };
5
10
  /** Structural views also accept native SDK values without converting or allocating seqs twice. */
6
11
  type Message = {
@@ -154,46 +159,119 @@ export function piHistoryFromEntries(sessionId: string, entries: readonly PiHist
154
159
  return projectHistory(rawWindows, highestSeq, branchSeqs);
155
160
  }
156
161
 
162
+ function slimMessage(message: Message): Message {
163
+ let content: unknown = message.content;
164
+ if (Array.isArray(content)) {
165
+ content = content.filter((part) => (typeof part === "object" && part !== null && ((part as { type?: unknown }).type === "text" || (part as { type?: unknown }).type === "toolCall")));
166
+ }
167
+ return {
168
+ role: message.role,
169
+ ...(content === undefined ? {} : { content }),
170
+ ...(message.output === undefined ? {} : { output: message.output }),
171
+ ...(message.summary === undefined ? {} : { summary: message.summary }),
172
+ ...(message.command === undefined ? {} : { command: message.command }),
173
+ ...(message.cancelled === undefined ? {} : { cancelled: message.cancelled }),
174
+ ...(message.exitCode === undefined ? {} : { exitCode: message.exitCode }),
175
+ ...(message.truncated === undefined ? {} : { truncated: message.truncated }),
176
+ ...(message.fullOutputPath === undefined ? {} : { fullOutputPath: message.fullOutputPath }),
177
+ ...(message.toolName === undefined ? {} : { toolName: message.toolName }),
178
+ ...(message.toolCallId === undefined ? {} : { toolCallId: message.toolCallId }),
179
+ ...(message.isError === undefined ? {} : { isError: message.isError }),
180
+ ...(message.nestedCalls === undefined ? {} : { nestedCalls: message.nestedCalls }),
181
+ };
182
+ }
183
+
184
+ function slimEntry(row: PiHistoryEntry): PiHistoryEntry {
185
+ return {
186
+ type: row.type,
187
+ id: row.id,
188
+ parentId: row.parentId,
189
+ ...(row.timestamp === undefined ? {} : { timestamp: row.timestamp }),
190
+ ...(row.summary === undefined ? {} : { summary: row.summary }),
191
+ ...(row.customType === undefined ? {} : { customType: row.customType }),
192
+ ...(row.customType === "notesoup/reset-marker" && row.data !== undefined ? { data: row.data } : {}),
193
+ ...(row.type === "custom_message" && row.content !== undefined ? { content: contentText(row.content) } : {}),
194
+ ...(row.type === "message" && row.message ? { message: slimMessage(row.message) } : {}),
195
+ };
196
+ }
197
+
198
+ function createPiJsonlParser(sessionId: string) {
199
+ const entries: PiHistoryEntry[] = [];
200
+ let header = false;
201
+ return {
202
+ push(line: string, lineNumber: number, allowIncompleteTail: boolean) {
203
+ if (line.trim() === "") return;
204
+ let row: PiHistoryEntry;
205
+ try { row = JSON.parse(line) as PiHistoryEntry; }
206
+ catch {
207
+ if (allowIncompleteTail) return;
208
+ throw new Error(`malformed Pi transcript JSON at line ${lineNumber}`);
209
+ }
210
+ if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string") throw new Error("invalid Pi transcript entry");
211
+ if (!header) {
212
+ if (row.type !== "session" || row.id !== sessionId) throw new Error("Pi transcript belongs to a different session or has no header");
213
+ header = true;
214
+ return;
215
+ }
216
+ if (row.parentId !== null && typeof row.parentId !== "string") throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
217
+ if (row.type === "message" && (!row.message || typeof row.message.role !== "string")) throw new Error("invalid Pi transcript message");
218
+ entries.push(slimEntry(row));
219
+ },
220
+ finish(): HistoryProjection {
221
+ if (!header) throw new Error("Pi transcript has no session header");
222
+ const byId = new Map<string, PiHistoryEntry>();
223
+ for (const entry of entries) {
224
+ if (byId.has(entry.id)) throw new Error(`duplicate Pi entry ID: ${entry.id}`);
225
+ byId.set(entry.id, entry);
226
+ }
227
+ const branch: PiHistoryEntry[] = [], seen = new Set<string>();
228
+ let cursor = entries.at(-1);
229
+ while (cursor) {
230
+ if (seen.has(cursor.id)) throw new Error("cyclic Pi transcript ancestry");
231
+ seen.add(cursor.id);
232
+ branch.push(cursor);
233
+ if (cursor.parentId === null) break;
234
+ const parent = byId.get(cursor.parentId!);
235
+ if (!parent) throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
236
+ cursor = parent;
237
+ }
238
+ return piHistoryFromEntries(sessionId, entries, branch.reverse());
239
+ },
240
+ };
241
+ }
242
+
157
243
  /** Offline files persist append order and parent links; select the final tree entry's ancestry. */
158
244
  export function piHistoryFromJsonl(text: string, sessionId: string): HistoryProjection {
159
245
  const lines = text.split("\n");
160
- const entries: PiHistoryEntry[] = [];
161
- let header = false;
246
+ const parser = createPiJsonlParser(sessionId);
162
247
  for (let index = 0; index < lines.length; index++) {
163
- const line = lines[index]!;
164
- if (line.trim() === "") continue;
165
- let row: PiHistoryEntry;
166
- try { row = JSON.parse(line) as PiHistoryEntry; }
167
- catch {
168
- if (index === lines.length - 1 && !text.endsWith("\n")) break;
169
- throw new Error(`malformed Pi transcript JSON at line ${index + 1}`);
170
- }
171
- if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string") throw new Error("invalid Pi transcript entry");
172
- if (!header) {
173
- if (row.type !== "session" || row.id !== sessionId) throw new Error("Pi transcript belongs to a different session or has no header");
174
- header = true;
175
- continue;
176
- }
177
- if (row.parentId !== null && typeof row.parentId !== "string") throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
178
- if (row.type === "message" && (!row.message || typeof row.message.role !== "string")) throw new Error("invalid Pi transcript message");
179
- entries.push(row);
248
+ parser.push(lines[index]!, index + 1, index === lines.length - 1 && !text.endsWith("\n"));
180
249
  }
181
- if (!header) throw new Error("Pi transcript has no session header");
182
- const byId = new Map<string, PiHistoryEntry>();
183
- for (const entry of entries) {
184
- if (byId.has(entry.id)) throw new Error(`duplicate Pi entry ID: ${entry.id}`);
185
- byId.set(entry.id, entry);
250
+ return parser.finish();
251
+ }
252
+
253
+ /** Stream oversized Pi JSONL files line-by-line so >512 MiB transcripts never hit V8's string limit. */
254
+ export async function piHistoryFromFile(path: string, sessionId: string, sizeHint?: number): Promise<HistoryProjection> {
255
+ const size = sizeHint ?? (await stat(path)).size;
256
+ if (size < STREAM_FILE_BYTES) return piHistoryFromJsonl(await readFile(path, "utf8"), sessionId);
257
+ const parser = createPiJsonlParser(sessionId);
258
+ const decoder = new StringDecoder("utf8");
259
+ let remainder = "";
260
+ let lineNumber = 0;
261
+ for await (const chunk of createReadStream(path, { highWaterMark: 1024 * 1024 })) {
262
+ const text = remainder + decoder.write(chunk as Buffer);
263
+ let start = 0;
264
+ for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
265
+ lineNumber++;
266
+ parser.push(text.slice(start, nl), lineNumber, false);
267
+ start = nl + 1;
268
+ }
269
+ remainder = text.slice(start);
186
270
  }
187
- const branch: PiHistoryEntry[] = [], seen = new Set<string>();
188
- let cursor = entries.at(-1);
189
- while (cursor) {
190
- if (seen.has(cursor.id)) throw new Error("cyclic Pi transcript ancestry");
191
- seen.add(cursor.id);
192
- branch.push(cursor);
193
- if (cursor.parentId === null) break;
194
- const parent = byId.get(cursor.parentId!);
195
- if (!parent) throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
196
- cursor = parent;
271
+ remainder += decoder.end();
272
+ if (remainder.length > 0) {
273
+ lineNumber++;
274
+ parser.push(remainder, lineNumber, true);
197
275
  }
198
- return piHistoryFromEntries(sessionId, entries, branch.reverse());
276
+ return parser.finish();
199
277
  }
@@ -15,6 +15,67 @@ const PRESENTATION = `Codex unknown arguments not recorded output nested calls c
15
15
  const HISTORY_BASE = '"history_base"';
16
16
  export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean, stopOnHit?: boolean) => Promise<boolean>;
17
17
 
18
+ const STREAM_HIGH_WATER_MARK = 256 * 1024;
19
+
20
+ function isHex(code: number): boolean {
21
+ return (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102);
22
+ }
23
+
24
+ /** Linear-time one-pass `\uXXXX` decoder: skips non-`\u` backslashes and bounds any trailing run to <= 6 chars. */
25
+ function decodeEscapes(source: string, final: boolean): { decoded: string; pending: string } {
26
+ const len = source.length;
27
+ let pending = "";
28
+ let limit = len;
29
+ if (!final && len > 0) {
30
+ let end = len;
31
+ let hexCount = 0;
32
+ while (end > 0 && hexCount < 3 && isHex(source.charCodeAt(end - 1))) {
33
+ end--;
34
+ hexCount++;
35
+ }
36
+ if (end >= 2 && source.charCodeAt(end - 1) === 117 && source.charCodeAt(end - 2) === 92) {
37
+ let slashStart = end - 2;
38
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92) slashStart--;
39
+ pending = `\\u${source.slice(end, len)}`;
40
+ limit = slashStart;
41
+ } else if (source.charCodeAt(len - 1) === 92) {
42
+ let slashStart = len - 1;
43
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92) slashStart--;
44
+ pending = "\\";
45
+ limit = slashStart;
46
+ }
47
+ }
48
+ if (limit < 6) {
49
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
50
+ }
51
+ let pos = source.indexOf("\\u");
52
+ if (pos < 0 || pos >= limit) {
53
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
54
+ }
55
+ let out = "";
56
+ let cursor = 0;
57
+ while (pos >= 0 && pos < limit) {
58
+ if (
59
+ pos + 6 <= limit
60
+ && isHex(source.charCodeAt(pos + 2))
61
+ && isHex(source.charCodeAt(pos + 3))
62
+ && isHex(source.charCodeAt(pos + 4))
63
+ && isHex(source.charCodeAt(pos + 5))
64
+ ) {
65
+ let slashStart = pos;
66
+ while (slashStart > cursor && source.charCodeAt(slashStart - 1) === 92) slashStart--;
67
+ if (slashStart > cursor) out += source.slice(cursor, slashStart);
68
+ out += String.fromCharCode(Number.parseInt(source.slice(pos + 2, pos + 6), 16));
69
+ cursor = pos + 6;
70
+ pos = source.indexOf("\\u", cursor);
71
+ } else {
72
+ pos = source.indexOf("\\u", pos + 2);
73
+ }
74
+ }
75
+ if (cursor < limit) out += source.slice(cursor, limit);
76
+ return { decoded: out, pending };
77
+ }
78
+
18
79
  /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
19
80
  export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter {
20
81
  let overlap = HISTORY_BASE.length;
@@ -31,20 +92,17 @@ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefi
31
92
  const decoder = new StringDecoder("utf8");
32
93
  const seen = alternatives.map((tokens) => tokens.map(() => false));
33
94
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
34
- // Unlike /\\+u(hex{4})/, this cannot backtrack quadratically over a long invalid run.
35
- const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
36
95
  const scan = (chunk: string, final = false) => {
37
- const raw = rawTail + chunk, source = pending + chunk;
38
- const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
39
- pending = "";
40
- const decoded = needsNormalization ? source.replace(escapes, (match, hex: string | undefined, offset: number) => {
41
- if (hex?.length === 4) return String.fromCharCode(Number.parseInt(hex, 16));
42
- // Tokens cannot include backslashes: an unresolved run needs only one separator,
43
- // plus at most 'u' and three hex digits, even if it spans arbitrarily many chunks.
44
- const literal = hex === undefined ? "\\" : `\\u${hex}`;
45
- if (!final && offset + match.length === source.length) { pending = literal; return ""; }
46
- return literal;
47
- }) : chunk;
96
+ const raw = rawTail + chunk;
97
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || (!final && chunk.endsWith("\\"));
98
+ let decoded = chunk;
99
+ if (needsNormalization) {
100
+ const result = decodeEscapes(pending + chunk, final);
101
+ decoded = result.decoded;
102
+ pending = result.pending;
103
+ } else {
104
+ pending = "";
105
+ }
48
106
  const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
49
107
  if (codex && raw.includes(HISTORY_BASE)) possible = true;
50
108
  else possible = alternatives.some((tokens, index) => {
@@ -68,13 +126,13 @@ export function createHistoryPrefilter(queries: readonly string[]): HistoryPrefi
68
126
  export async function historyFileMayMatch(path: string, prefilter: HistoryPrefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity): Promise<boolean> {
69
127
  // Plain Pi/Claude files will be read and validated by the strict decoder on a possible
70
128
  // hit. Don't drain a potentially huge file just to read it from the beginning again.
71
- if (!codex) return prefilter(createReadStream(path), false, true);
129
+ if (!codex) return prefilter(createReadStream(path, { highWaterMark: STREAM_HIGH_WATER_MARK }), false, true);
72
130
  const info = await stat(path);
73
131
  if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
74
132
  // Native Codex compression is zstd; scan through EOF to enforce the decoded size limit.
75
133
  const compressed = path.endsWith(".jsonl.zst");
76
134
  if (compressed && typeof zlib.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
77
- const input = createReadStream(path);
135
+ const input = createReadStream(path, { highWaterMark: STREAM_HIGH_WATER_MARK });
78
136
  const consume = async (chunks: AsyncIterable<Buffer>) => {
79
137
  let size = 0;
80
138
  async function* bounded() {
@@ -1,32 +1,17 @@
1
1
  /** Stable-anchor paging, folding and literal matching. The operation supplies the full-response budget check. */
2
- import { Type, type Static } from "typebox";
3
2
  import { success, type Outcome } from "../result.js";
4
- import { earliestMatchOffsetChars, prefixFit } from "../text-match.js";
5
- import { eventDocument, filteredItems, matchesFilter, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
3
+ import { compileSearchQueries, earliestMatchOffsetChars, prefixFit } from "../text-match.js";
4
+ import { eventDocument, eventTimestampMs, filteredItems, matchesFilter, visibleItem, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection, type HistoryRole } from "./history.js";
6
5
 
7
6
  type Candidate = { event: HistoryEvent; session?: string; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow; neighbors?: { events: HistoryEvent[]; index: number } };
8
- type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; multi?: boolean; discarded?: boolean; forward?: boolean };
9
- const multiPages = new WeakSet<HistoryPage>();
10
- export function isMultiPage(page: HistoryPage): boolean { return multiPages.has(page); }
11
- export function markMultiPage(page: HistoryPage): HistoryPage {
12
- multiPages.add(page);
13
- return page;
14
- }
15
-
16
- export type HistorySelection = HistoryFilter & { session?: string; limit?: number; query?: string[]; context?: number };
17
-
18
- export const HistoryPageSchema = Type.Object({
19
- notice: Type.Optional(Type.String()),
20
- items: Type.Array(HistoryPageItemSchema),
21
- folded_after: Type.Optional(HistoryFoldedRowSchema),
22
- has_older: Type.Boolean(),
23
- has_newer: Type.Boolean(),
24
- }, { additionalProperties: false });
7
+ type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; discarded?: boolean; forward?: boolean };
8
+ type TimelineSelection = HistoryFilter & { limit?: number };
9
+ export type HistorySelection = TimelineSelection & { query?: string[]; context?: number };
25
10
 
26
11
  /** One whole page payload, before it becomes an outcome. */
27
- export type HistoryPage = Static<typeof HistoryPageSchema>;
12
+ export type HistoryPage = { notice?: string; items: HistoryPageItem[]; folded_after?: HistoryFoldedRow; has_older: boolean; has_newer: boolean };
28
13
  /** A caller's budget rejected even the shortest page; tool limits and refusal copy belong to the caller. */
29
- export type HistoryPageResult = Outcome<HistoryPage> | { ok: false; pageTooLarge: { count: number; multi: boolean } };
14
+ export type HistoryPageResult = Outcome<HistoryPage> | { ok: false; pageTooLarge: true };
30
15
 
31
16
  /** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
32
17
  function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPageItem) => boolean): HistoryPageItem {
@@ -44,7 +29,7 @@ function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPag
44
29
  }
45
30
 
46
31
  /** Summarize one already ordered gap; omitted tool names never change its exact count. */
47
- function foldedRun(events: HistoryEvent[], session?: string): HistoryFoldedRow | undefined {
32
+ function foldedRun(events: HistoryEvent[]): HistoryFoldedRow | undefined {
48
33
  if (events.length === 0) return undefined;
49
34
  const counts = new Map<string, number>();
50
35
  for (const event of events) {
@@ -55,35 +40,34 @@ function foldedRun(events: HistoryEvent[], session?: string): HistoryFoldedRow |
55
40
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
56
41
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
57
42
  const tools = Object.fromEntries(entries);
58
- return { ...(session === undefined ? {} : { session }), first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
43
+ return { first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
59
44
  }
60
45
 
61
46
  // Tool/thinking-only envelopes are not dialogue, even with explicit roles.
62
47
  const visible = (event: HistoryEvent) => (event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "";
63
48
 
64
- function* queryHits(projection: HistoryProjection, params: HistorySelection, session?: string): Generator<Candidate> {
65
- const { query, context } = params;
49
+ function* queryHits(projection: HistoryProjection, params: HistorySelection, patterns: readonly RegExp[], session?: string): Generator<Candidate> {
50
+ const { context } = params;
66
51
  const events = filteredItems(projection, context ? {} : params).filter(visible);
67
52
  for (const [index, event] of events.entries()) {
68
53
  if (context && !matchesFilter(event, params)) continue;
69
- const matchOffset = earliestMatchOffsetChars(eventDocument(event), query!);
54
+ const matchOffset = earliestMatchOffsetChars(eventDocument(event), patterns);
70
55
  if (matchOffset >= 0) yield { event, session, matchOffset, neighbors: context ? { events, index } : undefined };
71
56
  }
72
57
  }
73
58
 
74
- function prepareSelection(projection: HistoryProjection, params: HistorySelection): PreparedSelection {
75
- const { query, roles, session } = params;
76
- if (query) return { candidates: [...queryHits(projection, params, session)] };
59
+ function prepareSelection(projection: HistoryProjection, params: TimelineSelection): PreparedSelection {
60
+ const { roles } = params;
77
61
  const candidates: Candidate[] = [];
78
62
  let run: HistoryEvent[] = [];
79
63
  for (const event of filteredItems(projection, params).filter(visible)) {
80
64
  if (!roles && (event.role === "tool" || event.role === "context")) run.push(event);
81
65
  else {
82
- candidates.push({ event, session, before: foldedRun(run, session) });
66
+ candidates.push({ event, before: foldedRun(run) });
83
67
  run = [];
84
68
  }
85
69
  }
86
- return { candidates, tail: foldedRun(run, session) };
70
+ return { candidates, tail: foldedRun(run) };
87
71
  }
88
72
 
89
73
  /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
@@ -95,19 +79,55 @@ function pageData(prepared: PreparedSelection, start: number, end: number, maxCh
95
79
  const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) });
96
80
  items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
97
81
  }
98
- const page = {
82
+ return {
99
83
  items,
100
84
  ...(end === candidates.length && tail ? { folded_after: tail } : {}),
101
85
  has_older: (start > 0 && start < end) || (!!prepared.discarded && !prepared.forward),
102
86
  has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && !!prepared.forward),
103
87
  };
104
- return prepared.multi ? markMultiPage(page) : page;
105
88
  }
106
89
 
107
- export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult {
90
+ export function selectPage(projection: HistoryProjection, params: TimelineSelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult {
108
91
  return selectPrepared(prepareSelection(projection, params), params, fits, maxChars);
109
92
  }
110
93
 
94
+ /** Strict single-pass overview summary: default representative, latest per role, and exact time span. */
95
+ export type ProjectionSummary = {
96
+ event: HistoryEvent | undefined;
97
+ latestByRole: Partial<Record<HistoryRole, HistoryEvent>>;
98
+ minCreatedAt: number | null;
99
+ maxCreatedAt: number | null;
100
+ hasUntimed: boolean;
101
+ };
102
+
103
+ export function summarizeProjection(projection: HistoryProjection): ProjectionSummary {
104
+ const events = filteredItems(projection, {}).filter(visible);
105
+ let firstUser: HistoryEvent | undefined;
106
+ let lastAssistant: HistoryEvent | undefined;
107
+ const latestByRole: Partial<Record<HistoryRole, HistoryEvent>> = {};
108
+ let minCreatedAt = Infinity;
109
+ let maxCreatedAt = -Infinity;
110
+ let hasUntimed = false;
111
+ for (const event of events) {
112
+ if (firstUser === undefined && event.role === "user") firstUser = event;
113
+ if (event.role === "assistant") lastAssistant = event;
114
+ latestByRole[event.role] = event;
115
+ const at = eventTimestampMs(event);
116
+ if (Number.isNaN(at)) hasUntimed = true;
117
+ else {
118
+ if (at < minCreatedAt) minCreatedAt = at;
119
+ if (at > maxCreatedAt) maxCreatedAt = at;
120
+ }
121
+ }
122
+ return {
123
+ event: firstUser ?? lastAssistant ?? events.at(-1),
124
+ latestByRole,
125
+ minCreatedAt: Number.isFinite(minCreatedAt) ? minCreatedAt : null,
126
+ maxCreatedAt: Number.isFinite(maxCreatedAt) ? maxCreatedAt : null,
127
+ hasUntimed,
128
+ };
129
+ }
130
+
111
131
  /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
112
132
  export function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined {
113
133
  const events = filteredItems(projection, scoped).filter(visible);
@@ -117,17 +137,14 @@ export function sessionRepresentative(projection: HistoryProjection, scoped: His
117
137
  ?? events.at(-1);
118
138
  }
119
139
 
120
- function eventTime(timestamp?: string | null): number {
121
- const at = Date.parse(timestamp ?? "");
122
- return Number.isNaN(at) ? -Infinity : at;
123
- }
124
- const compareCorpus = (a: Candidate, b: Candidate) => eventTime(a.event.createdAt) - eventTime(b.event.createdAt) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq;
140
+ const earliestIfUntimed = (at: number) => Number.isNaN(at) ? -Infinity : at;
141
+ const compareCorpus = (a: Candidate, b: Candidate) => earliestIfUntimed(eventTimestampMs(a.event)) - earliestIfUntimed(eventTimestampMs(b.event)) || (a.session ?? "").localeCompare(b.session ?? "") || a.event.seq - b.event.seq;
125
142
 
126
143
  /** Fill the remaining budget nearest first. Shared session/seq keys merge overlapping windows. */
127
144
  function addContext(page: HistoryPage, hits: Candidate[], radius: number, fits: (page: HistoryPage) => boolean, maxChars: number): void {
128
145
  const key = (session: string | undefined, seq: number) => `${session ?? ""}\0${seq}`;
129
146
  const seen = new Set(page.items.map(item => key(item.session, item.seq)));
130
- const compare = (a: HistoryPageItem, b: HistoryPageItem) => (isMultiPage(page) ? eventTime(a.created_at) - eventTime(b.created_at) || a.session!.localeCompare(b.session!) : 0) || a.seq - b.seq;
147
+ const compare = (a: HistoryPageItem, b: HistoryPageItem) => earliestIfUntimed(Date.parse(a.created_at ?? "")) - earliestIfUntimed(Date.parse(b.created_at ?? "")) || (a.session ?? "").localeCompare(b.session ?? "") || a.seq - b.seq;
131
148
  for (let distance = 1; distance <= radius; distance++) {
132
149
  let found = false;
133
150
  for (const { neighbors, session } of hits) {
@@ -153,9 +170,11 @@ function addContext(page: HistoryPage, hits: Candidate[], radius: number, fits:
153
170
  export class CorpusCollector {
154
171
  private readonly candidates: Candidate[] = [];
155
172
  private readonly limit: number;
173
+ private readonly compiledQuery: readonly RegExp[];
156
174
  private discarded = false;
157
175
  constructor(private readonly scoped: HistorySelection) {
158
176
  this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
177
+ this.compiledQuery = scoped.query?.length ? compileSearchQueries(scoped.query) : [];
159
178
  }
160
179
 
161
180
  private admit(candidate: Candidate): void {
@@ -180,50 +199,51 @@ export class CorpusCollector {
180
199
  this.candidates.splice(low, 0, candidate);
181
200
  }
182
201
 
183
- /** Admit an already selected strict overview event without selecting it a second time. */
184
- addRepresentative(session: string, event: HistoryEvent | undefined): boolean {
202
+ /** Admit a session's overview representative (pre-selected or picked from a projection). */
203
+ addRepresentative(session: string, source: HistoryEvent | HistoryProjection | undefined): boolean {
204
+ const event = source && "windows" in source ? sessionRepresentative(source, this.scoped) : source;
185
205
  if (!event) return false;
186
- this.admit({ session, event });
206
+ this.admit({ session: session || undefined, event });
187
207
  return true;
188
208
  }
189
209
 
190
- /** Returns whether this session contributes an overview representative. */
191
- add(session: string, projection: HistoryProjection): boolean {
192
- if (this.scoped.query === undefined) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
193
- for (const hit of queryHits(projection, this.scoped, session)) this.admit(hit);
194
- return true;
210
+ /** Admit every query match from one session; an empty query matches nothing. */
211
+ addMatches(session: string, projection: HistoryProjection): void {
212
+ if (this.compiledQuery.length === 0) return;
213
+ for (const hit of queryHits(projection, this.scoped, this.compiledQuery, session || undefined)) this.admit(hit);
195
214
  }
196
215
 
197
216
  page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited = false): HistoryPageResult {
198
- return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
217
+ const result = selectPrepared({ candidates: this.candidates, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
218
+ if (result.ok && this.compiledQuery.length > 0 && this.scoped.context) {
219
+ const count = result.data.items.length;
220
+ const hits = this.scoped.after ? this.candidates.slice(0, count) : this.candidates.slice(this.candidates.length - count);
221
+ addContext(result.data, hits, this.scoped.context, fits, maxChars);
222
+ }
223
+ return result;
199
224
  }
200
225
  }
201
226
 
202
- function selectPrepared(prepared: PreparedSelection, scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult {
227
+ function selectPrepared(prepared: PreparedSelection, scoped: TimelineSelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult {
203
228
  const { candidates } = prepared;
204
- // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
205
- const newest = scoped.after === undefined;
206
- let start = newest ? candidates.length : 0;
207
- let end = start;
208
- const limit = Math.max(1, scoped.limit ?? 20);
209
- for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
210
- const nextStart = newest ? start - 1 : start;
211
- const nextEnd = newest ? end : end + 1;
212
- if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
213
- start = nextStart;
214
- end = nextEnd;
215
- continue;
229
+ // Keep a contiguous interval from the requested end, always presented oldest first.
230
+ const newest = scoped.after === undefined && (scoped.before !== undefined || scoped.since === undefined);
231
+ const start = (count: number) => newest ? candidates.length - count : 0;
232
+ const pageFor = (count: number, preview?: HistoryPageItem) => pageData(prepared, start(count), start(count) + count, maxChars, preview);
233
+ let count = Math.min(Math.max(1, scoped.limit ?? 20), candidates.length);
234
+ if (count > 0 && !fits(pageFor(count))) {
235
+ let low = 0, high = count - 1;
236
+ while (low < high) {
237
+ const mid = Math.ceil((low + high) / 2);
238
+ if (fits(pageFor(mid))) low = mid;
239
+ else high = mid - 1;
216
240
  }
217
- if (start === end) {
218
- start = nextStart;
219
- end = nextEnd;
220
- const candidate = candidates[start]!;
221
- candidate.preview = truncateHistoryItem(candidate.preview!, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
241
+ count = Math.max(1, low);
242
+ if (low === 0) {
243
+ const candidate = candidates[start(1)]!;
244
+ candidate.preview = truncateHistoryItem(candidate.preview!, preview => fits(pageFor(1, preview)));
222
245
  }
223
- break;
224
246
  }
225
- const page = pageData(prepared, start, end, maxChars);
226
- if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
227
- if (scoped.context) addContext(page, candidates.slice(start, end), scoped.context, fits, maxChars);
228
- return success(page);
247
+ const page = pageFor(count);
248
+ return fits(page) ? success(page) : { ok: false, pageTooLarge: true };
229
249
  }