notesoup 0.39.0 → 0.40.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 +5 -2
- package/dist/src/boot/render.js +2 -2
- package/dist/src/boot/text.d.ts +0 -4
- package/dist/src/boot/text.js +9 -13
- package/dist/src/history/history.d.ts +23 -18
- package/dist/src/history/history.js +37 -20
- package/dist/src/history/query.d.ts +37 -49
- package/dist/src/history/query.js +114 -56
- package/dist/src/notes/store.d.ts +3 -4
- package/dist/src/notes/store.js +12 -16
- package/dist/src/pi/history-tools.d.ts +1 -1
- package/dist/src/pi/history-tools.js +2 -3
- package/dist/src/pi/runtime.js +1 -1
- package/dist/src/pi/tool-names.d.ts +0 -4
- package/dist/src/pi/tool-names.js +0 -4
- package/dist/src/tools/history.d.ts +24 -33
- package/dist/src/tools/history.js +57 -98
- package/dist/src/tools/notes.d.ts +26 -58
- package/dist/src/tools/notes.js +85 -103
- package/dist/src/tools/result.d.ts +16 -13
- package/dist/src/tools/result.js +24 -50
- package/dist/src/tools/schema.d.ts +2 -2
- package/dist/src/tools/schema.js +3 -3
- package/dist/test/agent-loop.test.js +1 -1
- package/dist/test/boot.integration.test.js +1 -1
- package/dist/test/claude-mod.test.js +4 -4
- package/dist/test/dependencies.test.js +1 -1
- package/dist/test/helpers/extension.js +2 -3
- package/dist/test/history.integration.test.js +200 -123
- package/dist/test/host-neutral.test.js +32 -58
- package/dist/test/notes-library.test.js +8 -8
- package/dist/test/notes.integration.test.js +75 -57
- package/dist/test/notes.test.js +44 -42
- package/docs/architecture.md +3 -3
- package/docs/notes-library.md +6 -6
- package/docs/tool-results.md +15 -25
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +119 -178
- package/mods/notesoup/hooks/register.ts +1 -2
- package/package.json +1 -1
- package/skills/memory/SKILL.md +6 -6
- package/src/boot/render.ts +2 -2
- package/src/boot/text.ts +9 -17
- package/src/history/history.ts +36 -20
- package/src/history/query.ts +130 -55
- package/src/notes/store.ts +15 -18
- package/src/pi/history-tools.ts +2 -3
- package/src/pi/runtime.ts +1 -1
- package/src/pi/tool-names.ts +0 -4
- package/src/tools/history.ts +61 -100
- package/src/tools/notes.ts +84 -97
- package/src/tools/result.ts +24 -49
- package/src/tools/schema.ts +3 -3
package/src/notes/store.ts
CHANGED
|
@@ -31,16 +31,16 @@ export type NotesQuery = (
|
|
|
31
31
|
| { scope?: undefined; who?: never }
|
|
32
32
|
| { scope: "session" | "project" | "human"; who?: never }
|
|
33
33
|
| { scope: "agent" | "model"; who?: string }
|
|
34
|
-
) & {
|
|
34
|
+
) & { glob?: string; crumpled?: boolean };
|
|
35
35
|
/** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
|
|
36
36
|
export type NoteReadResult = { meta: NoteMeta; body: string; resolvedScope: Scope };
|
|
37
37
|
export type NoteWriteResult = { meta: NoteMeta; outcome: "created" | "overwrote" | "uncrumpled" };
|
|
38
38
|
export type NoteChange =
|
|
39
39
|
| { kind: "none"; before: ""; after: "" }
|
|
40
|
-
| { kind: "body" | "metadata"
|
|
40
|
+
| { kind: "body" | "metadata"; before: string; after: string };
|
|
41
41
|
export type NoteEditResult = { meta: NoteMeta; applied: number; resolvedScope: Scope; change: NoteChange };
|
|
42
42
|
export type NoteRenameResult = { meta: NoteMeta; replacedCrumpledTarget: boolean };
|
|
43
|
-
export type NoteQueryStatus = {
|
|
43
|
+
export type NoteQueryStatus = { homesUnavailable: string[] };
|
|
44
44
|
export type NoteQueryResult<T> = { rows: T[]; status: NoteQueryStatus };
|
|
45
45
|
|
|
46
46
|
/** Public identity resolved for an operation, never a filesystem path. */
|
|
@@ -174,7 +174,7 @@ async function homesFor(identity: NotesIdentity, opts: NotesQuery): Promise<Home
|
|
|
174
174
|
return [{ scope }];
|
|
175
175
|
}
|
|
176
176
|
if (opts.who !== undefined) throw new NoteError("invalid_scope", "who requires agent or model scope");
|
|
177
|
-
return await homesForPattern(normalizePattern(opts.
|
|
177
|
+
return await homesForPattern(normalizePattern(opts.glob, identity), identity) ?? SCOPE_ORDER.map((scope) => ({ scope }));
|
|
178
178
|
}
|
|
179
179
|
|
|
180
180
|
/**
|
|
@@ -358,7 +358,9 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
358
358
|
assertSerializedSize(serialized);
|
|
359
359
|
const metadataChanged = originChanged || beforeMeta.crumpledAt !== meta.crumpledAt;
|
|
360
360
|
let change: NoteChange;
|
|
361
|
-
|
|
361
|
+
// A body edit that also rewrites frontmatter is still a body change; its diff inputs span the
|
|
362
|
+
// whole serialized file, so the frontmatter part stays visible in the diff.
|
|
363
|
+
if (bodyChanged && metadataChanged) change = { kind: "body", before: raw, after: serialized };
|
|
362
364
|
else if (bodyChanged) change = { kind: "body", before: body, after: next };
|
|
363
365
|
else if (metadataChanged) change = { kind: "metadata", before: frontmatterOf(beforeMeta), after: frontmatterOf(meta) };
|
|
364
366
|
else change = { kind: "none", before: "", after: "" };
|
|
@@ -406,20 +408,19 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
406
408
|
}
|
|
407
409
|
|
|
408
410
|
async function* scan(options: NotesQuery, status?: NoteQueryStatus): AsyncGenerator<Omit<NoteRow, "sizeBytes">> {
|
|
409
|
-
const matcher = matcherFor(normalizePattern(options.
|
|
411
|
+
const matcher = matcherFor(normalizePattern(options.glob, identity));
|
|
410
412
|
let homes: HomeRef[];
|
|
411
413
|
try {
|
|
412
414
|
homes = await homesFor(identity, options);
|
|
413
415
|
} catch (error) {
|
|
414
|
-
if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.
|
|
415
|
-
status.homesUnavailable.push(options.
|
|
416
|
+
if (!status || !isFilesystemError(error) || !/^@(agents|models)\//.test(options.glob ?? "")) throw error;
|
|
417
|
+
status.homesUnavailable.push(options.glob!.startsWith("@agents/") ? "@agents" : "@models");
|
|
416
418
|
return;
|
|
417
419
|
}
|
|
418
420
|
for (const home of homes) {
|
|
419
421
|
const scope = home.scope;
|
|
420
422
|
const root = scopeDir(scope, identity, home.who);
|
|
421
423
|
const homeRows: Array<Omit<NoteRow, "sizeBytes">> = [];
|
|
422
|
-
let excluded = 0;
|
|
423
424
|
try {
|
|
424
425
|
for (const path of await walkMarkdown(root)) {
|
|
425
426
|
if (matcher && !matcher.test(canonicalAddressFor(identity, scope, path, home.who))) continue;
|
|
@@ -428,10 +429,7 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
428
429
|
const raw = await withPathQueue(fullPath, () => readFile(fullPath, "utf8"));
|
|
429
430
|
const { meta, body } = parseNote(raw);
|
|
430
431
|
meta.scope = scope;
|
|
431
|
-
if ((meta.crumpledAt !== undefined) !== (options.
|
|
432
|
-
if (meta.crumpledAt !== undefined) excluded++;
|
|
433
|
-
continue;
|
|
434
|
-
}
|
|
432
|
+
if ((meta.crumpledAt !== undefined) !== (options.crumpled === true)) continue;
|
|
435
433
|
homeRows.push({ address, scope, path, meta, body });
|
|
436
434
|
}
|
|
437
435
|
} catch (error) {
|
|
@@ -439,7 +437,6 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
439
437
|
status.homesUnavailable.push(addressFor(identity, scope, "", home.who).replace(/\/$/, "") || "session");
|
|
440
438
|
continue;
|
|
441
439
|
}
|
|
442
|
-
if (status) status.crumpledExcluded += excluded;
|
|
443
440
|
for (const row of homeRows) yield row;
|
|
444
441
|
}
|
|
445
442
|
}
|
|
@@ -455,11 +452,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
455
452
|
rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
|
|
456
453
|
}
|
|
457
454
|
rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
|
|
458
|
-
return { rows, status: status ?? {
|
|
455
|
+
return { rows, status: status ?? { homesUnavailable: [] } };
|
|
459
456
|
}
|
|
460
457
|
|
|
461
458
|
function listWithStatus(options: NotesQuery = {}): Promise<NoteQueryResult<NoteRow>> {
|
|
462
|
-
return listRows(options, {
|
|
459
|
+
return listRows(options, { homesUnavailable: [] });
|
|
463
460
|
}
|
|
464
461
|
|
|
465
462
|
async function search(queries: string[], options: NotesQuery = {}): Promise<NoteSearchRow[]> {
|
|
@@ -486,11 +483,11 @@ export function createNotesStore(input: NotesIdentity): NotesStore {
|
|
|
486
483
|
if (matches.length > 0) rows.push({ address, path, scope, meta, matches });
|
|
487
484
|
}
|
|
488
485
|
rows.sort((a, b) => a.address.localeCompare(b.address));
|
|
489
|
-
return { rows, status: status ?? {
|
|
486
|
+
return { rows, status: status ?? { homesUnavailable: [] } };
|
|
490
487
|
}
|
|
491
488
|
|
|
492
489
|
function searchWithStatus(queries: string[], options: NotesQuery = {}): Promise<NoteQueryResult<NoteSearchRow>> {
|
|
493
|
-
return searchRows(queries, options, {
|
|
490
|
+
return searchRows(queries, options, { homesUnavailable: [] });
|
|
494
491
|
}
|
|
495
492
|
|
|
496
493
|
return { write, read, update, rename, list, search, listWithStatus, searchWithStatus };
|
package/src/pi/history-tools.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { historyWindows, historyList, historyRead
|
|
2
|
+
import { historyWindows, historyList, historyRead } from "../tools/history.js";
|
|
3
3
|
import { historyFromSession } from "./history.js";
|
|
4
4
|
import { HISTORY_NAMESPACE, registerOperation } from "./tool-result.js";
|
|
5
5
|
|
|
6
|
-
/** Register the
|
|
6
|
+
/** Register the three shared history operations; the adapter allocates addresses and supplies them. */
|
|
7
7
|
export function registerHistoryTools(pi: ExtensionAPI) {
|
|
8
8
|
registerOperation(pi, historyWindows, (params, ctx) => historyWindows.execute(params, historyFromSession(ctx), ctx.sessionManager.getSessionId()), HISTORY_NAMESPACE);
|
|
9
9
|
registerOperation(pi, historyList, (params, ctx) => historyList.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
10
10
|
registerOperation(pi, historyRead, (params, ctx) => historyRead.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
11
|
-
registerOperation(pi, historySearch, (params, ctx) => historySearch.execute(params, historyFromSession(ctx)), HISTORY_NAMESPACE);
|
|
12
11
|
}
|
package/src/pi/runtime.ts
CHANGED
|
@@ -56,7 +56,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
56
56
|
if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId)) return;
|
|
57
57
|
incompleteNotesNotified.add(windowId);
|
|
58
58
|
const homes = snapshot.unavailable.map((home) => home.label).join(", ");
|
|
59
|
-
ctx.ui.notify(`notesoup: notes index incomplete for ${homes}; notes_list can retry after recovery.`, "warning");
|
|
59
|
+
ctx.ui.notify(`notesoup: notes index incomplete for ${homes}; \`notes_list\` can retry after recovery.`, "warning");
|
|
60
60
|
};
|
|
61
61
|
const budget = registerBudget(pi, () => enabled, settingsManager, (windowId) => resets.closeOut(windowId, "automatic"));
|
|
62
62
|
|
package/src/pi/tool-names.ts
CHANGED
|
@@ -4,10 +4,6 @@ export const PI_TOOL_NAMES = {
|
|
|
4
4
|
notes: "notes_*",
|
|
5
5
|
notesList: "notes_list",
|
|
6
6
|
history: "history_*",
|
|
7
|
-
historyWindows: "history_windows",
|
|
8
|
-
historyList: "history_list",
|
|
9
|
-
historySearch: "history_search",
|
|
10
|
-
historyRead: "history_read",
|
|
11
7
|
remaining: "get_context_remaining",
|
|
12
8
|
wipe: "clear_memory",
|
|
13
9
|
} as const satisfies BootToolNames;
|
package/src/tools/history.ts
CHANGED
|
@@ -1,23 +1,10 @@
|
|
|
1
1
|
/** Host-neutral history operations: one bounded payload for text and structured results. */
|
|
2
2
|
import { Type, type Static } from "typebox";
|
|
3
|
-
import {
|
|
4
|
-
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowSchema, type Operation, type Outcome } from "./result.js";
|
|
5
|
-
import { historyRoles,
|
|
6
|
-
import { HistoryPageSchema,
|
|
7
|
-
import { allItems, eventDocument,
|
|
8
|
-
|
|
9
|
-
const HistoryWindowsDataSchema = Type.Object({
|
|
10
|
-
session_id: Type.String(),
|
|
11
|
-
windows: Type.Array(Type.Object({
|
|
12
|
-
window_id: Type.String(),
|
|
13
|
-
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
14
|
-
first_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
|
|
15
|
-
last_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
|
|
16
|
-
item_count: Type.Integer({ minimum: 0 }),
|
|
17
|
-
}, { additionalProperties: false }), { description: "Oldest first." }),
|
|
18
|
-
more: Type.Integer({ minimum: 0, description: "Omitted windows; history_list also supplies window ids." }),
|
|
19
|
-
}, { additionalProperties: false });
|
|
20
|
-
type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
|
|
3
|
+
import { HISTORY_PREVIEW_CHARS } from "./output.js";
|
|
4
|
+
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation, type Outcome } from "./result.js";
|
|
5
|
+
import { historyRoles, searchQuery } from "./schema.js";
|
|
6
|
+
import { HistoryPageSchema, selectPage, type HistoryPage } from "../history/query.js";
|
|
7
|
+
import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection, unknownWindowId } from "../history/history.js";
|
|
21
8
|
|
|
22
9
|
/** One read: identity, tool summary and a flat document slice. */
|
|
23
10
|
const HistoryReadDataSchema = Type.Object({
|
|
@@ -26,19 +13,32 @@ const HistoryReadDataSchema = Type.Object({
|
|
|
26
13
|
role: HistoryRoleSchema,
|
|
27
14
|
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
28
15
|
...ToolSummarySchema.properties,
|
|
16
|
+
nested_calls: Type.Optional(NestedCallSummarySchema),
|
|
29
17
|
...TextWindowSchema.properties,
|
|
30
18
|
}, { additionalProperties: false });
|
|
31
19
|
type HistoryReadData = Static<typeof HistoryReadDataSchema>;
|
|
32
20
|
|
|
21
|
+
const HistoryWindowsDataSchema = Type.Object({
|
|
22
|
+
session_id: Type.String(),
|
|
23
|
+
windows: Type.Array(Type.Object({
|
|
24
|
+
window_id: Type.String(),
|
|
25
|
+
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
26
|
+
first_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
|
|
27
|
+
last_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
|
|
28
|
+
}, { additionalProperties: false })),
|
|
29
|
+
more: Type.Integer({ minimum: 0, description: "How many more were left out." }),
|
|
30
|
+
}, { additionalProperties: false });
|
|
31
|
+
type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
|
|
32
|
+
|
|
33
33
|
/* ------------------------------------------------------------------ rendering */
|
|
34
34
|
|
|
35
35
|
function header(item: { seq: number; window_id: string; role: string }): string {
|
|
36
36
|
return `seq ${item.seq} | window ${item.window_id} | ${item.role}`;
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
function toolHeader(item: { role: string; tool?: string;
|
|
39
|
+
function toolHeader(item: { role: string; tool?: string; tool_status?: string; output_truncated?: true; full_output_path?: string; nested_calls?: { call_count: number; complete: boolean } }): string | undefined {
|
|
40
40
|
if (item.role !== "tool") return undefined;
|
|
41
|
-
const parts = [
|
|
41
|
+
const parts = [`tool ${item.tool}`, `status ${item.tool_status}`];
|
|
42
42
|
if (item.output_truncated) parts.push(`output truncated${item.full_output_path ? `, full text at ${item.full_output_path}` : ""}`);
|
|
43
43
|
if (item.nested_calls) {
|
|
44
44
|
parts.push(`nested calls ${item.nested_calls.call_count} recorded, ${item.nested_calls.complete ? "complete" : "incomplete"}`);
|
|
@@ -49,7 +49,7 @@ function toolHeader(item: { role: string; tool?: string; tool_name_omitted?: boo
|
|
|
49
49
|
function renderPageItem(item: HistoryPageItem): string {
|
|
50
50
|
const tool = toolHeader(item);
|
|
51
51
|
const lines = tool === undefined ? [header(item)] : [header(item), tool];
|
|
52
|
-
if (item.truncated) lines.push(`[
|
|
52
|
+
if (item.truncated) lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
|
|
53
53
|
lines.push(item.content);
|
|
54
54
|
return lines.join("\n");
|
|
55
55
|
}
|
|
@@ -60,9 +60,8 @@ function isFoldedRow(item: HistoryPageItem | HistoryFoldedRow): item is HistoryF
|
|
|
60
60
|
|
|
61
61
|
function renderFoldedRow(row: HistoryFoldedRow): string {
|
|
62
62
|
const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${omitted}${expand}`;
|
|
63
|
+
const expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
|
|
64
|
+
return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
|
|
66
65
|
}
|
|
67
66
|
|
|
68
67
|
function renderPage(page: HistoryPage): string {
|
|
@@ -70,15 +69,16 @@ function renderPage(page: HistoryPage): string {
|
|
|
70
69
|
if (page.items.length === 0) return "no events match this selection";
|
|
71
70
|
const body = page.items.map((item) => (isFoldedRow(item) ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
|
|
72
71
|
const cursors = [
|
|
73
|
-
page.
|
|
74
|
-
page.
|
|
72
|
+
page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
|
|
73
|
+
page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
|
|
75
74
|
].filter((line) => line !== "");
|
|
76
75
|
return cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`;
|
|
77
76
|
}
|
|
78
77
|
|
|
79
78
|
function renderRead(data: HistoryReadData): string {
|
|
80
79
|
const tool = toolHeader(data);
|
|
81
|
-
const
|
|
80
|
+
const afterSeq = data.seq - 10;
|
|
81
|
+
const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
|
|
82
82
|
return [header(data), ...(tool ? [tool] : []), neighborhood, "", renderTextWindow(data)].join("\n");
|
|
83
83
|
}
|
|
84
84
|
|
|
@@ -89,8 +89,13 @@ function pageFits(page: HistoryPage): boolean {
|
|
|
89
89
|
return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
// Sample known ids
|
|
93
|
-
const MAX_REPORTED_WINDOWS =
|
|
92
|
+
// Sample known ids in the refusal message itself, never as a second listing.
|
|
93
|
+
const MAX_REPORTED_WINDOWS = 5;
|
|
94
|
+
|
|
95
|
+
/** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
|
|
96
|
+
function knownWindowSuffix(known: string[]): string {
|
|
97
|
+
return known.length === 0 ? "" : `; known: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
|
|
98
|
+
}
|
|
94
99
|
|
|
95
100
|
export const PREVIOUS_WINDOW = "@previous";
|
|
96
101
|
|
|
@@ -100,18 +105,13 @@ function resolveWindowId(projection: HistoryProjection, windowId: string | undef
|
|
|
100
105
|
const previous = projection.windows.at(-2);
|
|
101
106
|
if (previous !== undefined) return { ok: true, window_id: previous.windowId };
|
|
102
107
|
const known = projection.windows.map((current) => current.windowId);
|
|
103
|
-
return { ok: false, outcome: failure("unknown_window_id", `unknown window_id "${PREVIOUS_WINDOW}": this session has no window before the current one
|
|
108
|
+
return { ok: false, outcome: failure("unknown_window_id", `unknown window_id "${PREVIOUS_WINDOW}": this session has no window before the current one${knownWindowSuffix(known)}`) };
|
|
104
109
|
}
|
|
105
110
|
|
|
106
111
|
function badWindowId(projection: HistoryProjection, params: HistoryFilter): Outcome<never> | undefined {
|
|
107
112
|
const badWindow = unknownWindowId(projection, params);
|
|
108
113
|
if (!badWindow) return undefined;
|
|
109
|
-
|
|
110
|
-
return failure("unknown_window_id", badWindow.message, {
|
|
111
|
-
window_id: params.window_id,
|
|
112
|
-
known_windows: known.slice(0, MAX_REPORTED_WINDOWS),
|
|
113
|
-
...(known.length > MAX_REPORTED_WINDOWS ? { known_windows_omitted: known.length - MAX_REPORTED_WINDOWS } : {}),
|
|
114
|
-
});
|
|
114
|
+
return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}`);
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
/* ------------------------------------------------------------------ history_windows */
|
|
@@ -121,7 +121,7 @@ export const historyWindowsParameters = Type.Object({}, { additionalProperties:
|
|
|
121
121
|
export const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string]> = {
|
|
122
122
|
name: "history_windows",
|
|
123
123
|
label: "History list windows",
|
|
124
|
-
description: "List session
|
|
124
|
+
description: "List this session's context windows, oldest first, with seq ranges.",
|
|
125
125
|
parameters: historyWindowsParameters,
|
|
126
126
|
outputSchema: resultSchema(HistoryWindowsDataSchema),
|
|
127
127
|
async execute(_params, projection, sessionId) {
|
|
@@ -134,37 +134,41 @@ export const historyWindows: Operation<typeof historyWindowsParameters, HistoryW
|
|
|
134
134
|
first = first === null ? event.seq : Math.min(first, event.seq);
|
|
135
135
|
last = last === null ? event.seq : Math.max(last, event.seq);
|
|
136
136
|
}
|
|
137
|
-
const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last
|
|
137
|
+
const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last };
|
|
138
138
|
if (!fits({ ...data, windows: [...data.windows, row], more: data.more - 1 })) break;
|
|
139
139
|
data.windows.push(row);
|
|
140
140
|
data.more--;
|
|
141
141
|
}
|
|
142
|
-
return fits(data) ? success(data) : failure("output_too_large", "The session identity does not fit one history_windows response.");
|
|
142
|
+
return fits(data) ? success(data) : failure("output_too_large", "The session identity does not fit one `history_windows` response.");
|
|
143
143
|
},
|
|
144
144
|
render: (result) => renderOutcome(result, renderWindows),
|
|
145
145
|
};
|
|
146
146
|
|
|
147
147
|
function renderWindows(data: HistoryWindowsData): string {
|
|
148
|
-
const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}
|
|
149
|
-
if (data.more > 0) lines.push(`${data.more} more windows not shown; history_list also reports window ids on events`);
|
|
148
|
+
const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
|
|
149
|
+
if (data.more > 0) lines.push(`${data.more} more windows not shown; \`history_list\` also reports window ids on events`);
|
|
150
150
|
return lines.join("\n");
|
|
151
151
|
}
|
|
152
152
|
|
|
153
153
|
/* ------------------------------------------------------------------ history_list */
|
|
154
154
|
|
|
155
155
|
export const historyListParameters = Type.Object({
|
|
156
|
-
|
|
156
|
+
query: Type.Optional(searchQuery("(optional) Text, or a list of texts (any match). Searches every role, tool arguments and output included; returns only hits.")),
|
|
157
157
|
roles: historyRoles(),
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
158
|
+
before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
|
|
159
|
+
after_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq above this." })),
|
|
160
|
+
since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
|
|
161
|
+
until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
|
|
162
|
+
from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
|
|
163
|
+
window_id: Type.Optional(Type.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
|
|
164
|
+
limit: Type.Optional(Type.Integer({ description: "(optional, default 20) Max events per page; folded rows don't count." })),
|
|
165
|
+
max_chars_per_item: Type.Optional(Type.Integer({ description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
|
|
162
166
|
}, { additionalProperties: false });
|
|
163
167
|
|
|
164
168
|
export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]> = {
|
|
165
169
|
name: "history_list",
|
|
166
170
|
label: "History list items",
|
|
167
|
-
description: "
|
|
171
|
+
description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
|
|
168
172
|
parameters: historyListParameters,
|
|
169
173
|
outputSchema: resultSchema(HistoryPageSchema),
|
|
170
174
|
async execute(params, projection) {
|
|
@@ -173,24 +177,19 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
|
|
|
173
177
|
const scoped = { ...params, window_id: resolved.window_id };
|
|
174
178
|
const badWindow = badWindowId(projection, scoped);
|
|
175
179
|
if (badWindow) return badWindow;
|
|
176
|
-
|
|
177
|
-
return selectPage(projection, scoped, items.map((event) => ({ event })), isConversationView(scoped), pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
|
|
180
|
+
return selectPage(projection, scoped, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
|
|
178
181
|
},
|
|
179
182
|
render: (result) => renderOutcome(result, renderPage),
|
|
180
183
|
};
|
|
181
184
|
|
|
182
185
|
/* ------------------------------------------------------------------ history_read */
|
|
183
186
|
|
|
184
|
-
export const historyReadParameters = Type.Object({
|
|
185
|
-
seq: Type.Integer({ minimum: 1, description: "Event address from history_list/search." }),
|
|
186
|
-
offset_chars: Type.Optional(Type.Integer({ description: "Code-point offset (default 0); negative counts from EOF." })),
|
|
187
|
-
limit_chars: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `Max code points (default ${DEFAULT_READ_WINDOW_CHARS}); also bounded by output bytes.` })),
|
|
188
|
-
}, { additionalProperties: false });
|
|
187
|
+
export const historyReadParameters = Type.Object({ seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`." }), ...TextWindowRequestSchema }, { additionalProperties: false });
|
|
189
188
|
|
|
190
189
|
export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection]> = {
|
|
191
190
|
name: "history_read",
|
|
192
191
|
label: "History read item",
|
|
193
|
-
description: "Read
|
|
192
|
+
description: "Read one event in full: tool arguments, output, and nested calls.",
|
|
194
193
|
parameters: historyReadParameters,
|
|
195
194
|
outputSchema: resultSchema(HistoryReadDataSchema),
|
|
196
195
|
async execute(params, projection) {
|
|
@@ -198,33 +197,34 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
|
|
|
198
197
|
// Address checks run in one order: past the end of the file, off this branch, then
|
|
199
198
|
// consumed by a pairing. Only the last two can mention what is at the address.
|
|
200
199
|
if (item === undefined && params.seq > projection.highestSeq) {
|
|
201
|
-
return failure("unknown_seq", `unknown seq ${params.seq}: this session's items run 1..${projection.highestSeq}
|
|
200
|
+
return failure("unknown_seq", `unknown seq ${params.seq}: this session's items run 1..${projection.highestSeq}`);
|
|
202
201
|
}
|
|
203
202
|
if (!projection.branchSeqs.has(params.seq)) {
|
|
204
|
-
return failure("not_on_branch", `seq ${params.seq} is on another branch and is not readable here
|
|
203
|
+
return failure("not_on_branch", `seq ${params.seq} is on another branch and is not readable here`);
|
|
205
204
|
}
|
|
206
205
|
if (item === undefined) {
|
|
207
206
|
const callSeq = projection.pairedResults.get(params.seq);
|
|
208
207
|
if (callSeq !== undefined) {
|
|
209
|
-
return failure("not_an_event", `seq ${params.seq} is a tool result already shown inside the call at seq ${callSeq}; read that seq instead
|
|
208
|
+
return failure("not_an_event", `seq ${params.seq} is a tool result already shown inside the call at seq ${callSeq}; read that seq instead`);
|
|
210
209
|
}
|
|
211
|
-
return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event
|
|
210
|
+
return failure("unknown_seq", `seq ${params.seq} is on this branch but carries no readable event`);
|
|
212
211
|
}
|
|
213
212
|
const document = eventDocument(item);
|
|
214
213
|
const totalChars = Array.from(document).length;
|
|
215
214
|
if (typeof params.offset_chars === "number" && params.offset_chars > totalChars) {
|
|
216
|
-
return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end: the item has ${totalChars} chars; the largest legal offset is ${totalChars} (an empty end-read)
|
|
215
|
+
return failure("invalid_offset", `offset_chars ${params.offset_chars} is past the end: the item has ${totalChars} chars; the largest legal offset is ${totalChars} (an empty end-read)`);
|
|
217
216
|
}
|
|
218
217
|
return readTextWindow(
|
|
219
218
|
document,
|
|
220
219
|
params.offset_chars,
|
|
221
|
-
params.
|
|
220
|
+
params.max_chars,
|
|
222
221
|
(window) => ({
|
|
223
222
|
seq: item.seq,
|
|
224
223
|
window_id: item.windowId,
|
|
225
224
|
role: item.role,
|
|
226
225
|
created_at: item.createdAt ?? null,
|
|
227
226
|
...toolSummary(item),
|
|
227
|
+
...nestedCallSummary(item),
|
|
228
228
|
...window,
|
|
229
229
|
}),
|
|
230
230
|
(result) => renderOutcome(result, renderRead),
|
|
@@ -232,42 +232,3 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
|
|
|
232
232
|
},
|
|
233
233
|
render: (result) => renderOutcome(result, renderRead),
|
|
234
234
|
};
|
|
235
|
-
|
|
236
|
-
/* ------------------------------------------------------------------ history_search */
|
|
237
|
-
|
|
238
|
-
export const historySearchParameters = Type.Object({
|
|
239
|
-
query: searchQuery(),
|
|
240
|
-
limit: Type.Optional(Type.Integer({ description: "Optional. Maximum matching items returned." })),
|
|
241
|
-
roles: historyRoles(),
|
|
242
|
-
before: Type.Optional(Type.Integer({ description: "Optional. Upper bound: only events with seq strictly below this. Together with after, selects the events strictly between the two." })),
|
|
243
|
-
after: Type.Optional(Type.Integer({ description: "Optional. Lower bound: only events with seq strictly above this. Together with before, selects the events strictly between the two." })),
|
|
244
|
-
window_id: Type.Optional(Type.String({ minLength: 1, description: `Optional. Limit to one context window. Values come from history_windows or any event; "${PREVIOUS_WINDOW}" names the window before the current one.` })),
|
|
245
|
-
max_chars_per_item: Type.Optional(Type.Integer({ description: `Optional. Maximum preview characters per item (default ${HISTORY_PREVIEW_CHARS}); use history_read for full content.` })),
|
|
246
|
-
}, { additionalProperties: false });
|
|
247
|
-
|
|
248
|
-
export const historySearch: Operation<typeof historySearchParameters, HistoryPage, [HistoryProjection]> = {
|
|
249
|
-
name: "history_search",
|
|
250
|
-
label: "History search",
|
|
251
|
-
description: "Search session events for case-insensitive literal queries (OR), including tool arguments/output and nested calls. Defaults to all roles; no folded rows. Read a hit with its seq and offset_chars. before/after are strict bounds; the footer prints the exact calls to page older or newer.",
|
|
252
|
-
parameters: historySearchParameters,
|
|
253
|
-
outputSchema: resultSchema(HistorySearchPageSchema),
|
|
254
|
-
async execute(params, projection) {
|
|
255
|
-
const resolved = resolveWindowId(projection, params.window_id);
|
|
256
|
-
if (!resolved.ok) return resolved.outcome;
|
|
257
|
-
const scoped = { ...params, window_id: resolved.window_id };
|
|
258
|
-
const badWindow = badWindowId(projection, scoped);
|
|
259
|
-
if (badWindow) return badWindow;
|
|
260
|
-
let queries: string[];
|
|
261
|
-
try {
|
|
262
|
-
queries = searchQueries(scoped.query);
|
|
263
|
-
} catch (error) {
|
|
264
|
-
if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
|
|
265
|
-
throw error;
|
|
266
|
-
}
|
|
267
|
-
const matches = filteredItems(projection, scoped, "search")
|
|
268
|
-
.map((event) => ({ event, matchOffset: earliestMatchOffsetChars(eventDocument(event), queries) }))
|
|
269
|
-
.filter((candidate) => candidate.matchOffset >= 0);
|
|
270
|
-
return selectPage(projection, scoped, matches, false, pageFits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
|
|
271
|
-
},
|
|
272
|
-
render: (result) => renderOutcome(result, renderPage),
|
|
273
|
-
};
|