notesoup 0.56.1 → 0.57.1
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/entries.d.ts +0 -1
- package/dist/plugins/pi/entries.js +0 -1
- package/dist/plugins/pi/reset/lifecycle.d.ts +2 -1
- package/dist/plugins/pi/reset/lifecycle.js +19 -36
- package/dist/plugins/pi/runtime.js +14 -10
- package/dist/plugins/pi/text.d.ts +0 -2
- package/dist/plugins/pi/text.js +2 -6
- 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 +143 -110
- 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/marker.test.js +1 -1
- package/dist/test/model-facing-text.test.js +3 -4
- package/dist/test/reset-lifecycle.test.js +52 -12
- package/docs/history-sessions.md +26 -2
- package/docs/reset-lifecycle.md +14 -13
- 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/entries.ts +0 -1
- package/plugins/pi/reset/lifecycle.ts +19 -35
- package/plugins/pi/runtime.ts +14 -10
- package/plugins/pi/text.ts +2 -7
- 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
|
@@ -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>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** Conservative streaming proof-of-miss. A possible hit still needs the normal strict decoder. */
|
|
2
|
+
import { createReadStream } from "node:fs";
|
|
3
|
+
import { stat } from "node:fs/promises";
|
|
4
|
+
import { pipeline } from "node:stream/promises";
|
|
5
|
+
import { StringDecoder } from "node:string_decoder";
|
|
6
|
+
import * as zlib from "node:zlib";
|
|
7
|
+
import { CODEX_TRANSCRIPT_MAX_BYTES } from "./codex-transcript.js";
|
|
8
|
+
const PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
|
|
9
|
+
copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
|
|
10
|
+
does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
|
|
11
|
+
not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
|
|
12
|
+
FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
|
|
13
|
+
the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
|
|
14
|
+
const HISTORY_BASE = '"history_base"';
|
|
15
|
+
/** Compile literal Unicode case matching once, then keep only per-file token bits and a bounded tail. */
|
|
16
|
+
export function createHistoryPrefilter(queries) {
|
|
17
|
+
let overlap = HISTORY_BASE.length;
|
|
18
|
+
const alternatives = queries.map((query) => (query.match(/[\p{L}\p{N}_-]+/gu) ?? []).flatMap((token) => {
|
|
19
|
+
const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
|
|
20
|
+
return parts.map((part) => {
|
|
21
|
+
overlap = Math.max(overlap, part.length);
|
|
22
|
+
return new RegExp(part, "iu");
|
|
23
|
+
}).filter((literal) => !literal.test(PRESENTATION));
|
|
24
|
+
}));
|
|
25
|
+
// No safe tokens (or generated text alone) cannot prove a miss.
|
|
26
|
+
const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
|
|
27
|
+
return async (chunks, codex = false) => {
|
|
28
|
+
const decoder = new StringDecoder("utf8");
|
|
29
|
+
const seen = alternatives.map((tokens) => tokens.map(() => false));
|
|
30
|
+
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
|
+
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;
|
|
49
|
+
const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
|
|
50
|
+
if (codex && raw.includes(HISTORY_BASE))
|
|
51
|
+
possible = true;
|
|
52
|
+
else
|
|
53
|
+
possible = alternatives.some((tokens, index) => {
|
|
54
|
+
const bits = seen[index];
|
|
55
|
+
for (let token = 0; token < tokens.length; token++)
|
|
56
|
+
bits[token] ||= tokens[token].test(raw) || (normalized !== raw && tokens[token].test(normalized));
|
|
57
|
+
return bits.every(Boolean);
|
|
58
|
+
});
|
|
59
|
+
rawTail = raw.slice(-overlap);
|
|
60
|
+
normalizedTail = normalized.slice(-overlap);
|
|
61
|
+
};
|
|
62
|
+
for await (const chunk of chunks)
|
|
63
|
+
if (!possible)
|
|
64
|
+
scan(decoder.write(chunk));
|
|
65
|
+
if (!possible)
|
|
66
|
+
scan(decoder.end(), true);
|
|
67
|
+
return possible;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** The byte budget comes from the strict Codex reader; Pi/Claude have no such native limit. */
|
|
71
|
+
export async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
|
|
72
|
+
if (codex) {
|
|
73
|
+
const info = await stat(path);
|
|
74
|
+
if (!info.isFile() || info.size > maxBytes)
|
|
75
|
+
throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
|
|
76
|
+
}
|
|
77
|
+
// Native Codex compression is zstd; no decoded file or full Buffer is materialized.
|
|
78
|
+
const compressed = codex && path.endsWith(".jsonl.zst");
|
|
79
|
+
if (compressed && typeof zlib.createZstdDecompress !== "function")
|
|
80
|
+
throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
|
|
81
|
+
const input = createReadStream(path);
|
|
82
|
+
const consume = async (chunks) => {
|
|
83
|
+
let size = 0;
|
|
84
|
+
async function* bounded() {
|
|
85
|
+
for await (const chunk of chunks) {
|
|
86
|
+
size += chunk.length;
|
|
87
|
+
if (size > maxBytes)
|
|
88
|
+
throw new Error("Unavailable Codex transcript: decoded size limit exceeded");
|
|
89
|
+
yield chunk;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return prefilter(bounded(), codex);
|
|
93
|
+
};
|
|
94
|
+
return compressed ? pipeline(input, zlib.createZstdDecompress(), consume) : pipeline(input, consume);
|
|
95
|
+
}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
import { Type, type Static } from "typebox";
|
|
3
3
|
import { type Outcome } from "../tools/result.js";
|
|
4
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;
|
|
5
7
|
/** Which end of one selection `limit` is taken from; page items always come back ascending. */
|
|
6
8
|
export type HistoryOrder = "newest" | "oldest";
|
|
7
9
|
/**
|
|
@@ -18,18 +20,9 @@ export type HistorySelection = HistoryFilter & {
|
|
|
18
20
|
until?: string;
|
|
19
21
|
max_chars_per_item?: number;
|
|
20
22
|
};
|
|
21
|
-
export declare const HistoryOlderSchema: Type.TObject<{
|
|
22
|
-
session: Type.TOptional<Type.TString>;
|
|
23
|
-
before_seq: Type.TInteger;
|
|
24
|
-
}>;
|
|
25
|
-
export declare const HistoryNewerSchema: Type.TObject<{
|
|
26
|
-
session: Type.TOptional<Type.TString>;
|
|
27
|
-
after_seq: Type.TInteger;
|
|
28
|
-
from: Type.TLiteral<"oldest">;
|
|
29
|
-
}>;
|
|
30
23
|
export declare const HistoryPageSchema: Type.TObject<{
|
|
31
24
|
notice: Type.TOptional<Type.TString>;
|
|
32
|
-
items: Type.TArray<Type.
|
|
25
|
+
items: Type.TArray<Type.TObject<{
|
|
33
26
|
content: Type.TString;
|
|
34
27
|
truncated: Type.TBoolean;
|
|
35
28
|
offset_chars: Type.TOptional<Type.TInteger>;
|
|
@@ -38,26 +31,26 @@ export declare const HistoryPageSchema: Type.TObject<{
|
|
|
38
31
|
output_truncated: Type.TOptional<Type.TLiteral<true>>;
|
|
39
32
|
full_output_path: Type.TOptional<Type.TString>;
|
|
40
33
|
session: Type.TOptional<Type.TString>;
|
|
34
|
+
folded_before: Type.TOptional<Type.TObject<{
|
|
35
|
+
session: Type.TOptional<Type.TString>;
|
|
36
|
+
first_seq: Type.TInteger;
|
|
37
|
+
last_seq: Type.TInteger;
|
|
38
|
+
count: Type.TInteger;
|
|
39
|
+
tools: Type.TRecord<"^.*$", Type.TInteger>;
|
|
40
|
+
}>>;
|
|
41
41
|
seq: Type.TInteger;
|
|
42
42
|
role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
|
|
43
43
|
created_at: Type.TUnion<[Type.TString, Type.TNull]>;
|
|
44
|
-
}
|
|
44
|
+
}>>;
|
|
45
|
+
folded_after: Type.TOptional<Type.TObject<{
|
|
45
46
|
session: Type.TOptional<Type.TString>;
|
|
46
|
-
folded: Type.TLiteral<true>;
|
|
47
47
|
first_seq: Type.TInteger;
|
|
48
48
|
last_seq: Type.TInteger;
|
|
49
49
|
count: Type.TInteger;
|
|
50
50
|
tools: Type.TRecord<"^.*$", Type.TInteger>;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
before_seq: Type.TInteger;
|
|
55
|
-
}>, Type.TNull]>;
|
|
56
|
-
page_newer: Type.TUnion<[Type.TObject<{
|
|
57
|
-
session: Type.TOptional<Type.TString>;
|
|
58
|
-
after_seq: Type.TInteger;
|
|
59
|
-
from: Type.TLiteral<"oldest">;
|
|
60
|
-
}>, Type.TNull]>;
|
|
51
|
+
}>>;
|
|
52
|
+
has_older: Type.TBoolean;
|
|
53
|
+
has_newer: Type.TBoolean;
|
|
61
54
|
}>;
|
|
62
55
|
/** One whole page payload, before it becomes an outcome. */
|
|
63
56
|
export type HistoryPage = Static<typeof HistoryPageSchema>;
|
|
@@ -66,8 +59,17 @@ export declare function selectPage(projection: HistoryProjection, params: Histor
|
|
|
66
59
|
export declare function corpusSelection(params: HistorySelection): Outcome<HistorySelection>;
|
|
67
60
|
/** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
|
|
68
61
|
export declare function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined;
|
|
69
|
-
/**
|
|
70
|
-
export declare
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
62
|
+
/** Keep only the requested end of the globally ordered selection while sessions are released. */
|
|
63
|
+
export declare class CorpusCollector {
|
|
64
|
+
private readonly scoped;
|
|
65
|
+
private readonly candidates;
|
|
66
|
+
private readonly limit;
|
|
67
|
+
private discarded;
|
|
68
|
+
constructor(scoped: HistorySelection);
|
|
69
|
+
private admit;
|
|
70
|
+
/** Admit an already selected strict overview event without selecting it a second time. */
|
|
71
|
+
addRepresentative(session: string, event: HistoryEvent | undefined): boolean;
|
|
72
|
+
/** Returns whether this session contributes an overview representative. */
|
|
73
|
+
add(session: string, projection: HistoryProjection): boolean;
|
|
74
|
+
page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited?: boolean): Outcome<HistoryPage>;
|
|
75
|
+
}
|
|
@@ -5,6 +5,12 @@ import { prefixFit, TOOL_OUTPUT_LIMIT } from "../tools/output.js";
|
|
|
5
5
|
import { earliestMatchOffsetChars } from "../text-match.js";
|
|
6
6
|
import { InvalidQueryError, searchQueries } from "../tools/schema.js";
|
|
7
7
|
import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
|
|
8
|
+
const multiPages = new WeakSet();
|
|
9
|
+
export function isMultiPage(page) { return multiPages.has(page); }
|
|
10
|
+
export function markMultiPage(page) {
|
|
11
|
+
multiPages.add(page);
|
|
12
|
+
return page;
|
|
13
|
+
}
|
|
8
14
|
/** ISO 8601 date or date-time; the offset is optional (group 1) and a missing one is read as UTC. */
|
|
9
15
|
const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[+-]\d{2}:?\d{2})?$/;
|
|
10
16
|
/** Epoch ms for one optional time param, or a refusal naming it. */
|
|
@@ -28,20 +34,12 @@ function resolveTimeBounds(params) {
|
|
|
28
34
|
}
|
|
29
35
|
return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
|
|
30
36
|
}
|
|
31
|
-
export const HistoryOlderSchema = Type.Object({
|
|
32
|
-
session: Type.Optional(Type.String()),
|
|
33
|
-
before_seq: Type.Integer({ minimum: 1 }),
|
|
34
|
-
}, { additionalProperties: false });
|
|
35
|
-
export const HistoryNewerSchema = Type.Object({
|
|
36
|
-
session: Type.Optional(Type.String()),
|
|
37
|
-
after_seq: Type.Integer({ minimum: 1 }),
|
|
38
|
-
from: Type.Literal("oldest"),
|
|
39
|
-
}, { additionalProperties: false });
|
|
40
37
|
export const HistoryPageSchema = Type.Object({
|
|
41
38
|
notice: Type.Optional(Type.String()),
|
|
42
|
-
items: Type.Array(
|
|
43
|
-
|
|
44
|
-
|
|
39
|
+
items: Type.Array(HistoryPageItemSchema),
|
|
40
|
+
folded_after: Type.Optional(HistoryFoldedRowSchema),
|
|
41
|
+
has_older: Type.Boolean(),
|
|
42
|
+
has_newer: Type.Boolean(),
|
|
45
43
|
}, { additionalProperties: false });
|
|
46
44
|
/** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
|
|
47
45
|
function truncateHistoryItem(item, fits) {
|
|
@@ -74,7 +72,7 @@ function foldedRun(events, session) {
|
|
|
74
72
|
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
75
73
|
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
76
74
|
const tools = Object.fromEntries(entries);
|
|
77
|
-
return { ...(session === undefined ? {} : { session }),
|
|
75
|
+
return { ...(session === undefined ? {} : { session }), first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
|
|
78
76
|
}
|
|
79
77
|
/** Filter and order once. Conversation candidates own the folded gap immediately before them. */
|
|
80
78
|
function prepareSelection(projection, params) {
|
|
@@ -100,21 +98,19 @@ function prepareSelection(projection, params) {
|
|
|
100
98
|
/** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
|
|
101
99
|
function pageData(prepared, start, end, maxChars, preview) {
|
|
102
100
|
const { candidates, tail } = prepared;
|
|
103
|
-
const identity = prepared.session === undefined ? {} : { session: prepared.session };
|
|
104
101
|
const items = [];
|
|
105
102
|
for (let index = start; index < end; index++) {
|
|
106
103
|
const candidate = candidates[index];
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
items.push(preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) }));
|
|
104
|
+
const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) });
|
|
105
|
+
items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
|
|
110
106
|
}
|
|
111
|
-
|
|
112
|
-
items.push(tail);
|
|
113
|
-
return {
|
|
107
|
+
const page = {
|
|
114
108
|
items,
|
|
115
|
-
|
|
116
|
-
|
|
109
|
+
...(end === candidates.length && tail ? { folded_after: tail } : {}),
|
|
110
|
+
has_older: (start > 0 && start < end) || (!!prepared.discarded && prepared.from !== "oldest"),
|
|
111
|
+
has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && prepared.from === "oldest"),
|
|
117
112
|
};
|
|
113
|
+
return prepared.multi ? markMultiPage(page) : page;
|
|
118
114
|
}
|
|
119
115
|
/**
|
|
120
116
|
* Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
|
|
@@ -155,22 +151,74 @@ export function sessionRepresentative(projection, scoped) {
|
|
|
155
151
|
?? events.filter((event) => event.role === "assistant").at(-1)
|
|
156
152
|
?? events.at(-1);
|
|
157
153
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
154
|
+
const eventTime = (event) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
|
|
155
|
+
const compareCorpus = (a, b) => eventTime(a.event) - eventTime(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
|
|
156
|
+
/** Keep only the requested end of the globally ordered selection while sessions are released. */
|
|
157
|
+
export class CorpusCollector {
|
|
158
|
+
scoped;
|
|
159
|
+
candidates = [];
|
|
160
|
+
limit;
|
|
161
|
+
discarded = false;
|
|
162
|
+
constructor(scoped) {
|
|
163
|
+
this.scoped = scoped;
|
|
164
|
+
this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
|
|
165
|
+
}
|
|
166
|
+
admit(candidate) {
|
|
167
|
+
// Upper bound preserves the stable ordering of equal candidates.
|
|
168
|
+
let low = 0, high = this.candidates.length;
|
|
169
|
+
while (low < high) {
|
|
170
|
+
const mid = (low + high) >>> 1;
|
|
171
|
+
if (compareCorpus(this.candidates[mid], candidate) <= 0)
|
|
172
|
+
low = mid + 1;
|
|
173
|
+
else
|
|
174
|
+
high = mid;
|
|
175
|
+
}
|
|
176
|
+
if (this.candidates.length === this.limit) {
|
|
177
|
+
this.discarded = true;
|
|
178
|
+
if (this.scoped.from === "oldest") {
|
|
179
|
+
if (low === this.limit)
|
|
180
|
+
return;
|
|
181
|
+
this.candidates.pop();
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
if (low === 0)
|
|
185
|
+
return;
|
|
186
|
+
this.candidates.shift();
|
|
187
|
+
low--;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
this.candidates.splice(low, 0, candidate);
|
|
191
|
+
}
|
|
192
|
+
/** Admit an already selected strict overview event without selecting it a second time. */
|
|
193
|
+
addRepresentative(session, event) {
|
|
194
|
+
if (!event)
|
|
195
|
+
return false;
|
|
196
|
+
this.admit({ session, event });
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
/** Returns whether this session contributes an overview representative. */
|
|
200
|
+
add(session, projection) {
|
|
201
|
+
if (this.scoped.query === undefined)
|
|
202
|
+
return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
|
|
203
|
+
for (const event of filteredItems(projection, this.scoped, false)) {
|
|
204
|
+
const document = eventDocument(event);
|
|
205
|
+
if ((event.role === "user" || event.role === "assistant") && document === "")
|
|
206
|
+
continue;
|
|
207
|
+
const matchOffset = earliestMatchOffsetChars(document, this.scoped.query);
|
|
208
|
+
if (matchOffset >= 0)
|
|
209
|
+
this.admit({ session, event, matchOffset });
|
|
210
|
+
}
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
page(fits, maxChars, unvisited = false) {
|
|
214
|
+
return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
|
|
215
|
+
}
|
|
169
216
|
}
|
|
170
217
|
function selectPrepared(prepared, scoped, fits, maxChars) {
|
|
171
218
|
const { candidates } = prepared;
|
|
172
219
|
// Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
|
|
173
|
-
const
|
|
220
|
+
const from = scoped.from ?? (scoped.after_seq !== undefined ? "oldest" : "newest");
|
|
221
|
+
const newest = from === "newest";
|
|
174
222
|
let start = newest ? candidates.length : 0;
|
|
175
223
|
let end = start;
|
|
176
224
|
const limit = Math.max(1, scoped.limit ?? 20);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type HistorySession, type HistorySessionData, type HistorySessionRepresentative } from "./corpus.js";
|
|
2
|
+
import { type CodexLineageSource } from "./codex-transcript.js";
|
|
3
|
+
/** Internal root selection; the host's home/env seams also keep filesystem tests hermetic. */
|
|
4
|
+
export declare function historySummaryCacheRoot(home?: string, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
|
|
5
|
+
export type RepresentativeLoad = (track: (path: string) => Promise<void>) => Promise<{
|
|
6
|
+
data: HistorySessionData;
|
|
7
|
+
lineageSources?: CodexLineageSource[];
|
|
8
|
+
}>;
|
|
9
|
+
/** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
|
|
10
|
+
export declare function cachedSessionRepresentative(session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad): Promise<HistorySessionRepresentative>;
|