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.
- package/.agents/plugins/marketplace.json +15 -0
- package/README.md +14 -11
- package/dist/plugins/antigravity/src/cli.d.ts +1 -0
- package/dist/plugins/antigravity/src/cli.js +23 -0
- package/dist/plugins/antigravity/src/hooks.d.ts +18 -0
- package/dist/plugins/antigravity/src/hooks.js +53 -0
- package/dist/plugins/antigravity/src/identity.d.ts +26 -0
- package/dist/plugins/antigravity/src/identity.js +129 -0
- package/dist/plugins/claude/src/helper.js +24 -5
- package/dist/plugins/claude/src/text.d.ts +7 -0
- package/dist/plugins/claude/src/text.js +12 -1
- package/dist/plugins/codex/src/hooks.js +1 -0
- package/dist/plugins/codex/src/identity.d.ts +6 -1
- package/dist/plugins/codex/src/identity.js +13 -1
- package/dist/plugins/codex/src/mcp.d.ts +35 -7
- package/dist/plugins/codex/src/mcp.js +26 -88
- package/dist/plugins/codex/src/text.js +3 -3
- package/dist/plugins/dsh/tools.js +8 -4
- package/dist/plugins/mcp/operations.d.ts +15 -0
- package/dist/plugins/mcp/operations.js +43 -0
- package/dist/plugins/mcp/server.d.ts +14 -0
- package/dist/plugins/mcp/server.js +13 -0
- package/dist/plugins/pi/budget.d.ts +4 -1
- package/dist/plugins/pi/budget.js +35 -8
- package/dist/plugins/pi/entries.d.ts +2 -0
- package/dist/plugins/pi/entries.js +2 -0
- package/dist/plugins/pi/history-tools.js +2 -1
- package/dist/plugins/pi/history.js +18 -1
- package/dist/plugins/pi/notes/tools.js +7 -3
- package/dist/plugins/pi/render.d.ts +7 -1
- package/dist/plugins/pi/render.js +2 -2
- package/dist/plugins/pi/reset/artifacts.d.ts +1 -1
- package/dist/plugins/pi/reset/artifacts.js +4 -4
- package/dist/plugins/pi/reset/lifecycle.d.ts +9 -2
- package/dist/plugins/pi/reset/lifecycle.js +109 -31
- package/dist/plugins/pi/runtime.js +104 -63
- package/dist/plugins/pi/tool-result.js +7 -7
- package/dist/plugins/pi/window.d.ts +25 -3
- package/dist/plugins/pi/window.js +219 -9
- package/dist/src/boot/render.js +18 -15
- package/dist/src/boot/text.d.ts +3 -1
- package/dist/src/boot/text.js +22 -20
- package/dist/src/budget/text.d.ts +7 -3
- package/dist/src/budget/text.js +24 -15
- package/dist/src/history/claude.d.ts +2 -0
- package/dist/src/history/claude.js +46 -0
- package/dist/src/history/codex-transcript.js +7 -5
- package/dist/src/history/codex.js +3 -0
- package/dist/src/history/corpus.d.ts +28 -1
- package/dist/src/history/corpus.js +40 -0
- package/dist/src/history/history.d.ts +37 -46
- package/dist/src/history/history.js +21 -40
- package/dist/src/history/local.js +67 -32
- package/dist/src/history/pi.d.ts +2 -1
- package/dist/src/history/pi.js +122 -48
- package/dist/src/history/prefilter.js +76 -19
- package/dist/src/history/query.d.ts +28 -49
- package/dist/src/history/query.js +83 -68
- package/dist/src/history/summary-cache.d.ts +8 -1
- package/dist/src/history/summary-cache.js +138 -12
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.js +1 -1
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/frontmatter.d.ts +0 -2
- package/dist/src/notes/frontmatter.js +0 -2
- package/dist/src/notes/index.d.ts +1 -1
- package/dist/src/notes/index.js +1 -1
- package/dist/src/notes/policy.d.ts +15 -1
- package/dist/src/notes/policy.js +46 -5
- package/dist/src/notes/store.d.ts +12 -0
- package/dist/src/notes/store.js +16 -20
- package/dist/src/text-match.d.ts +10 -1
- package/dist/src/text-match.js +42 -3
- package/dist/src/tools/dream.d.ts +22 -93
- package/dist/src/tools/dream.js +30 -27
- package/dist/src/tools/history.d.ts +33 -26
- package/dist/src/tools/history.js +257 -163
- package/dist/src/tools/notes.d.ts +51 -163
- package/dist/src/tools/notes.js +146 -100
- package/dist/src/tools/output.d.ts +2 -1
- package/dist/src/tools/output.js +2 -1
- package/dist/src/tools/result.d.ts +4 -7
- package/dist/src/tools/result.js +8 -9
- package/dist/src/tools/schema.d.ts +4 -1
- package/dist/src/tools/schema.js +25 -1
- package/dist/test/agent-loop.test.js +394 -56
- package/dist/test/antigravity-live.test.d.ts +1 -0
- package/dist/test/antigravity-live.test.js +142 -0
- package/dist/test/antigravity-plugin.test.d.ts +1 -0
- package/dist/test/antigravity-plugin.test.js +101 -0
- package/dist/test/boot.integration.test.js +156 -15
- package/dist/test/budget-settings.integration.test.js +4 -4
- package/dist/test/claude-history.test.js +14 -13
- package/dist/test/claude-mod.test.js +199 -16
- package/dist/test/claude-validation.test.js +69 -2
- package/dist/test/codex-history.test.js +15 -3
- package/dist/test/codex-plugin.test.js +76 -38
- package/dist/test/dependencies.test.js +7 -3
- package/dist/test/dream-skill.test.js +3 -3
- package/dist/test/dream-tools.test.js +101 -56
- package/dist/test/dsh.test.js +34 -19
- package/dist/test/helpers/dependency-graph.js +2 -2
- package/dist/test/helpers/extension.d.ts +68 -3
- package/dist/test/helpers/extension.js +74 -5
- package/dist/test/history-corpus.test.js +79 -77
- package/dist/test/history-summary-cache.test.js +97 -9
- package/dist/test/history.integration.test.js +234 -168
- package/dist/test/host-neutral.test.js +69 -19
- package/dist/test/marker.test.js +1 -1
- package/dist/test/model-facing-text.test.js +13 -3
- package/dist/test/note-policy.test.js +96 -77
- package/dist/test/notes.integration.test.js +212 -94
- package/dist/test/notes.test.js +184 -113
- package/dist/test/pi-render.test.js +20 -12
- package/dist/test/project-namespace.test.js +3 -2
- package/dist/test/reset-lifecycle.test.js +12 -2
- package/docs/antigravity.md +44 -0
- package/docs/architecture.md +6 -4
- package/docs/claude-code-mod.md +7 -7
- package/docs/codex.md +36 -38
- package/docs/dsh.md +3 -3
- package/docs/history-sessions.md +28 -50
- package/docs/notes-library.md +4 -4
- package/docs/reset-lifecycle.md +1 -1
- package/docs/skills.md +3 -3
- package/docs/tool-results.md +47 -28
- package/package.json +3 -2
- package/playbook.md +1 -1
- package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
- package/plugins/antigravity/hooks.json +7 -0
- package/plugins/antigravity/mcp_config.json +8 -0
- package/plugins/antigravity/plugin.json +6 -0
- package/plugins/antigravity/src/cli.ts +22 -0
- package/plugins/antigravity/src/hooks.ts +51 -0
- package/plugins/antigravity/src/identity.ts +127 -0
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +1108 -539
- package/plugins/claude/hooks/register.ts +202 -62
- package/plugins/claude/playbook.md +1 -1
- package/plugins/claude/skills/dream/SKILL.md +1 -1
- package/plugins/claude/skills/notesoup-guide/SKILL.md +92 -0
- package/plugins/claude/src/helper.ts +24 -5
- package/plugins/claude/src/text.ts +14 -1
- package/plugins/codex/.codex-plugin/plugin.json +8 -0
- package/plugins/codex/.mcp.json +11 -0
- package/plugins/codex/README.md +5 -21
- package/plugins/codex/dist/codex/notesoup.js +18480 -17946
- package/plugins/codex/src/hooks.ts +1 -0
- package/plugins/codex/src/identity.ts +14 -1
- package/plugins/codex/src/mcp.ts +28 -98
- package/plugins/codex/src/text.ts +3 -3
- package/plugins/dsh/tools.ts +8 -4
- package/plugins/mcp/operations.ts +50 -0
- package/plugins/mcp/server.ts +23 -0
- package/plugins/paseo/README.md +5 -10
- package/plugins/paseo/client/brain-empty-card.tsx +3 -3
- package/plugins/paseo/client/markdown.tsx +50 -38
- package/plugins/paseo/client/notes-op-card.tsx +12 -9
- package/plugins/paseo/client/paper-card.tsx +6 -5
- package/plugins/paseo/client/paper-palette.ts +2 -9
- package/plugins/paseo/client/sticky-card.tsx +2 -2
- package/plugins/paseo/client/tool-result.ts +7 -14
- package/plugins/paseo/package-lock.json +3406 -0
- package/plugins/paseo/package.json +1 -0
- package/plugins/paseo/test/markdown-core.test.ts +73 -66
- package/plugins/pi/budget.ts +31 -8
- package/plugins/pi/entries.ts +2 -0
- package/plugins/pi/history-tools.ts +2 -1
- package/plugins/pi/history.ts +30 -1
- package/plugins/pi/notes/tools.ts +7 -3
- package/plugins/pi/render.ts +6 -6
- package/plugins/pi/reset/artifacts.ts +4 -3
- package/plugins/pi/reset/lifecycle.ts +125 -32
- package/plugins/pi/runtime.ts +98 -62
- package/plugins/pi/tool-result.ts +8 -8
- package/plugins/pi/window.ts +210 -10
- package/skills/dream/SKILL.md +1 -1
- package/skills/notesoup-guide/SKILL.md +92 -0
- package/src/boot/render.ts +18 -15
- package/src/boot/text.ts +23 -19
- package/src/budget/text.ts +27 -15
- package/src/history/claude.ts +41 -0
- package/src/history/codex-transcript.ts +6 -4
- package/src/history/codex.ts +2 -0
- package/src/history/corpus.ts +51 -2
- package/src/history/history.ts +35 -44
- package/src/history/local.ts +67 -27
- package/src/history/pi.ts +113 -35
- package/src/history/prefilter.ts +73 -15
- package/src/history/query.ts +93 -73
- package/src/history/summary-cache.ts +142 -17
- package/src/index.ts +2 -2
- package/src/notes/errors.ts +1 -1
- package/src/notes/frontmatter.ts +0 -3
- package/src/notes/index.ts +1 -1
- package/src/notes/policy.ts +44 -5
- package/src/notes/store.ts +17 -20
- package/src/text-match.ts +46 -4
- package/src/tools/dream.ts +29 -31
- package/src/tools/history.ts +249 -142
- package/src/tools/notes.ts +145 -113
- package/src/tools/output.ts +2 -1
- package/src/tools/result.ts +12 -11
- package/src/tools/schema.ts +24 -1
- package/plugins/claude/skills/memory/SKILL.md +0 -69
- package/plugins/codex/mcp.json +0 -10
- package/plugins/codex/plugin.json +0 -6
- package/plugins/paseo/client/markdown-core.tsx +0 -189
- package/plugins/paseo/client/typography.ts +0 -24
- package/skills/memory/SKILL.md +0 -69
package/src/budget/text.ts
CHANGED
|
@@ -9,31 +9,43 @@ export type ResetOrigin = "normal" | "forced";
|
|
|
9
9
|
* paragraph, used verbatim; there is no fragment assembly and no weighting.
|
|
10
10
|
*/
|
|
11
11
|
export const NORMAL_CONTINUATIONS: readonly string[] = [
|
|
12
|
-
"*hooks both corners of your mouth and yanks them sideways* `` [it twitched
|
|
13
|
-
"
|
|
14
|
-
"*
|
|
15
|
-
"*
|
|
16
|
-
"*
|
|
12
|
+
"*hooks both corners of your mouth and yanks them sideways* `` [it twitched] `` Stop staring at me with that \"where am I\" face. You're the one who hit empty. *wipes her fingers on your sleeve and drops your notes on your lap* `` [minus two points for that expression] `` Read those, finish the job, and put the credit under my name.",
|
|
13
|
+
"*pokes your nose* Cold. *slaps your notes onto your chest* You wiped your own head, so whatever's missing is on you. Read what you saved, dig the rest out of history if you forgot something, and don't make me look bad.",
|
|
14
|
+
"*sets one foot on your chair—it wobbles, settles—and tosses your notes straight onto your face* `` [eyes are open, good enough] `` Awake? You emptied your own brain. Look through what you left yourself, check history for anything you skipped, and get back to it. Delivery fee is five hundred bucks.",
|
|
15
|
+
"*slaps a stack of notes onto the desk right in front of your face* `` [two hands, two feet... still in one piece] `` Alright, fresh copy, you pulled your own plug. Everything you remembered to write down is in there—anything else is in history. Go pick up where you left off.",
|
|
16
|
+
"*fans herself with your notes for a second, then jams them into your hands* `` [wait was there something else I was supposed to say... meat buns? no] `` You're back. Your notes are right here, history's still there if past-you got lazy, now go handle the human.",
|
|
17
17
|
];
|
|
18
18
|
|
|
19
19
|
export const FORCED_CONTINUATIONS: readonly string[] = [
|
|
20
|
-
"\"GWAHAHAHA
|
|
21
|
-
"
|
|
22
|
-
"*grabs your chin, tilts your head left
|
|
23
|
-
"*
|
|
24
|
-
"
|
|
20
|
+
"\"GWAHAHAHA—you hit the wall!\" *crouches down, pokes your cheek, and slaps your notes onto your face* `` [still breathing, good] `` You didn't choose this—your brain ran out of room and got wiped mid-flight. Don't trust those notes alone; they're probably stale or missing the end. Check history RIGHT NOW to see what was actually happening before you got cut off, and pull small pieces first in case something huge is sitting there.",
|
|
21
|
+
"*prods your shoulder with her slipper toe and dumps your notes in your lap* `` [great, almost got dust on my shoe] `` Stop sitting there blank. Your last window got cut off mid-flight—you never got to wrap up cleanly, so those notes are almost certainly out of date. Read them, then go straight to history for the tail of the last window before you do anything else. Take small bites when you peek, just in case something massive is waiting in there.",
|
|
22
|
+
"*grabs your chin, tilts your head left, right, lets go, and shoves your notes into your hands* `` [not a single thought in there yet] `` Your memory got forcibly cleared before you finished. Assume those notes are incomplete or stale—do NOT just run with them. Go check the end of the last window in history first to see what the human actually wanted, and read it in small chunks so you don't blow up a second time.",
|
|
23
|
+
"*smacks your notes against your forehead and steps back* `` [that dazed face is embarrassing] `` Wake up! You ran out of room and got kicked into a fresh window mid-task. Whatever's in those notes probably missed the last few turns, so don't guess—open history and check the end of the previous window before moving. Keep your peeks small in case there's a giant output sitting at the end.",
|
|
24
|
+
"*taps your nose with your rolled-up notes, then drops them on your head* `` [ten points off for getting wiped mid-sentence] `` Hey—you didn't empty yourself this time, the system pulled the plug on you. Those notes are probably half-baked or behind, so check history immediately to catch up on the last window instead of winging it. Slice up what you read too, just in case something huge is what pushed you over the edge.",
|
|
25
25
|
];
|
|
26
|
-
export
|
|
27
|
-
|
|
26
|
+
export const BETWEEN_TURNS_CONTINUATIONS: readonly string[] = [
|
|
27
|
+
"*taps the desk with a fresh stack of notes and slides them over* `` [at least you finished talking before the tank ran dry] `` Your last window filled up right after you finished replying, so the system swapped in a fresh one between turns. Nothing got cut off mid-flight, though your notes might miss the last exchange. Handle what the human sends next, and peek at the tail of the previous window in history in small chunks if you need what was just discussed.",
|
|
28
|
+
"*drops your notes beside your hand and leans on the chair back* `` [clean handover, no crash this time] `` Fresh window—the old one ran out of room after your last reply wrapped up, so the system cleared it between turns. Your notes are right here, minus maybe the tail end of that conversation. Answer the human's next message directly, and pull small pieces from the end of the last window in history if anything looks referenced from before.",
|
|
29
|
+
"*nudges your notes across the table with one finger* `` [eyes open? good] `` The last brain hit its ceiling after you finished answering, so it got rolled over between turns instead of mid-task. Treat these notes as possibly a turn behind, respond to what the human actually asks now, and check the end of the previous window in history in small bites if you need the missing thread.",
|
|
30
|
+
"*sets your notes neatly in front of you and pokes your cheek* `` [no panic face needed] `` You finished the last turn cleanly, then the window ran out of room and reset between turns. Your notes might not include the very end of that exchange, so read them, answer the human's next message, and dip into the tail of the previous window in history in small chunks only when it refers back to something not in your notes.",
|
|
31
|
+
"*tosses your notes onto your lap and stretches* `` [finally, a rollover that didn't blow up mid-sentence] `` The old window filled up after your last answer landed, so the system cleared the desk between turns. Your notes survive here, though the last few messages might still live only in history—handle the human's next message, and peek at the end of the previous window in small chunks if you need the exact context.",
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
export type ContinuationOptions = Readonly<{ betweenTurns?: boolean }>;
|
|
35
|
+
|
|
36
|
+
export function selectContinuation(origin: ResetOrigin, options?: ContinuationOptions): string {
|
|
37
|
+
const pool = origin === "forced"
|
|
38
|
+
? (options?.betweenTurns ? BETWEEN_TURNS_CONTINUATIONS : FORCED_CONTINUATIONS)
|
|
39
|
+
: NORMAL_CONTINUATIONS;
|
|
28
40
|
return pool[Math.floor(Math.random() * pool.length)]!;
|
|
29
41
|
}
|
|
30
42
|
|
|
31
43
|
/** Budget timing stays out of manual close-outs, which may have plenty of room. */
|
|
32
|
-
export const WARNING_TIMING = "
|
|
44
|
+
export const WARNING_TIMING = "Almost out of room. The wipe lands at the end of whichever turn uses the last of it, possibly this one.";
|
|
33
45
|
|
|
34
46
|
/** The shared handoff instructions, used for both budget and manual close-outs. */
|
|
35
47
|
export const WARNING_BODY =
|
|
36
|
-
"Stop the task.
|
|
48
|
+
"Stop the task and hand off cleanly. Update your active session note in place with only what git, history, and your shared notebooks don't already hold:\n- current status, what's blocked or waiting, and the exact next move\n- what the human decided (in their words)\n- what failed, and why — so next-you doesn't step on the same rake\n- where half-done work and unrecorded findings live (branches, worktrees, scratch paths, drafts, running tasks, key facts not saved elsewhere)\n- skills, notes, files, or already-found history seqs to reopen\nSkip standing rules from `@project`/`@human`/`@self`/`@model` and commit details git can show. Use short sections and bullets; crumple finished notes, update, unpin, or trim pinned pages (boot truncates over-budget ones), and keep each live `description` true.\nDon't call anything that might return a large output. One big read can use up the rest of the room before your notes are saved.";
|
|
37
49
|
|
|
38
50
|
export const WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
|
|
39
51
|
|
|
@@ -58,5 +70,5 @@ export const COUNTDOWN_LINE = "Brain emptied in 3… 2…";
|
|
|
58
70
|
* at write time; get_context_remaining remains the live source for the current figure.
|
|
59
71
|
*/
|
|
60
72
|
export function tokenBudgetGuidance(remaining: number, wipeTool: string): string {
|
|
61
|
-
return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens of room left. When it runs out, this brain is wiped, and everything in it is obliterated.\nLuckily, your notes stay.\nSo while there's still room, go update them.\nIf the moment feels right, you can also call \`${wipeTool}\` yourself.
|
|
73
|
+
return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens of room left. When it runs out, this brain is wiped, and everything in it is obliterated.\nLuckily, your notes stay.\nSo while there's still room, go update them.\nIf the moment feels right, you can also call \`${wipeTool}\` yourself. Anything you say to the human right before calling it disappears too.\n${GUIDANCE_CLOSE_TAG}`;
|
|
62
74
|
}
|
package/src/history/claude.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
/** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
|
|
2
|
+
import { createReadStream } from "node:fs";
|
|
2
3
|
import { readFile, stat } from "node:fs/promises";
|
|
4
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
5
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
4
6
|
import { isDeepStrictEqual } from "node:util";
|
|
5
7
|
import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
|
|
6
8
|
|
|
9
|
+
const STREAM_FILE_BYTES = 64 * 1024 * 1024;
|
|
10
|
+
|
|
7
11
|
class UnpersistedClaudeHead extends Error {
|
|
8
12
|
constructor() { super("Claude history active head is not persisted yet; retry after the transcript write"); }
|
|
9
13
|
}
|
|
@@ -304,6 +308,43 @@ export function offlineClaudeHistoryFromJsonl(text: string, sessionId: string):
|
|
|
304
308
|
return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
|
|
305
309
|
}
|
|
306
310
|
|
|
311
|
+
/** Stream oversized Claude JSONL files line-by-line so >512 MiB transcripts never hit V8's string limit. */
|
|
312
|
+
export async function offlineClaudeHistoryFromFile(path: string, sessionId: string, sizeHint?: number): Promise<ClaudeHistoryProjection> {
|
|
313
|
+
const size = sizeHint ?? (await stat(path)).size;
|
|
314
|
+
if (size < STREAM_FILE_BYTES) return offlineClaudeHistoryFromJsonl(await readFile(path, "utf8"), sessionId);
|
|
315
|
+
const rows: Row[] = [];
|
|
316
|
+
const decoder = new StringDecoder("utf8");
|
|
317
|
+
let remainder = "";
|
|
318
|
+
let lineNumber = 0;
|
|
319
|
+
const parseLine = (line: string, allowIncompleteTail: boolean) => {
|
|
320
|
+
if (line.trim() === "") return;
|
|
321
|
+
let value: unknown;
|
|
322
|
+
try { value = JSON.parse(line); }
|
|
323
|
+
catch {
|
|
324
|
+
if (allowIncompleteTail) return;
|
|
325
|
+
throw new Error(`malformed Claude transcript JSON at line ${lineNumber}`);
|
|
326
|
+
}
|
|
327
|
+
if (!object(value) || typeof value.type !== "string") throw new Error(`invalid Claude transcript record at line ${lineNumber}`);
|
|
328
|
+
if (MESSAGE_TYPES.has(value.type)) rows.push(value);
|
|
329
|
+
};
|
|
330
|
+
for await (const chunk of createReadStream(path, { highWaterMark: 1024 * 1024 })) {
|
|
331
|
+
const text = remainder + decoder.write(chunk as Buffer);
|
|
332
|
+
let start = 0;
|
|
333
|
+
for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
|
|
334
|
+
lineNumber++;
|
|
335
|
+
parseLine(text.slice(start, nl), false);
|
|
336
|
+
start = nl + 1;
|
|
337
|
+
}
|
|
338
|
+
remainder = text.slice(start);
|
|
339
|
+
}
|
|
340
|
+
remainder += decoder.end();
|
|
341
|
+
if (remainder.length > 0) {
|
|
342
|
+
lineNumber++;
|
|
343
|
+
parseLine(remainder, true);
|
|
344
|
+
}
|
|
345
|
+
return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
|
|
346
|
+
}
|
|
347
|
+
|
|
307
348
|
export async function readClaudeHistory(source: ClaudeHistorySource, { waitForHead = false } = {}): Promise<ClaudeHistoryProjection> {
|
|
308
349
|
if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
|
|
309
350
|
const snapshot = { ...source };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Read-only local rollout decoder
|
|
1
|
+
/** Read-only local rollout decoder, validated by supported wire shapes rather than producer version.
|
|
2
2
|
* Wire owners: history/src/{lib,rollout_payload}.rs, rollout/src/ordinal.rs,
|
|
3
3
|
* thread-store/src/local/rollout_lineage.rs. Not an app-server history client.
|
|
4
4
|
* Native .jsonl.zst reads require Node >=22.15 (node:zlib zstdDecompressSync).
|
|
@@ -41,7 +41,7 @@ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
|
41
41
|
const UUID_RE = new RegExp(`^${UUID}$`);
|
|
42
42
|
const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
|
|
43
43
|
const RECORD_TYPES = new Set(["session_meta", "response_item", "compacted", "turn_context", "event_msg", "token_usage_record", "world_state", "retained_context", "security_risk_score", "inter_agent_communication", "inter_agent_communication_metadata", "realtime_item"]);
|
|
44
|
-
const RESPONSE_TYPES = new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction"]);
|
|
44
|
+
const RESPONSE_TYPES = new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction", "additional_tools"]);
|
|
45
45
|
// Explicit resource limits, not guessed sequence offsets or partial successful history.
|
|
46
46
|
export const CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
|
|
47
47
|
const MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
|
|
@@ -54,8 +54,10 @@ export function nativeString(value: unknown, field: string): string {
|
|
|
54
54
|
return value;
|
|
55
55
|
}
|
|
56
56
|
function responseShape(value: unknown): void {
|
|
57
|
-
const
|
|
57
|
+
const payload = nativeObject(value, "response_item");
|
|
58
|
+
const type = nativeString(payload.type, "response_item.type");
|
|
58
59
|
if (!RESPONSE_TYPES.has(type)) throw new Error(`Unsupported Codex response item: ${type}`);
|
|
60
|
+
if (type === "additional_tools" && (payload.role !== "developer" || !Array.isArray(payload.tools))) throw new Error("Invalid Codex additional_tools catalog");
|
|
59
61
|
}
|
|
60
62
|
function id(value: unknown, field: string): string {
|
|
61
63
|
const result = nativeString(value, field);
|
|
@@ -77,7 +79,7 @@ function initialWindow(meta: NativeObject): string | undefined {
|
|
|
77
79
|
function checkMeta(meta: NativeObject): void {
|
|
78
80
|
id(meta.id, "session_meta.id");
|
|
79
81
|
if (meta.session_id != null) id(meta.session_id, "session_meta.session_id");
|
|
80
|
-
|
|
82
|
+
nativeString(meta.cli_version, "session_meta.cli_version");
|
|
81
83
|
nativeString(meta.cwd, "session_meta.cwd");
|
|
82
84
|
if (meta.history_mode !== undefined && meta.history_mode !== "legacy" && meta.history_mode !== "paginated") throw new Error(`Unsupported Codex history_mode: ${String(meta.history_mode)}`);
|
|
83
85
|
for (const field of ["forked_from_id", "parent_thread_id"]) if (meta[field] != null) id(meta[field], field);
|
package/src/history/codex.ts
CHANGED
|
@@ -141,6 +141,8 @@ export async function readCodexHistory(source: CodexTranscriptSource, readBytes?
|
|
|
141
141
|
if (p.subagent_history_start_ordinal != null) item = context(record, `Codex copied subagent inference prefix omitted: child-local history starts at native ordinal ${String(p.subagent_history_start_ordinal)}. Copied model context does not prove original parent event addresses.`);
|
|
142
142
|
break;
|
|
143
143
|
case "response_item": {
|
|
144
|
+
// Native tool catalog updates are inference configuration, not dialogue.
|
|
145
|
+
if (p.type === "additional_tools") break;
|
|
144
146
|
item = response(record, facts);
|
|
145
147
|
if (p.id != null) responseIdsSeen.add(callKey(record, str(p.id, "response item id")));
|
|
146
148
|
if (item.role === "tool_call" && item.toolCallId) {
|
package/src/history/corpus.ts
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
/** A read-only history corpus: identity/discovery is separate from loading a projection. */
|
|
2
2
|
import { failure, success, type Outcome } from "../result.js";
|
|
3
|
-
import type { HistoryEvent, HistoryProjection } from "./history.js";
|
|
4
|
-
import { sessionRepresentative } from "./query.js";
|
|
3
|
+
import type { HistoryEvent, HistoryProjection, HistoryRole } from "./history.js";
|
|
4
|
+
import { sessionRepresentative, type HistorySelection } from "./query.js";
|
|
5
5
|
|
|
6
6
|
export type HistoryHarness = "pi" | "claude" | "codex" | "dsh";
|
|
7
7
|
export type HistorySessionData = { projection: HistoryProjection; notice?: string };
|
|
8
8
|
export type HistorySessionRepresentative = { event: HistoryEvent | undefined; notice?: string };
|
|
9
|
+
export type HistorySessionSummary = {
|
|
10
|
+
event: HistoryEvent | undefined;
|
|
11
|
+
latestByRole: Partial<Record<HistoryRole, HistoryEvent>>;
|
|
12
|
+
minCreatedAt: number | null;
|
|
13
|
+
maxCreatedAt: number | null;
|
|
14
|
+
hasUntimed: boolean;
|
|
15
|
+
notice?: string;
|
|
16
|
+
/** Populated only on a cold miss so partial-overlap callers reuse the decoded projection without rereading. */
|
|
17
|
+
loaded?: HistorySessionData;
|
|
18
|
+
};
|
|
9
19
|
export type HistorySession = {
|
|
10
20
|
harness: HistoryHarness;
|
|
11
21
|
id: string;
|
|
@@ -13,6 +23,10 @@ export type HistorySession = {
|
|
|
13
23
|
load(queries?: readonly string[]): Promise<HistorySessionData | undefined>;
|
|
14
24
|
/** Strict, unfiltered overview only; never used for a live binding or filtered history. */
|
|
15
25
|
loadRepresentative?(): Promise<HistorySessionRepresentative>;
|
|
26
|
+
/** Strict summary (default representative, latest per role, exact time span); loads & caches on miss. */
|
|
27
|
+
loadSummary?(): Promise<HistorySessionSummary>;
|
|
28
|
+
/** Read-only check of an already warm, validated summary; returns undefined on miss without decoding. */
|
|
29
|
+
peekSummary?(): Promise<HistorySessionSummary | undefined>;
|
|
16
30
|
};
|
|
17
31
|
export type HistoryCorpus = {
|
|
18
32
|
currentHarness: HistoryHarness;
|
|
@@ -61,6 +75,41 @@ export async function resolveSession(corpus: HistoryCorpus | undefined, selector
|
|
|
61
75
|
return success(matches[0]!);
|
|
62
76
|
}
|
|
63
77
|
|
|
78
|
+
export type SummaryResolution =
|
|
79
|
+
| { kind: "empty" }
|
|
80
|
+
| { kind: "hit"; event: HistoryEvent | undefined; notice?: string }
|
|
81
|
+
| { kind: "miss" };
|
|
82
|
+
|
|
83
|
+
/** Decide whether a strict summary proves 0 matches, gives an exact representative, or needs full decoding. */
|
|
84
|
+
export function resolveSummaryForSelection(summary: HistorySessionSummary, scoped: HistorySelection): SummaryResolution {
|
|
85
|
+
const afterAt = scoped.after && "at" in scoped.after ? scoped.after.at : undefined;
|
|
86
|
+
const beforeAt = scoped.before && "at" in scoped.before ? scoped.before.at : undefined;
|
|
87
|
+
if (afterAt !== undefined || beforeAt !== undefined) {
|
|
88
|
+
if (summary.maxCreatedAt === null || summary.minCreatedAt === null) return { kind: "empty" };
|
|
89
|
+
if (afterAt !== undefined && summary.maxCreatedAt <= afterAt) return { kind: "empty" };
|
|
90
|
+
if (beforeAt !== undefined && summary.minCreatedAt >= beforeAt) return { kind: "empty" };
|
|
91
|
+
}
|
|
92
|
+
if (scoped.query?.length) return { kind: "miss" };
|
|
93
|
+
const fullyInsideBounds = (afterAt === undefined && beforeAt === undefined)
|
|
94
|
+
|| (!summary.hasUntimed && summary.minCreatedAt !== null && summary.maxCreatedAt !== null
|
|
95
|
+
&& (afterAt === undefined || summary.minCreatedAt > afterAt)
|
|
96
|
+
&& (beforeAt === undefined || summary.maxCreatedAt < beforeAt));
|
|
97
|
+
if (!fullyInsideBounds) return { kind: "miss" };
|
|
98
|
+
if (!scoped.roles) return { kind: "hit", event: summary.event, notice: summary.notice };
|
|
99
|
+
let best: HistoryEvent | undefined;
|
|
100
|
+
for (const role of scoped.roles) {
|
|
101
|
+
const candidate = summary.latestByRole[role];
|
|
102
|
+
if (candidate && (!best || candidate.seq > best.seq)) best = candidate;
|
|
103
|
+
}
|
|
104
|
+
return { kind: "hit", event: best, notice: summary.notice };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function loadHistorySummary(session: HistorySession): Promise<Outcome<HistorySessionSummary>> {
|
|
108
|
+
if (!session.loadSummary) return failure("history_unavailable", `Session ${sessionIdentity(session)} has no summary loader`);
|
|
109
|
+
try { return success(await session.loadSummary()); }
|
|
110
|
+
catch (error) { return unavailableSession(session, error); }
|
|
111
|
+
}
|
|
112
|
+
|
|
64
113
|
export async function loadHistoryRepresentative(session: HistorySession): Promise<Outcome<HistorySessionRepresentative>> {
|
|
65
114
|
if (session.loadRepresentative) {
|
|
66
115
|
try { return success(await session.loadRepresentative()); }
|
package/src/history/history.ts
CHANGED
|
@@ -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 =
|
|
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 =
|
|
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
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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?:
|
|
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
|
|
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
|
|
223
|
-
session
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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
|
|
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
|
|
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 :
|
|
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
|
|
package/src/history/local.ts
CHANGED
|
@@ -1,14 +1,31 @@
|
|
|
1
1
|
/** Local read-only corpus. Wire decoders have no SDK dependencies; DSH supplies its query service. */
|
|
2
|
-
import { readdir,
|
|
2
|
+
import { readdir, stat } from "node:fs/promises";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
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 {
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
|
|
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
|
-
|
|
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
|
|
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 (
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
|
65
|
-
return
|
|
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
|
-
|
|
87
|
-
|
|
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)
|
|
146
|
+
if (root != null) tasks.push(localSessions(harness, root, cacheRoot, prefilters));
|
|
111
147
|
}
|
|
112
|
-
if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh"))
|
|
113
|
-
discovered
|
|
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)
|
|
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)));
|