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/src/history/query.ts
CHANGED
|
@@ -7,7 +7,13 @@ import { InvalidQueryError, searchQueries } from "../tools/schema.js";
|
|
|
7
7
|
import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
|
|
8
8
|
|
|
9
9
|
type Candidate = { event: HistoryEvent; session?: string; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
|
|
10
|
-
type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; session?: string; multi?: boolean };
|
|
10
|
+
type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; session?: string; multi?: boolean; discarded?: boolean; from?: HistoryOrder };
|
|
11
|
+
const multiPages = new WeakSet<HistoryPage>();
|
|
12
|
+
export function isMultiPage(page: HistoryPage): boolean { return multiPages.has(page); }
|
|
13
|
+
export function markMultiPage(page: HistoryPage): HistoryPage {
|
|
14
|
+
multiPages.add(page);
|
|
15
|
+
return page;
|
|
16
|
+
}
|
|
11
17
|
|
|
12
18
|
/** Which end of one selection `limit` is taken from; page items always come back ascending. */
|
|
13
19
|
export type HistoryOrder = "newest" | "oldest";
|
|
@@ -50,21 +56,12 @@ function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number
|
|
|
50
56
|
return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
|
|
51
57
|
}
|
|
52
58
|
|
|
53
|
-
export const HistoryOlderSchema = Type.Object({
|
|
54
|
-
session: Type.Optional(Type.String()),
|
|
55
|
-
before_seq: Type.Integer({ minimum: 1 }),
|
|
56
|
-
}, { additionalProperties: false });
|
|
57
|
-
export const HistoryNewerSchema = Type.Object({
|
|
58
|
-
session: Type.Optional(Type.String()),
|
|
59
|
-
after_seq: Type.Integer({ minimum: 1 }),
|
|
60
|
-
from: Type.Literal("oldest"),
|
|
61
|
-
}, { additionalProperties: false });
|
|
62
|
-
|
|
63
59
|
export const HistoryPageSchema = Type.Object({
|
|
64
60
|
notice: Type.Optional(Type.String()),
|
|
65
|
-
items: Type.Array(
|
|
66
|
-
|
|
67
|
-
|
|
61
|
+
items: Type.Array(HistoryPageItemSchema),
|
|
62
|
+
folded_after: Type.Optional(HistoryFoldedRowSchema),
|
|
63
|
+
has_older: Type.Boolean(),
|
|
64
|
+
has_newer: Type.Boolean(),
|
|
68
65
|
}, { additionalProperties: false });
|
|
69
66
|
|
|
70
67
|
/** One whole page payload, before it becomes an outcome. */
|
|
@@ -97,7 +94,7 @@ function foldedRun(events: HistoryEvent[], session?: string): HistoryFoldedRow |
|
|
|
97
94
|
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
98
95
|
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
99
96
|
const tools = Object.fromEntries(entries);
|
|
100
|
-
return { ...(session === undefined ? {} : { session }),
|
|
97
|
+
return { ...(session === undefined ? {} : { session }), first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
|
|
101
98
|
}
|
|
102
99
|
|
|
103
100
|
/** Filter and order once. Conversation candidates own the folded gap immediately before them. */
|
|
@@ -123,19 +120,19 @@ function prepareSelection(projection: HistoryProjection, params: HistorySelectio
|
|
|
123
120
|
/** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
|
|
124
121
|
function pageData(prepared: PreparedSelection, start: number, end: number, maxChars: number, preview?: HistoryPageItem): HistoryPage {
|
|
125
122
|
const { candidates, tail } = prepared;
|
|
126
|
-
const identity = prepared.session === undefined ? {} : { session: prepared.session };
|
|
127
123
|
const items: HistoryPage["items"] = [];
|
|
128
124
|
for (let index = start; index < end; index++) {
|
|
129
125
|
const candidate = candidates[index]!;
|
|
130
|
-
|
|
131
|
-
items.push(
|
|
126
|
+
const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) });
|
|
127
|
+
items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
|
|
132
128
|
}
|
|
133
|
-
|
|
134
|
-
return {
|
|
129
|
+
const page = {
|
|
135
130
|
items,
|
|
136
|
-
|
|
137
|
-
|
|
131
|
+
...(end === candidates.length && tail ? { folded_after: tail } : {}),
|
|
132
|
+
has_older: (start > 0 && start < end) || (!!prepared.discarded && prepared.from !== "oldest"),
|
|
133
|
+
has_newer: (end < candidates.length && start < end) || (!!prepared.discarded && prepared.from === "oldest"),
|
|
138
134
|
};
|
|
135
|
+
return prepared.multi ? markMultiPage(page) : page;
|
|
139
136
|
}
|
|
140
137
|
|
|
141
138
|
/**
|
|
@@ -176,22 +173,69 @@ export function sessionRepresentative(projection: HistoryProjection, scoped: His
|
|
|
176
173
|
?? events.at(-1);
|
|
177
174
|
}
|
|
178
175
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
176
|
+
const eventTime = (event: HistoryEvent) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
|
|
177
|
+
const compareCorpus = (a: Candidate, b: Candidate) => eventTime(a.event) - eventTime(b.event) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq;
|
|
178
|
+
|
|
179
|
+
/** Keep only the requested end of the globally ordered selection while sessions are released. */
|
|
180
|
+
export class CorpusCollector {
|
|
181
|
+
private readonly candidates: Candidate[] = [];
|
|
182
|
+
private readonly limit: number;
|
|
183
|
+
private discarded = false;
|
|
184
|
+
constructor(private readonly scoped: HistorySelection) {
|
|
185
|
+
this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
private admit(candidate: Candidate): void {
|
|
189
|
+
// Upper bound preserves the stable ordering of equal candidates.
|
|
190
|
+
let low = 0, high = this.candidates.length;
|
|
191
|
+
while (low < high) {
|
|
192
|
+
const mid = (low + high) >>> 1;
|
|
193
|
+
if (compareCorpus(this.candidates[mid]!, candidate) <= 0) low = mid + 1;
|
|
194
|
+
else high = mid;
|
|
195
|
+
}
|
|
196
|
+
if (this.candidates.length === this.limit) {
|
|
197
|
+
this.discarded = true;
|
|
198
|
+
if (this.scoped.from === "oldest") {
|
|
199
|
+
if (low === this.limit) return;
|
|
200
|
+
this.candidates.pop();
|
|
201
|
+
} else {
|
|
202
|
+
if (low === 0) return;
|
|
203
|
+
this.candidates.shift();
|
|
204
|
+
low--;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
this.candidates.splice(low, 0, candidate);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Admit an already selected strict overview event without selecting it a second time. */
|
|
211
|
+
addRepresentative(session: string, event: HistoryEvent | undefined): boolean {
|
|
212
|
+
if (!event) return false;
|
|
213
|
+
this.admit({ session, event });
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Returns whether this session contributes an overview representative. */
|
|
218
|
+
add(session: string, projection: HistoryProjection): boolean {
|
|
219
|
+
if (this.scoped.query === undefined) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
|
|
220
|
+
for (const event of filteredItems(projection, this.scoped, false)) {
|
|
221
|
+
const document = eventDocument(event);
|
|
222
|
+
if ((event.role === "user" || event.role === "assistant") && document === "") continue;
|
|
223
|
+
const matchOffset = earliestMatchOffsetChars(document, this.scoped.query as string[]);
|
|
224
|
+
if (matchOffset >= 0) this.admit({ session, event, matchOffset });
|
|
225
|
+
}
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
page(fits: (page: HistoryPage) => boolean, maxChars: number, unvisited = false): Outcome<HistoryPage> {
|
|
230
|
+
return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, from: this.scoped.from }, this.scoped, fits, maxChars);
|
|
231
|
+
}
|
|
189
232
|
}
|
|
190
233
|
|
|
191
234
|
function selectPrepared(prepared: PreparedSelection, scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
|
|
192
235
|
const { candidates } = prepared;
|
|
193
236
|
// Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
|
|
194
|
-
const
|
|
237
|
+
const from = scoped.from ?? (scoped.after_seq !== undefined ? "oldest" : "newest");
|
|
238
|
+
const newest = from === "newest";
|
|
195
239
|
let start = newest ? candidates.length : 0;
|
|
196
240
|
let end = start;
|
|
197
241
|
const limit = Math.max(1, scoped.limit ?? 20);
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** Strict offline overview summaries, never projections or search indexes. Cache failures are misses. */
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdir, open, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { Type, type Static } from "typebox";
|
|
7
|
+
import { Check } from "typebox/value";
|
|
8
|
+
import { sessionIdentity, type HistorySession, type HistorySessionData, type HistorySessionRepresentative } from "./corpus.js";
|
|
9
|
+
import { HistoryRoleSchema, ToolCallStatusSchema } from "./history.js";
|
|
10
|
+
import { sessionRepresentative } from "./query.js";
|
|
11
|
+
import { validateCodexLineageSources, type CodexLineageSource } from "./codex-transcript.js";
|
|
12
|
+
|
|
13
|
+
// Bump whenever strict decoding, representative selection, or cached event presentation changes.
|
|
14
|
+
const VERSION = "strict-representative-v1";
|
|
15
|
+
const MAX_ENTRY_BYTES = 8 * 1024 * 1024;
|
|
16
|
+
const FingerprintSchema = Type.Object({
|
|
17
|
+
path: Type.String(), dev: Type.String(), ino: Type.String(), size: Type.String(), mtimeNs: Type.String(), ctimeNs: Type.String(),
|
|
18
|
+
}, { additionalProperties: false });
|
|
19
|
+
type Fingerprint = Static<typeof FingerprintSchema>;
|
|
20
|
+
const EventSchema = Type.Object({
|
|
21
|
+
seq: Type.Integer({ minimum: 1 }), windowId: Type.String(), role: HistoryRoleSchema,
|
|
22
|
+
createdAt: Type.Optional(Type.String()), text: Type.String(),
|
|
23
|
+
execution: Type.Optional(Type.Object({
|
|
24
|
+
name: Type.String(), status: ToolCallStatusSchema,
|
|
25
|
+
arguments: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
26
|
+
outputTruncated: Type.Optional(Type.Boolean()), fullOutputPath: Type.Optional(Type.String()),
|
|
27
|
+
nestedCalls: Type.Optional(Type.Object({ complete: Type.Boolean(), calls: Type.Array(Type.Object({
|
|
28
|
+
id: Type.String(), name: Type.String(), status: ToolCallStatusSchema,
|
|
29
|
+
arguments: Type.Optional(Type.Record(Type.String(), Type.Unknown())), argumentsBytes: Type.Optional(Type.Number()),
|
|
30
|
+
durationMs: Type.Optional(Type.Number()), error: Type.Optional(Type.String()),
|
|
31
|
+
}, { additionalProperties: false })) }, { additionalProperties: false })),
|
|
32
|
+
}, { additionalProperties: false })),
|
|
33
|
+
}, { additionalProperties: false });
|
|
34
|
+
const EntrySchema = Type.Object({
|
|
35
|
+
version: Type.Literal(VERSION), path: Type.String(), session: Type.String(),
|
|
36
|
+
event: Type.Union([EventSchema, Type.Null()]), notice: Type.Optional(Type.String()),
|
|
37
|
+
fingerprints: Type.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
|
|
38
|
+
lineageSources: Type.Array(Type.Object({ home: Type.String(), rolloutId: Type.String(), path: Type.String() }, { additionalProperties: false }), { maxItems: 63 }),
|
|
39
|
+
}, { additionalProperties: false });
|
|
40
|
+
|
|
41
|
+
/** Internal root selection; the host's home/env seams also keep filesystem tests hermetic. */
|
|
42
|
+
export function historySummaryCacheRoot(home = homedir(), env = process.env, platform = process.platform): string {
|
|
43
|
+
return platform === "darwin" ? join(home, "Library/Caches/notesoup/history") : join(env.XDG_CACHE_HOME || join(home, ".cache"), "notesoup/history");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function fingerprint(path: string): Promise<Fingerprint> {
|
|
47
|
+
const info = await stat(path, { bigint: true });
|
|
48
|
+
if (!info.isFile()) throw new Error("Not a regular transcript file");
|
|
49
|
+
return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
|
|
50
|
+
}
|
|
51
|
+
async function unchanged(sources: Fingerprint[]): Promise<boolean> {
|
|
52
|
+
for (const source of sources) if (JSON.stringify(await fingerprint(source.path)) !== JSON.stringify(source)) return false;
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One fingerprint per actual decoder read, in root-to-ancestor order; no untracked witnesses. */
|
|
57
|
+
function completeDependencies(path: string, harness: HistorySession["harness"], sources: Fingerprint[], lineage: CodexLineageSource[]): boolean {
|
|
58
|
+
if (harness !== "codex" && lineage.length !== 0) return false;
|
|
59
|
+
const expected = [path, ...lineage.map((source) => source.path)];
|
|
60
|
+
return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function readEntry(path: string): Promise<unknown> {
|
|
64
|
+
const file = await open(path, "r");
|
|
65
|
+
try {
|
|
66
|
+
const info = await file.stat();
|
|
67
|
+
if (!info.isFile() || info.size > MAX_ENTRY_BYTES) return undefined;
|
|
68
|
+
const buffer = Buffer.alloc(info.size + 1);
|
|
69
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
70
|
+
if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES) return undefined;
|
|
71
|
+
return JSON.parse(buffer.toString("utf8", 0, bytesRead));
|
|
72
|
+
} finally { await file.close(); }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type RepresentativeLoad = (track: (path: string) => Promise<void>) => Promise<{ data: HistorySessionData; lineageSources?: CodexLineageSource[] }>;
|
|
76
|
+
|
|
77
|
+
/** The loader always runs the strict decoder on misses; transcript errors deliberately escape. */
|
|
78
|
+
export async function cachedSessionRepresentative(
|
|
79
|
+
session: Pick<HistorySession, "harness" | "id">, transcriptPath: string, cacheRoot: string, load: RepresentativeLoad,
|
|
80
|
+
): Promise<HistorySessionRepresentative> {
|
|
81
|
+
let canonical: string | undefined, cachePath: string | undefined;
|
|
82
|
+
const identity = sessionIdentity(session);
|
|
83
|
+
try {
|
|
84
|
+
canonical = await realpath(transcriptPath);
|
|
85
|
+
cachePath = join(cacheRoot, createHash("sha256").update(JSON.stringify([VERSION, canonical, session.harness, session.id])).digest("hex") + ".json");
|
|
86
|
+
const entry = await readEntry(cachePath);
|
|
87
|
+
if (Check(EntrySchema, entry) && entry.path === canonical && entry.session === identity
|
|
88
|
+
&& completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources)
|
|
89
|
+
&& await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints)
|
|
90
|
+
&& await realpath(transcriptPath) === canonical) {
|
|
91
|
+
return { event: entry.event === null ? undefined : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
|
|
92
|
+
}
|
|
93
|
+
} catch { /* Absent/corrupt/unwritable cache or changed source: strict load below. */ }
|
|
94
|
+
|
|
95
|
+
const fingerprints = new Map<string, Fingerprint>();
|
|
96
|
+
let stable = canonical !== undefined;
|
|
97
|
+
const track = async (path: string) => {
|
|
98
|
+
try { if (!fingerprints.has(path)) fingerprints.set(path, await fingerprint(path)); }
|
|
99
|
+
catch { stable = false; }
|
|
100
|
+
};
|
|
101
|
+
if (canonical) await track(canonical);
|
|
102
|
+
const { data, lineageSources = [] } = await load(track);
|
|
103
|
+
const event = sessionRepresentative(data.projection, {});
|
|
104
|
+
const result = { event, notice: data.notice };
|
|
105
|
+
try {
|
|
106
|
+
const sources = [...fingerprints.values()];
|
|
107
|
+
if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources)
|
|
108
|
+
|| !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath(transcriptPath) !== canonical) return result;
|
|
109
|
+
const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
|
|
110
|
+
if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES) return result;
|
|
111
|
+
await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
|
|
112
|
+
const temporary = `${cachePath}.${randomUUID()}.tmp`;
|
|
113
|
+
try {
|
|
114
|
+
await writeFile(temporary, entry, { flag: "wx", mode: 0o600 });
|
|
115
|
+
await rename(temporary, cachePath);
|
|
116
|
+
} finally { await unlink(temporary).catch(() => {}); }
|
|
117
|
+
} catch { /* The cache cannot turn readable history into a refusal. */ }
|
|
118
|
+
return result;
|
|
119
|
+
}
|
package/src/tools/history.ts
CHANGED
|
@@ -3,8 +3,8 @@ import { Type, type Static } from "typebox";
|
|
|
3
3
|
import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS } from "./output.js";
|
|
4
4
|
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation } from "./result.js";
|
|
5
5
|
import { historyRoles, searchQuery } from "./schema.js";
|
|
6
|
-
import { HistoryPageSchema, corpusSelection,
|
|
7
|
-
import { currentHistory, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity, type HistoryContext } from "../history/corpus.js";
|
|
6
|
+
import { HistoryPageSchema, CorpusCollector, corpusSelection, isMultiPage, markMultiPage, selectPage, type HistoryPage } from "../history/query.js";
|
|
7
|
+
import { currentHistory, loadHistoryRepresentative, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity, type HistoryContext } from "../history/corpus.js";
|
|
8
8
|
import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryFoldedRow, type HistoryPageItem } from "../history/history.js";
|
|
9
9
|
|
|
10
10
|
/** One read: identity, tool summary and a flat document slice. */
|
|
@@ -47,25 +47,31 @@ function renderPageItem(item: HistoryPageItem): string {
|
|
|
47
47
|
function renderFoldedRow(row: HistoryFoldedRow): string {
|
|
48
48
|
const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
|
|
49
49
|
const identity = row.session === undefined ? {} : { session: row.session };
|
|
50
|
-
const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1,
|
|
50
|
+
const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, roles: ["tool", "context"] })}`;
|
|
51
51
|
return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
function renderPage(page: HistoryPage): string {
|
|
55
55
|
// An empty selection has no anchors either, so it would otherwise render as nothing at all.
|
|
56
|
-
if (page.items.length === 0) return `${page.notice ?? ""}No events match these filters.`;
|
|
57
|
-
const body = page.items.
|
|
56
|
+
if (page.items.length === 0 && !page.folded_after) return `${page.notice ?? ""}No events match these filters.`;
|
|
57
|
+
const body = [...page.items.flatMap((item) => [...(item.folded_before ? [renderFoldedRow(item.folded_before)] : []), renderPageItem(item)]), ...(page.folded_after ? [renderFoldedRow(page.folded_after)] : [])].join("\n\n");
|
|
58
|
+
if (isMultiPage(page)) {
|
|
59
|
+
const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
|
|
60
|
+
return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with since/until, query, roles or the session pattern` : "");
|
|
61
|
+
}
|
|
62
|
+
const first = page.items[0]!;
|
|
63
|
+
const last = page.items.at(-1)!;
|
|
64
|
+
|
|
58
65
|
const cursors = [
|
|
59
|
-
page.
|
|
60
|
-
page.
|
|
66
|
+
page.has_older ? `→ older: ${JSON.stringify({ ...(first.session === undefined ? {} : { session: first.session }), before_seq: first.seq })}` : "",
|
|
67
|
+
page.has_newer ? `→ newer: ${JSON.stringify({ ...(last.session === undefined ? {} : { session: last.session }), after_seq: last.seq })}` : "",
|
|
61
68
|
].filter((line) => line !== "");
|
|
62
69
|
return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
|
|
63
70
|
}
|
|
64
71
|
|
|
65
72
|
function renderRead(data: HistoryReadData): string {
|
|
66
73
|
const tool = toolHeader(data);
|
|
67
|
-
const
|
|
68
|
-
const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
|
|
74
|
+
const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), after_seq: Math.max(0, data.seq - 10), before_seq: data.seq + 10 })})`;
|
|
69
75
|
return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
|
|
70
76
|
}
|
|
71
77
|
|
|
@@ -84,11 +90,11 @@ export const historyListParameters = Type.Object({
|
|
|
84
90
|
query: Type.Optional(searchQuery("(optional) Text, or a list of texts (any match). Empty text/list means no search filter; empty entries are ignored. Searches every role, tool arguments and output included; returns only hits.")),
|
|
85
91
|
roles: historyRoles(),
|
|
86
92
|
before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
|
|
87
|
-
after_seq: Type.Optional(Type.Integer({ minimum:
|
|
93
|
+
after_seq: Type.Optional(Type.Integer({ minimum: 0, description: "(optional) Only events with seq above this; 0 means from the start." })),
|
|
88
94
|
since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
|
|
89
95
|
until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
|
|
90
|
-
from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional
|
|
91
|
-
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded
|
|
96
|
+
from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional) Which end `limit` counts from: newest or oldest (default oldest when `after_seq` is set, else newest). Results stay oldest first." })),
|
|
97
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded runs don't count." })),
|
|
92
98
|
max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
|
|
93
99
|
}, { additionalProperties: false });
|
|
94
100
|
|
|
@@ -113,19 +119,26 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
|
|
|
113
119
|
const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
|
|
114
120
|
const queries = Array.isArray(scoped.data.query) ? scoped.data.query : undefined;
|
|
115
121
|
if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
|
|
116
|
-
const
|
|
122
|
+
const representative = !queries && scoped.data.roles === undefined && scoped.data.since === undefined && scoped.data.until === undefined;
|
|
123
|
+
const collector = new CorpusCollector(scoped.data);
|
|
124
|
+
let qualifying = 0;
|
|
117
125
|
const notices: string[] = [];
|
|
118
|
-
|
|
119
|
-
|
|
126
|
+
let unvisited = false;
|
|
127
|
+
for (const [index, session] of sessions.entries()) {
|
|
128
|
+
const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, queries);
|
|
120
129
|
if (!result.ok || !result.data) continue;
|
|
121
|
-
|
|
122
|
-
|
|
130
|
+
const added = "projection" in result.data ? collector.add(sessionIdentity(session), result.data.projection) : collector.addRepresentative(sessionIdentity(session), result.data.event);
|
|
131
|
+
if (!added) continue;
|
|
132
|
+
qualifying++;
|
|
123
133
|
if (result.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
|
|
124
|
-
if (!queries &&
|
|
134
|
+
if (!queries && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
|
|
135
|
+
unvisited = index + 1 < sessions.length;
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
125
138
|
}
|
|
126
139
|
const notice = notices.length ? { notice: notices.join("") } : {};
|
|
127
|
-
const result =
|
|
128
|
-
return result.ok ? success({ ...result.data, ...notice }) : result;
|
|
140
|
+
const result = collector.page((page) => fits(markMultiPage({ ...page, ...notice })), maxChars, unvisited);
|
|
141
|
+
return result.ok ? success(markMultiPage({ ...result.data, ...notice })) : result;
|
|
129
142
|
}
|
|
130
143
|
const target = await resolveSession(corpus, selector.data);
|
|
131
144
|
if (!target.ok) return target;
|