notesoup 0.54.0 → 0.54.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 +4 -2
- package/dist/plugins/claude/src/helper.d.ts +2 -1
- package/dist/plugins/claude/src/helper.js +19 -23
- package/dist/plugins/claude/src/history.d.ts +3 -14
- package/dist/plugins/claude/src/history.js +2 -298
- package/dist/plugins/claude/src/text.d.ts +0 -1
- package/dist/plugins/claude/src/text.js +0 -1
- package/dist/plugins/codex/src/history.d.ts +3 -8
- package/dist/plugins/codex/src/history.js +2 -238
- package/dist/plugins/codex/src/mcp.js +7 -7
- package/dist/plugins/codex/src/transcript.d.ts +3 -39
- package/dist/plugins/codex/src/transcript.js +2 -313
- package/dist/plugins/dsh/history.d.ts +3 -0
- package/dist/plugins/dsh/history.js +15 -0
- package/dist/plugins/dsh/tools.js +4 -5
- package/dist/plugins/pi/history-tools.d.ts +1 -1
- package/dist/plugins/pi/history-tools.js +9 -5
- package/dist/plugins/pi/history.d.ts +2 -3
- package/dist/plugins/pi/history.js +4 -147
- package/dist/src/boot/render.js +2 -4
- package/dist/src/boot/text.d.ts +3 -1
- package/dist/src/boot/text.js +11 -5
- package/dist/src/history/claude.d.ts +16 -0
- package/dist/src/history/claude.js +336 -0
- package/dist/src/history/codex-transcript.d.ts +39 -0
- package/dist/src/history/codex-transcript.js +315 -0
- package/dist/src/history/codex.d.ts +8 -0
- package/dist/src/history/codex.js +238 -0
- package/dist/src/history/corpus.d.ts +35 -0
- package/dist/src/history/corpus.js +54 -0
- package/dist/src/history/history.d.ts +4 -8
- package/dist/src/history/history.js +3 -11
- package/dist/src/history/local.d.ts +17 -0
- package/dist/src/history/local.js +101 -0
- package/dist/src/history/pi.d.ts +36 -0
- package/dist/src/history/pi.js +202 -0
- package/dist/src/history/query.d.ts +15 -5
- package/dist/src/history/query.js +42 -13
- package/dist/src/index.d.ts +4 -2
- package/dist/src/index.js +4 -3
- package/dist/src/tools/history.d.ts +7 -19
- package/dist/src/tools/history.js +80 -93
- package/dist/test/boot.integration.test.js +1 -2
- package/dist/test/claude-history.test.js +47 -34
- package/dist/test/claude-mod.test.js +7 -7
- package/dist/test/codex-history.test.js +4 -10
- package/dist/test/codex-plugin.test.js +32 -11
- package/dist/test/dependencies.test.js +3 -3
- package/dist/test/dsh.test.js +26 -4
- package/dist/test/helpers/extension.d.ts +0 -1
- package/dist/test/helpers/history-corpus.d.ts +7 -0
- package/dist/test/helpers/history-corpus.js +26 -0
- package/dist/test/history-corpus.test.d.ts +1 -0
- package/dist/test/history-corpus.test.js +307 -0
- package/dist/test/history.integration.test.js +40 -48
- package/dist/test/host-neutral.test.js +3 -18
- package/dist/test/model-facing-text.test.js +2 -0
- package/dist/test/notes.integration.test.js +1 -1
- package/dist/test/notes.test.js +1 -1
- package/docs/architecture.md +7 -5
- package/docs/claude-code-mod.md +7 -5
- package/docs/codex.md +3 -3
- package/docs/dsh.md +2 -2
- package/docs/history-sessions.md +52 -0
- package/docs/notes-library.md +1 -1
- package/docs/skills.md +1 -1
- package/docs/tool-results.md +8 -6
- package/package.json +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +1507 -746
- package/plugins/claude/skills/memory/SKILL.md +5 -3
- package/plugins/claude/src/helper.ts +19 -23
- package/plugins/claude/src/history.ts +3 -257
- package/plugins/claude/src/text.ts +0 -1
- package/plugins/codex/dist/codex/notesoup.js +705 -154
- package/plugins/codex/src/history.ts +3 -193
- package/plugins/codex/src/mcp.ts +7 -7
- package/plugins/codex/src/transcript.ts +3 -275
- package/plugins/dsh/history.ts +17 -0
- package/plugins/dsh/tools.ts +4 -5
- package/plugins/paseo/client/markdown.tsx +19 -39
- package/plugins/pi/history-tools.ts +11 -5
- package/plugins/pi/history.ts +8 -157
- package/skills/memory/SKILL.md +5 -3
- package/src/boot/render.ts +2 -5
- package/src/boot/text.ts +11 -5
- package/src/history/claude.ts +286 -0
- package/src/history/codex-transcript.ts +276 -0
- package/src/history/codex.ts +193 -0
- package/src/history/corpus.ts +69 -0
- package/src/history/history.ts +5 -12
- package/src/history/local.ts +93 -0
- package/src/history/pi.ts +199 -0
- package/src/history/query.ts +45 -15
- package/src/index.ts +5 -3
- package/src/tools/history.ts +71 -101
|
@@ -30,14 +30,17 @@ function resolveTimeBounds(params) {
|
|
|
30
30
|
}
|
|
31
31
|
/** The params to merge into the previous call to continue toward older events. */
|
|
32
32
|
export const HistoryOlderSchema = Type.Object({
|
|
33
|
+
session: Type.Optional(Type.String()),
|
|
33
34
|
before_seq: Type.Integer({ minimum: 1 }),
|
|
34
35
|
}, { additionalProperties: false });
|
|
35
36
|
/** The params to merge into the previous call to continue toward newer events. */
|
|
36
37
|
export const HistoryNewerSchema = Type.Object({
|
|
38
|
+
session: Type.Optional(Type.String()),
|
|
37
39
|
after_seq: Type.Integer({ minimum: 1 }),
|
|
38
40
|
from: Type.Literal("oldest"),
|
|
39
41
|
}, { additionalProperties: false });
|
|
40
42
|
export const HistoryPageSchema = Type.Object({
|
|
43
|
+
notice: Type.Optional(Type.String()),
|
|
41
44
|
items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
|
|
42
45
|
page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
|
|
43
46
|
page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
|
|
@@ -60,7 +63,7 @@ function truncateHistoryItem(item, fits) {
|
|
|
60
63
|
return fits(withoutName) ? withoutName : shrinkContent(withoutName);
|
|
61
64
|
}
|
|
62
65
|
/** Summarize one already ordered gap; omitted tool names never change its exact count. */
|
|
63
|
-
function foldedRun(events) {
|
|
66
|
+
function foldedRun(events, session) {
|
|
64
67
|
if (events.length === 0)
|
|
65
68
|
return undefined;
|
|
66
69
|
const counts = new Map();
|
|
@@ -73,7 +76,7 @@ function foldedRun(events) {
|
|
|
73
76
|
const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
|
|
74
77
|
// fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
|
|
75
78
|
const tools = Object.fromEntries(entries);
|
|
76
|
-
return { folded: true, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
|
|
79
|
+
return { ...(session === undefined ? {} : { session }), folded: true, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
|
|
77
80
|
}
|
|
78
81
|
/** Filter and order once. Conversation candidates own the folded gap immediately before them. */
|
|
79
82
|
function prepareSelection(projection, params) {
|
|
@@ -91,48 +94,73 @@ function prepareSelection(projection, params) {
|
|
|
91
94
|
const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query);
|
|
92
95
|
if (matchOffset !== undefined && matchOffset < 0)
|
|
93
96
|
continue;
|
|
94
|
-
candidates.push({ event, matchOffset, before: foldedRun(run) });
|
|
97
|
+
candidates.push({ event, ...(params.session === undefined ? {} : { session: params.session }), matchOffset, before: foldedRun(run, params.session) });
|
|
95
98
|
run = [];
|
|
96
99
|
}
|
|
97
|
-
return { candidates, tail: foldedRun(run) };
|
|
100
|
+
return { candidates, session: params.session, tail: foldedRun(run, params.session) };
|
|
98
101
|
}
|
|
99
102
|
/** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
|
|
100
103
|
function pageData(prepared, start, end, maxChars, preview) {
|
|
101
104
|
const { candidates, tail } = prepared;
|
|
105
|
+
const identity = prepared.session === undefined ? {} : { session: prepared.session };
|
|
102
106
|
const items = [];
|
|
103
107
|
for (let index = start; index < end; index++) {
|
|
104
108
|
const candidate = candidates[index];
|
|
105
109
|
if (candidate.before && (index > start || start === 0))
|
|
106
110
|
items.push(candidate.before);
|
|
107
|
-
items.push(preview ?? (candidate.preview ??= visibleItem(candidate.event, maxChars, candidate.matchOffset)));
|
|
111
|
+
items.push(preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) }));
|
|
108
112
|
}
|
|
109
113
|
if (end === candidates.length && tail)
|
|
110
114
|
items.push(tail);
|
|
111
115
|
return {
|
|
112
116
|
items,
|
|
113
|
-
page_older: start > 0 && start < end ? { before_seq: candidates[start].event.seq } : null,
|
|
114
|
-
page_newer: end < candidates.length && start < end ? { after_seq: candidates[end - 1].event.seq, from: "oldest" } : null,
|
|
117
|
+
page_older: !prepared.multi && start > 0 && start < end ? { ...identity, before_seq: candidates[start].event.seq } : null,
|
|
118
|
+
page_newer: !prepared.multi && end < candidates.length && start < end ? { ...identity, after_seq: candidates[end - 1].event.seq, from: "oldest" } : null,
|
|
115
119
|
};
|
|
116
120
|
}
|
|
117
121
|
/**
|
|
118
122
|
* Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
|
|
119
123
|
* Grow the page in selection order; shorten the first preview only when no full row fits.
|
|
120
124
|
*/
|
|
121
|
-
|
|
125
|
+
function resolveSelection(params) {
|
|
122
126
|
const bounds = resolveTimeBounds(params);
|
|
123
127
|
if (!bounds.ok)
|
|
124
128
|
return bounds;
|
|
125
|
-
let queries;
|
|
126
129
|
try {
|
|
127
|
-
queries = searchQueries(params.query);
|
|
130
|
+
const queries = searchQueries(params.query);
|
|
131
|
+
return success({ ...params, ...bounds.data, query: queries.length ? queries : undefined });
|
|
128
132
|
}
|
|
129
133
|
catch (error) {
|
|
130
134
|
if (error instanceof InvalidQueryError)
|
|
131
135
|
return failure("invalid_query", error.message);
|
|
132
136
|
throw error;
|
|
133
137
|
}
|
|
134
|
-
|
|
135
|
-
|
|
138
|
+
}
|
|
139
|
+
export function selectPage(projection, params, fits, maxChars) {
|
|
140
|
+
const scoped = resolveSelection(params);
|
|
141
|
+
if (!scoped.ok)
|
|
142
|
+
return scoped;
|
|
143
|
+
return selectPrepared(prepareSelection(projection, scoped.data), scoped.data, fits, maxChars);
|
|
144
|
+
}
|
|
145
|
+
/** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
|
|
146
|
+
export function corpusSelection(params) {
|
|
147
|
+
const scoped = resolveSelection(params);
|
|
148
|
+
if (!scoped.ok)
|
|
149
|
+
return scoped;
|
|
150
|
+
if (scoped.data.query === undefined)
|
|
151
|
+
return failure("missing_query", "Wildcard session search requires a non-empty `query`.");
|
|
152
|
+
if (params.before_seq !== undefined || params.after_seq !== undefined)
|
|
153
|
+
return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
|
|
154
|
+
return scoped;
|
|
155
|
+
}
|
|
156
|
+
/** Merge events, never folds or per-session cursors. Equal timestamps have a stable identity tie-break. */
|
|
157
|
+
export function selectCorpusPage(sessions, scoped, fits, maxChars) {
|
|
158
|
+
const candidates = sessions.flatMap(({ session, projection }) => prepareSelection(projection, { ...scoped, session }).candidates);
|
|
159
|
+
const time = (event) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
|
|
160
|
+
candidates.sort((a, b) => (time(a.event) - time(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq));
|
|
161
|
+
return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
|
|
162
|
+
}
|
|
163
|
+
function selectPrepared(prepared, scoped, fits, maxChars) {
|
|
136
164
|
const { candidates } = prepared;
|
|
137
165
|
// Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
|
|
138
166
|
const newest = scoped.from !== "oldest";
|
|
@@ -157,7 +185,8 @@ export function selectPage(projection, params, fits, maxChars) {
|
|
|
157
185
|
}
|
|
158
186
|
const page = pageData(prepared, start, end, maxChars);
|
|
159
187
|
if (!fits(page)) {
|
|
160
|
-
|
|
188
|
+
const narrow = prepared.multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
|
|
189
|
+
return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows${prepared.multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
|
|
161
190
|
}
|
|
162
191
|
return success(page);
|
|
163
192
|
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* Host-neutral core entry.
|
|
3
3
|
*
|
|
4
4
|
* Everything under `src/` is independent of any host SDK: notes, boot, history, budget and the
|
|
5
|
-
* shared operations
|
|
5
|
+
* shared operations use explicit facts, not live Pi, Claude Code or dsh services. History's
|
|
6
|
+
* read-only wire decoders understand persisted formats without importing those hosts. Each plugin under `plugins/`
|
|
6
7
|
* composes these domains into that host's registration and owns that host's text, lifecycle and
|
|
7
8
|
* SDK types. Nothing here imports a plugin.
|
|
8
9
|
*
|
|
@@ -20,9 +21,10 @@ export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
|
|
|
20
21
|
export type { BootToolNames } from "./boot/text.js";
|
|
21
22
|
export { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "./tools/notes.js";
|
|
22
23
|
export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
|
|
23
|
-
export { historyList, historyRead
|
|
24
|
+
export { historyList, historyRead } from "./tools/history.js";
|
|
24
25
|
export { projectHistory } from "./history/history.js";
|
|
25
26
|
export type { HistoryProjection } from "./history/history.js";
|
|
27
|
+
export type { HistoryContext, HistoryCorpus, HistoryHarness, HistorySession, HistorySessionData } from "./history/corpus.js";
|
|
26
28
|
export type { Operation, OperationError, Outcome, Renderer, TextWindow } from "./tools/result.js";
|
|
27
29
|
export { deriveThresholds, remainingBudget } from "./budget/policy.js";
|
|
28
30
|
export type { ResolvedThresholds } from "./budget/policy.js";
|
package/dist/src/index.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* Host-neutral core entry.
|
|
3
3
|
*
|
|
4
4
|
* Everything under `src/` is independent of any host SDK: notes, boot, history, budget and the
|
|
5
|
-
* shared operations
|
|
5
|
+
* shared operations use explicit facts, not live Pi, Claude Code or dsh services. History's
|
|
6
|
+
* read-only wire decoders understand persisted formats without importing those hosts. Each plugin under `plugins/`
|
|
6
7
|
* composes these domains into that host's registration and owns that host's text, lifecycle and
|
|
7
8
|
* SDK types. Nothing here imports a plugin.
|
|
8
9
|
*
|
|
@@ -17,10 +18,10 @@ export { loadNotesSnapshot, unavailableNotesSnapshot } from "./boot/snapshot.js"
|
|
|
17
18
|
export { renderBootBlock } from "./boot/render.js";
|
|
18
19
|
export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
|
|
19
20
|
// Operations: the schemas and typed outcomes a host registers as its own tools, over a
|
|
20
|
-
// host-supplied notes tool context or decoded history projection.
|
|
21
|
+
// host-supplied notes tool context or decoded history projection/lazy corpus context.
|
|
21
22
|
export { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "./tools/notes.js";
|
|
22
23
|
export { notesIdentityForCall, notesToolContext } from "./tools/notes-context.js";
|
|
23
|
-
export { historyList, historyRead
|
|
24
|
+
export { historyList, historyRead } from "./tools/history.js";
|
|
24
25
|
export { projectHistory } from "./history/history.js";
|
|
25
26
|
// Budget: pure thresholds and the approved reset prose.
|
|
26
27
|
export { deriveThresholds, remainingBudget } from "./budget/policy.js";
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { Type, type Static } from "typebox";
|
|
3
3
|
import { type Operation } from "./result.js";
|
|
4
4
|
import { type HistoryPage } from "../history/query.js";
|
|
5
|
-
import { type
|
|
5
|
+
import { type HistoryContext } from "../history/corpus.js";
|
|
6
6
|
/** One read: identity, tool summary and a flat document slice. */
|
|
7
7
|
declare const HistoryReadDataSchema: Type.TObject<{
|
|
8
8
|
text: Type.TString;
|
|
@@ -16,29 +16,17 @@ declare const HistoryReadDataSchema: Type.TObject<{
|
|
|
16
16
|
tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
|
|
17
17
|
output_truncated: Type.TOptional<Type.TLiteral<true>>;
|
|
18
18
|
full_output_path: Type.TOptional<Type.TString>;
|
|
19
|
+
session: Type.TOptional<Type.TString>;
|
|
20
|
+
notice: Type.TOptional<Type.TString>;
|
|
19
21
|
seq: Type.TInteger;
|
|
20
|
-
window_id: Type.TString;
|
|
21
22
|
role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
|
|
22
23
|
created_at: Type.TUnion<[Type.TString, Type.TNull]>;
|
|
23
24
|
}>;
|
|
24
25
|
type HistoryReadData = Static<typeof HistoryReadDataSchema>;
|
|
25
|
-
declare const HistoryWindowsDataSchema: Type.TObject<{
|
|
26
|
-
session_id: Type.TString;
|
|
27
|
-
windows: Type.TArray<Type.TObject<{
|
|
28
|
-
window_id: Type.TString;
|
|
29
|
-
created_at: Type.TUnion<[Type.TString, Type.TNull]>;
|
|
30
|
-
first_seq: Type.TUnion<[Type.TInteger, Type.TNull]>;
|
|
31
|
-
last_seq: Type.TUnion<[Type.TInteger, Type.TNull]>;
|
|
32
|
-
}>>;
|
|
33
|
-
more: Type.TInteger;
|
|
34
|
-
}>;
|
|
35
|
-
type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
|
|
36
26
|
/** Pure host decoration, measured during selection and applied unchanged by the caller at delivery. */
|
|
37
27
|
export type HistoryTextWrapper = (text: string) => string;
|
|
38
|
-
export declare const PREVIOUS_WINDOW = "@previous";
|
|
39
|
-
export declare const historyWindowsParameters: Type.TObject<{}>;
|
|
40
|
-
export declare const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string, HistoryTextWrapper?]>;
|
|
41
28
|
export declare const historyListParameters: Type.TObject<{
|
|
29
|
+
session: Type.TOptional<Type.TString>;
|
|
42
30
|
query: Type.TOptional<Type.TUnion<[Type.TString, Type.TArray<Type.TString>]>>;
|
|
43
31
|
roles: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>>>;
|
|
44
32
|
before_seq: Type.TOptional<Type.TInteger>;
|
|
@@ -46,15 +34,15 @@ export declare const historyListParameters: Type.TObject<{
|
|
|
46
34
|
since: Type.TOptional<Type.TString>;
|
|
47
35
|
until: Type.TOptional<Type.TString>;
|
|
48
36
|
from: Type.TOptional<Type.TUnion<[Type.TLiteral<"newest">, Type.TLiteral<"oldest">]>>;
|
|
49
|
-
window_id: Type.TOptional<Type.TString>;
|
|
50
37
|
limit: Type.TOptional<Type.TInteger>;
|
|
51
38
|
max_chars_per_item: Type.TOptional<Type.TInteger>;
|
|
52
39
|
}>;
|
|
53
|
-
export declare const historyList: Operation<typeof historyListParameters, HistoryPage, [
|
|
40
|
+
export declare const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryContext, HistoryTextWrapper?]>;
|
|
54
41
|
export declare const historyReadParameters: Type.TObject<{
|
|
55
42
|
offset_chars: Type.TOptional<Type.TInteger>;
|
|
56
43
|
max_chars: Type.TOptional<Type.TInteger>;
|
|
44
|
+
session: Type.TOptional<Type.TString>;
|
|
57
45
|
seq: Type.TInteger;
|
|
58
46
|
}>;
|
|
59
|
-
export declare const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [
|
|
47
|
+
export declare const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryContext, HistoryTextWrapper?]>;
|
|
60
48
|
export {};
|
|
@@ -1,33 +1,25 @@
|
|
|
1
1
|
/** Host-neutral history operations: one bounded payload for text and structured results. */
|
|
2
2
|
import { Type } from "typebox";
|
|
3
|
-
import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS
|
|
3
|
+
import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS } from "./output.js";
|
|
4
4
|
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema } from "./result.js";
|
|
5
5
|
import { historyRoles, searchQuery } from "./schema.js";
|
|
6
|
-
import { HistoryPageSchema, selectPage } from "../history/query.js";
|
|
7
|
-
import {
|
|
6
|
+
import { HistoryPageSchema, corpusSelection, selectCorpusPage, selectPage } from "../history/query.js";
|
|
7
|
+
import { currentHistory, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity } from "../history/corpus.js";
|
|
8
|
+
import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema } from "../history/history.js";
|
|
8
9
|
/** One read: identity, tool summary and a flat document slice. */
|
|
9
10
|
const HistoryReadDataSchema = Type.Object({
|
|
11
|
+
session: Type.Optional(Type.String()),
|
|
12
|
+
notice: Type.Optional(Type.String()),
|
|
10
13
|
seq: Type.Integer({ minimum: 1 }),
|
|
11
|
-
window_id: Type.String(),
|
|
12
14
|
role: HistoryRoleSchema,
|
|
13
15
|
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
14
16
|
...ToolSummarySchema.properties,
|
|
15
17
|
nested_calls: Type.Optional(NestedCallSummarySchema),
|
|
16
18
|
...TextWindowSchema.properties,
|
|
17
19
|
}, { additionalProperties: false });
|
|
18
|
-
const HistoryWindowsDataSchema = Type.Object({
|
|
19
|
-
session_id: Type.String(),
|
|
20
|
-
windows: Type.Array(Type.Object({
|
|
21
|
-
window_id: Type.String(),
|
|
22
|
-
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
23
|
-
first_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
|
|
24
|
-
last_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
|
|
25
|
-
}, { additionalProperties: false })),
|
|
26
|
-
more: Type.Integer({ minimum: 0, description: "How many more were left out." }),
|
|
27
|
-
}, { additionalProperties: false });
|
|
28
20
|
/* ------------------------------------------------------------------ rendering */
|
|
29
21
|
function header(item) {
|
|
30
|
-
return `
|
|
22
|
+
return `${item.session === undefined ? "" : `session ${item.session} | `}seq ${item.seq} | ${item.role}`;
|
|
31
23
|
}
|
|
32
24
|
function toolHeader(item) {
|
|
33
25
|
if (item.role !== "tool")
|
|
@@ -50,86 +42,32 @@ function renderPageItem(item) {
|
|
|
50
42
|
}
|
|
51
43
|
function renderFoldedRow(row) {
|
|
52
44
|
const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
|
|
53
|
-
const
|
|
54
|
-
|
|
45
|
+
const identity = row.session === undefined ? {} : { session: row.session };
|
|
46
|
+
const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, from: "oldest", roles: ["tool", "context"] })}`;
|
|
47
|
+
return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
|
|
55
48
|
}
|
|
56
49
|
function renderPage(page) {
|
|
57
50
|
// An empty selection has no anchors either, so it would otherwise render as nothing at all.
|
|
58
51
|
if (page.items.length === 0)
|
|
59
|
-
return "No events match these filters
|
|
52
|
+
return `${page.notice ?? ""}No events match these filters.`;
|
|
60
53
|
const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
|
|
61
54
|
const cursors = [
|
|
62
55
|
page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
|
|
63
56
|
page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
|
|
64
57
|
].filter((line) => line !== "");
|
|
65
|
-
return cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}
|
|
58
|
+
return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
|
|
66
59
|
}
|
|
67
60
|
function renderRead(data) {
|
|
68
61
|
const tool = toolHeader(data);
|
|
69
62
|
const afterSeq = data.seq - 10;
|
|
70
|
-
const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
|
|
71
|
-
return [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
|
|
63
|
+
const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
|
|
64
|
+
return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
|
|
72
65
|
}
|
|
73
66
|
const plainText = (text) => text;
|
|
74
|
-
// Sample known ids in the refusal message itself, never as a second listing.
|
|
75
|
-
const MAX_REPORTED_WINDOWS = 5;
|
|
76
|
-
/** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
|
|
77
|
-
function knownWindowSuffix(known) {
|
|
78
|
-
return known.length === 0 ? "" : `; its windows: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
|
|
79
|
-
}
|
|
80
|
-
export const PREVIOUS_WINDOW = "@previous";
|
|
81
|
-
/** Resolve "@previous" against oldest-first windows; every other value passes through. */
|
|
82
|
-
function resolveWindowId(projection, windowId) {
|
|
83
|
-
if (windowId !== PREVIOUS_WINDOW)
|
|
84
|
-
return { ok: true, window_id: windowId };
|
|
85
|
-
const previous = projection.windows.at(-2);
|
|
86
|
-
if (previous !== undefined)
|
|
87
|
-
return { ok: true, window_id: previous.windowId };
|
|
88
|
-
const known = projection.windows.map((current) => current.windowId);
|
|
89
|
-
return { ok: false, outcome: failure("unknown_window_id", `"${PREVIOUS_WINDOW}" has nothing to point at: this session has no window before the current one${knownWindowSuffix(known)}.`) };
|
|
90
|
-
}
|
|
91
|
-
function badWindowId(projection, params) {
|
|
92
|
-
const badWindow = unknownWindowId(projection, params);
|
|
93
|
-
if (!badWindow)
|
|
94
|
-
return undefined;
|
|
95
|
-
return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}.`);
|
|
96
|
-
}
|
|
97
|
-
/* ------------------------------------------------------------------ history_windows */
|
|
98
|
-
export const historyWindowsParameters = Type.Object({}, { additionalProperties: false });
|
|
99
|
-
export const historyWindows = {
|
|
100
|
-
name: "history_windows",
|
|
101
|
-
label: "History list windows",
|
|
102
|
-
description: "List this session's context windows, oldest first, with seq ranges.",
|
|
103
|
-
parameters: historyWindowsParameters,
|
|
104
|
-
outputSchema: resultSchema(HistoryWindowsDataSchema),
|
|
105
|
-
async execute(_params, projection, sessionId, wrapText = plainText) {
|
|
106
|
-
const data = { session_id: sessionId, windows: [], more: projection.windows.length };
|
|
107
|
-
const fits = (candidate) => fitsResult(success(candidate), (result) => wrapText(renderOutcome(result, renderWindows)));
|
|
108
|
-
for (const window of projection.windows) {
|
|
109
|
-
let first = null;
|
|
110
|
-
let last = null;
|
|
111
|
-
for (const event of window.items) {
|
|
112
|
-
first = first === null ? event.seq : Math.min(first, event.seq);
|
|
113
|
-
last = last === null ? event.seq : Math.max(last, event.seq);
|
|
114
|
-
}
|
|
115
|
-
const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last };
|
|
116
|
-
if (!fits({ ...data, windows: [...data.windows, row], more: data.more - 1 }))
|
|
117
|
-
break;
|
|
118
|
-
data.windows.push(row);
|
|
119
|
-
data.more--;
|
|
120
|
-
}
|
|
121
|
-
return fits(data) ? success(data) : failure("output_too_large", `The session id alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry.`);
|
|
122
|
-
},
|
|
123
|
-
render: (result) => renderOutcome(result, renderWindows),
|
|
124
|
-
};
|
|
125
|
-
function renderWindows(data) {
|
|
126
|
-
const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
|
|
127
|
-
if (data.more > 0)
|
|
128
|
-
lines.push(`${data.more} more windows not shown; every \`history_list\` event also names its window.`);
|
|
129
|
-
return lines.join("\n");
|
|
130
|
-
}
|
|
131
67
|
/* ------------------------------------------------------------------ history_list */
|
|
68
|
+
const sessionParameter = Type.Optional(Type.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions (query required); history_read needs one session." }));
|
|
132
69
|
export const historyListParameters = Type.Object({
|
|
70
|
+
session: sessionParameter,
|
|
133
71
|
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.")),
|
|
134
72
|
roles: historyRoles(),
|
|
135
73
|
before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
|
|
@@ -137,39 +75,86 @@ export const historyListParameters = Type.Object({
|
|
|
137
75
|
since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
|
|
138
76
|
until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
|
|
139
77
|
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." })),
|
|
140
|
-
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.` })),
|
|
141
78
|
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
|
|
142
79
|
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.` })),
|
|
143
80
|
}, { additionalProperties: false });
|
|
144
81
|
export const historyList = {
|
|
145
82
|
name: "history_list",
|
|
146
83
|
label: "History list items",
|
|
147
|
-
description: "Browse or search
|
|
84
|
+
description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or * with query to search across local harnesses. Read one in full with `history_read`.",
|
|
148
85
|
parameters: historyListParameters,
|
|
149
86
|
outputSchema: resultSchema(HistoryPageSchema),
|
|
150
|
-
async execute(params,
|
|
151
|
-
|
|
152
|
-
if (!resolved.ok)
|
|
153
|
-
return resolved.outcome;
|
|
154
|
-
const scoped = { ...params, window_id: resolved.window_id };
|
|
155
|
-
const badWindow = badWindowId(projection, scoped);
|
|
156
|
-
if (badWindow)
|
|
157
|
-
return badWindow;
|
|
158
|
-
// Charge wrapped rendering and cursors, not only event previews.
|
|
87
|
+
async execute(params, context, wrapText = plainText) {
|
|
88
|
+
// Charge wrapped rendering, identities, notices and recipes, not only event previews.
|
|
159
89
|
const fits = (page) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
|
|
160
|
-
|
|
90
|
+
const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
|
|
91
|
+
if (params.session === undefined)
|
|
92
|
+
return selectPage(await currentHistory(context), params, fits, maxChars);
|
|
93
|
+
const selector = parseSessionSelector(params.session);
|
|
94
|
+
if (!selector.ok)
|
|
95
|
+
return selector;
|
|
96
|
+
const corpus = "corpus" in context ? context.corpus : undefined;
|
|
97
|
+
if (selector.data.wildcard) {
|
|
98
|
+
const scoped = corpusSelection(params);
|
|
99
|
+
if (!scoped.ok)
|
|
100
|
+
return scoped;
|
|
101
|
+
if (corpus === undefined)
|
|
102
|
+
return failure("unknown_session", "This host supplied no cross-session history corpus.");
|
|
103
|
+
const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
|
|
104
|
+
const loaded = [];
|
|
105
|
+
const notices = [];
|
|
106
|
+
for (const session of sessions) {
|
|
107
|
+
const result = await loadHistorySession(session);
|
|
108
|
+
if (!result.ok)
|
|
109
|
+
return result;
|
|
110
|
+
loaded.push({ session: sessionIdentity(session), projection: result.data.projection });
|
|
111
|
+
if (result.data.notice)
|
|
112
|
+
notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
|
|
113
|
+
}
|
|
114
|
+
const notice = notices.length ? { notice: notices.join("") } : {};
|
|
115
|
+
const result = selectCorpusPage(loaded, scoped.data, (page) => fits({ ...page, ...notice }), maxChars);
|
|
116
|
+
return result.ok ? success({ ...result.data, ...notice }) : result;
|
|
117
|
+
}
|
|
118
|
+
const target = await resolveSession(corpus, selector.data);
|
|
119
|
+
if (!target.ok)
|
|
120
|
+
return target;
|
|
121
|
+
const loaded = await loadHistorySession(target.data);
|
|
122
|
+
if (!loaded.ok)
|
|
123
|
+
return loaded;
|
|
124
|
+
const notice = loaded.data.notice === undefined ? {} : { notice: loaded.data.notice };
|
|
125
|
+
const result = selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars);
|
|
126
|
+
return result.ok ? success({ ...result.data, ...notice }) : result;
|
|
161
127
|
},
|
|
162
128
|
render: (result) => renderOutcome(result, renderPage),
|
|
163
129
|
};
|
|
164
130
|
/* ------------------------------------------------------------------ history_read */
|
|
165
|
-
export const historyReadParameters = Type.Object({ seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`." }), ...TextWindowRequestSchema }, { additionalProperties: false });
|
|
131
|
+
export const historyReadParameters = Type.Object({ session: sessionParameter, seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`. Pass its session too when present." }), ...TextWindowRequestSchema }, { additionalProperties: false });
|
|
166
132
|
export const historyRead = {
|
|
167
133
|
name: "history_read",
|
|
168
134
|
label: "History read item",
|
|
169
135
|
description: "Read one event in full: tool arguments, output, and nested calls.",
|
|
170
136
|
parameters: historyReadParameters,
|
|
171
137
|
outputSchema: resultSchema(HistoryReadDataSchema),
|
|
172
|
-
async execute(params,
|
|
138
|
+
async execute(params, context, wrapText = plainText) {
|
|
139
|
+
let projection;
|
|
140
|
+
let identity = {};
|
|
141
|
+
if (params.session === undefined)
|
|
142
|
+
projection = await currentHistory(context);
|
|
143
|
+
else {
|
|
144
|
+
const selector = parseSessionSelector(params.session);
|
|
145
|
+
if (!selector.ok)
|
|
146
|
+
return selector;
|
|
147
|
+
if (selector.data.wildcard)
|
|
148
|
+
return failure("invalid_session", "`history_read` reads one session; pass a specific `session` ID, not a wildcard.");
|
|
149
|
+
const target = await resolveSession("corpus" in context ? context.corpus : undefined, selector.data);
|
|
150
|
+
if (!target.ok)
|
|
151
|
+
return target;
|
|
152
|
+
const loaded = await loadHistorySession(target.data);
|
|
153
|
+
if (!loaded.ok)
|
|
154
|
+
return loaded;
|
|
155
|
+
projection = loaded.data.projection;
|
|
156
|
+
identity = { session: sessionIdentity(target.data), ...(loaded.data.notice === undefined ? {} : { notice: loaded.data.notice }) };
|
|
157
|
+
}
|
|
173
158
|
const item = allItems(projection).find((event) => event.seq === params.seq);
|
|
174
159
|
// Address checks run in one order: past the end of the file, off this branch, then
|
|
175
160
|
// consumed by a pairing. Only the last two can mention what is at the address.
|
|
@@ -177,6 +162,8 @@ export const historyRead = {
|
|
|
177
162
|
return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
|
|
178
163
|
}
|
|
179
164
|
if (!projection.branchSeqs.has(params.seq)) {
|
|
165
|
+
if (identity.notice)
|
|
166
|
+
return failure("unconfirmed_seq", `Seq ${params.seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`);
|
|
180
167
|
return failure("not_on_branch", `Seq ${params.seq} is on another branch of this session; it can't be read from here.`);
|
|
181
168
|
}
|
|
182
169
|
if (item === undefined) {
|
|
@@ -192,8 +179,8 @@ export const historyRead = {
|
|
|
192
179
|
return failure("invalid_offset", `This event ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
|
|
193
180
|
}
|
|
194
181
|
return readTextWindow(document, params.offset_chars, params.max_chars, (window) => ({
|
|
182
|
+
...identity,
|
|
195
183
|
seq: item.seq,
|
|
196
|
-
window_id: item.windowId,
|
|
197
184
|
role: item.role,
|
|
198
185
|
created_at: item.createdAt ?? null,
|
|
199
186
|
...toolSummary(item),
|
|
@@ -301,8 +301,7 @@ test("off preserves an existing marker window and still cancels native compactio
|
|
|
301
301
|
assert.deepEqual(before, { cancel: true });
|
|
302
302
|
const projected = await runContextWithSystemHook(captured, ctx, sessionManager.buildSessionContext().messages);
|
|
303
303
|
assert.equal(JSON.stringify(projected?.messages ?? []).includes("old context must stay hidden"), false);
|
|
304
|
-
|
|
305
|
-
assert.equal(windows.windows.at(-1)?.window_id, windowId);
|
|
304
|
+
assert.equal(historyFromSession(ctx).windows.at(-1)?.windowId, windowId);
|
|
306
305
|
});
|
|
307
306
|
test("empty_brain uses one turn boundary and never calls ctx.compact", async () => {
|
|
308
307
|
const sessionManager = manager();
|