notesoup 0.61.0 → 0.62.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 (200) 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 +2 -1
  10. package/dist/plugins/codex/src/hooks.js +1 -0
  11. package/dist/plugins/codex/src/identity.d.ts +6 -1
  12. package/dist/plugins/codex/src/identity.js +13 -1
  13. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  14. package/dist/plugins/codex/src/mcp.js +26 -88
  15. package/dist/plugins/codex/src/text.js +3 -3
  16. package/dist/plugins/dsh/tools.js +8 -4
  17. package/dist/plugins/mcp/operations.d.ts +15 -0
  18. package/dist/plugins/mcp/operations.js +43 -0
  19. package/dist/plugins/mcp/server.d.ts +14 -0
  20. package/dist/plugins/mcp/server.js +13 -0
  21. package/dist/plugins/pi/budget.d.ts +1 -1
  22. package/dist/plugins/pi/budget.js +3 -2
  23. package/dist/plugins/pi/entries.d.ts +1 -0
  24. package/dist/plugins/pi/entries.js +1 -0
  25. package/dist/plugins/pi/history-tools.js +2 -1
  26. package/dist/plugins/pi/history.js +18 -1
  27. package/dist/plugins/pi/notes/tools.js +7 -3
  28. package/dist/plugins/pi/render.d.ts +7 -1
  29. package/dist/plugins/pi/render.js +2 -2
  30. package/dist/plugins/pi/reset/lifecycle.d.ts +1 -1
  31. package/dist/plugins/pi/reset/lifecycle.js +8 -9
  32. package/dist/plugins/pi/runtime.js +102 -61
  33. package/dist/plugins/pi/tool-result.js +7 -7
  34. package/dist/plugins/pi/window.d.ts +33 -3
  35. package/dist/plugins/pi/window.js +209 -9
  36. package/dist/src/boot/render.js +18 -15
  37. package/dist/src/boot/text.d.ts +3 -1
  38. package/dist/src/boot/text.js +22 -20
  39. package/dist/src/budget/text.d.ts +2 -2
  40. package/dist/src/budget/text.js +13 -13
  41. package/dist/src/history/claude.d.ts +2 -0
  42. package/dist/src/history/claude.js +46 -0
  43. package/dist/src/history/codex-transcript.js +7 -5
  44. package/dist/src/history/codex.js +3 -0
  45. package/dist/src/history/corpus.d.ts +28 -1
  46. package/dist/src/history/corpus.js +40 -0
  47. package/dist/src/history/history.d.ts +37 -46
  48. package/dist/src/history/history.js +21 -40
  49. package/dist/src/history/local.js +67 -32
  50. package/dist/src/history/pi.d.ts +2 -1
  51. package/dist/src/history/pi.js +122 -48
  52. package/dist/src/history/prefilter.js +76 -19
  53. package/dist/src/history/query.d.ts +28 -49
  54. package/dist/src/history/query.js +83 -68
  55. package/dist/src/history/summary-cache.d.ts +8 -1
  56. package/dist/src/history/summary-cache.js +138 -12
  57. package/dist/src/index.d.ts +1 -1
  58. package/dist/src/index.js +1 -1
  59. package/dist/src/notes/errors.d.ts +1 -1
  60. package/dist/src/notes/frontmatter.d.ts +0 -2
  61. package/dist/src/notes/frontmatter.js +0 -2
  62. package/dist/src/notes/index.d.ts +1 -1
  63. package/dist/src/notes/index.js +1 -1
  64. package/dist/src/notes/policy.d.ts +15 -1
  65. package/dist/src/notes/policy.js +46 -5
  66. package/dist/src/notes/store.d.ts +12 -0
  67. package/dist/src/notes/store.js +16 -20
  68. package/dist/src/text-match.d.ts +10 -1
  69. package/dist/src/text-match.js +42 -3
  70. package/dist/src/tools/dream.d.ts +22 -93
  71. package/dist/src/tools/dream.js +30 -27
  72. package/dist/src/tools/history.d.ts +33 -26
  73. package/dist/src/tools/history.js +257 -163
  74. package/dist/src/tools/notes.d.ts +51 -163
  75. package/dist/src/tools/notes.js +146 -100
  76. package/dist/src/tools/output.d.ts +2 -1
  77. package/dist/src/tools/output.js +2 -1
  78. package/dist/src/tools/result.d.ts +4 -7
  79. package/dist/src/tools/result.js +8 -9
  80. package/dist/src/tools/schema.d.ts +4 -1
  81. package/dist/src/tools/schema.js +25 -1
  82. package/dist/test/agent-loop.test.js +198 -16
  83. package/dist/test/antigravity-live.test.d.ts +1 -0
  84. package/dist/test/antigravity-live.test.js +142 -0
  85. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  86. package/dist/test/antigravity-plugin.test.js +101 -0
  87. package/dist/test/boot.integration.test.js +133 -14
  88. package/dist/test/claude-history.test.js +14 -13
  89. package/dist/test/claude-mod.test.js +9 -6
  90. package/dist/test/codex-history.test.js +15 -3
  91. package/dist/test/codex-plugin.test.js +76 -38
  92. package/dist/test/dependencies.test.js +7 -3
  93. package/dist/test/dream-skill.test.js +3 -3
  94. package/dist/test/dream-tools.test.js +101 -56
  95. package/dist/test/dsh.test.js +34 -19
  96. package/dist/test/helpers/dependency-graph.js +2 -2
  97. package/dist/test/helpers/extension.d.ts +65 -2
  98. package/dist/test/helpers/extension.js +72 -3
  99. package/dist/test/history-corpus.test.js +79 -77
  100. package/dist/test/history-summary-cache.test.js +97 -9
  101. package/dist/test/history.integration.test.js +234 -168
  102. package/dist/test/host-neutral.test.js +69 -19
  103. package/dist/test/marker.test.js +1 -1
  104. package/dist/test/note-policy.test.js +96 -77
  105. package/dist/test/notes.integration.test.js +212 -94
  106. package/dist/test/notes.test.js +184 -113
  107. package/dist/test/pi-render.test.js +20 -12
  108. package/dist/test/project-namespace.test.js +3 -2
  109. package/dist/test/reset-lifecycle.test.js +2 -2
  110. package/docs/antigravity.md +44 -0
  111. package/docs/architecture.md +6 -4
  112. package/docs/claude-code-mod.md +2 -2
  113. package/docs/codex.md +36 -38
  114. package/docs/dsh.md +3 -3
  115. package/docs/history-sessions.md +28 -50
  116. package/docs/notes-library.md +4 -4
  117. package/docs/skills.md +3 -3
  118. package/docs/tool-results.md +47 -28
  119. package/package.json +3 -2
  120. package/playbook.md +1 -1
  121. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  122. package/plugins/antigravity/hooks.json +7 -0
  123. package/plugins/antigravity/mcp_config.json +8 -0
  124. package/plugins/antigravity/plugin.json +6 -0
  125. package/plugins/antigravity/src/cli.ts +22 -0
  126. package/plugins/antigravity/src/hooks.ts +51 -0
  127. package/plugins/antigravity/src/identity.ts +127 -0
  128. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  129. package/plugins/claude/dist/claude/helper.js +1059 -534
  130. package/plugins/claude/hooks/register.ts +2 -2
  131. package/plugins/claude/playbook.md +1 -1
  132. package/plugins/claude/skills/dream/SKILL.md +1 -1
  133. package/plugins/claude/skills/notesoup/SKILL.md +92 -0
  134. package/plugins/claude/src/helper.ts +2 -1
  135. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  136. package/plugins/codex/.mcp.json +11 -0
  137. package/plugins/codex/README.md +5 -21
  138. package/plugins/codex/dist/codex/notesoup.js +18480 -17946
  139. package/plugins/codex/src/hooks.ts +1 -0
  140. package/plugins/codex/src/identity.ts +14 -1
  141. package/plugins/codex/src/mcp.ts +28 -98
  142. package/plugins/codex/src/text.ts +3 -3
  143. package/plugins/dsh/tools.ts +8 -4
  144. package/plugins/mcp/operations.ts +50 -0
  145. package/plugins/mcp/server.ts +23 -0
  146. package/plugins/paseo/README.md +5 -10
  147. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  148. package/plugins/paseo/client/markdown.tsx +50 -38
  149. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  150. package/plugins/paseo/client/paper-card.tsx +6 -5
  151. package/plugins/paseo/client/paper-palette.ts +2 -9
  152. package/plugins/paseo/client/sticky-card.tsx +2 -2
  153. package/plugins/paseo/client/tool-result.ts +7 -14
  154. package/plugins/paseo/package-lock.json +3406 -0
  155. package/plugins/paseo/package.json +1 -0
  156. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  157. package/plugins/pi/budget.ts +3 -3
  158. package/plugins/pi/entries.ts +1 -0
  159. package/plugins/pi/history-tools.ts +2 -1
  160. package/plugins/pi/history.ts +30 -1
  161. package/plugins/pi/notes/tools.ts +7 -3
  162. package/plugins/pi/render.ts +6 -6
  163. package/plugins/pi/reset/lifecycle.ts +9 -10
  164. package/plugins/pi/runtime.ts +96 -60
  165. package/plugins/pi/tool-result.ts +8 -8
  166. package/plugins/pi/window.ts +198 -9
  167. package/skills/dream/SKILL.md +1 -1
  168. package/skills/notesoup/SKILL.md +92 -0
  169. package/src/boot/render.ts +18 -15
  170. package/src/boot/text.ts +23 -19
  171. package/src/budget/text.ts +13 -13
  172. package/src/history/claude.ts +41 -0
  173. package/src/history/codex-transcript.ts +6 -4
  174. package/src/history/codex.ts +2 -0
  175. package/src/history/corpus.ts +51 -2
  176. package/src/history/history.ts +35 -44
  177. package/src/history/local.ts +67 -27
  178. package/src/history/pi.ts +113 -35
  179. package/src/history/prefilter.ts +73 -15
  180. package/src/history/query.ts +93 -73
  181. package/src/history/summary-cache.ts +142 -17
  182. package/src/index.ts +1 -1
  183. package/src/notes/errors.ts +1 -1
  184. package/src/notes/frontmatter.ts +0 -3
  185. package/src/notes/index.ts +1 -1
  186. package/src/notes/policy.ts +44 -5
  187. package/src/notes/store.ts +17 -20
  188. package/src/text-match.ts +46 -4
  189. package/src/tools/dream.ts +29 -31
  190. package/src/tools/history.ts +249 -142
  191. package/src/tools/notes.ts +145 -113
  192. package/src/tools/output.ts +2 -1
  193. package/src/tools/result.ts +12 -11
  194. package/src/tools/schema.ts +24 -1
  195. package/plugins/claude/skills/memory/SKILL.md +0 -69
  196. package/plugins/codex/mcp.json +0 -10
  197. package/plugins/codex/plugin.json +0 -6
  198. package/plugins/paseo/client/markdown-core.tsx +0 -189
  199. package/plugins/paseo/client/typography.ts +0 -24
  200. package/skills/memory/SKILL.md +0 -69
