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
@@ -1,14 +1,30 @@
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 } from "./prefilter.js";
10
10
  import { sessionIdentity } from "./corpus.js";
11
- import { cachedSessionRepresentative, historySummaryCacheRoot } from "./summary-cache.js";
11
+ import { cachedSessionSummary, historySummaryCacheRoot, peekCachedSessionSummary } from "./summary-cache.js";
12
+ const DIR_CONCURRENCY = 32;
13
+ const STAT_CONCURRENCY = 64;
14
+ async function mapConcurrent(items, concurrency, fn) {
15
+ if (items.length === 0)
16
+ return [];
17
+ const results = new Array(items.length);
18
+ let next = 0;
19
+ const workers = Math.min(concurrency, items.length);
20
+ await Promise.all(Array.from({ length: workers }, async () => {
21
+ while (next < items.length) {
22
+ const index = next++;
23
+ results[index] = await fn(items[index]);
24
+ }
25
+ }));
26
+ return results;
27
+ }
12
28
  function rootsFor(options) {
13
29
  const env = options.env ?? process.env;
14
30
  const home = options.home ?? env.HOME ?? homedir();
@@ -29,39 +45,48 @@ async function filesAt(root, depth) {
29
45
  return [];
30
46
  throw error;
31
47
  }
32
- const paths = [];
33
- for (const entry of entries) {
34
- const path = join(root, entry.name);
35
- if (entry.isDirectory() && depth > 0)
36
- paths.push(...await filesAt(path, depth - 1));
37
- else if (entry.isFile() && depth === 0)
38
- paths.push(path);
48
+ if (depth === 0) {
49
+ const paths = [];
50
+ for (const entry of entries)
51
+ if (entry.isFile())
52
+ paths.push(join(root, entry.name));
53
+ return paths;
39
54
  }
40
- return paths;
55
+ const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => join(root, entry.name));
56
+ const nested = await mapConcurrent(dirs, DIR_CONCURRENCY, (dir) => filesAt(dir, depth - 1));
57
+ return nested.flat();
41
58
  }
