notesoup 0.56.1 → 0.57.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/README.md +1 -1
- package/dist/plugins/pi/runtime.js +8 -8
- package/dist/plugins/pi/text.js +1 -1
- package/dist/src/history/claude.d.ts +2 -0
- package/dist/src/history/claude.js +13 -2
- package/dist/src/history/codex-transcript.d.ts +15 -3
- package/dist/src/history/codex-transcript.js +57 -21
- package/dist/src/history/codex.d.ts +4 -2
- package/dist/src/history/codex.js +3 -3
- package/dist/src/history/corpus.d.ts +8 -1
- package/dist/src/history/corpus.js +17 -1
- package/dist/src/history/history.d.ts +16 -10
- package/dist/src/history/history.js +9 -9
- package/dist/src/history/local.d.ts +2 -0
- package/dist/src/history/local.js +35 -38
- package/dist/src/history/prefilter.d.ts +5 -0
- package/dist/src/history/prefilter.js +95 -0
- package/dist/src/history/query.d.ts +29 -27
- package/dist/src/history/query.js +82 -34
- package/dist/src/history/summary-cache.d.ts +10 -0
- package/dist/src/history/summary-cache.js +129 -0
- package/dist/src/tools/history.js +31 -20
- package/dist/test/agent-loop.test.js +18 -26
- package/dist/test/codex-history.test.js +90 -4
- package/dist/test/codex-plugin.test.js +6 -2
- package/dist/test/history-corpus.test.js +221 -33
- package/dist/test/history-prefilter.test.d.ts +1 -0
- package/dist/test/history-prefilter.test.js +174 -0
- package/dist/test/history-summary-cache.test.d.ts +1 -0
- package/dist/test/history-summary-cache.test.js +297 -0
- package/dist/test/history.integration.test.js +87 -52
- package/dist/test/model-facing-text.test.js +1 -1
- package/dist/test/reset-lifecycle.test.js +4 -6
- package/docs/history-sessions.md +26 -2
- package/docs/reset-lifecycle.md +4 -4
- package/docs/tool-results.md +4 -2
- package/package.json +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +425 -122
- package/plugins/codex/dist/codex/notesoup.js +423 -123
- package/plugins/pi/runtime.ts +8 -8
- package/plugins/pi/text.ts +1 -1
- package/src/history/claude.ts +16 -2
- package/src/history/codex-transcript.ts +52 -17
- package/src/history/codex.ts +5 -5
- package/src/history/corpus.ts +19 -2
- package/src/history/history.ts +11 -11
- package/src/history/local.ts +34 -38
- package/src/history/prefilter.ts +86 -0
- package/src/history/query.ts +77 -33
- package/src/history/summary-cache.ts +119 -0
- package/src/tools/history.ts +33 -20
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ pi -e npm:notesoup
|
|
|
28
28
|
|
|
29
29
|
## What you get
|
|
30
30
|
|
|
31
|
-
- **Durable context windows.** `/fresh-window` (alias `/empty`) clears and stops
|
|
31
|
+
- **Durable context windows.** `/fresh-window` (alias `/empty`) clears and stops, with any command text available for close-out notes. Separate human input received during emptying continues in the fresh window. The model can also request a window itself with `empty_brain`, and a budget close-out fires automatically before the window runs out. Abort and ordinary errors never count as completion; the raw conversation stays in the session, just out of the next context.
|
|
32
32
|
- **A boot block at every window head.** Static once-per-window content (cache-stable) with the window identity, the recent-notes index, and a short protocol teaching the model how to recover: notes for its own bookkeeping, history tools for everything before the reset.
|
|
33
33
|
- **`get_context_remaining`** — how much room the brain has left before the hard-reserve wipe, including the warning runway.
|
|
34
34
|
- **Seven history/notes tools**, flattened from the original Codex actions:
|
|
@@ -174,8 +174,8 @@ export function registerContext(pi, settingsManager) {
|
|
|
174
174
|
cmdCtx.ui.notify(`🥣 notesoup ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens left`}`, "info");
|
|
175
175
|
},
|
|
176
176
|
});
|
|
177
|
-
const emptyBrainCommand = {
|
|
178
|
-
description: "Flush memory to notes and
|
|
177
|
+
const emptyBrainCommand = (name) => ({
|
|
178
|
+
description: "Flush memory to notes, reset, and stop; optional text provides close-out context",
|
|
179
179
|
handler: async (args, cmdCtx) => {
|
|
180
180
|
if (!enabled) {
|
|
181
181
|
cmdCtx.ui.notify("🥣 notesoup is off · no brain to empty", "error");
|
|
@@ -187,27 +187,27 @@ export function registerContext(pi, settingsManager) {
|
|
|
187
187
|
if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId)
|
|
188
188
|
return;
|
|
189
189
|
}
|
|
190
|
-
// Manual wipes close out at settlement, then stop
|
|
190
|
+
// Manual wipes close out at settlement, then stop unless later human input arrives. The hidden warning is triggered when idle,
|
|
191
191
|
// steered into the running turn when busy — so the agent closes out promptly
|
|
192
192
|
// instead of the reset waiting for the whole run.
|
|
193
193
|
const prompt = args.trim() ? args : undefined;
|
|
194
|
-
const armed = resets.command(requestedWindowId,
|
|
194
|
+
const armed = resets.command(requestedWindowId, false);
|
|
195
195
|
if (armed === "already-pending") {
|
|
196
196
|
cmdCtx.ui.notify("🥣 Brain already being emptied", "info");
|
|
197
197
|
return;
|
|
198
198
|
}
|
|
199
199
|
cmdCtx.ui.notify("🥣 Dumping Brain", "info");
|
|
200
200
|
try {
|
|
201
|
-
pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ?
|
|
201
|
+
pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: commandWarningContent(prompt !== undefined ? `/${name} ${prompt}` : undefined), display: false }, { triggerTurn: true, deliverAs: "steer" });
|
|
202
202
|
}
|
|
203
203
|
catch (error) {
|
|
204
204
|
resets.clear();
|
|
205
205
|
cmdCtx.ui.notify(`🥣 Brain refused to empty: ${errorMessage(error)}`, "error");
|
|
206
206
|
}
|
|
207
207
|
},
|
|
208
|
-
};
|
|
209
|
-
pi.registerCommand("empty", emptyBrainCommand);
|
|
210
|
-
pi.registerCommand("fresh-window", emptyBrainCommand);
|
|
208
|
+
});
|
|
209
|
+
pi.registerCommand("empty", emptyBrainCommand("empty"));
|
|
210
|
+
pi.registerCommand("fresh-window", emptyBrainCommand("fresh-window"));
|
|
211
211
|
pi.registerTool(defineTool({
|
|
212
212
|
name: "empty_brain",
|
|
213
213
|
label: "Empty Brain",
|
package/dist/plugins/pi/text.js
CHANGED
|
@@ -18,7 +18,7 @@ export function promptBlock(commandLine) {
|
|
|
18
18
|
}
|
|
19
19
|
/** Approved manual close-out notices; both variants live here. */
|
|
20
20
|
export const COMMAND_NOTICE = {
|
|
21
|
-
prompted: "The human ran /empty. Save your notes now and call `empty_brain` immediately. Anything you say here will be erased afterward — put the handoff in your notes. The
|
|
21
|
+
prompted: "The human ran /empty. Save your notes now and call `empty_brain` immediately. Anything you say here will be erased afterward — put the handoff in your notes. The command below is context for your notes, not a task for the fresh window. Anything the human sends separately from now on should be handled after the reset.",
|
|
22
22
|
bare: "The human ran /empty. Save your notes now and call `empty_brain` immediately. Anything you say here will be erased afterward — put the handoff in your notes. Anything the human sends from now on should be handled after the reset.",
|
|
23
23
|
};
|
|
24
24
|
/** Manual orders omit budget timing hints; deferred work sits outside the notice. */
|
|
@@ -13,4 +13,6 @@ export type ClaudeHistoryProjection = HistoryProjection & {
|
|
|
13
13
|
export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection;
|
|
14
14
|
/** Offline files have no live append binding: prefer non-attachment leaves, then transcript order. */
|
|
15
15
|
export declare function offlineClaudeHead(text: string): string;
|
|
16
|
+
/** Select an offline head and build its projection from the same decoded records. */
|
|
17
|
+
export declare function offlineClaudeHistoryFromJsonl(text: string, sessionId: string): ClaudeHistoryProjection;
|
|
16
18
|
export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
|
|
@@ -128,9 +128,12 @@ function bootOrdinal(row, retained) {
|
|
|
128
128
|
}
|
|
129
129
|
/** All addresses are allocated on the full first-occurrence log, before branch selection. */
|
|
130
130
|
export function claudeHistoryFromJsonl(text, source) {
|
|
131
|
+
return claudeHistoryFromRows(rowsOf(text), source);
|
|
132
|
+
}
|
|
133
|
+
function claudeHistoryFromRows(rows, source) {
|
|
131
134
|
const nodes = new Map();
|
|
132
135
|
let nextSeq = 1;
|
|
133
|
-
for (const row of
|
|
136
|
+
for (const row of rows) {
|
|
134
137
|
// Ignore non-message records, including future metadata. If selected ancestry
|
|
135
138
|
// reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
|
|
136
139
|
if (!MESSAGE_TYPES.has(row.type))
|
|
@@ -293,8 +296,11 @@ export function claudeHistoryFromJsonl(text, source) {
|
|
|
293
296
|
}
|
|
294
297
|
/** Offline files have no live append binding: prefer non-attachment leaves, then transcript order. */
|
|
295
298
|
export function offlineClaudeHead(text) {
|
|
299
|
+
return offlineClaudeHeadFromRows(rowsOf(text));
|
|
300
|
+
}
|
|
301
|
+
function offlineClaudeHeadFromRows(rows) {
|
|
296
302
|
const latest = new Map();
|
|
297
|
-
for (const row of
|
|
303
|
+
for (const row of rows) {
|
|
298
304
|
if (!MESSAGE_TYPES.has(row.type))
|
|
299
305
|
continue;
|
|
300
306
|
const uuid = requiredString(row.uuid, "uuid");
|
|
@@ -334,6 +340,11 @@ export function offlineClaudeHead(text) {
|
|
|
334
340
|
const candidates = nonAttachments.length ? nonAttachments : leaves;
|
|
335
341
|
return candidates.at(-1);
|
|
336
342
|
}
|
|
343
|
+
/** Select an offline head and build its projection from the same decoded records. */
|
|
344
|
+
export function offlineClaudeHistoryFromJsonl(text, sessionId) {
|
|
345
|
+
const rows = rowsOf(text);
|
|
346
|
+
return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
|
|
347
|
+
}
|
|
337
348
|
export async function readClaudeHistory(source) {
|
|
338
349
|
if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
|
|
339
350
|
throw new Error("Claude history transcript_path is unavailable");
|
|
@@ -2,6 +2,12 @@ export type CodexTranscriptSource = {
|
|
|
2
2
|
transcriptPath: string;
|
|
3
3
|
threadId: string;
|
|
4
4
|
};
|
|
5
|
+
/** A successful native discovery decision, rechecked before trusting an offline summary. */
|
|
6
|
+
export type CodexLineageSource = {
|
|
7
|
+
home: string;
|
|
8
|
+
rolloutId: string;
|
|
9
|
+
path: string;
|
|
10
|
+
};
|
|
5
11
|
export type CodexTranscriptState = {
|
|
6
12
|
threadId: string;
|
|
7
13
|
rootSessionId: string;
|
|
@@ -27,15 +33,21 @@ export type CodexRecord = {
|
|
|
27
33
|
/** Native window at this point, absent only when the producer did not persist it. */
|
|
28
34
|
windowId?: string;
|
|
29
35
|
};
|
|
36
|
+
export declare const CODEX_TRANSCRIPT_MAX_BYTES: number;
|
|
30
37
|
export declare function nativeObject(value: unknown, field: string): NativeObject;
|
|
31
38
|
export declare function nativeString(value: unknown, field: string): string;
|
|
32
|
-
/**
|
|
33
|
-
export declare function
|
|
39
|
+
/** Fingerprints alone cannot detect a newly ambiguous or missing native rollout source. */
|
|
40
|
+
export declare function validateCodexLineageSources(sources: CodexLineageSource[]): Promise<boolean>;
|
|
41
|
+
export type CodexTranscriptReader = (path: string, remaining?: number) => Promise<Buffer>;
|
|
42
|
+
/** One load only: prefilter and lineage decoder share the original decoded Buffers. */
|
|
43
|
+
export declare function createCodexTranscriptReader(): CodexTranscriptReader;
|
|
34
44
|
/** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
|
|
35
|
-
export declare function readCodexTranscript(source: CodexTranscriptSource): Promise<{
|
|
45
|
+
export declare function readCodexTranscript(source: CodexTranscriptSource, readBytes?: CodexTranscriptReader): Promise<{
|
|
36
46
|
state: CodexTranscriptState;
|
|
37
47
|
records: CodexRecord[];
|
|
38
48
|
highestSeq: number;
|
|
49
|
+
dependencies: string[];
|
|
50
|
+
lineageSources: CodexLineageSource[];
|
|
39
51
|
}>;
|
|
40
52
|
/** Same decoder and ownership as history; no independently guessed boot window. */
|
|
41
53
|
export declare function readCodexTranscriptState(source: CodexTranscriptSource): Promise<CodexTranscriptState>;
|
|
@@ -12,7 +12,8 @@ const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(
|
|
|
12
12
|
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"]);
|
|
13
13
|
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"]);
|
|
14
14
|
// Explicit resource limits, not guessed sequence offsets or partial successful history.
|
|
15
|
-
const
|
|
15
|
+
export const CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
|
|
16
|
+
const MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
|
|
16
17
|
export function nativeObject(value, field) {
|
|
17
18
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
18
19
|
throw new Error(`Invalid Codex ${field}: expected an object`);
|
|
@@ -189,34 +190,70 @@ async function referencedPath(home, rolloutId) {
|
|
|
189
190
|
throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
|
|
190
191
|
return matches[0];
|
|
191
192
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
193
|
+
async function resolveLineageSource(home, rolloutId) {
|
|
194
|
+
const path = await realpath(await referencedPath(home, rolloutId));
|
|
195
|
+
if (![join(home, "sessions"), join(home, "archived_sessions")].some((root) => within(root, path)))
|
|
196
|
+
throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
|
|
197
|
+
return path;
|
|
198
|
+
}
|
|
199
|
+
/** Fingerprints alone cannot detect a newly ambiguous or missing native rollout source. */
|
|
200
|
+
export async function validateCodexLineageSources(sources) {
|
|
201
|
+
try {
|
|
202
|
+
for (const source of sources)
|
|
203
|
+
if (await resolveLineageSource(source.home, source.rolloutId) !== source.path)
|
|
204
|
+
return false;
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** One load only: prefilter and lineage decoder share the original decoded Buffers. */
|
|
212
|
+
export function createCodexTranscriptReader() {
|
|
213
|
+
const cache = new Map();
|
|
214
|
+
return async (path, remaining = CODEX_TRANSCRIPT_MAX_BYTES) => {
|
|
215
|
+
const canonical = await realpath(path);
|
|
216
|
+
let pending = cache.get(canonical);
|
|
217
|
+
if (!pending) {
|
|
218
|
+
pending = (async () => {
|
|
219
|
+
const info = await stat(canonical);
|
|
220
|
+
if (!info.isFile() || info.size > remaining)
|
|
221
|
+
throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
|
|
222
|
+
const stored = await readFile(canonical);
|
|
223
|
+
if (stored.length > remaining)
|
|
224
|
+
throw new Error("Unavailable Codex transcript: read size limit exceeded");
|
|
225
|
+
// 0.160.1 compression.rs uses zstd, NOT gzip. No decoded file is materialized.
|
|
226
|
+
if (canonical.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function")
|
|
227
|
+
throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
|
|
228
|
+
const bytes = canonical.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(stored, { maxOutputLength: remaining }) : stored;
|
|
229
|
+
return { bytes, storedSize: Math.max(info.size, stored.length) };
|
|
230
|
+
})();
|
|
231
|
+
cache.set(canonical, pending);
|
|
232
|
+
}
|
|
233
|
+
const { bytes, storedSize } = await pending;
|
|
234
|
+
// Reuse never exempts a semantic consumption from its remaining lineage budget.
|
|
235
|
+
if (storedSize > remaining)
|
|
236
|
+
throw new Error("Unavailable Codex transcript: read size limit exceeded");
|
|
237
|
+
if (bytes.length > remaining)
|
|
238
|
+
throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
|
|
239
|
+
return bytes;
|
|
240
|
+
};
|
|
205
241
|
}
|
|
206
242
|
/** Internal shared read: both boot facts and history use exactly this lineage and window owner. */
|
|
207
|
-
export async function readCodexTranscript(source) {
|
|
243
|
+
export async function readCodexTranscript(source, readBytes = createCodexTranscriptReader()) {
|
|
208
244
|
if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath)
|
|
209
245
|
throw new Error("Codex transcript_path is unavailable");
|
|
210
246
|
id(source.threadId, "requested threadId");
|
|
211
247
|
try {
|
|
212
248
|
let path = await realpath(source.transcriptPath), cutoff, home;
|
|
213
|
-
let remaining =
|
|
249
|
+
let remaining = CODEX_TRANSCRIPT_MAX_BYTES;
|
|
214
250
|
const segments = [], seen = new Set();
|
|
251
|
+
const lineageSources = [];
|
|
215
252
|
while (true) {
|
|
216
253
|
if (segments.length >= MAX_SEGMENTS || seen.has(path))
|
|
217
254
|
throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
|
|
218
255
|
seen.add(path);
|
|
219
|
-
const bytes = await
|
|
256
|
+
const bytes = await readBytes(path, remaining);
|
|
220
257
|
remaining -= bytes.length;
|
|
221
258
|
const segment = segmentFromBytes(bytes, cutoff);
|
|
222
259
|
if (segments.length === 0 && segment.meta.id !== source.threadId)
|
|
@@ -233,9 +270,8 @@ export async function readCodexTranscript(source) {
|
|
|
233
270
|
if (base.end_ordinal_exclusive === 0)
|
|
234
271
|
throw new Error("Invalid Codex lineage: history_base must include source metadata");
|
|
235
272
|
home ??= storageHome(path);
|
|
236
|
-
path = await
|
|
237
|
-
|
|
238
|
-
throw new Error("Unsafe Codex lineage: referenced path escapes native storage roots");
|
|
273
|
+
path = await resolveLineageSource(home, base.thread_id);
|
|
274
|
+
lineageSources.push({ home, rolloutId: base.thread_id, path });
|
|
239
275
|
cutoff = base;
|
|
240
276
|
}
|
|
241
277
|
// history_base is physical; forked_from_ordinal_exclusive is the logical
|
|
@@ -304,7 +340,7 @@ export async function readCodexTranscript(source) {
|
|
|
304
340
|
// compaction (history/src/lib.rs latest_disabled_plugin_ids has same ownership).
|
|
305
341
|
if (settingsModel ?? contextModel)
|
|
306
342
|
state.model = settingsModel ?? contextModel;
|
|
307
|
-
return { state, records, highestSeq: lastSeq };
|
|
343
|
+
return { state, records, highestSeq: lastSeq, dependencies: [...seen], lineageSources };
|
|
308
344
|
}
|
|
309
345
|
catch (error) {
|
|
310
346
|
throw new Error(`Cannot read Codex history at ${source.transcriptPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
|
|
2
2
|
import { type HistoryProjection } from "./history.js";
|
|
3
|
-
import { type CodexTranscriptSource, type CodexTranscriptState } from "./codex-transcript.js";
|
|
3
|
+
import { type CodexLineageSource, type CodexTranscriptReader, type CodexTranscriptSource, type CodexTranscriptState } from "./codex-transcript.js";
|
|
4
4
|
export type { CodexTranscriptSource } from "./codex-transcript.js";
|
|
5
5
|
export type CodexHistoryState = CodexTranscriptState & {
|
|
6
6
|
projection: HistoryProjection;
|
|
7
|
+
dependencies: string[];
|
|
8
|
+
lineageSources: CodexLineageSource[];
|
|
7
9
|
};
|
|
8
|
-
export declare function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState>;
|
|
10
|
+
export declare function readCodexHistory(source: CodexTranscriptSource, readBytes?: CodexTranscriptReader): Promise<CodexHistoryState>;
|
|
@@ -110,8 +110,8 @@ function standaloneTool(record, item) {
|
|
|
110
110
|
const name = `${str(item.server, "MCP server")}/${str(item.tool, "MCP tool")}`;
|
|
111
111
|
return { ...base, role: "tool", toolName: name, arguments: obj(item.arguments, "MCP arguments"), text: recorded.text ?? (item.error == null ? "" : JSON.stringify(item.error)), recordedStatus: item.status === "inProgress" ? "unfinished" : recorded.error ? "error" : "ok" };
|
|
112
112
|
}
|
|
113
|
-
export async function readCodexHistory(source) {
|
|
114
|
-
const { state, records, highestSeq } = await readCodexTranscript(source);
|
|
113
|
+
export async function readCodexHistory(source, readBytes) {
|
|
114
|
+
const { state, records, highestSeq, dependencies, lineageSources } = await readCodexTranscript(source, readBytes);
|
|
115
115
|
const facts = new Map(), callsSeen = new Set(), responseIdsSeen = new Set();
|
|
116
116
|
const windows = new Map(), branchSeqs = new Set();
|
|
117
117
|
const addWindow = (nativeId, createdAt) => {
|
|
@@ -234,5 +234,5 @@ export async function readCodexHistory(source) {
|
|
|
234
234
|
if (item)
|
|
235
235
|
addWindow(record.windowId).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
|
|
236
236
|
}
|
|
237
|
-
return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
|
|
237
|
+
return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs), dependencies, lineageSources };
|
|
238
238
|
}
|
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
/** A read-only history corpus: identity/discovery is separate from loading a projection. */
|
|
2
2
|
import { type Outcome } from "../tools/result.js";
|
|
3
|
-
import type { HistoryProjection } from "./history.js";
|
|
3
|
+
import type { HistoryEvent, HistoryProjection } from "./history.js";
|
|
4
4
|
export type HistoryHarness = "pi" | "claude" | "codex" | "dsh";
|
|
5
5
|
export type HistorySessionData = {
|
|
6
6
|
projection: HistoryProjection;
|
|
7
7
|
notice?: string;
|
|
8
8
|
};
|
|
9
|
+
export type HistorySessionRepresentative = {
|
|
10
|
+
event: HistoryEvent | undefined;
|
|
11
|
+
notice?: string;
|
|
12
|
+
};
|
|
9
13
|
export type HistorySession = {
|
|
10
14
|
harness: HistoryHarness;
|
|
11
15
|
id: string;
|
|
12
16
|
modifiedAt: number;
|
|
13
17
|
load(queries?: readonly string[]): Promise<HistorySessionData | undefined>;
|
|
18
|
+
/** Strict, unfiltered overview only; never used for a live binding or filtered history. */
|
|
19
|
+
loadRepresentative?(): Promise<HistorySessionRepresentative>;
|
|
14
20
|
};
|
|
15
21
|
export type HistoryCorpus = {
|
|
16
22
|
currentHarness: HistoryHarness;
|
|
@@ -31,6 +37,7 @@ export declare function parseSessionSelector(value: string): Outcome<SessionSele
|
|
|
31
37
|
/** '*' is the only metacharacter; all other characters match literally. */
|
|
32
38
|
export declare function matchesSession(session: HistorySession, selector: SessionSelector): boolean;
|
|
33
39
|
export declare function resolveSession(corpus: HistoryCorpus | undefined, selector: SessionSelector): Promise<Outcome<HistorySession>>;
|
|
40
|
+
export declare function loadHistoryRepresentative(session: HistorySession): Promise<Outcome<HistorySessionRepresentative>>;
|
|
34
41
|
export declare function loadHistorySession(session: HistorySession): Promise<Outcome<HistorySessionData>>;
|
|
35
42
|
export declare function loadHistorySession(session: HistorySession, queries: readonly string[] | undefined): Promise<Outcome<HistorySessionData | undefined>>;
|
|
36
43
|
export declare function currentHistory(context: HistoryContext): HistoryProjection | Promise<HistoryProjection>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** A read-only history corpus: identity/discovery is separate from loading a projection. */
|
|
2
2
|
import { failure, success } from "../tools/result.js";
|
|
3
|
+
import { sessionRepresentative } from "./query.js";
|
|
3
4
|
const HARNESSES = new Set(["pi", "claude", "codex", "dsh"]);
|
|
4
5
|
export function sessionIdentity(session) {
|
|
5
6
|
return `${session.harness}:${session.id}`;
|
|
@@ -41,6 +42,21 @@ export async function resolveSession(corpus, selector) {
|
|
|
41
42
|
return failure("ambiguous_session", `Session selector is ambiguous: ${matches.slice(0, 5).map(sessionIdentity).join(", ")}${matches.length > 5 ? ` (${matches.length - 5} more)` : ""}. Pass a longer ID or a harness-qualified ID.`);
|
|
42
43
|
return success(matches[0]);
|
|
43
44
|
}
|
|
45
|
+
export async function loadHistoryRepresentative(session) {
|
|
46
|
+
if (session.loadRepresentative) {
|
|
47
|
+
try {
|
|
48
|
+
return success(await session.loadRepresentative());
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
return unavailableSession(session, error);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const result = await loadHistorySession(session);
|
|
55
|
+
return result.ok ? success({ event: sessionRepresentative(result.data.projection, {}), notice: result.data.notice }) : result;
|
|
56
|
+
}
|
|
57
|
+
function unavailableSession(session, error) {
|
|
58
|
+
return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
59
|
+
}
|
|
44
60
|
export async function loadHistorySession(session, queries) {
|
|
45
61
|
try {
|
|
46
62
|
const data = await session.load(queries);
|
|
@@ -49,7 +65,7 @@ export async function loadHistorySession(session, queries) {
|
|
|
49
65
|
return success(data);
|
|
50
66
|
}
|
|
51
67
|
catch (error) {
|
|
52
|
-
return
|
|
68
|
+
return unavailableSession(session, error);
|
|
53
69
|
}
|
|
54
70
|
}
|
|
55
71
|
export function currentHistory(context) {
|
|
@@ -110,6 +110,15 @@ export declare function toolSummary(event: HistoryEvent): Static<typeof ToolSumm
|
|
|
110
110
|
export declare function nestedCallSummary(event: HistoryEvent): {
|
|
111
111
|
nested_calls?: Static<typeof NestedCallSummarySchema>;
|
|
112
112
|
};
|
|
113
|
+
/** A run of tool/context events the conversation view replaces with counts. */
|
|
114
|
+
export declare const HistoryFoldedRowSchema: Type.TObject<{
|
|
115
|
+
session: Type.TOptional<Type.TString>;
|
|
116
|
+
first_seq: Type.TInteger;
|
|
117
|
+
last_seq: Type.TInteger;
|
|
118
|
+
count: Type.TInteger;
|
|
119
|
+
tools: Type.TRecord<"^.*$", Type.TInteger>;
|
|
120
|
+
}>;
|
|
121
|
+
export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
|
|
113
122
|
/** Stable identity and a verbatim preview, starting at the search match when present. */
|
|
114
123
|
export declare const HistoryPageItemSchema: Type.TObject<{
|
|
115
124
|
content: Type.TString;
|
|
@@ -120,21 +129,18 @@ export declare const HistoryPageItemSchema: Type.TObject<{
|
|
|
120
129
|
output_truncated: Type.TOptional<Type.TLiteral<true>>;
|
|
121
130
|
full_output_path: Type.TOptional<Type.TString>;
|
|
122
131
|
session: Type.TOptional<Type.TString>;
|
|
132
|
+
folded_before: Type.TOptional<Type.TObject<{
|
|
133
|
+
session: Type.TOptional<Type.TString>;
|
|
134
|
+
first_seq: Type.TInteger;
|
|
135
|
+
last_seq: Type.TInteger;
|
|
136
|
+
count: Type.TInteger;
|
|
137
|
+
tools: Type.TRecord<"^.*$", Type.TInteger>;
|
|
138
|
+
}>>;
|
|
123
139
|
seq: Type.TInteger;
|
|
124
140
|
role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
|
|
125
141
|
created_at: Type.TUnion<[Type.TString, Type.TNull]>;
|
|
126
142
|
}>;
|
|
127
143
|
export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
|
|
128
|
-
/** A run of tool/context events the conversation view replaces with counts. */
|
|
129
|
-
export declare const HistoryFoldedRowSchema: Type.TObject<{
|
|
130
|
-
session: Type.TOptional<Type.TString>;
|
|
131
|
-
folded: Type.TLiteral<true>;
|
|
132
|
-
first_seq: Type.TInteger;
|
|
133
|
-
last_seq: Type.TInteger;
|
|
134
|
-
count: Type.TInteger;
|
|
135
|
-
tools: Type.TRecord<"^.*$", Type.TInteger>;
|
|
136
|
-
}>;
|
|
137
|
-
export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
|
|
138
144
|
/** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
|
|
139
145
|
export declare const MAX_FOLD_TOOL_NAMES = 20;
|
|
140
146
|
/** Longest tool name a fold row lists. */
|
|
@@ -134,9 +134,18 @@ export function nestedCallSummary(event) {
|
|
|
134
134
|
const nested = event.execution?.nestedCalls;
|
|
135
135
|
return nested === undefined ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
|
|
136
136
|
}
|
|
137
|
+
/** A run of tool/context events the conversation view replaces with counts. */
|
|
138
|
+
export const HistoryFoldedRowSchema = Type.Object({
|
|
139
|
+
session: Type.Optional(Type.String()),
|
|
140
|
+
first_seq: Type.Integer({ minimum: 1 }),
|
|
141
|
+
last_seq: Type.Integer({ minimum: 1 }),
|
|
142
|
+
count: Type.Integer({ minimum: 1 }),
|
|
143
|
+
tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
|
|
144
|
+
}, { additionalProperties: false });
|
|
137
145
|
/** Stable identity and a verbatim preview, starting at the search match when present. */
|
|
138
146
|
export const HistoryPageItemSchema = Type.Object({
|
|
139
147
|
session: Type.Optional(Type.String()),
|
|
148
|
+
folded_before: Type.Optional(HistoryFoldedRowSchema),
|
|
140
149
|
seq: Type.Integer({ minimum: 1 }),
|
|
141
150
|
role: HistoryRoleSchema,
|
|
142
151
|
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
@@ -145,15 +154,6 @@ export const HistoryPageItemSchema = Type.Object({
|
|
|
145
154
|
truncated: Type.Boolean({ description: "Preview is partial." }),
|
|
146
155
|
offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Where the preview starts." })),
|
|
147
156
|
}, { additionalProperties: false });
|
|
148
|
-
/** A run of tool/context events the conversation view replaces with counts. */
|
|
149
|
-
export const HistoryFoldedRowSchema = Type.Object({
|
|
150
|
-
session: Type.Optional(Type.String()),
|
|
151
|
-
folded: Type.Literal(true),
|
|
152
|
-
first_seq: Type.Integer({ minimum: 1 }),
|
|
153
|
-
last_seq: Type.Integer({ minimum: 1 }),
|
|
154
|
-
count: Type.Integer({ minimum: 1 }),
|
|
155
|
-
tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
|
|
156
|
-
}, { additionalProperties: false });
|
|
157
157
|
/** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
|
|
158
158
|
export const MAX_FOLD_TOOL_NAMES = 20;
|
|
159
159
|
/** Longest tool name a fold row lists. */
|
|
@@ -6,6 +6,8 @@ export type LocalHistoryOptions = {
|
|
|
6
6
|
roots?: LocalHistoryRoots;
|
|
7
7
|
home?: string;
|
|
8
8
|
env?: NodeJS.ProcessEnv;
|
|
9
|
+
/** Internal hermetic-test seam, not a tool parameter or host setting. */
|
|
10
|
+
summaryCacheRoot?: string;
|
|
9
11
|
/** Available only inside DSH; descriptors load through ctx.sessionQuery.readSession. */
|
|
10
12
|
dshSessions?: () => Promise<HistorySession[]>;
|
|
11
13
|
};
|
|
@@ -3,10 +3,12 @@ import { readdir, readFile, stat } from "node:fs/promises";
|
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { piHistoryFromJsonl } from "./pi.js";
|
|
6
|
-
import {
|
|
6
|
+
import { offlineClaudeHistoryFromJsonl } from "./claude.js";
|
|
7
7
|
import { readCodexHistory } from "./codex.js";
|
|
8
|
-
import {
|
|
8
|
+
import { createCodexTranscriptReader } from "./codex-transcript.js";
|
|
9
|
+
import { createHistoryPrefilter, historyFileMayMatch } from "./prefilter.js";
|
|
9
10
|
import { sessionIdentity } from "./corpus.js";
|
|
11
|
+
import { cachedSessionRepresentative, historySummaryCacheRoot } from "./summary-cache.js";
|
|
10
12
|
function rootsFor(options) {
|
|
11
13
|
const env = options.env ?? process.env;
|
|
12
14
|
const home = options.home ?? env.HOME ?? homedir();
|
|
@@ -37,34 +39,7 @@ async function filesAt(root, depth) {
|
|
|
37
39
|
}
|
|
38
40
|
return paths;
|
|
39
41
|
}
|
|
40
|
-
|
|
41
|
-
copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
|
|
42
|
-
does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
|
|
43
|
-
not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
|
|
44
|
-
FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
|
|
45
|
-
the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
|
|
46
|
-
function escapeRegExp(value) {
|
|
47
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
48
|
-
}
|
|
49
|
-
/** Only prove misses, not hits. Only \\uXXXX can encode a word character; other JSON escapes are control/quote/slash. */
|
|
50
|
-
function mayMatch(text, queries, codex) {
|
|
51
|
-
if (codex && text.includes('"history_base"'))
|
|
52
|
-
return true;
|
|
53
|
-
const unescaped = text.includes("\\u")
|
|
54
|
-
? text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)))
|
|
55
|
-
: text;
|
|
56
|
-
return queries.some((query) => {
|
|
57
|
-
const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
|
|
58
|
-
return tokens === null || tokens.every((token) => {
|
|
59
|
-
const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
|
|
60
|
-
return parts.every((part) => {
|
|
61
|
-
const literal = new RegExp(escapeRegExp(part), "iu");
|
|
62
|
-
return literal.test(unescaped) || (unescaped !== text && literal.test(text)) || literal.test(PRESENTATION);
|
|
63
|
-
});
|
|
64
|
-
});
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
async function localSessions(harness, root) {
|
|
42
|
+
async function localSessions(harness, root, cacheRoot, prefilters) {
|
|
68
43
|
const paths = await filesAt(root, harness === "codex" ? 3 : 1);
|
|
69
44
|
const sessions = [];
|
|
70
45
|
for (const path of paths) {
|
|
@@ -85,17 +60,36 @@ async function localSessions(harness, root) {
|
|
|
85
60
|
}
|
|
86
61
|
sessions.push({
|
|
87
62
|
harness, id, modifiedAt,
|
|
63
|
+
async loadRepresentative() {
|
|
64
|
+
return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
|
|
65
|
+
if (harness === "codex") {
|
|
66
|
+
const readBytes = createCodexTranscriptReader();
|
|
67
|
+
const history = await readCodexHistory({ threadId: id, transcriptPath: path }, async (source, remaining) => {
|
|
68
|
+
await track(source);
|
|
69
|
+
return readBytes(source, remaining);
|
|
70
|
+
});
|
|
71
|
+
return { data: { projection: history.projection }, lineageSources: history.lineageSources };
|
|
72
|
+
}
|
|
73
|
+
const data = await this.load();
|
|
74
|
+
if (!data)
|
|
75
|
+
throw new Error("Session returned no history");
|
|
76
|
+
return { data };
|
|
77
|
+
});
|
|
78
|
+
},
|
|
88
79
|
async load(queries) {
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
80
|
+
if (queries?.length) {
|
|
81
|
+
let prefilter = prefilters.get(queries);
|
|
82
|
+
if (!prefilter)
|
|
83
|
+
prefilters.set(queries, prefilter = createHistoryPrefilter(queries));
|
|
84
|
+
if (!await historyFileMayMatch(path, prefilter, harness === "codex"))
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
94
87
|
if (harness === "codex")
|
|
95
88
|
return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
|
|
89
|
+
const text = await readFile(path, "utf8");
|
|
96
90
|
if (harness === "pi")
|
|
97
91
|
return { projection: piHistoryFromJsonl(text, id) };
|
|
98
|
-
const projection =
|
|
92
|
+
const projection = offlineClaudeHistoryFromJsonl(text, id);
|
|
99
93
|
const missing = projection.missingAncestors;
|
|
100
94
|
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` }) };
|
|
101
95
|
},
|
|
@@ -109,13 +103,16 @@ export function localHistoryCorpus(options) {
|
|
|
109
103
|
currentHarness: options.current.harness,
|
|
110
104
|
async sessions(onlyHarness) {
|
|
111
105
|
const roots = rootsFor(options);
|
|
106
|
+
const env = options.env ?? process.env;
|
|
107
|
+
const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir(), env);
|
|
112
108
|
const discovered = [];
|
|
109
|
+
const prefilters = new WeakMap();
|
|
113
110
|
for (const harness of ["pi", "claude", "codex"]) {
|
|
114
111
|
if (onlyHarness !== undefined && onlyHarness !== harness)
|
|
115
112
|
continue;
|
|
116
113
|
const root = roots[harness];
|
|
117
114
|
if (root != null)
|
|
118
|
-
discovered.push(...await localSessions(harness, root));
|
|
115
|
+
discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
|
|
119
116
|
}
|
|
120
117
|
if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh"))
|
|
121
118
|
discovered.push(...await options.dshSessions());
|
|
@@ -124,7 +121,7 @@ export function localHistoryCorpus(options) {
|
|
|
124
121
|
for (const session of discovered)
|
|
125
122
|
if (!unique.has(sessionIdentity(session)))
|
|
126
123
|
unique.set(sessionIdentity(session), session);
|
|
127
|
-
const current = {
|
|
124
|
+
const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
|
|
128
125
|
if (onlyHarness === undefined || onlyHarness === current.harness)
|
|
129
126
|
unique.set(sessionIdentity(current), current);
|
|
130
127
|
return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type HistoryPrefilter = (chunks: AsyncIterable<Uint8Array>, codex?: boolean) => Promise<boolean>;
|
|
2
|
+
/** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
|
|
3
|
+
export declare function createHistoryPrefilter(queries: readonly string[]): HistoryPrefilter;
|
|
4
|
+
/** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
|
|
5
|
+
export declare function historyFileMayMatch(path: string, prefilter: HistoryPrefilter, codex?: boolean, maxBytes?: number): Promise<boolean>;
|