@@ -1,12 +1,17 @@
1
1
  /** Recorded details live once, in the pageable event document; tools expose a small summary. */
2
2
  import { Type, type Static } from "typebox";
3
+ import { sliceCodePoints } from "../text-match.js";
4
+
5
+ export function stringEnum<const T extends readonly [string, ...string[]]>(values: T, options: Record<string, unknown> = {}) {
6
+ return Type.Unsafe<T[number]>({ ...Type.Enum([...values], options), type: "string" });
7
+ }
3
8
 
4
9
  /** The four public roles a history event carries on the wire, in presentation order. */
5
- export const HistoryRoleSchema = Type.Union([Type.Literal("user"), Type.Literal("assistant"), Type.Literal("tool"), Type.Literal("context")]);
10
+ export const HistoryRoleSchema = stringEnum(["user", "assistant", "tool", "context"]);
6
11
  export type HistoryRole = Static<typeof HistoryRoleSchema>;
7
12
 
8
13
  /** How a recorded tool run ended. A call with no recorded result has not ended. */
9
- export const ToolCallStatusSchema = Type.Union([Type.Literal("ok"), Type.Literal("error"), Type.Literal("unfinished")]);
14
+ export const ToolCallStatusSchema = stringEnum(["ok", "error", "unfinished"]);
10
15
  export type ToolCallStatus = Static<typeof ToolCallStatusSchema>;