42
59
  async function localSessions(harness, root, cacheRoot, prefilters) {
43
60
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
44
- const sessions = [];
61
+ const matched = [];
45
62
  for (const path of paths) {
46
63
  const name = path.split(/[\\/]/).at(-1);
47
64
  const id = harness === "pi" ? /^.+_(.+)\.jsonl$/.exec(name)?.[1]
48
65
  : harness === "claude" ? /^(.+)\.jsonl$/.exec(name)?.[1]
49
66
  : /^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];
50
- if (!id)
51
- continue;
52
- let modifiedAt;
67
+ if (id)
68
+ matched.push({ path, id });
69
+ }
70
+ const statted = await mapConcurrent(matched, STAT_CONCURRENCY, async ({ path, id }) => {
53
71
  try {
54
- modifiedAt = (await stat(path)).mtimeMs;
72
+ const info = await stat(path);
73
+ return { path, id, modifiedAt: info.mtimeMs, size: info.size };
55
74
  }
56
75
  catch (error) {
57
76
  if (error.code === "ENOENT")
58
- continue;
77
+ return undefined;
59
78
  throw error;
60
79
  }
61
- sessions.push({
80
+ });
81
+ const sessions = [];
82
+ for (const entry of statted) {
83
+ if (!entry)
84
+ continue;
85
+ const { path, id, modifiedAt, size } = entry;
86
+ const session = {
62
87
  harness, id, modifiedAt,
63
- async loadRepresentative() {
64
- return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
88
+ async loadSummary() {
89
+ return cachedSessionSummary(this, path, cacheRoot, async (track) => {
65
90
  if (harness === "codex") {
66
91
  const readBytes = createCodexTranscriptReader();
67
92
  const history = await readCodexHistory({ threadId: id, transcriptPath: path }, async (source, remaining) => {
@@ -76,6 +101,13 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
76
101
  return { data };
77
102
  });
78
103
  },
104
+ async loadRepresentative() {
105
+ const { event, notice } = await this.loadSummary();
106
+ return { event, notice };
107
+ },
108
+ async peekSummary() {
109
+ return peekCachedSessionSummary(this, path, cacheRoot);
110
+ },
79
111
  async load(queries) {
80
112
  if (queries?.length) {
81
113
  let prefilter = prefilters.get(queries);
@@ -86,14 +118,14 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
86
118
  }
87
119
  if (harness === "codex")
88
120
  return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
89
- const text = await readFile(path, "utf8");
90
121
  if (harness === "pi")
91
- return { projection: piHistoryFromJsonl(text, id) };
92
- const projection = offlineClaudeHistoryFromJsonl(text, id);
122
+ return { projection: await piHistoryFromFile(path, id, size) };
123
+ const projection = await offlineClaudeHistoryFromFile(path, id, size);
93
124
  const missing = projection.missingAncestors;
94
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` }) };
95
126
  },
96
- });
127
+ };
128
+ sessions.push(session);
97
129
  }
98
130
  return sessions;
99
131
  }
@@ -105,22 +137,25 @@ export function localHistoryCorpus(options) {
105
137
  const roots = rootsFor(options);
106
138
  const env = options.env ?? process.env;
107
139
  const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir(), env);
108
- const discovered = [];
109
140
  const prefilters = new WeakMap();
141
+ const tasks = [];
110
142
  for (const harness of ["pi", "claude", "codex"]) {
111
143
  if (onlyHarness !== undefined && onlyHarness !== harness)
112
144
  continue;
113
145
  const root = roots[harness];
114
146
  if (root != null)
115
- discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
147
+ tasks.push(localSessions(harness, root, cacheRoot, prefilters));
116
148
  }
117
149
  if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh"))
118
- discovered.push(...await options.dshSessions());
119
- discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
150
+ tasks.push(options.dshSessions());
151
+ const discovered = (await Promise.all(tasks)).flat();
120
152
  const unique = new Map();
121
- for (const session of discovered)
122
- if (!unique.has(sessionIdentity(session)))
123
- unique.set(sessionIdentity(session), session);
153
+ for (const session of discovered) {
154
+ const key = sessionIdentity(session);
155
+ const existing = unique.get(key);
156
+ if (!existing || session.modifiedAt > existing.modifiedAt)
157
+ unique.set(key, session);
158
+ }
124
159
  const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
125
160
  if (onlyHarness === undefined || onlyHarness === current.harness)
126
161
  unique.set(sessionIdentity(current), current);
@@ -1,4 +1,3 @@
1
- /** Pi's persisted entry/message wire format, independent of the Pi SDK. */
2
1
  import { type HistoryProjection, type RecordedNestedCalls } from "./history.js";
3
2
  /** Structural views also accept native SDK values without converting or allocating seqs twice. */
4
3
  type Message = {
@@ -33,4 +32,6 @@ export declare function piSequenceCount(entry: Pick<PiHistoryEntry, "type" | "me
33
32
  export declare function piHistoryFromEntries(sessionId: string, entries: readonly PiHistoryEntry[], branch: readonly PiHistoryEntry[]): HistoryProjection;
34
33
  /** Offline files persist append order and parent links; select the final tree entry's ancestry. */
35
34
  export declare function piHistoryFromJsonl(text: string, sessionId: string): HistoryProjection;
35
+ /** Stream oversized Pi JSONL files line-by-line so >512 MiB transcripts never hit V8's string limit. */
36
+ export declare function piHistoryFromFile(path: string, sessionId: string, sizeHint?: number): Promise<HistoryProjection>;
36
37
  export {};
@@ -1,5 +1,9 @@
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 } from "./history.js";
6
+ const STREAM_FILE_BYTES = 64 * 1024 * 1024;
3
7
  function mapRole(role) {
4
8
  if (role === "user" || role === "assistant")
5
9
  return role;
@@ -144,59 +148,129 @@ export function piHistoryFromEntries(sessionId, entries, branch) {
144
148
  }
145
149
  return projectHistory(rawWindows, highestSeq, branchSeqs);
146
150
  }
151
+ function slimMessage(message) {
152
+ let content = message.content;
153
+ if (Array.isArray(content)) {
154
+ content = content.filter((part) => (typeof part === "object" && part !== null && (part.type === "text" || part.type === "toolCall")));
155
+ }
156
+ return {
157
+ role: message.role,
158
+ ...(content === undefined ? {} : { content }),
159
+ ...(message.output === undefined ? {} : { output: message.output }),
160
+ ...(message.summary === undefined ? {} : { summary: message.summary }),
161
+ ...(message.command === undefined ? {} : { command: message.command }),
162
+ ...(message.cancelled === undefined ? {} : { cancelled: message.cancelled }),
163
+ ...(message.exitCode === undefined ? {} : { exitCode: message.exitCode }),
164
+ ...(message.truncated === undefined ? {} : { truncated: message.truncated }),
165
+ ...(message.fullOutputPath === undefined ? {} : { fullOutputPath: message.fullOutputPath }),
166
+ ...(message.toolName === undefined ? {} : { toolName: message.toolName }),
167
+ ...(message.toolCallId === undefined ? {} : { toolCallId: message.toolCallId }),
168
+ ...(message.isError === undefined ? {} : { isError: message.isError }),
169
+ ...(message.nestedCalls === undefined ? {} : { nestedCalls: message.nestedCalls }),
170
+ };
171
+ }
172
+ function slimEntry(row) {
173
+ return {
174
+ type: row.type,
175
+ id: row.id,
176
+ parentId: row.parentId,
177
+ ...(row.timestamp === undefined ? {} : { timestamp: row.timestamp }),
178
+ ...(row.summary === undefined ? {} : { summary: row.summary }),
179
+ ...(row.customType === undefined ? {} : { customType: row.customType }),
180
+ ...(row.customType === "notesoup/reset-marker" && row.data !== undefined ? { data: row.data } : {}),
181
+ ...(row.type === "custom_message" && row.content !== undefined ? { content: contentText(row.content) } : {}),
182
+ ...(row.type === "message" && row.message ? { message: slimMessage(row.message) } : {}),
183
+ };
184
+ }
185
+ function createPiJsonlParser(sessionId) {
186
+ const entries = [];
187
+ let header = false;
188
+ return {
189
+ push(line, lineNumber, allowIncompleteTail) {
190
+ if (line.trim() === "")
191
+ return;
192
+ let row;
193
+ try {
194
+ row = JSON.parse(line);
195
+ }
196
+ catch {
197
+ if (allowIncompleteTail)
198
+ return;
199
+ throw new Error(`malformed Pi transcript JSON at line ${lineNumber}`);
200
+ }
201
+ if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string")
202
+ throw new Error("invalid Pi transcript entry");
203
+ if (!header) {
204
+ if (row.type !== "session" || row.id !== sessionId)
205
+ throw new Error("Pi transcript belongs to a different session or has no header");
206
+ header = true;
207
+ return;
208
+ }
209
+ if (row.parentId !== null && typeof row.parentId !== "string")
210
+ throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
211
+ if (row.type === "message" && (!row.message || typeof row.message.role !== "string"))
212
+ throw new Error("invalid Pi transcript message");
213
+ entries.push(slimEntry(row));
214
+ },
215
+ finish() {
216
+ if (!header)
217
+ throw new Error("Pi transcript has no session header");
218
+ const byId = new Map();
219
+ for (const entry of entries) {
220
+ if (byId.has(entry.id))
221
+ throw new Error(`duplicate Pi entry ID: ${entry.id}`);
222
+ byId.set(entry.id, entry);
223
+ }
224
+ const branch = [], seen = new Set();
225
+ let cursor = entries.at(-1);
226
+ while (cursor) {
227
+ if (seen.has(cursor.id))
228
+ throw new Error("cyclic Pi transcript ancestry");
229
+ seen.add(cursor.id);
230
+ branch.push(cursor);
231
+ if (cursor.parentId === null)
232
+ break;
233
+ const parent = byId.get(cursor.parentId);
234
+ if (!parent)
235
+ throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
236
+ cursor = parent;
237
+ }
238
+ return piHistoryFromEntries(sessionId, entries, branch.reverse());
239
+ },
240
+ };
241
+ }
147
242
  /** Offline files persist append order and parent links; select the final tree entry's ancestry. */
148
243
  export function piHistoryFromJsonl(text, sessionId) {
149
244
  const lines = text.split("\n");
150
- const entries = [];
151
- let header = false;
245
+ const parser = createPiJsonlParser(sessionId);
152
246
  for (let index = 0; index < lines.length; index++) {
153
- const line = lines[index];
154
- if (line.trim() === "")
155
- continue;
156
- let row;
157
- try {
158
- row = JSON.parse(line);
159
- }
160
- catch {
161
- if (index === lines.length - 1 && !text.endsWith("\n"))
162
- break;
163
- throw new Error(`malformed Pi transcript JSON at line ${index + 1}`);
164
- }
165
- if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string")
166
- throw new Error("invalid Pi transcript entry");
167
- if (!header) {
168
- if (row.type !== "session" || row.id !== sessionId)
169
- throw new Error("Pi transcript belongs to a different session or has no header");
170
- header = true;
171
- continue;
172
- }
173
- if (row.parentId !== null && typeof row.parentId !== "string")
174
- throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
175
- if (row.type === "message" && (!row.message || typeof row.message.role !== "string"))
176
- throw new Error("invalid Pi transcript message");
177
- entries.push(row);
247
+ parser.push(lines[index], index + 1, index === lines.length - 1 && !text.endsWith("\n"));
178
248
  }
179
- if (!header)
180
- throw new Error("Pi transcript has no session header");
181
- const byId = new Map();
182
- for (const entry of entries) {
183
- if (byId.has(entry.id))
184
- throw new Error(`duplicate Pi entry ID: ${entry.id}`);
185
- byId.set(entry.id, entry);
249
+ return parser.finish();
250
+ }
251
+ /** Stream oversized Pi JSONL files line-by-line so >512 MiB transcripts never hit V8's string limit. */
252
+ export async function piHistoryFromFile(path, sessionId, sizeHint) {
253
+ const size = sizeHint ?? (await stat(path)).size;
254
+ if (size < STREAM_FILE_BYTES)
255
+ return piHistoryFromJsonl(await readFile(path, "utf8"), sessionId);
256
+ const parser = createPiJsonlParser(sessionId);
257
+ const decoder = new StringDecoder("utf8");
258
+ let remainder = "";
259
+ let lineNumber = 0;
260
+ for await (const chunk of createReadStream(path, { highWaterMark: 1024 * 1024 })) {
261
+ const text = remainder + decoder.write(chunk);
262
+ let start = 0;
263
+ for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
264
+ lineNumber++;
265
+ parser.push(text.slice(start, nl), lineNumber, false);
266
+ start = nl + 1;
267
+ }
268
+ remainder = text.slice(start);
186
269
  }
187
- const branch = [], seen = new Set();
188
- let cursor = entries.at(-1);
189
- while (cursor) {
190
- if (seen.has(cursor.id))
191
- throw new Error("cyclic Pi transcript ancestry");
192
- seen.add(cursor.id);
193
- branch.push(cursor);
194
- if (cursor.parentId === null)
195
- break;
196
- const parent = byId.get(cursor.parentId);
197
- if (!parent)
198
- throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
199
- cursor = parent;
270
+ remainder += decoder.end();
271
+ if (remainder.length > 0) {
272
+ lineNumber++;
273
+ parser.push(remainder, lineNumber, true);
200
274
  }
201
- return piHistoryFromEntries(sessionId, entries, branch.reverse());
275
+ return parser.finish();
202
276
  }
@@ -12,6 +12,69 @@ const PRESENTATION = `Codex unknown arguments not recorded output nested calls c
12
12
  FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
13
13
  the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
14
14
  const HISTORY_BASE = '"history_base"';
15
+ const STREAM_HIGH_WATER_MARK = 256 * 1024;
16
+ function isHex(code) {
17
+ return (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102);
18
+ }
19
+ /** Linear-time one-pass `\uXXXX` decoder: skips non-`\u` backslashes and bounds any trailing run to <= 6 chars. */
20
+ function decodeEscapes(source, final) {
21
+ const len = source.length;
22
+ let pending = "";
23
+ let limit = len;
24
+ if (!final && len > 0) {
25
+ let end = len;
26
+ let hexCount = 0;
27
+ while (end > 0 && hexCount < 3 && isHex(source.charCodeAt(end - 1))) {
28
+ end--;
29
+ hexCount++;
30
+ }
31
+ if (end >= 2 && source.charCodeAt(end - 1) === 117 && source.charCodeAt(end - 2) === 92) {
32
+ let slashStart = end - 2;
33
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92)
34
+ slashStart--;
35
+ pending = `\\u${source.slice(end, len)}`;
36
+ limit = slashStart;
37
+ }
38
+ else if (source.charCodeAt(len - 1) === 92) {
39
+ let slashStart = len - 1;
40
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92)
41
+ slashStart--;
42
+ pending = "\\";
43
+ limit = slashStart;
44
+ }
45
+ }
46
+ if (limit < 6) {
47
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
48
+ }
49
+ let pos = source.indexOf("\\u");
50
+ if (pos < 0 || pos >= limit) {
51
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
52
+ }
53
+ let out = "";
54
+ let cursor = 0;
55
+ while (pos >= 0 && pos < limit) {
56
+ if (pos + 6 <= limit
57
+ && isHex(source.charCodeAt(pos + 2))
58
+ && isHex(source.charCodeAt(pos + 3))
59
+ && isHex(source.charCodeAt(pos + 4))
60
+ && isHex(source.charCodeAt(pos + 5))) {
61
+ let slashStart = pos;
62
+ while (slashStart > cursor && source.charCodeAt(slashStart - 1) === 92)
63
+ slashStart--;
64
+ if (slashStart > cursor)
65
+ out += source.slice(cursor, slashStart);
66
+ out += String.fromCharCode(Number.parseInt(source.slice(pos + 2, pos + 6), 16));
67
+ cursor = pos + 6;
68
+ pos = source.indexOf("\\u", cursor);
69
+ }
70
+ else {
71
+ pos = source.indexOf("\\u", pos + 2);
72
+ }
73
+ }
74
+ if (cursor < limit)
75
+ out += source.slice(cursor, limit);
76
+ return { decoded: out, pending };
77
+ }
15
78
  /** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
16
79
  export function createHistoryPrefilter(queries) {
17
80
  let overlap = HISTORY_BASE.length;
@@ -28,24 +91,18 @@ export function createHistoryPrefilter(queries) {
28
91
  const decoder = new StringDecoder("utf8");
29
92
  const seen = alternatives.map((tokens) => tokens.map(() => false));
30
93
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
31
- // Unlike /\\+u(hex{4})/, this cannot backtrack quadratically over a long invalid run.
32
- const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
33
94
  const scan = (chunk, final = false) => {
34
- const raw = rawTail + chunk, source = pending + chunk;
35
- const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
36
- pending = "";
37
- const decoded = needsNormalization ? source.replace(escapes, (match, hex, offset) => {
38
- if (hex?.length === 4)
39
- return String.fromCharCode(Number.parseInt(hex, 16));
40
- // Tokens cannot include backslashes: an unresolved run needs only one separator,
41
- // plus at most 'u' and three hex digits, even if it spans arbitrarily many chunks.
42
- const literal = hex === undefined ? "\\" : `\\u${hex}`;
43
- if (!final && offset + match.length === source.length) {
44
- pending = literal;
45
- return "";
46
- }
47
- return literal;
48
- }) : chunk;
95
+ const raw = rawTail + chunk;
96
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || (!final && chunk.endsWith("\\"));
97
+ let decoded = chunk;
98
+ if (needsNormalization) {
99
+ const result = decodeEscapes(pending + chunk, final);
100
+ decoded = result.decoded;
101
+ pending = result.pending;
102
+ }
103
+ else {
104
+ pending = "";
105
+ }
49
106
  const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
50
107
  if (codex && raw.includes(HISTORY_BASE))
51
108
  possible = true;
@@ -75,7 +132,7 @@ export async function historyFileMayMatch(path, prefilter, codex = false, maxByt
75
132
  // Plain Pi/Claude files will be read and validated by the strict decoder on a possible
76
133
  // hit. Don't drain a potentially huge file just to read it from the beginning again.
77
134
  if (!codex)
78
- return prefilter(createReadStream(path), false, true);
135
+ return prefilter(createReadStream(path, { highWaterMark: STREAM_HIGH_WATER_MARK }), false, true);
79
136
  const info = await stat(path);
80
137
  if (!info.isFile() || info.size > maxBytes)
81
138
  throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
@@ -83,7 +140,7 @@ export async function historyFileMayMatch(path, prefilter, codex = false, maxByt
83
140
  const compressed = path.endsWith(".jsonl.zst");
84
141
  if (compressed && typeof zlib.createZstdDecompress !== "function")
85
142
  throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
86
- const input = createReadStream(path);
143
+ const input = createReadStream(path, { highWaterMark: STREAM_HIGH_WATER_MARK });
87
144
  const consume = async (chunks) => {
88
145
  let size = 0;
89
146
  async function* bounded() {
@@ -1,59 +1,36 @@
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 { type Outcome } from "../result.js";
4
- import { type HistoryEvent, type HistoryFilter, type HistoryProjection } from "./history.js";
5
- export declare function isMultiPage(page: HistoryPage): boolean;
6
- export declare function markMultiPage(page: HistoryPage): HistoryPage;
7
- export type HistorySelection = HistoryFilter & {
8
- session?: string;
3
+ import { type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection, type HistoryRole } from "./history.js";
4
+ type TimelineSelection = HistoryFilter & {
9
5
  limit?: number;
6
+ };
7
+ export type HistorySelection = TimelineSelection & {
10
8
  query?: string[];
11
9
  context?: number;
12
10
  };
13
- export declare const HistoryPageSchema: Type.TObject<{
14
- notice: Type.TOptional<Type.TString>;
15
- items: Type.TArray<Type.TObject<{
16
- content: Type.TString;
17
- truncated: Type.TBoolean;
18
- offset_chars: Type.TOptional<Type.TInteger>;
19
- tool: Type.TOptional<Type.TString>;
20
- tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
21
- output_truncated: Type.TOptional<Type.TLiteral<true>>;
22
- full_output_path: Type.TOptional<Type.TString>;
23
- session: Type.TOptional<Type.TString>;
24
- folded_before: Type.TOptional<Type.TObject<{
25
- session: Type.TOptional<Type.TString>;
26
- first_seq: Type.TInteger;
27
- last_seq: Type.TInteger;
28
- count: Type.TInteger;
29
- tools: Type.TRecord<"^.*$", Type.TInteger>;
30
- }>>;
31
- context: Type.TOptional<Type.TLiteral<true>>;
32
- seq: Type.TInteger;
33
- role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
34
- created_at: Type.TUnion<[Type.TString, Type.TNull]>;
35
- }>>;
36
- folded_after: Type.TOptional<Type.TObject<{
37
- session: Type.TOptional<Type.TString>;
38
- first_seq: Type.TInteger;
39
- last_seq: Type.TInteger;
40
- count: Type.TInteger;
41
- tools: Type.TRecord<"^.*$", Type.TInteger>;
42
- }>>;
43
- has_older: Type.TBoolean;
44
- has_newer: Type.TBoolean;
45
- }>;
46
11
  /** One whole page payload, before it becomes an outcome. */
47
- export type HistoryPage = Static<typeof HistoryPageSchema>;
12
+ export type HistoryPage = {
13
+ notice?: string;
14
+ items: HistoryPageItem[];
15
+ folded_after?: HistoryFoldedRow;
16
+ has_older: boolean;
17
+ has_newer: boolean;
18
+ };
48
19
  /** A caller's budget rejected even the shortest page; tool limits and refusal copy belong to the caller. */
49
20
  export type HistoryPageResult = Outcome<HistoryPage> | {
50
21
  ok: false;
51
- pageTooLarge: {
52
- count: number;
53
- multi: boolean;
54
- };
22
+ pageTooLarge: true;
23
+ };
24
+ export declare function selectPage(projection: HistoryProjection, params: TimelineSelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult;
25
+ /** Strict single-pass overview summary: default representative, latest per role, and exact time span. */
26
+ export type ProjectionSummary = {
27
+ event: HistoryEvent | undefined;
28
+ latestByRole: Partial<Record<HistoryRole, HistoryEvent>>;
29
+ minCreatedAt: number | null;
30
+ maxCreatedAt: number | null;
31
+ hasUntimed: boolean;
55
32
  };
56
- export declare function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): HistoryPageResult;
33
+ export declare function summarizeProjection(projection: HistoryProjection): ProjectionSummary;
57
34
  /** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
58
35
  export declare function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined;
59
36
  /** Keep only the requested end of the globally ordered selection while sessions are released. */
@@ -61,12 +38,14 @@ export declare class CorpusCollector {
61
38
  private readonly scoped;
62
39
  private readonly candidates;
63
40
  private readonly limit;
41
+ private readonly compiledQuery;
64
42
  private discarded;
65
43
  constructor(scoped: HistorySelection);
66
44
  private admit;
67
- /** Admit an already selected strict overview event without selecting it a second time. */
68
- addRepresentative(session: string, event: HistoryEvent | undefined): boolean;
69
- /** Returns whether this session contributes an overview representative. */
70
- add(session: string, projection: HistoryProjection): boolean;
45
+ /** Admit a session's overview representative (pre-selected or picked from a projection). */
46
+ addRepresentative(session: string, source: HistoryEvent | HistoryProjection | undefined): boolean;
47
+ /** Admit every query match from one session; an empty query matches nothing. */
48
+ addMatches(session: string, projection: HistoryProjection): void;
71
49
  page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited?: boolean): HistoryPageResult;
72
50
  }
51
+ export {};