notesoup 0.55.0 → 0.55.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/dist/plugins/pi/runtime.js +1 -3
- package/dist/plugins/pi/tool-result.js +1 -1
- package/dist/src/history/claude.d.ts +1 -1
- package/dist/src/history/claude.js +11 -6
- package/dist/src/history/codex-transcript.d.ts +2 -0
- package/dist/src/history/codex-transcript.js +3 -2
- package/dist/src/history/corpus.d.ts +2 -1
- package/dist/src/history/corpus.js +5 -2
- package/dist/src/history/local.d.ts +2 -6
- package/dist/src/history/local.js +34 -2
- package/dist/src/history/query.d.ts +4 -2
- package/dist/src/history/query.js +17 -8
- package/dist/src/tools/history.js +13 -6
- package/dist/test/boot.integration.test.js +24 -0
- package/dist/test/history-corpus.test.js +237 -13
- package/docs/claude-code-mod.md +1 -1
- package/docs/history-sessions.md +9 -7
- package/docs/skills.md +1 -1
- package/docs/tool-results.md +2 -2
- package/package.json +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +60 -18
- package/plugins/claude/skills/memory/SKILL.md +4 -2
- package/plugins/codex/dist/codex/notesoup.js +60 -18
- package/plugins/pi/runtime.ts +1 -2
- package/plugins/pi/tool-result.ts +1 -1
- package/skills/memory/SKILL.md +4 -2
- package/src/history/claude.ts +9 -4
- package/src/history/codex-transcript.ts +3 -2
- package/src/history/corpus.ts +9 -3
- package/src/history/local.ts +36 -4
- package/src/history/query.ts +17 -6
- package/src/tools/history.ts +9 -5
|
@@ -26471,14 +26471,20 @@ function selectPage(projection, params, fits, maxChars) {
|
|
|
26471
26471
|
return selectPrepared(prepareSelection(projection, scoped.data), scoped.data, fits, maxChars);
|
|
26472
26472
|
}
|
|
26473
26473
|
function corpusSelection(params) {
|
|
26474
|
-
const scoped = resolveSelection(params);
|
|
26475
|
-
if (!scoped.ok) return scoped;
|
|
26476
|
-
if (scoped.data.query === void 0) return failure2("missing_query", "Wildcard session search requires a non-empty `query`.");
|
|
26477
26474
|
if (params.before_seq !== void 0 || params.after_seq !== void 0) return failure2("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
|
|
26478
|
-
return
|
|
26475
|
+
return resolveSelection(params);
|
|
26476
|
+
}
|
|
26477
|
+
function sessionRepresentative(projection, scoped) {
|
|
26478
|
+
const events = filteredItems(projection, scoped, false).filter((event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "");
|
|
26479
|
+
if (scoped.roles) return events.at(-1);
|
|
26480
|
+
return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
|
|
26479
26481
|
}
|
|
26480
26482
|
function selectCorpusPage(sessions, scoped, fits, maxChars) {
|
|
26481
|
-
const candidates = sessions.flatMap(({ session, projection }) =>
|
|
26483
|
+
const candidates = sessions.flatMap(({ session, projection }) => {
|
|
26484
|
+
if (scoped.query !== void 0) return prepareSelection(projection, { ...scoped, session }).candidates;
|
|
26485
|
+
const event = sessionRepresentative(projection, scoped);
|
|
26486
|
+
return event === void 0 ? [] : [{ session, event }];
|
|
26487
|
+
});
|
|
26482
26488
|
const time3 = (event) => event.createdAt === void 0 || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
|
|
26483
26489
|
candidates.sort((a, b) => time3(a.event) - time3(b.event) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq);
|
|
26484
26490
|
return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
|
|
@@ -26548,9 +26554,11 @@ async function resolveSession(corpus, selector) {
|
|
|
26548
26554
|
if (matches.length > 1) return failure2("ambiguous_session", `Session selector is ambiguous: ${matches.slice(0, 5).map(sessionIdentity).join(", ")}${matches.length > 5 ? ` (${matches.length - 5} more)` : ""}. Pass a longer ID or a harness-qualified ID.`);
|
|
26549
26555
|
return success(matches[0]);
|
|
26550
26556
|
}
|
|
26551
|
-
async function loadHistorySession(session) {
|
|
26557
|
+
async function loadHistorySession(session, queries) {
|
|
26552
26558
|
try {
|
|
26553
|
-
|
|
26559
|
+
const data = await session.load(queries);
|
|
26560
|
+
if (data === void 0 && !queries?.length) throw new Error("Session returned no history");
|
|
26561
|
+
return success(data);
|
|
26554
26562
|
} catch (error2) {
|
|
26555
26563
|
return failure2("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error2 instanceof Error ? error2.message : String(error2)}`);
|
|
26556
26564
|
}
|
|
@@ -26614,7 +26622,7 @@ function renderRead(data) {
|
|
|
26614
26622
|
return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
|
|
26615
26623
|
}
|
|
26616
26624
|
var plainText = (text2) => text2;
|
|
26617
|
-
var sessionParameter = typebox_exports.Optional(typebox_exports.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
|
|
26625
|
+
var sessionParameter = typebox_exports.Optional(typebox_exports.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 with query or lists recent sessions without it; history_read needs one session." }));
|
|
26618
26626
|
var historyListParameters = typebox_exports.Object({
|
|
26619
26627
|
session: sessionParameter,
|
|
26620
26628
|
query: typebox_exports.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.")),
|
|
@@ -26630,7 +26638,7 @@ var historyListParameters = typebox_exports.Object({
|
|
|
26630
26638
|
var historyList = {
|
|
26631
26639
|
name: "history_list",
|
|
26632
26640
|
label: "History list items",
|
|
26633
|
-
description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or *
|
|
26641
|
+
description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or * to browse recent sessions across local harnesses (add query to search). Read one in full with `history_read`.",
|
|
26634
26642
|
parameters: historyListParameters,
|
|
26635
26643
|
outputSchema: resultSchema(HistoryPageSchema),
|
|
26636
26644
|
async execute(params, context2, wrapText = plainText) {
|
|
@@ -26645,13 +26653,17 @@ var historyList = {
|
|
|
26645
26653
|
if (!scoped.ok) return scoped;
|
|
26646
26654
|
if (corpus === void 0) return failure2("unknown_session", "This host supplied no cross-session history corpus.");
|
|
26647
26655
|
const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
|
|
26656
|
+
const queries = Array.isArray(scoped.data.query) ? scoped.data.query : void 0;
|
|
26657
|
+
if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
|
|
26648
26658
|
const loaded2 = [];
|
|
26649
26659
|
const notices = [];
|
|
26650
26660
|
for (const session of sessions) {
|
|
26651
|
-
const result3 = await loadHistorySession(session);
|
|
26652
|
-
if (!result3.ok
|
|
26661
|
+
const result3 = await loadHistorySession(session, queries);
|
|
26662
|
+
if (!result3.ok || !result3.data) continue;
|
|
26663
|
+
if (!queries && !sessionRepresentative(result3.data.projection, scoped.data)) continue;
|
|
26653
26664
|
loaded2.push({ session: sessionIdentity(session), projection: result3.data.projection });
|
|
26654
26665
|
if (result3.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result3.data.notice}`);
|
|
26666
|
+
if (!queries && loaded2.length >= Math.max(1, params.limit ?? 20)) break;
|
|
26655
26667
|
}
|
|
26656
26668
|
const notice2 = notices.length ? { notice: notices.join("") } : {};
|
|
26657
26669
|
const result2 = selectCorpusPage(loaded2, scoped.data, (page) => fits({ ...page, ...notice2 }), maxChars);
|
|
@@ -26987,7 +26999,7 @@ async function referencedPath(home, rolloutId) {
|
|
|
26987
26999
|
if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
|
|
26988
27000
|
return matches[0];
|
|
26989
27001
|
}
|
|
26990
|
-
async function
|
|
27002
|
+
async function readCodexTranscriptBytes(path, remaining = MAX_BYTES) {
|
|
26991
27003
|
const info = await stat(path);
|
|
26992
27004
|
if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
|
|
26993
27005
|
const bytes = await readFile3(path);
|
|
@@ -27006,7 +27018,7 @@ async function readCodexTranscript(source) {
|
|
|
27006
27018
|
while (true) {
|
|
27007
27019
|
if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
|
|
27008
27020
|
seen.add(path);
|
|
27009
|
-
const bytes = await
|
|
27021
|
+
const bytes = await readCodexTranscriptBytes(path, remaining);
|
|
27010
27022
|
remaining -= bytes.length;
|
|
27011
27023
|
const segment = segmentFromBytes(bytes, cutoff);
|
|
27012
27024
|
if (segments.length === 0 && segment.meta.id !== source.threadId) throw new Error(`Codex transcript belongs to thread ${String(segment.meta.id)}, not requested threadId ${source.threadId} (session_id is root-scoped)`);
|
|
@@ -27668,7 +27680,10 @@ function claudeHistoryFromJsonl(text2, source) {
|
|
|
27668
27680
|
function offlineClaudeHead(text2) {
|
|
27669
27681
|
const latest = /* @__PURE__ */ new Map();
|
|
27670
27682
|
for (const row of rowsOf(text2)) {
|
|
27671
|
-
if (MESSAGE_TYPES.has(row.type))
|
|
27683
|
+
if (!MESSAGE_TYPES.has(row.type)) continue;
|
|
27684
|
+
const uuid2 = requiredString(row.uuid, "uuid");
|
|
27685
|
+
latest.delete(uuid2);
|
|
27686
|
+
latest.set(uuid2, row);
|
|
27672
27687
|
}
|
|
27673
27688
|
const ancestors = /* @__PURE__ */ new Set();
|
|
27674
27689
|
for (const row of latest.values()) {
|
|
@@ -27691,8 +27706,10 @@ function offlineClaudeHead(text2) {
|
|
|
27691
27706
|
}
|
|
27692
27707
|
}
|
|
27693
27708
|
const leaves = [...latest.keys()].filter((uuid2) => !ancestors.has(uuid2));
|
|
27694
|
-
if (leaves.length
|
|
27695
|
-
|
|
27709
|
+
if (leaves.length === 0) throw new Error("Offline Claude transcript has 0 possible heads");
|
|
27710
|
+
const nonAttachments = leaves.filter((uuid2) => latest.get(uuid2).type !== "attachment");
|
|
27711
|
+
const candidates = nonAttachments.length ? nonAttachments : leaves;
|
|
27712
|
+
return candidates.at(-1);
|
|
27696
27713
|
}
|
|
27697
27714
|
|
|
27698
27715
|
// src/history/local.ts
|
|
@@ -27721,6 +27738,29 @@ async function filesAt(root, depth) {
|
|
|
27721
27738
|
}
|
|
27722
27739
|
return paths;
|
|
27723
27740
|
}
|
|
27741
|
+
var PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
|
|
27742
|
+
copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
|
|
27743
|
+
does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
|
|
27744
|
+
not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
|
|
27745
|
+
FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
|
|
27746
|
+
the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
|
|
27747
|
+
function escapeRegExp(value) {
|
|
27748
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
27749
|
+
}
|
|
27750
|
+
function mayMatch(text2, queries, codex) {
|
|
27751
|
+
if (codex && text2.includes('"history_base"')) return true;
|
|
27752
|
+
const unescaped = text2.includes("\\u") ? text2.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))) : text2;
|
|
27753
|
+
return queries.some((query) => {
|
|
27754
|
+
const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
|
|
27755
|
+
return tokens === null || tokens.every((token) => {
|
|
27756
|
+
const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
|
|
27757
|
+
return parts.every((part) => {
|
|
27758
|
+
const literal2 = new RegExp(escapeRegExp(part), "iu");
|
|
27759
|
+
return literal2.test(unescaped) || unescaped !== text2 && literal2.test(text2) || literal2.test(PRESENTATION);
|
|
27760
|
+
});
|
|
27761
|
+
});
|
|
27762
|
+
});
|
|
27763
|
+
}
|
|
27724
27764
|
async function localSessions(harness, root) {
|
|
27725
27765
|
const paths = await filesAt(root, harness === "codex" ? 3 : 1);
|
|
27726
27766
|
const sessions = [];
|
|
@@ -27739,9 +27779,11 @@ async function localSessions(harness, root) {
|
|
|
27739
27779
|
harness,
|
|
27740
27780
|
id: id2,
|
|
27741
27781
|
modifiedAt,
|
|
27742
|
-
async load() {
|
|
27782
|
+
async load(queries) {
|
|
27783
|
+
if (harness === "codex" && !queries?.length) return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
|
|
27784
|
+
const text2 = harness === "codex" ? (await readCodexTranscriptBytes(path)).toString("utf8") : await readFile4(path, "utf8");
|
|
27785
|
+
if (queries?.length && !mayMatch(text2, queries, harness === "codex")) return void 0;
|
|
27743
27786
|
if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
|
|
27744
|
-
const text2 = await readFile4(path, "utf8");
|
|
27745
27787
|
if (harness === "pi") return { projection: piHistoryFromJsonl(text2, id2) };
|
|
27746
27788
|
const projection = claudeHistoryFromJsonl(text2, { sessionId: id2, headUuid: offlineClaudeHead(text2) });
|
|
27747
27789
|
const missing = projection.missingAncestors;
|
package/plugins/pi/runtime.ts
CHANGED
|
@@ -129,8 +129,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
129
129
|
const windowId = reset?.data.windowId ?? rootWindowId(ctx.sessionManager.getSessionId());
|
|
130
130
|
try {
|
|
131
131
|
if (reset) {
|
|
132
|
-
|
|
133
|
-
return { messages: isCheckpointBackedReset(ctx, reset) ? event.messages : projectWindow(event.messages, windowId) };
|
|
132
|
+
return { messages: projectWindow(event.messages, windowId) };
|
|
134
133
|
}
|
|
135
134
|
return { messages: projectRootWindow(event.messages, windowId) };
|
|
136
135
|
} catch (error) {
|
|
@@ -25,7 +25,7 @@ function piOperationResult<TData, TDetails = undefined>(render: Renderer<TData>,
|
|
|
25
25
|
export type ToolNamespace = { name: string; description: string };
|
|
26
26
|
export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
|
|
27
27
|
export const DREAM_NAMESPACE: ToolNamespace = { name: "dream", description: "Consolidate one project's notes: begin, edit with notes_*, forget crumpled notes, end." };
|
|
28
|
-
export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "
|
|
28
|
+
export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "Session history (this or other local sessions): history_list to browse/search, history_read to read one event." };
|
|
29
29
|
|
|
30
30
|
/** Optional TUI renderers; without them the host draws its default call line and receipt text. */
|
|
31
31
|
export type OperationRenderers<TParams extends TSchema, TDetails = undefined> = Pick<ToolDefinition<TParams, TDetails>, "renderCall" | "renderResult">;
|
package/skills/memory/SKILL.md
CHANGED
|
@@ -44,9 +44,11 @@ For list/search, omit `glob` or use the collection alias `@default` for this ses
|
|
|
44
44
|
- **Something that happened**: `history_list` to browse or search this session's events; `history_read` the seq for the whole event.
|
|
45
45
|
- **An earlier window**: use its seq range from the boot window tree with `history_list`'s `before_seq` / `after_seq` bounds, or search for a remembered phrase.
|
|
46
46
|
- **Another session**: pass `session: "<id-or-prefix>"` or `"pi:<id>"`, `"claude:<id>"`, `"codex:<id>"`, `"dsh:<id>"`. An unqualified selector checks this harness first. If ambiguous, use a longer ID or a harness prefix; never pick a candidate blindly.
|
|
47
|
-
- **A phrase across sessions**: `history_list({ session: "*", query: "remembered phrase" })`, or restrict to a harness with `"pi:*"`. A wildcard
|
|
47
|
+
- **A phrase across sessions**: `history_list({ session: "*", query: "remembered phrase" })`, or restrict to a harness with `"pi:*"`. A wildcard cannot use `before_seq`/`after_seq` or `history_read`. Query results cover every role unless `roles` narrows them, are chronological, and have no paging cursors; narrow by time, role, query or session pattern instead. DSH sessions are discoverable only from DSH.
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
- **Recent sessions, no remembered phrase**: `history_list({ session: "*" })` returns one representative event per session, preferring its first visible user prompt, up to `limit` (default 20). Sessions are chosen newest-modified first (`from: "oldest"` reverses that), then results are sorted chronologically. Empty queries also browse. Role/time filters apply before choosing representatives; with `roles`, the latest matching event represents each session. No paging cursors.
|
|
50
|
+
|
|
51
|
+
Seqs are stable **within a session**. When a hit carries `session`, copy it together with `seq` into `history_read` and save both in your note. The paging/expand/neighborhood recipes already preserve the resolved session. Omit `session` only when you mean your current host session. A single unreadable or unsupported local transcript refuses explicitly; wildcards skip individual sessions that cannot load. An empty result is not proof the remembered event never happened.
|
|
50
52
|
|
|
51
53
|
## Saving recovery state
|
|
52
54
|
|
package/src/history/claude.ts
CHANGED
|
@@ -251,11 +251,14 @@ export function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistoryS
|
|
|
251
251
|
return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : undefined };
|
|
252
252
|
}
|
|
253
253
|
|
|
254
|
-
/** Offline files have no live append binding
|
|
254
|
+
/** Offline files have no live append binding: prefer non-attachment leaves, then transcript order. */
|
|
255
255
|
export function offlineClaudeHead(text: string): string {
|
|
256
256
|
const latest = new Map<string, Row>();
|
|
257
257
|
for (const row of rowsOf(text)) {
|
|
258
|
-
if (MESSAGE_TYPES.has(row.type as string))
|
|
258
|
+
if (!MESSAGE_TYPES.has(row.type as string)) continue;
|
|
259
|
+
const uuid = requiredString(row.uuid, "uuid");
|
|
260
|
+
latest.delete(uuid);
|
|
261
|
+
latest.set(uuid, row);
|
|
259
262
|
}
|
|
260
263
|
const ancestors = new Set<string>();
|
|
261
264
|
for (const row of latest.values()) {
|
|
@@ -276,8 +279,10 @@ export function offlineClaudeHead(text: string): string {
|
|
|
276
279
|
}
|
|
277
280
|
}
|
|
278
281
|
const leaves = [...latest.keys()].filter((uuid) => !ancestors.has(uuid));
|
|
279
|
-
if (leaves.length
|
|
280
|
-
|
|
282
|
+
if (leaves.length === 0) throw new Error("Offline Claude transcript has 0 possible heads");
|
|
283
|
+
const nonAttachments = leaves.filter((uuid) => latest.get(uuid)!.type !== "attachment");
|
|
284
|
+
const candidates = nonAttachments.length ? nonAttachments : leaves;
|
|
285
|
+
return candidates.at(-1)!;
|
|
281
286
|
}
|
|
282
287
|
|
|
283
288
|
export async function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection> {
|
|
@@ -172,7 +172,8 @@ async function referencedPath(home: string, rolloutId: string): Promise<string>
|
|
|
172
172
|
if (matches.length !== 1) throw new Error(`Unavailable Codex lineage: rollout ${rolloutId} has ${matches.length ? "ambiguous native files" : "no local source file"}`);
|
|
173
173
|
return matches[0]!;
|
|
174
174
|
}
|
|
175
|
-
|
|
175
|
+
/** Bounded decoded bytes, also used by the local corpus's pre-projection miss check. */
|
|
176
|
+
export async function readCodexTranscriptBytes(path: string, remaining = MAX_BYTES): Promise<Buffer> {
|
|
176
177
|
const info = await stat(path);
|
|
177
178
|
if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
|
|
178
179
|
const bytes = await readFile(path);
|
|
@@ -194,7 +195,7 @@ export async function readCodexTranscript(source: CodexTranscriptSource): Promis
|
|
|
194
195
|
while (true) {
|
|
195
196
|
if (segments.length >= MAX_SEGMENTS || seen.has(path)) throw new Error("Unavailable Codex lineage: cycle or ancestry depth limit exceeded");
|
|
196
197
|
seen.add(path);
|
|
197
|
-
const bytes = await
|
|
198
|
+
const bytes = await readCodexTranscriptBytes(path, remaining);
|
|
198
199
|
remaining -= bytes.length;
|
|
199
200
|
const segment = segmentFromBytes(bytes, cutoff);
|
|
200
201
|
if (segments.length === 0 && segment.meta.id !== source.threadId) throw new Error(`Codex transcript belongs to thread ${String(segment.meta.id)}, not requested threadId ${source.threadId} (session_id is root-scoped)`);
|
package/src/history/corpus.ts
CHANGED
|
@@ -8,7 +8,7 @@ export type HistorySession = {
|
|
|
8
8
|
harness: HistoryHarness;
|
|
9
9
|
id: string;
|
|
10
10
|
modifiedAt: number;
|
|
11
|
-
load(): Promise<HistorySessionData>;
|
|
11
|
+
load(queries?: readonly string[]): Promise<HistorySessionData | undefined>;
|
|
12
12
|
};
|
|
13
13
|
export type HistoryCorpus = {
|
|
14
14
|
currentHarness: HistoryHarness;
|
|
@@ -57,8 +57,14 @@ export async function resolveSession(corpus: HistoryCorpus | undefined, selector
|
|
|
57
57
|
return success(matches[0]!);
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
export
|
|
61
|
-
|
|
60
|
+
export function loadHistorySession(session: HistorySession): Promise<Outcome<HistorySessionData>>;
|
|
61
|
+
export function loadHistorySession(session: HistorySession, queries: readonly string[] | undefined): Promise<Outcome<HistorySessionData | undefined>>;
|
|
62
|
+
export async function loadHistorySession(session: HistorySession, queries?: readonly string[]): Promise<Outcome<HistorySessionData | undefined>> {
|
|
63
|
+
try {
|
|
64
|
+
const data = await session.load(queries);
|
|
65
|
+
if (data === undefined && !queries?.length) throw new Error("Session returned no history");
|
|
66
|
+
return success(data);
|
|
67
|
+
}
|
|
62
68
|
catch (error) {
|
|
63
69
|
return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
64
70
|
}
|
package/src/history/local.ts
CHANGED
|
@@ -5,11 +5,12 @@ import { join } from "node:path";
|
|
|
5
5
|
import { piHistoryFromJsonl } from "./pi.js";
|
|
6
6
|
import { claudeHistoryFromJsonl, offlineClaudeHead } from "./claude.js";
|
|
7
7
|
import { readCodexHistory } from "./codex.js";
|
|
8
|
-
import {
|
|
8
|
+
import { readCodexTranscriptBytes } from "./codex-transcript.js";
|
|
9
|
+
import { sessionIdentity, type HistoryCorpus, type HistorySession } from "./corpus.js";
|
|
9
10
|
|
|
10
11
|
export type LocalHistoryRoots = Partial<Record<"pi" | "claude" | "codex", string | null>>;
|
|
11
12
|
export type LocalHistoryOptions = {
|
|
12
|
-
current:
|
|
13
|
+
current: Pick<HistorySession, "harness" | "id" | "load">;
|
|
13
14
|
/** Undefined uses the harness default; null disables that harness's filesystem discovery. */
|
|
14
15
|
roots?: LocalHistoryRoots;
|
|
15
16
|
home?: string;
|
|
@@ -42,6 +43,35 @@ async function filesAt(root: string, depth: number): Promise<string[]> {
|
|
|
42
43
|
return paths;
|
|
43
44
|
}
|
|
44
45
|
|
|
46
|
+
const PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
|
|
47
|
+
copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
|
|
48
|
+
does not prove original parent event addresses compaction boundary replacement_history is an inference checkpoint
|
|
49
|
+
not new conversation events opaque content omitted not recovered plaintext MCP completion without a recorded raw call
|
|
50
|
+
FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
|
|
51
|
+
the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
|
|
52
|
+
|
|
53
|
+
function escapeRegExp(value: string): string {
|
|
54
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Only prove misses, not hits. Only \\uXXXX can encode a word character; other JSON escapes are control/quote/slash. */
|
|
58
|
+
function mayMatch(text: string, queries: readonly string[], codex: boolean): boolean {
|
|
59
|
+
if (codex && text.includes('"history_base"')) return true;
|
|
60
|
+
const unescaped = text.includes("\\u")
|
|
61
|
+
? text.replace(/\\+u([0-9a-fA-F]{4})/g, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)))
|
|
62
|
+
: text;
|
|
63
|
+
return queries.some((query) => {
|
|
64
|
+
const tokens = query.match(/[\p{L}\p{N}_-]+/gu);
|
|
65
|
+
return tokens === null || tokens.every((token) => {
|
|
66
|
+
const parts = /^\d+ms$/iu.test(token) ? [token.slice(0, -2), "ms"] : [token];
|
|
67
|
+
return parts.every((part) => {
|
|
68
|
+
const literal = new RegExp(escapeRegExp(part), "iu");
|
|
69
|
+
return literal.test(unescaped) || (unescaped !== text && literal.test(text)) || literal.test(PRESENTATION);
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
45
75
|
async function localSessions(harness: "pi" | "claude" | "codex", root: string): Promise<HistorySession[]> {
|
|
46
76
|
const paths = await filesAt(root, harness === "codex" ? 3 : 1);
|
|
47
77
|
const sessions: HistorySession[] = [];
|
|
@@ -56,9 +86,11 @@ async function localSessions(harness: "pi" | "claude" | "codex", root: string):
|
|
|
56
86
|
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
57
87
|
sessions.push({
|
|
58
88
|
harness, id, modifiedAt,
|
|
59
|
-
async load() {
|
|
89
|
+
async load(queries) {
|
|
90
|
+
if (harness === "codex" && !queries?.length) return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
|
|
91
|
+
const text = harness === "codex" ? (await readCodexTranscriptBytes(path)).toString("utf8") : await readFile(path, "utf8");
|
|
92
|
+
if (queries?.length && !mayMatch(text, queries, harness === "codex")) return undefined;
|
|
60
93
|
if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
|
|
61
|
-
const text = await readFile(path, "utf8");
|
|
62
94
|
if (harness === "pi") return { projection: piHistoryFromJsonl(text, id) };
|
|
63
95
|
const projection = claudeHistoryFromJsonl(text, { sessionId: id, headUuid: offlineClaudeHead(text) });
|
|
64
96
|
const missing = projection.missingAncestors;
|
package/src/history/query.ts
CHANGED
|
@@ -164,16 +164,27 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
|
|
|
164
164
|
|
|
165
165
|
/** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
|
|
166
166
|
export function corpusSelection(params: HistorySelection): Outcome<HistorySelection> {
|
|
167
|
-
const scoped = resolveSelection(params);
|
|
168
|
-
if (!scoped.ok) return scoped;
|
|
169
|
-
if (scoped.data.query === undefined) return failure("missing_query", "Wildcard session search requires a non-empty `query`.");
|
|
170
167
|
if (params.before_seq !== undefined || params.after_seq !== undefined) return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
|
|
171
|
-
return
|
|
168
|
+
return resolveSelection(params);
|
|
172
169
|
}
|
|
173
170
|
|
|
174
|
-
/**
|
|
171
|
+
/** One topic per session, after role/time filtering; empty dialogue envelopes are not visible. */
|
|
172
|
+
export function sessionRepresentative(projection: HistoryProjection, scoped: HistorySelection): HistoryEvent | undefined {
|
|
173
|
+
const events = filteredItems(projection, scoped, false).filter((event) =>
|
|
174
|
+
(event.role !== "user" && event.role !== "assistant") || eventDocument(event) !== "");
|
|
175
|
+
if (scoped.roles) return events.at(-1);
|
|
176
|
+
return events.find((event) => event.role === "user")
|
|
177
|
+
?? events.filter((event) => event.role === "assistant").at(-1)
|
|
178
|
+
?? events.at(-1);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Merge hits or session representatives, never folds or per-session cursors. Timestamp ties use identity. */
|
|
175
182
|
export function selectCorpusPage(sessions: { session: string; projection: HistoryProjection }[], scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
|
|
176
|
-
const candidates = sessions.flatMap(({ session, projection }) =>
|
|
183
|
+
const candidates = sessions.flatMap(({ session, projection }): Candidate[] => {
|
|
184
|
+
if (scoped.query !== undefined) return prepareSelection(projection, { ...scoped, session }).candidates;
|
|
185
|
+
const event = sessionRepresentative(projection, scoped);
|
|
186
|
+
return event === undefined ? [] : [{ session, event }];
|
|
187
|
+
});
|
|
177
188
|
const time = (event: HistoryEvent) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
|
|
178
189
|
candidates.sort((a, b) => (time(a.event) - time(b.event) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq));
|
|
179
190
|
return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
|
package/src/tools/history.ts
CHANGED
|
@@ -3,7 +3,7 @@ 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, selectCorpusPage, selectPage, type HistoryPage } from "../history/query.js";
|
|
6
|
+
import { HistoryPageSchema, corpusSelection, selectCorpusPage, selectPage, sessionRepresentative, type HistoryPage } from "../history/query.js";
|
|
7
7
|
import { currentHistory, 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
|
|
|
@@ -77,7 +77,7 @@ const plainText: HistoryTextWrapper = (text) => text;
|
|
|
77
77
|
|
|
78
78
|
/* ------------------------------------------------------------------ history_list */
|
|
79
79
|
|
|
80
|
-
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
|
|
80
|
+
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 with query or lists recent sessions without it; history_read needs one session." }));
|
|
81
81
|
|
|
82
82
|
export const historyListParameters = Type.Object({
|
|
83
83
|
session: sessionParameter,
|
|
@@ -95,7 +95,7 @@ export const historyListParameters = Type.Object({
|
|
|
95
95
|
export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryContext, HistoryTextWrapper?]> = {
|
|
96
96
|
name: "history_list",
|
|
97
97
|
label: "History list items",
|
|
98
|
-
description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or *
|
|
98
|
+
description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or * to browse recent sessions across local harnesses (add query to search). Read one in full with `history_read`.",
|
|
99
99
|
parameters: historyListParameters,
|
|
100
100
|
outputSchema: resultSchema(HistoryPageSchema),
|
|
101
101
|
async execute(params, context, wrapText = plainText) {
|
|
@@ -111,13 +111,17 @@ export const historyList: Operation<typeof historyListParameters, HistoryPage, [
|
|
|
111
111
|
if (!scoped.ok) return scoped;
|
|
112
112
|
if (corpus === undefined) return failure("unknown_session", "This host supplied no cross-session history corpus.");
|
|
113
113
|
const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
|
|
114
|
+
const queries = Array.isArray(scoped.data.query) ? scoped.data.query : undefined;
|
|
115
|
+
if (!queries) sessions.sort((a, b) => (scoped.data.from === "oldest" ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
|
|
114
116
|
const loaded = [];
|
|
115
117
|
const notices: string[] = [];
|
|
116
118
|
for (const session of sessions) {
|
|
117
|
-
const result = await loadHistorySession(session);
|
|
118
|
-
if (!result.ok
|
|
119
|
+
const result = await loadHistorySession(session, queries);
|
|
120
|
+
if (!result.ok || !result.data) continue;
|
|
121
|
+
if (!queries && !sessionRepresentative(result.data.projection, scoped.data)) continue;
|
|
119
122
|
loaded.push({ session: sessionIdentity(session), projection: result.data.projection });
|
|
120
123
|
if (result.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
|
|
124
|
+
if (!queries && loaded.length >= Math.max(1, params.limit ?? 20)) break;
|
|
121
125
|
}
|
|
122
126
|
const notice = notices.length ? { notice: notices.join("") } : {};
|
|
123
127
|
const result = selectCorpusPage(loaded, scoped.data, (page) => fits({ ...page, ...notice }), maxChars);
|