11
16
 
12
17
  /** Internal recorded facts, not a second copy in the public read schema. */
@@ -47,7 +52,7 @@ export type HistoryWindow = { windowId: string; createdAt?: string; items: Histo
47
52
  export type HistoryProjection = { windows: HistoryWindow[]; highestSeq: number; branchSeqs: Set<number>; pairedResults: Map<number, number> };
48
53
  /** The filters one selection applies before paging: roles, seq bounds, and parsed epoch-ms time bounds. */
49
54
  export type HistoryBound = { seq: number } | { at: number };
50
- export type HistoryFilter = { roles?: HistoryRole[]; after?: HistoryBound; before?: HistoryBound };
55
+ export type HistoryFilter = { roles?: HistoryRole[]; after?: HistoryBound; before?: HistoryBound; since?: number; until?: number };
51
56
 
52
57
  /** Native entries after the adapter allocates seqs and selects the active branch. */
53
58
  export type DecodedHistoryItem = {
@@ -178,20 +183,10 @@ export function projectHistory(rawWindows: DecodedHistoryWindow[], highestSeq: n
178
183
  }
179
184
 
180
185
  /** Summary shared by list, search and read. Full arguments/calls are in the document. */
181
- export const NestedCallSummarySchema = Type.Object({
182
- call_count: Type.Integer({ minimum: 0 }),
183
- complete: Type.Boolean({ description: "true = every nested call was recorded." }),
184
- }, { additionalProperties: false });
185
-
186
- /** Tool-run facts shared by list rows and reads; full arguments and calls live in the document. */
187
- export const ToolSummarySchema = Type.Object({
188
- tool: Type.Optional(Type.String()),
189
- tool_status: Type.Optional(ToolCallStatusSchema),
190
- output_truncated: Type.Optional(Type.Literal(true)),
191
- full_output_path: Type.Optional(Type.String()),
192
- }, { additionalProperties: false });
193
-
194
- export function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchema> {
186
+ export type NestedCallSummary = { call_count: number; complete: boolean };
187
+ export type ToolSummary = { tool?: string; tool_status?: ToolCallStatus; output_truncated?: true; full_output_path?: string };
188
+
189
+ export function toolSummary(event: HistoryEvent): ToolSummary {
195
190
  const execution = event.execution;
196
191
  if (!execution) return {};
197
192
  return {
@@ -203,35 +198,20 @@ export function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchem
203
198
  }
204
199
 
205
200
  /** Nested-call evidence is read with one event, not listed on every page row. */
206
- export function nestedCallSummary(event: HistoryEvent): { nested_calls?: Static<typeof NestedCallSummarySchema> } {
201
+ export function nestedCallSummary(event: HistoryEvent): { nested_calls?: NestedCallSummary } {
207
202
  const nested = event.execution?.nestedCalls;
208
203
  return nested === undefined ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
209
204
  }
210
205
 
211
206
  /** A run of tool/context events the conversation view replaces with counts. */
212
- export const HistoryFoldedRowSchema = Type.Object({
213
- session: Type.Optional(Type.String()),
214
- first_seq: Type.Integer({ minimum: 1 }),
215
- last_seq: Type.Integer({ minimum: 1 }),
216
- count: Type.Integer({ minimum: 1 }),
217
- tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
218
- }, { additionalProperties: false });
219
- export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
207
+ export type HistoryFoldedRow = { first_seq: number; last_seq: number; count: number; tools: Record<string, number> };
220
208
 
221
209
  /** Stable identity and a verbatim preview, starting at the search match when present. */
222
- export const HistoryPageItemSchema = Type.Object({
223
- session: Type.Optional(Type.String()),
224
- folded_before: Type.Optional(HistoryFoldedRowSchema),
225
- context: Type.Optional(Type.Literal(true, { description: "A neighbor of a search hit, not a hit in this page." })),
226
- seq: Type.Integer({ minimum: 1 }),
227
- role: HistoryRoleSchema,
228
- created_at: Type.Union([Type.String(), Type.Null()]),
229
- ...ToolSummarySchema.properties,
230
- content: Type.String(),
231
- truncated: Type.Boolean({ description: "Preview is partial." }),
232
- offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Where the preview starts." })),
233
- }, { additionalProperties: false });
234
- export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
210
+ export type HistoryPageItem = ToolSummary & {
211
+ session?: string; folded_before?: HistoryFoldedRow; context?: true;
212
+ seq: number; role: HistoryRole; created_at: string | null;
213
+ content: string; truncated: boolean; offset_chars?: number;
214
+ };
235
215
 
236
216
  /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
237
217
  export const MAX_FOLD_TOOL_NAMES = 20;
@@ -242,17 +222,16 @@ export const MAX_FOLD_TOOL_NAME_CHARS = 120;
242
222
  /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
243
223
  export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?: number): HistoryPageItem {
244
224
  const document = eventDocument(event);
245
- const chars = Array.from(document);
246
225
  const start = matchOffset ?? 0;
247
226
  // A negative budget would cut the tail and still call the result a prefix.
248
227
  const limit = Math.max(0, maxChars);
249
- const truncated = start > 0 || start + limit < chars.length;
228
+ const { text: content, truncated } = sliceCodePoints(document, start, limit);
250
229
  return {
251
230
  seq: event.seq,
252
231
  role: event.role,
253
232
  created_at: event.createdAt ?? null,
254
233
  ...toolSummary(event),
255
- content: truncated ? chars.slice(start, start + limit).join("") : document,
234
+ content,
256
235
  truncated,
257
236
  ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
258
237
  };
@@ -262,12 +241,24 @@ export function allItems(projection: HistoryProjection): HistoryEvent[] {
262
241
  return projection.windows.flatMap((current) => current.items);
263
242
  }
264
243
 
244
+ const timestamps = new WeakMap<HistoryEvent, number>();
245
+
246
+ /** Memoized `Date.parse(event.createdAt)` (NaN when missing or invalid). */
247
+ export function eventTimestampMs(event: HistoryEvent): number {
248
+ const cached = timestamps.get(event);
249
+ if (cached !== undefined) return cached;
250
+ const parsed = event.createdAt ? Date.parse(event.createdAt) : NaN;
251
+ timestamps.set(event, parsed);
252
+ return parsed;
253
+ }
254
+
265
255
  function compareBound(event: HistoryEvent, bound: HistoryBound): number {
266
- return "seq" in bound ? event.seq - bound.seq : Date.parse(event.createdAt ?? "") - bound.at;
256
+ return "seq" in bound ? event.seq - bound.seq : eventTimestampMs(event) - bound.at;
267
257
  }
268
258
 
269
- export function matchesFilter(event: HistoryEvent, { after, before, roles }: HistoryFilter): boolean {
259
+ export function matchesFilter(event: HistoryEvent, { after, before, since, until, roles }: HistoryFilter): boolean {
270
260
  return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0)
261
+ && (since === undefined || eventTimestampMs(event) > since) && (until === undefined || eventTimestampMs(event) < until)
271
262
  && (!roles || roles.includes(event.role));
272
263
  }
273
264
 
@@ -1,14 +1,31 @@
1
1
  /** Local read-only corpus. Wire decoders have no SDK dependencies; DSH supplies its query service. */
2
- import { readdir, readFile, stat } from "node:fs/promises";
2
+ import { readdir, stat } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { piHistoryFromJsonl } from "./pi.js";
6
- import { offlineClaudeHistoryFromJsonl } from "./claude.js";
5
+ import { piHistoryFromFile } from "./pi.js";
6
+ import { offlineClaudeHistoryFromFile } from "./claude.js";
7
7
  import { readCodexHistory } from "./codex.js";
8
8
  import { createCodexTranscriptReader } from "./codex-transcript.js";
9
9
  import { createHistoryPrefilter, historyFileMayMatch, type HistoryPrefilter } from "./prefilter.js";
10
10
  import { sessionIdentity, type HistoryCorpus, type HistorySession } from "./corpus.js";
11
- import { cachedSessionRepresentative, historySummaryCacheRoot } from "./summary-cache.js";
11
+ import { cachedSessionSummary, historySummaryCacheRoot, peekCachedSessionSummary } from "./summary-cache.js";
12
+
13
+ const DIR_CONCURRENCY = 32;
14
+ const STAT_CONCURRENCY = 64;
15
+
16
+ async function mapConcurrent<T, R>(items: readonly T[], concurrency: number, fn: (item: T) => Promise<R>): Promise<R[]> {
17
+ if (items.length === 0) return [];
18
+ const results = new Array<R>(items.length);
19
+ let next = 0;
20
+ const workers = Math.min(concurrency, items.length);
21
+ await Promise.all(Array.from({ length: workers }, async () => {
22
+ while (next < items.length) {
23
+ const index = next++;
24
+ results[index] = await fn(items[index]!);
25
+ }
26
+ }));
27
+ return results;
28
+ }
12
29
 
13
30
  export type LocalHistoryRoots = Partial<Record<"pi" | "claude" | "codex", string | null>>;
14
31
  export type LocalHistoryOptions = {
@@ -38,31 +55,43 @@ async function filesAt(root: string, depth: number): Promise<string[]> {
38
55
  let entries;
39
56
  try { entries = await readdir(root, { withFileTypes: true }); }
40
57
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
41
- const paths: string[] = [];
42
- for (const entry of entries) {
43
- const path = join(root, entry.name);
44
- if (entry.isDirectory() && depth > 0) paths.push(...await filesAt(path, depth - 1));
45
- else if (entry.isFile() && depth === 0) paths.push(path);
58
+ if (depth === 0) {
59
+ const paths: string[] = [];
60
+ for (const entry of entries) if (entry.isFile()) paths.push(join(root, entry.name));
61
+ return paths;
46
62
  }
47
- return paths;
63
+ const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => join(root, entry.name));
64
+ const nested = await mapConcurrent(dirs, DIR_CONCURRENCY, (dir) => filesAt(dir, depth - 1));
65
+ return nested.flat();
48
66
  }
49
67
 
50
68
  async function localSessions(harness: "pi" | "claude" | "codex", root: string, cacheRoot: string, prefilters: WeakMap<readonly string[], HistoryPrefilter>): Promise<HistorySession[]> {
51
69
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
52
- const sessions: HistorySession[] = [];
70
+ const matched: Array<{ path: string; id: string }> = [];
53
71
  for (const path of paths) {
54
72
  const name = path.split(/[\\/]/).at(-1)!;
55
73
  const id = harness === "pi" ? /^.+_(.+)\.jsonl$/.exec(name)?.[1]
56
74
  : harness === "claude" ? /^(.+)\.jsonl$/.exec(name)?.[1]
57
75
  : /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/.exec(name)?.[1];
58
- if (!id) continue;
59
- let modifiedAt: number;
60
- try { modifiedAt = (await stat(path)).mtimeMs; }
61
- catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
62
- sessions.push({
76
+ if (id) matched.push({ path, id });
77
+ }
78
+ const statted = await mapConcurrent(matched, STAT_CONCURRENCY, async ({ path, id }) => {
79
+ try {
80
+ const info = await stat(path);
81
+ return { path, id, modifiedAt: info.mtimeMs, size: info.size };
82
+ } catch (error) {
83
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
84
+ throw error;
85
+ }
86
+ });
87
+ const sessions: HistorySession[] = [];
88
+ for (const entry of statted) {
89
+ if (!entry) continue;
90
+ const { path, id, modifiedAt, size } = entry;
91
+ const session: HistorySession = {
63
92
  harness, id, modifiedAt,
64
- async loadRepresentative() {
65
- return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
93
+ async loadSummary() {
94
+ return cachedSessionSummary(this, path, cacheRoot, async (track) => {
66
95
  if (harness === "codex") {
67
96
  const readBytes = createCodexTranscriptReader();
68
97
  const history = await readCodexHistory({ threadId: id, transcriptPath: path }, async (source, remaining) => {
@@ -76,6 +105,13 @@ async function localSessions(harness: "pi" | "claude" | "codex", root: string, c
76
105
  return { data };
77
106
  });
78
107
  },
108
+ async loadRepresentative() {
109
+ const { event, notice } = await this.loadSummary!();
110
+ return { event, notice };
111
+ },
112
+ async peekSummary() {
113
+ return peekCachedSessionSummary(this, path, cacheRoot);
114
+ },
79
115
  async load(queries) {
80
116
  if (queries?.length) {
81
117
  let prefilter = prefilters.get(queries);
@@ -83,13 +119,13 @@ async function localSessions(harness: "pi" | "claude" | "codex", root: string, c
83
119
  if (!await historyFileMayMatch(path, prefilter, harness === "codex")) return undefined;
84
120
  }
85
121
  if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
86
- const text = await readFile(path, "utf8");
87
- if (harness === "pi") return { projection: piHistoryFromJsonl(text, id) };
88
- const projection = offlineClaudeHistoryFromJsonl(text, id);
122
+ if (harness === "pi") return { projection: await piHistoryFromFile(path, id, size) };
123
+ const projection = await offlineClaudeHistoryFromFile(path, id, size);
89
124
  const missing = projection.missingAncestors;
90
125
  return { projection, ...(missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.\n\n` }) };
91
126
  },
92
- });
127
+ };
128
+ sessions.push(session);
93
129
  }
94
130
  return sessions;
95
131
  }
@@ -102,17 +138,21 @@ export function localHistoryCorpus(options: LocalHistoryOptions): HistoryCorpus
102
138
  const roots = rootsFor(options);
103
139
  const env = options.env ?? process.env;
104
140
  const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir(), env);
105
- const discovered: HistorySession[] = [];
106
141
  const prefilters = new WeakMap<readonly string[], HistoryPrefilter>();
142
+ const tasks: Array<Promise<HistorySession[]>> = [];
107
143
  for (const harness of ["pi", "claude", "codex"] as const) {
108
144
  if (onlyHarness !== undefined && onlyHarness !== harness) continue;
109
145
  const root = roots[harness];
110
- if (root != null) discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
146
+ if (root != null) tasks.push(localSessions(harness, root, cacheRoot, prefilters));
111
147
  }
112
- if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
113
- discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
148
+ if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh")) tasks.push(options.dshSessions());
149
+ const discovered = (await Promise.all(tasks)).flat();
114
150
  const unique = new Map<string, HistorySession>();
115
- for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
151
+ for (const session of discovered) {
152
+ const key = sessionIdentity(session);
153
+ const existing = unique.get(key);
154
+ if (!existing || session.modifiedAt > existing.modifiedAt) unique.set(key, session);
155
+ }
116
156
  const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
117
157
  if (onlyHarness === undefined || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
118
158
  return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
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() {