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
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** A read-only history corpus: identity/discovery is separate from loading a projection. */
|
|
2
|
+
import { failure, success } from "../tools/result.js";
|
|
3
|
+
const HARNESSES = new Set(["pi", "claude", "codex", "dsh"]);
|
|
4
|
+
export function sessionIdentity(session) {
|
|
5
|
+
return `${session.harness}:${session.id}`;
|
|
6
|
+
}
|
|
7
|
+
export function parseSessionSelector(value) {
|
|
8
|
+
const colon = value.indexOf(":");
|
|
9
|
+
const harness = colon < 0 ? undefined : value.slice(0, colon);
|
|
10
|
+
const id = colon < 0 ? value : value.slice(colon + 1);
|
|
11
|
+
if (id.length === 0 || id.includes(":") || (harness !== undefined && !HARNESSES.has(harness))) {
|
|
12
|
+
return failure("invalid_session", "Pass a session ID or prefix, optionally prefixed by pi:, claude:, codex:, or dsh:.");
|
|
13
|
+
}
|
|
14
|
+
return success({ ...(harness === undefined ? {} : { harness: harness }), id, wildcard: id.includes("*") });
|
|
15
|
+
}
|
|
16
|
+
/** '*' is the only metacharacter; all other characters match literally. */
|
|
17
|
+
export function matchesSession(session, selector) {
|
|
18
|
+
if (selector.harness !== undefined && selector.harness !== session.harness)
|
|
19
|
+
return false;
|
|
20
|
+
const escaped = selector.id.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
21
|
+
return new RegExp(`^${escaped}$`).test(session.id);
|
|
22
|
+
}
|
|
23
|
+
export async function resolveSession(corpus, selector) {
|
|
24
|
+
if (corpus === undefined)
|
|
25
|
+
return failure("unknown_session", "This host supplied no cross-session history corpus.");
|
|
26
|
+
const matching = (pool) => {
|
|
27
|
+
const exact = pool.filter((session) => session.id === selector.id);
|
|
28
|
+
return exact.length ? exact : pool.filter((session) => session.id.startsWith(selector.id));
|
|
29
|
+
};
|
|
30
|
+
let matches;
|
|
31
|
+
if (selector.harness !== undefined)
|
|
32
|
+
matches = matching((await corpus.sessions(selector.harness)).filter((session) => session.harness === selector.harness));
|
|
33
|
+
else {
|
|
34
|
+
matches = matching((await corpus.sessions(corpus.currentHarness)).filter((session) => session.harness === corpus.currentHarness));
|
|
35
|
+
if (matches.length === 0)
|
|
36
|
+
matches = matching((await corpus.sessions()).filter((session) => session.harness !== corpus.currentHarness));
|
|
37
|
+
}
|
|
38
|
+
if (matches.length === 0)
|
|
39
|
+
return failure("unknown_session", `No local session matches ${JSON.stringify(selector.harness ? `${selector.harness}:${selector.id}` : selector.id)}.`);
|
|
40
|
+
if (matches.length > 1)
|
|
41
|
+
return failure("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.`);
|
|
42
|
+
return success(matches[0]);
|
|
43
|
+
}
|
|
44
|
+
export async function loadHistorySession(session) {
|
|
45
|
+
try {
|
|
46
|
+
return success(await session.load());
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function currentHistory(context) {
|
|
53
|
+
return "current" in context ? context.current() : context;
|
|
54
|
+
}
|
|
@@ -51,9 +51,8 @@ export type HistoryProjection = {
|
|
|
51
51
|
branchSeqs: Set<number>;
|
|
52
52
|
pairedResults: Map<number, number>;
|
|
53
53
|
};
|
|
54
|
-
/** The filters one selection applies before paging:
|
|
54
|
+
/** The filters one selection applies before paging: roles, seq bounds, and parsed epoch-ms time bounds. */
|
|
55
55
|
export type HistoryFilter = {
|
|
56
|
-
window_id?: string | null;
|
|
57
56
|
roles?: HistoryRole[] | null;
|
|
58
57
|
after_seq?: number;
|
|
59
58
|
before_seq?: number;
|
|
@@ -120,14 +119,15 @@ export declare const HistoryPageItemSchema: Type.TObject<{
|
|
|
120
119
|
tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
|
|
121
120
|
output_truncated: Type.TOptional<Type.TLiteral<true>>;
|
|
122
121
|
full_output_path: Type.TOptional<Type.TString>;
|
|
122
|
+
session: Type.TOptional<Type.TString>;
|
|
123
123
|
seq: Type.TInteger;
|
|
124
|
-
window_id: Type.TString;
|
|
125
124
|
role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
|
|
126
125
|
created_at: Type.TUnion<[Type.TString, Type.TNull]>;
|
|
127
126
|
}>;
|
|
128
127
|
export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
|
|
129
128
|
/** A run of tool/context events the conversation view replaces with counts. */
|
|
130
129
|
export declare const HistoryFoldedRowSchema: Type.TObject<{
|
|
130
|
+
session: Type.TOptional<Type.TString>;
|
|
131
131
|
folded: Type.TLiteral<true>;
|
|
132
132
|
first_seq: Type.TInteger;
|
|
133
133
|
last_seq: Type.TInteger;
|
|
@@ -142,12 +142,8 @@ export declare const MAX_FOLD_TOOL_NAME_CHARS = 120;
|
|
|
142
142
|
/** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
|
|
143
143
|
export declare function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?: number): HistoryPageItem;
|
|
144
144
|
export declare function allItems(projection: HistoryProjection): HistoryEvent[];
|
|
145
|
-
export declare function unknownWindowId(projection: HistoryProjection, params: HistoryFilter): {
|
|
146
|
-
message: string;
|
|
147
|
-
known: string[];
|
|
148
|
-
} | undefined;
|
|
149
145
|
/**
|
|
150
|
-
* Whether one event is inside the selection: its
|
|
146
|
+
* Whether one event is inside the selection: its seq bounds, and a half-open
|
|
151
147
|
* [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
|
|
152
148
|
* time or a time that cannot be read.
|
|
153
149
|
*/
|
|
@@ -136,8 +136,8 @@ export function nestedCallSummary(event) {
|
|
|
136
136
|
}
|
|
137
137
|
/** Stable identity and a verbatim preview, starting at the search match when present. */
|
|
138
138
|
export const HistoryPageItemSchema = Type.Object({
|
|
139
|
+
session: Type.Optional(Type.String()),
|
|
139
140
|
seq: Type.Integer({ minimum: 1 }),
|
|
140
|
-
window_id: Type.String(),
|
|
141
141
|
role: HistoryRoleSchema,
|
|
142
142
|
created_at: Type.Union([Type.String(), Type.Null()]),
|
|
143
143
|
...ToolSummarySchema.properties,
|
|
@@ -147,6 +147,7 @@ export const HistoryPageItemSchema = Type.Object({
|
|
|
147
147
|
}, { additionalProperties: false });
|
|
148
148
|
/** A run of tool/context events the conversation view replaces with counts. */
|
|
149
149
|
export const HistoryFoldedRowSchema = Type.Object({
|
|
150
|
+
session: Type.Optional(Type.String()),
|
|
150
151
|
folded: Type.Literal(true),
|
|
151
152
|
first_seq: Type.Integer({ minimum: 1 }),
|
|
152
153
|
last_seq: Type.Integer({ minimum: 1 }),
|
|
@@ -167,7 +168,6 @@ export function visibleItem(event, maxChars, matchOffset) {
|
|
|
167
168
|
const truncated = start > 0 || start + limit < chars.length;
|
|
168
169
|
return {
|
|
169
170
|
seq: event.seq,
|
|
170
|
-
window_id: event.windowId,
|
|
171
171
|
role: event.role,
|
|
172
172
|
created_at: event.createdAt ?? null,
|
|
173
173
|
...toolSummary(event),
|
|
@@ -179,20 +179,12 @@ export function visibleItem(event, maxChars, matchOffset) {
|
|
|
179
179
|
export function allItems(projection) {
|
|
180
180
|
return projection.windows.flatMap((current) => current.items);
|
|
181
181
|
}
|
|
182
|
-
export function unknownWindowId(projection, params) {
|
|
183
|
-
if (typeof params.window_id !== "string")
|
|
184
|
-
return undefined;
|
|
185
|
-
const known = projection.windows.map((current) => current.windowId);
|
|
186
|
-
return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
|
|
187
|
-
}
|
|
188
182
|
/**
|
|
189
|
-
* Whether one event is inside the selection: its
|
|
183
|
+
* Whether one event is inside the selection: its seq bounds, and a half-open
|
|
190
184
|
* [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
|
|
191
185
|
* time or a time that cannot be read.
|
|
192
186
|
*/
|
|
193
187
|
export function inSelection(event, params) {
|
|
194
|
-
if (typeof params.window_id === "string" && params.window_id !== event.windowId)
|
|
195
|
-
return false;
|
|
196
188
|
if (params.after_seq !== undefined && event.seq <= params.after_seq)
|
|
197
189
|
return false;
|
|
198
190
|
if (params.before_seq !== undefined && event.seq >= params.before_seq)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type HistoryCorpus, type HistoryHarness, type HistorySession, type HistorySessionData } from "./corpus.js";
|
|
2
|
+
export type LocalHistoryRoots = Partial<Record<"pi" | "claude" | "codex", string | null>>;
|
|
3
|
+
export type LocalHistoryOptions = {
|
|
4
|
+
current: {
|
|
5
|
+
harness: HistoryHarness;
|
|
6
|
+
id: string;
|
|
7
|
+
load(): Promise<HistorySessionData>;
|
|
8
|
+
};
|
|
9
|
+
/** Undefined uses the harness default; null disables that harness's filesystem discovery. */
|
|
10
|
+
roots?: LocalHistoryRoots;
|
|
11
|
+
home?: string;
|
|
12
|
+
env?: NodeJS.ProcessEnv;
|
|
13
|
+
/** Available only inside DSH; descriptors load through ctx.sessionQuery.readSession. */
|
|
14
|
+
dshSessions?: () => Promise<HistorySession[]>;
|
|
15
|
+
};
|
|
16
|
+
/** Fresh discovery per call; a live binding wins over its persisted descriptor. No transcript writes. */
|
|
17
|
+
export declare function localHistoryCorpus(options: LocalHistoryOptions): HistoryCorpus;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Local read-only corpus. Wire decoders have no SDK dependencies; DSH supplies its query service. */
|
|
2
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { piHistoryFromJsonl } from "./pi.js";
|
|
6
|
+
import { claudeHistoryFromJsonl, offlineClaudeHead } from "./claude.js";
|
|
7
|
+
import { readCodexHistory } from "./codex.js";
|
|
8
|
+
import { sessionIdentity } from "./corpus.js";
|
|
9
|
+
function rootsFor(options) {
|
|
10
|
+
const env = options.env ?? process.env;
|
|
11
|
+
const home = options.home ?? env.HOME ?? homedir();
|
|
12
|
+
return {
|
|
13
|
+
pi: options.roots?.pi !== undefined ? options.roots.pi : env.NOTESOUP_HISTORY_PI_ROOT ?? join(env.PI_CODING_AGENT_DIR ?? join(home, ".pi", "agent"), "sessions"),
|
|
14
|
+
claude: options.roots?.claude !== undefined ? options.roots.claude : env.NOTESOUP_HISTORY_CLAUDE_ROOT ?? join(env.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "projects"),
|
|
15
|
+
codex: options.roots?.codex !== undefined ? options.roots.codex : env.NOTESOUP_HISTORY_CODEX_ROOT ?? join(env.CODEX_HOME ?? join(home, ".codex"), "sessions"),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Match the native layouts, without following symlinks or wandering into subagent/attachment stores. */
|
|
19
|
+
async function filesAt(root, depth) {
|
|
20
|
+
let entries;
|
|
21
|
+
try {
|
|
22
|
+
entries = await readdir(root, { withFileTypes: true });
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error.code === "ENOENT")
|
|
26
|
+
return [];
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
const paths = [];
|
|
30
|
+
for (const entry of entries) {
|
|
31
|
+
const path = join(root, entry.name);
|
|
32
|
+
if (entry.isDirectory() && depth > 0)
|
|
33
|
+
paths.push(...await filesAt(path, depth - 1));
|
|
34
|
+
else if (entry.isFile() && depth === 0)
|
|
35
|
+
paths.push(path);
|
|
36
|
+
}
|
|
37
|
+
return paths;
|
|
38
|
+
}
|
|
39
|
+
async function localSessions(harness, root) {
|
|
40
|
+
const paths = await filesAt(root, harness === "codex" ? 3 : 1);
|
|
41
|
+
const sessions = [];
|
|
42
|
+
for (const path of paths) {
|
|
43
|
+
const name = path.split(/[\\/]/).at(-1);
|
|
44
|
+
const id = harness === "pi" ? /^.+_(.+)\.jsonl$/.exec(name)?.[1]
|
|
45
|
+
: harness === "claude" ? /^(.+)\.jsonl$/.exec(name)?.[1]
|
|
46
|
+
: /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/.exec(name)?.[1];
|
|
47
|
+
if (!id)
|
|
48
|
+
continue;
|
|
49
|
+
let modifiedAt;
|
|
50
|
+
try {
|
|
51
|
+
modifiedAt = (await stat(path)).mtimeMs;
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error.code === "ENOENT")
|
|
55
|
+
continue;
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
sessions.push({
|
|
59
|
+
harness, id, modifiedAt,
|
|
60
|
+
async load() {
|
|
61
|
+
if (harness === "codex")
|
|
62
|
+
return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
|
|
63
|
+
const text = await readFile(path, "utf8");
|
|
64
|
+
if (harness === "pi")
|
|
65
|
+
return { projection: piHistoryFromJsonl(text, id) };
|
|
66
|
+
const projection = claudeHistoryFromJsonl(text, { sessionId: id, headUuid: offlineClaudeHead(text) });
|
|
67
|
+
const missing = projection.missingAncestors;
|
|
68
|
+
return { projection, ...(missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.\n\n` }) };
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return sessions;
|
|
73
|
+
}
|
|
74
|
+
/** Fresh discovery per call; a live binding wins over its persisted descriptor. No transcript writes. */
|
|
75
|
+
export function localHistoryCorpus(options) {
|
|
76
|
+
return {
|
|
77
|
+
currentHarness: options.current.harness,
|
|
78
|
+
async sessions(onlyHarness) {
|
|
79
|
+
const roots = rootsFor(options);
|
|
80
|
+
const discovered = [];
|
|
81
|
+
for (const harness of ["pi", "claude", "codex"]) {
|
|
82
|
+
if (onlyHarness !== undefined && onlyHarness !== harness)
|
|
83
|
+
continue;
|
|
84
|
+
const root = roots[harness];
|
|
85
|
+
if (root != null)
|
|
86
|
+
discovered.push(...await localSessions(harness, root));
|
|
87
|
+
}
|
|
88
|
+
if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh"))
|
|
89
|
+
discovered.push(...await options.dshSessions());
|
|
90
|
+
discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
|
|
91
|
+
const unique = new Map();
|
|
92
|
+
for (const session of discovered)
|
|
93
|
+
if (!unique.has(sessionIdentity(session)))
|
|
94
|
+
unique.set(sessionIdentity(session), session);
|
|
95
|
+
const current = { ...options.current, modifiedAt: Date.now() };
|
|
96
|
+
if (onlyHarness === undefined || onlyHarness === current.harness)
|
|
97
|
+
unique.set(sessionIdentity(current), current);
|
|
98
|
+
return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Pi's persisted entry/message wire format, independent of the Pi SDK. */
|
|
2
|
+
import { type HistoryProjection, type RecordedNestedCalls } from "./history.js";
|
|
3
|
+
/** Structural views also accept native SDK values without converting or allocating seqs twice. */
|
|
4
|
+
type Message = {
|
|
5
|
+
role: string;
|
|
6
|
+
content?: unknown;
|
|
7
|
+
output?: string;
|
|
8
|
+
summary?: string;
|
|
9
|
+
command?: string;
|
|
10
|
+
cancelled?: boolean;
|
|
11
|
+
exitCode?: number;
|
|
12
|
+
truncated?: boolean;
|
|
13
|
+
fullOutputPath?: string;
|
|
14
|
+
toolName?: string;
|
|
15
|
+
toolCallId?: string;
|
|
16
|
+
isError?: boolean;
|
|
17
|
+
nestedCalls?: RecordedNestedCalls;
|
|
18
|
+
};
|
|
19
|
+
export type PiHistoryEntry = {
|
|
20
|
+
type: string;
|
|
21
|
+
id: string;
|
|
22
|
+
parentId?: string | null;
|
|
23
|
+
timestamp?: string;
|
|
24
|
+
message?: Message;
|
|
25
|
+
summary?: string;
|
|
26
|
+
customType?: string;
|
|
27
|
+
data?: unknown;
|
|
28
|
+
content?: unknown;
|
|
29
|
+
};
|
|
30
|
+
/** Seq allocation depends on entry kind and role, never on visible content. */
|
|
31
|
+
export declare function piSequenceCount(entry: Pick<PiHistoryEntry, "type" | "message">): number;
|
|
32
|
+
/** Build stable internal addresses, then project the active branch into public events. */
|
|
33
|
+
export declare function piHistoryFromEntries(sessionId: string, entries: readonly PiHistoryEntry[], branch: readonly PiHistoryEntry[]): HistoryProjection;
|
|
34
|
+
/** Offline files persist append order and parent links; select the final tree entry's ancestry. */
|
|
35
|
+
export declare function piHistoryFromJsonl(text: string, sessionId: string): HistoryProjection;
|
|
36
|
+
export {};
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/** Pi's persisted entry/message wire format, independent of the Pi SDK. */
|
|
2
|
+
import { contentText, projectHistory } from "./history.js";
|
|
3
|
+
function mapRole(role) {
|
|
4
|
+
if (role === "user" || role === "assistant")
|
|
5
|
+
return role;
|
|
6
|
+
if (role === "toolResult" || role === "bashExecution")
|
|
7
|
+
return "tool";
|
|
8
|
+
if (role === "custom")
|
|
9
|
+
return "developer";
|
|
10
|
+
if (role === "compactionSummary" || role === "branchSummary")
|
|
11
|
+
return "system";
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
function isToolCall(part) {
|
|
15
|
+
return typeof part === "object" && part !== null && part.type === "toolCall";
|
|
16
|
+
}
|
|
17
|
+
/** Seq allocation depends on entry kind and role, never on visible content. */
|
|
18
|
+
export function piSequenceCount(entry) {
|
|
19
|
+
if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message")
|
|
20
|
+
return 1;
|
|
21
|
+
if (entry.type !== "message" || !entry.message || mapRole(entry.message.role) === undefined)
|
|
22
|
+
return 0;
|
|
23
|
+
if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content))
|
|
24
|
+
return 1;
|
|
25
|
+
return 1 + entry.message.content.filter(isToolCall).length;
|
|
26
|
+
}
|
|
27
|
+
function messageContent(message) {
|
|
28
|
+
switch (message.role) {
|
|
29
|
+
case "bashExecution":
|
|
30
|
+
return message.output ?? "";
|
|
31
|
+
case "branchSummary":
|
|
32
|
+
case "compactionSummary":
|
|
33
|
+
return message.summary ?? "";
|
|
34
|
+
default:
|
|
35
|
+
return contentText(message.content);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Pass the host's nested-call record through as recorded. It is evidence about calls this run made,
|
|
40
|
+
* not a second transcript: the host stores no nested results, and this lane invents none.
|
|
41
|
+
*/
|
|
42
|
+
function nestedCallsOf(message) {
|
|
43
|
+
if (message.role !== "toolResult" || message.nestedCalls === undefined)
|
|
44
|
+
return undefined;
|
|
45
|
+
return { calls: message.nestedCalls.calls, complete: message.nestedCalls.complete };
|
|
46
|
+
}
|
|
47
|
+
function toolInfo(message) {
|
|
48
|
+
if (message.role === "bashExecution") {
|
|
49
|
+
// A standalone bash run records its own outcome, so its status is read here rather than
|
|
50
|
+
// inferred from a result message that will never arrive: a cancelled or nonzero run is an
|
|
51
|
+
// error, and a run with no recorded exit code stays unknown instead of being called ok.
|
|
52
|
+
const status = message.cancelled === true ? "error" : typeof message.exitCode === "number" ? (message.exitCode === 0 ? "ok" : "error") : "unfinished";
|
|
53
|
+
// A truncated run is only half the record without the on-disk path: surface both.
|
|
54
|
+
return { toolName: "bash", arguments: { command: message.command }, recordedStatus: status, outputTruncated: message.truncated || undefined, fullOutputPath: message.truncated ? message.fullOutputPath : undefined };
|
|
55
|
+
}
|
|
56
|
+
if (message.role !== "toolResult")
|
|
57
|
+
return {};
|
|
58
|
+
const nestedCalls = nestedCallsOf(message);
|
|
59
|
+
return {
|
|
60
|
+
toolName: message.toolName,
|
|
61
|
+
toolCallId: message.toolCallId,
|
|
62
|
+
toolError: message.isError === true ? true : undefined,
|
|
63
|
+
...(nestedCalls ? { nestedCalls } : {}),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function toolCallItems(windowId, entry, message, entrySeq) {
|
|
67
|
+
if (message.role !== "assistant" || !Array.isArray(message.content))
|
|
68
|
+
return [];
|
|
69
|
+
const items = [];
|
|
70
|
+
let callIndex = 0;
|
|
71
|
+
for (const part of message.content) {
|
|
72
|
+
if (!isToolCall(part))
|
|
73
|
+
continue;
|
|
74
|
+
items.push({
|
|
75
|
+
seq: entrySeq + callIndex + 1,
|
|
76
|
+
windowId,
|
|
77
|
+
role: "tool_call",
|
|
78
|
+
text: "",
|
|
79
|
+
createdAt: entry.timestamp,
|
|
80
|
+
toolName: part.name,
|
|
81
|
+
toolCallId: part.id,
|
|
82
|
+
arguments: part.arguments,
|
|
83
|
+
});
|
|
84
|
+
callIndex += 1;
|
|
85
|
+
}
|
|
86
|
+
return items;
|
|
87
|
+
}
|
|
88
|
+
/** Build stable internal addresses, then project the active branch into public events. */
|
|
89
|
+
export function piHistoryFromEntries(sessionId, entries, branch) {
|
|
90
|
+
const seqByEntryId = new Map();
|
|
91
|
+
let nextSeq = 1;
|
|
92
|
+
for (const entry of entries) {
|
|
93
|
+
const count = piSequenceCount(entry);
|
|
94
|
+
if (count === 0)
|
|
95
|
+
continue;
|
|
96
|
+
seqByEntryId.set(entry.id, nextSeq);
|
|
97
|
+
nextSeq += count;
|
|
98
|
+
}
|
|
99
|
+
const highestSeq = nextSeq - 1;
|
|
100
|
+
let window = { windowId: `pcw:${sessionId.slice(0, 8)}:root`, items: [] };
|
|
101
|
+
const rawWindows = [window];
|
|
102
|
+
const branchSeqs = new Set();
|
|
103
|
+
for (const entry of branch) {
|
|
104
|
+
if (entry.type === "custom" && entry.customType === "notesoup/reset-marker" && typeof entry.data === "object" && entry.data !== null && "windowId" in entry.data && typeof entry.data.windowId === "string" && entry.data.windowId.length > 0) {
|
|
105
|
+
window = { windowId: entry.data.windowId, createdAt: entry.timestamp, items: [] };
|
|
106
|
+
rawWindows.push(window);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const entrySeq = seqByEntryId.get(entry.id);
|
|
110
|
+
if (entrySeq === undefined)
|
|
111
|
+
continue;
|
|
112
|
+
branchSeqs.add(entrySeq);
|
|
113
|
+
if (entry.type === "compaction" || entry.type === "branch_summary") {
|
|
114
|
+
window.items.push({ seq: entrySeq, windowId: window.windowId, role: "system", text: entry.summary ?? "", createdAt: entry.timestamp });
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (entry.type === "message" && entry.message) {
|
|
118
|
+
const role = mapRole(entry.message.role);
|
|
119
|
+
if (!role)
|
|
120
|
+
continue;
|
|
121
|
+
window.items.push({
|
|
122
|
+
seq: entrySeq,
|
|
123
|
+
windowId: window.windowId,
|
|
124
|
+
role,
|
|
125
|
+
text: messageContent(entry.message),
|
|
126
|
+
createdAt: entry.timestamp,
|
|
127
|
+
...toolInfo(entry.message),
|
|
128
|
+
});
|
|
129
|
+
const calls = toolCallItems(window.windowId, entry, entry.message, entrySeq);
|
|
130
|
+
for (const call of calls)
|
|
131
|
+
branchSeqs.add(call.seq);
|
|
132
|
+
window.items.push(...calls);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (entry.type === "custom_message") {
|
|
136
|
+
window.items.push({
|
|
137
|
+
seq: entrySeq,
|
|
138
|
+
windowId: window.windowId,
|
|
139
|
+
role: "developer",
|
|
140
|
+
text: contentText(entry.content),
|
|
141
|
+
createdAt: entry.timestamp,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return projectHistory(rawWindows, highestSeq, branchSeqs);
|
|
146
|
+
}
|
|
147
|
+
/** Offline files persist append order and parent links; select the final tree entry's ancestry. */
|
|
148
|
+
export function piHistoryFromJsonl(text, sessionId) {
|
|
149
|
+
const lines = text.split("\n");
|
|
150
|
+
const entries = [];
|
|
151
|
+
let header = false;
|
|
152
|
+
for (let index = 0; index < lines.length; index++) {
|
|
153
|
+
const line = lines[index];
|
|
154
|
+
if (line.trim() === "")
|
|
155
|
+
continue;
|
|
156
|
+
let row;
|
|
157
|
+
try {
|
|
158
|
+
row = JSON.parse(line);
|
|
159
|
+
}
|
|
160
|
+
catch {
|
|
161
|
+
if (index === lines.length - 1 && !text.endsWith("\n"))
|
|
162
|
+
break;
|
|
163
|
+
throw new Error(`malformed Pi transcript JSON at line ${index + 1}`);
|
|
164
|
+
}
|
|
165
|
+
if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string")
|
|
166
|
+
throw new Error("invalid Pi transcript entry");
|
|
167
|
+
if (!header) {
|
|
168
|
+
if (row.type !== "session" || row.id !== sessionId)
|
|
169
|
+
throw new Error("Pi transcript belongs to a different session or has no header");
|
|
170
|
+
header = true;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (row.parentId !== null && typeof row.parentId !== "string")
|
|
174
|
+
throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
|
|
175
|
+
if (row.type === "message" && (!row.message || typeof row.message.role !== "string"))
|
|
176
|
+
throw new Error("invalid Pi transcript message");
|
|
177
|
+
entries.push(row);
|
|
178
|
+
}
|
|
179
|
+
if (!header)
|
|
180
|
+
throw new Error("Pi transcript has no session header");
|
|
181
|
+
const byId = new Map();
|
|
182
|
+
for (const entry of entries) {
|
|
183
|
+
if (byId.has(entry.id))
|
|
184
|
+
throw new Error(`duplicate Pi entry ID: ${entry.id}`);
|
|
185
|
+
byId.set(entry.id, entry);
|
|
186
|
+
}
|
|
187
|
+
const branch = [], seen = new Set();
|
|
188
|
+
let cursor = entries.at(-1);
|
|
189
|
+
while (cursor) {
|
|
190
|
+
if (seen.has(cursor.id))
|
|
191
|
+
throw new Error("cyclic Pi transcript ancestry");
|
|
192
|
+
seen.add(cursor.id);
|
|
193
|
+
branch.push(cursor);
|
|
194
|
+
if (cursor.parentId === null)
|
|
195
|
+
break;
|
|
196
|
+
const parent = byId.get(cursor.parentId);
|
|
197
|
+
if (!parent)
|
|
198
|
+
throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
|
|
199
|
+
cursor = parent;
|
|
200
|
+
}
|
|
201
|
+
return piHistoryFromEntries(sessionId, entries, branch.reverse());
|
|
202
|
+
}
|
|
@@ -10,6 +10,7 @@ export type HistoryOrder = "newest" | "oldest";
|
|
|
10
10
|
* every role, with no folded rows.
|
|
11
11
|
*/
|
|
12
12
|
export type HistorySelection = HistoryFilter & {
|
|
13
|
+
session?: string;
|
|
13
14
|
from?: HistoryOrder;
|
|
14
15
|
limit?: number;
|
|
15
16
|
query?: string | string[];
|
|
@@ -19,14 +20,17 @@ export type HistorySelection = HistoryFilter & {
|
|
|
19
20
|
};
|
|
20
21
|
/** The params to merge into the previous call to continue toward older events. */
|
|
21
22
|
export declare const HistoryOlderSchema: Type.TObject<{
|
|
23
|
+
session: Type.TOptional<Type.TString>;
|
|
22
24
|
before_seq: Type.TInteger;
|
|
23
25
|
}>;
|
|
24
26
|
/** The params to merge into the previous call to continue toward newer events. */
|
|
25
27
|
export declare const HistoryNewerSchema: Type.TObject<{
|
|
28
|
+
session: Type.TOptional<Type.TString>;
|
|
26
29
|
after_seq: Type.TInteger;
|
|
27
30
|
from: Type.TLiteral<"oldest">;
|
|
28
31
|
}>;
|
|
29
32
|
export declare const HistoryPageSchema: Type.TObject<{
|
|
33
|
+
notice: Type.TOptional<Type.TString>;
|
|
30
34
|
items: Type.TArray<Type.TUnion<[Type.TObject<{
|
|
31
35
|
content: Type.TString;
|
|
32
36
|
truncated: Type.TBoolean;
|
|
@@ -35,11 +39,12 @@ export declare const HistoryPageSchema: Type.TObject<{
|
|
|
35
39
|
tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
|
|
36
40
|
output_truncated: Type.TOptional<Type.TLiteral<true>>;
|
|
37
41
|
full_output_path: Type.TOptional<Type.TString>;
|
|
42
|
+
session: Type.TOptional<Type.TString>;
|
|
38
43
|
seq: Type.TInteger;
|
|
39
|
-
window_id: Type.TString;
|
|
40
44
|
role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
|
|
41
45
|
created_at: Type.TUnion<[Type.TString, Type.TNull]>;
|
|
42
46
|
}>, Type.TObject<{
|
|
47
|
+
session: Type.TOptional<Type.TString>;
|
|
43
48
|
folded: Type.TLiteral<true>;
|
|
44
49
|
first_seq: Type.TInteger;
|
|
45
50
|
last_seq: Type.TInteger;
|
|
@@ -47,17 +52,22 @@ export declare const HistoryPageSchema: Type.TObject<{
|
|
|
47
52
|
tools: Type.TRecord<"^.*$", Type.TInteger>;
|
|
48
53
|
}>]>>;
|
|
49
54
|
page_older: Type.TUnion<[Type.TObject<{
|
|
55
|
+
session: Type.TOptional<Type.TString>;
|
|
50
56
|
before_seq: Type.TInteger;
|
|
51
57
|
}>, Type.TNull]>;
|
|
52
58
|
page_newer: Type.TUnion<[Type.TObject<{
|
|
59
|
+
session: Type.TOptional<Type.TString>;
|
|
53
60
|
after_seq: Type.TInteger;
|
|
54
61
|
from: Type.TLiteral<"oldest">;
|
|
55
62
|
}>, Type.TNull]>;
|
|
56
63
|
}>;
|
|
57
64
|
/** One whole page payload, before it becomes an outcome. */
|
|
58
65
|
export type HistoryPage = Static<typeof HistoryPageSchema>;
|
|
59
|
-
/**
|
|
60
|
-
* Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
|
|
61
|
-
* Grow the page in selection order; shorten the first preview only when no full row fits.
|
|
62
|
-
*/
|
|
63
66
|
export declare function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage>;
|
|
67
|
+
/** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
|
|
68
|
+
export declare function corpusSelection(params: HistorySelection): Outcome<HistorySelection>;
|
|
69
|
+
/** Merge events, never folds or per-session cursors. Equal timestamps have a stable identity tie-break. */
|
|
70
|
+
export declare function selectCorpusPage(sessions: {
|
|
71
|
+
session: string;
|
|
72
|
+
projection: HistoryProjection;
|
|
73
|
+
}[], scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage>;
|