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.
Files changed (96) hide show
  1. package/README.md +4 -2
  2. package/dist/plugins/claude/src/helper.d.ts +2 -1
  3. package/dist/plugins/claude/src/helper.js +19 -23
  4. package/dist/plugins/claude/src/history.d.ts +3 -14
  5. package/dist/plugins/claude/src/history.js +2 -298
  6. package/dist/plugins/claude/src/text.d.ts +0 -1
  7. package/dist/plugins/claude/src/text.js +0 -1
  8. package/dist/plugins/codex/src/history.d.ts +3 -8
  9. package/dist/plugins/codex/src/history.js +2 -238
  10. package/dist/plugins/codex/src/mcp.js +7 -7
  11. package/dist/plugins/codex/src/transcript.d.ts +3 -39
  12. package/dist/plugins/codex/src/transcript.js +2 -313
  13. package/dist/plugins/dsh/history.d.ts +3 -0
  14. package/dist/plugins/dsh/history.js +15 -0
  15. package/dist/plugins/dsh/tools.js +4 -5
  16. package/dist/plugins/pi/history-tools.d.ts +1 -1
  17. package/dist/plugins/pi/history-tools.js +9 -5
  18. package/dist/plugins/pi/history.d.ts +2 -3
  19. package/dist/plugins/pi/history.js +4 -147
  20. package/dist/src/boot/render.js +2 -4
  21. package/dist/src/boot/text.d.ts +3 -1
  22. package/dist/src/boot/text.js +11 -5
  23. package/dist/src/history/claude.d.ts +16 -0
  24. package/dist/src/history/claude.js +336 -0
  25. package/dist/src/history/codex-transcript.d.ts +39 -0
  26. package/dist/src/history/codex-transcript.js +315 -0
  27. package/dist/src/history/codex.d.ts +8 -0
  28. package/dist/src/history/codex.js +238 -0
  29. package/dist/src/history/corpus.d.ts +35 -0
  30. package/dist/src/history/corpus.js +54 -0
  31. package/dist/src/history/history.d.ts +4 -8
  32. package/dist/src/history/history.js +3 -11
  33. package/dist/src/history/local.d.ts +17 -0
  34. package/dist/src/history/local.js +101 -0
  35. package/dist/src/history/pi.d.ts +36 -0
  36. package/dist/src/history/pi.js +202 -0
  37. package/dist/src/history/query.d.ts +15 -5
  38. package/dist/src/history/query.js +42 -13
  39. package/dist/src/index.d.ts +4 -2
  40. package/dist/src/index.js +4 -3
  41. package/dist/src/tools/history.d.ts +7 -19
  42. package/dist/src/tools/history.js +80 -93
  43. package/dist/test/boot.integration.test.js +1 -2
  44. package/dist/test/claude-history.test.js +47 -34
  45. package/dist/test/claude-mod.test.js +7 -7
  46. package/dist/test/codex-history.test.js +4 -10
  47. package/dist/test/codex-plugin.test.js +32 -11
  48. package/dist/test/dependencies.test.js +3 -3
  49. package/dist/test/dsh.test.js +26 -4
  50. package/dist/test/helpers/extension.d.ts +0 -1
  51. package/dist/test/helpers/history-corpus.d.ts +7 -0
  52. package/dist/test/helpers/history-corpus.js +26 -0
  53. package/dist/test/history-corpus.test.d.ts +1 -0
  54. package/dist/test/history-corpus.test.js +307 -0
  55. package/dist/test/history.integration.test.js +40 -48
  56. package/dist/test/host-neutral.test.js +3 -18
  57. package/dist/test/model-facing-text.test.js +2 -0
  58. package/dist/test/notes.integration.test.js +1 -1
  59. package/dist/test/notes.test.js +1 -1
  60. package/docs/architecture.md +7 -5
  61. package/docs/claude-code-mod.md +7 -5
  62. package/docs/codex.md +3 -3
  63. package/docs/dsh.md +2 -2
  64. package/docs/history-sessions.md +52 -0
  65. package/docs/notes-library.md +1 -1
  66. package/docs/skills.md +1 -1
  67. package/docs/tool-results.md +8 -6
  68. package/package.json +1 -1
  69. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  70. package/plugins/claude/dist/claude/helper.js +1507 -746
  71. package/plugins/claude/skills/memory/SKILL.md +5 -3
  72. package/plugins/claude/src/helper.ts +19 -23
  73. package/plugins/claude/src/history.ts +3 -257
  74. package/plugins/claude/src/text.ts +0 -1
  75. package/plugins/codex/dist/codex/notesoup.js +705 -154
  76. package/plugins/codex/src/history.ts +3 -193
  77. package/plugins/codex/src/mcp.ts +7 -7
  78. package/plugins/codex/src/transcript.ts +3 -275
  79. package/plugins/dsh/history.ts +17 -0
  80. package/plugins/dsh/tools.ts +4 -5
  81. package/plugins/paseo/client/markdown.tsx +19 -39
  82. package/plugins/pi/history-tools.ts +11 -5
  83. package/plugins/pi/history.ts +8 -157
  84. package/skills/memory/SKILL.md +5 -3
  85. package/src/boot/render.ts +2 -5
  86. package/src/boot/text.ts +11 -5
  87. package/src/history/claude.ts +286 -0
  88. package/src/history/codex-transcript.ts +276 -0
  89. package/src/history/codex.ts +193 -0
  90. package/src/history/corpus.ts +69 -0
  91. package/src/history/history.ts +5 -12
  92. package/src/history/local.ts +93 -0
  93. package/src/history/pi.ts +199 -0
  94. package/src/history/query.ts +45 -15
  95. package/src/index.ts +5 -3
  96. package/src/tools/history.ts +71 -101
@@ -0,0 +1,193 @@
1
+ /** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
2
+ import { projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "./history.js";
3
+ import { nativeObject as obj, nativeString as str, readCodexTranscript, type CodexRecord, type CodexTranscriptSource, type CodexTranscriptState, type NativeObject } from "./codex-transcript.js";
4
+ export type { CodexTranscriptSource } from "./codex-transcript.js";
5
+ export type CodexHistoryState = CodexTranscriptState & { projection: HistoryProjection };
6
+
7
+ const DISPLAY_COPIES = new Set(["user_message", "agent_message", "agent_reasoning", "agent_reasoning_raw_content", "context_compacted", "web_search_end", "image_generation_end"]);
8
+ const ITEM_COPIES = new Set(["UserMessage", "AgentMessage", "Reasoning", "ContextCompaction", "WebSearch", "ImageGeneration", "HookPrompt"]);
9
+ // protocol.rs serializes v1 task_* spellings; turn_* are explicit serde aliases.
10
+ const HOST_EVENTS = new Set(["token_count", "thread_goal_updated", "task_started", "task_complete", "turn_started", "turn_complete", "turn_aborted", "thread_settings_applied", "entered_review_mode", "exited_review_mode", "patch_apply_end", "sub_agent_activity"]);
11
+ const HOST_ITEMS = new Set(["Plan", "FileChange", "CollabAgentToolCall", "SubAgentActivity", "ImageView", "Extension", "EnteredReviewMode", "ExitedReviewMode"]);
12
+ const OPAQUE_RESPONSES = new Set(["reasoning", "compaction", "compaction_summary", "context_compaction", "image_generation_call"]);
13
+ const HOST_RESPONSES = new Set(["configuration_update", "tool_search_call", "tool_search_output", "web_search_call"]);
14
+ function optionalString(value: unknown, field: string): string | undefined { return value == null ? undefined : str(value, field); }
15
+ function array(value: unknown, field: string): unknown[] {
16
+ if (!Array.isArray(value)) throw new Error(`Invalid Codex ${field}: expected an array`);
17
+ return value;
18
+ }
19
+ /** No image/audio decoding, opaque plaintext recovery, or stringification disguised as message text. */
20
+ function textContent(value: unknown): string {
21
+ return array(value, "content").map((value) => {
22
+ const part = obj(value, "content part");
23
+ switch (part.type) {
24
+ case "input_text": case "output_text": return str(part.text, "content text");
25
+ case "input_image": return "[Codex image content omitted]";
26
+ case "input_audio": return "[Codex audio content omitted]";
27
+ case "encrypted_content": return "[Codex encrypted content unavailable]";
28
+ default: throw new Error(`Unsupported Codex content part: ${String(part.type)}`);
29
+ }
30
+ }).join("\n");
31
+ }
32
+ function output(value: unknown): string { return typeof value === "string" ? value : textContent(value); }
33
+ function argumentsOf(raw: string): NativeObject {
34
+ // Custom/invalid/non-object JSON cannot fit the shared object field. Keep the
35
+ // original wire string under an explicit raw label rather than lose it.
36
+ try {
37
+ const parsed: unknown = JSON.parse(raw);
38
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as NativeObject;
39
+ } catch { /* Native tool calls may persist unparseable model arguments. */ }
40
+ return { raw_arguments: raw };
41
+ }
42
+ function callKey(record: CodexRecord, callId: string): string { return `${record.owner}:${callId}`; }
43
+ function context(record: CodexRecord, text: string): DecodedHistoryItem {
44
+ if (!record.windowId) throw new Error(`Unavailable Codex history: native window identity missing at seq ${record.seq}; cannot assign a stable window address`);
45
+ return { seq: record.seq, windowId: record.windowId, role: "system", text, createdAt: record.timestamp };
46
+ }
47
+ function host(record: CodexRecord, kind: string, payload: unknown): DecodedHistoryItem { return context(record, `Codex ${kind}\n${JSON.stringify(payload)}`); }
48
+
49
+ type ToolFact = { error?: boolean; text?: string };
50
+ /** Presentation records contribute OUTCOME evidence, never duplicate raw tool dialogue. */
51
+ function fact(item: NativeObject): ToolFact {
52
+ if (item.type === "CommandExecution") {
53
+ const status = str(item.status, "CommandExecution.status");
54
+ if (!["completed", "failed", "declined", "in_progress"].includes(status)) throw new Error(`Unsupported Codex command status: ${status}`);
55
+ return { error: status === "failed" || status === "declined" || (typeof item.exit_code === "number" && item.exit_code !== 0), text: optionalString(item.formatted_output, "formatted_output") };
56
+ }
57
+ if (item.type === "McpToolCall") {
58
+ const result = item.result == null ? undefined : obj(item.result, "MCP result");
59
+ if (result?.isError != null && typeof result.isError !== "boolean") throw new Error("Invalid Codex MCP isError");
60
+ return { error: item.status === "failed" || item.error != null || result?.isError === true, ...(result === undefined ? {} : { text: JSON.stringify(result) }) };
61
+ }
62
+ if (item.type === "DynamicToolCall") return { error: item.success === false || item.status === "failed" || item.error != null };
63
+ if (item.type === "FileChange" || item.type === "CollabAgentToolCall") return { error: item.status === "failed" || item.status === "declined" || item.status === "interrupted" };
64
+ return {};
65
+ }
66
+ function toolDisplay(item: NativeObject): boolean {
67
+ return ["CommandExecution", "McpToolCall", "DynamicToolCall", "CollabAgentToolCall", "FileChange", "ImageView", "Extension"].includes(String(item.type));
68
+ }
69
+ function response(record: CodexRecord, facts: Map<string, ToolFact>): DecodedHistoryItem {
70
+ const p = record.payload, type = str(p.type, "response_item.type"), base = context(record, "");
71
+ if (type === "message") {
72
+ if (!["user", "assistant", "system", "developer"].includes(str(p.role, "message.role"))) throw new Error(`Unsupported Codex message role: ${String(p.role)}`);
73
+ return { ...base, role: record.metadata?.compaction_output === true ? "system" : p.role as "user" | "assistant" | "system" | "developer", text: textContent(p.content) };
74
+ }
75
+ if (type === "function_call" || type === "custom_tool_call" || type === "local_shell_call") {
76
+ const callId = optionalString(p.call_id, "call_id") ?? (type === "local_shell_call" ? optionalString(p.id, "local shell id") : undefined);
77
+ if (!callId) throw new Error("Invalid Codex tool call: missing native call ID");
78
+ const name = type === "local_shell_call" ? "local_shell" : str(p.name, "tool name");
79
+ const args = type === "local_shell_call" ? obj(p.action, "local shell action") : type === "custom_tool_call" ? { input: str(p.input, "custom tool input") } : argumentsOf(str(p.arguments, "function arguments"));
80
+ return { ...base, role: "tool_call", toolName: p.namespace ? `${str(p.namespace, "namespace")}.${name}` : name, toolCallId: callKey(record, callId), arguments: args };
81
+ }
82
+ if (type === "function_call_output" || type === "custom_tool_call_output") {
83
+ const callId = optionalString(p.call_id, "output.call_id"), recorded = callId ? facts.get(callKey(record, callId)) : undefined;
84
+ return { ...base, role: "tool", text: output(p.output), ...(callId ? { toolCallId: callKey(record, callId) } : {}), ...(p.name == null ? {} : { toolName: str(p.name, "output.name") }), ...(recorded?.error === undefined ? {} : { toolError: recorded.error }) };
85
+ }
86
+ if (type === "agent_message") return host(record, "agent_message", { author: p.author, recipient: p.recipient, text: textContent(p.content) });
87
+ if (OPAQUE_RESPONSES.has(type)) {
88
+ // Preserve recorded summaries and available metadata, not encrypted blobs or image bytes.
89
+ const { encrypted_content: _encrypted, result: _image, ...readable } = p;
90
+ return host(record, `${type} (opaque content omitted; not recovered plaintext)`, readable);
91
+ }
92
+ if (HOST_RESPONSES.has(type)) return host(record, type, p);
93
+ throw new Error(`Unsupported Codex response item: ${type}`);
94
+ }
95
+
96
+ /** One display record without a raw equivalent (e.g. user-shell command). */
97
+ function standaloneTool(record: CodexRecord, item: NativeObject): DecodedHistoryItem {
98
+ const base = context(record, ""), recorded = fact(item);
99
+ if (item.type === "CommandExecution") {
100
+ array(item.command, "command").forEach((part) => str(part, "command argument"));
101
+ return { ...base, role: "tool", toolName: "terminal", arguments: { command: item.command, cwd: item.cwd, source: item.source, ...(item.interaction_input == null ? {} : { interaction_input: item.interaction_input }) }, text: recorded.text ?? JSON.stringify({ stdout: item.stdout, stderr: item.stderr, aggregated_output: item.aggregated_output }), recordedStatus: item.status === "in_progress" ? "unfinished" : recorded.error ? "error" : "ok" };
102
+ }
103
+ const name = `${str(item.server, "MCP server")}/${str(item.tool, "MCP tool")}`;
104
+ return { ...base, role: "tool", toolName: name, arguments: obj(item.arguments, "MCP arguments"), text: recorded.text ?? (item.error == null ? "" : JSON.stringify(item.error)), recordedStatus: item.status === "inProgress" ? "unfinished" : recorded.error ? "error" : "ok" };
105
+ }
106
+
107
+ export async function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState> {
108
+ const { state, records, highestSeq } = await readCodexTranscript(source);
109
+ const facts = new Map<string, ToolFact>(), callsSeen = new Set<string>(), responseIdsSeen = new Set<string>();
110
+ const windows = new Map<string, DecodedHistoryWindow>(), branchSeqs = new Set<number>();
111
+ const addWindow = (nativeId: string, createdAt?: string): DecodedHistoryWindow => {
112
+ const windowId = `codex:${source.threadId}:${nativeId}`;
113
+ let window = windows.get(windowId);
114
+ if (!window) { window = { windowId, createdAt, items: [] }; windows.set(windowId, window); }
115
+ return window;
116
+ };
117
+ // Outcome inventory can enrich the raw result even when ItemCompleted follows it.
118
+ for (const record of records) {
119
+ const p = record.payload;
120
+ if (record.type === "event_msg" && p.type === "item_completed") {
121
+ if (p.thread_id !== record.owner) throw new Error("Invalid Codex ItemCompleted thread identity");
122
+ const item = obj(p.item, "ItemCompleted.item");
123
+ if (toolDisplay(item)) facts.set(callKey(record, str(item.id, "TurnItem.id")), fact(item));
124
+ } else if (record.type === "event_msg" && p.type === "patch_apply_end") {
125
+ if (typeof p.success !== "boolean") throw new Error("Invalid Codex patch_apply_end.success");
126
+ facts.set(callKey(record, str(p.call_id, "patch call_id")), { error: !p.success });
127
+ } else if (record.type === "event_msg" && p.type === "mcp_tool_call_end") {
128
+ const result = obj(p.result, "MCP Result envelope");
129
+ const ok = result.Ok == null ? undefined : obj(result.Ok, "MCP Result.Ok");
130
+ if (ok === undefined && typeof result.Err !== "string") throw new Error("Invalid Codex MCP Result: expected Ok or Err");
131
+ facts.set(callKey(record, str(p.call_id, "MCP call_id")), { error: result.Err != null || ok?.isError === true, text: JSON.stringify(result) });
132
+ }
133
+ }
134
+ for (const record of records) {
135
+ branchSeqs.add(record.seq);
136
+ if (record.windowId) addWindow(record.windowId, record.type === "session_meta" || record.type === "compacted" ? record.timestamp : undefined);
137
+ const p = record.payload;
138
+ let item: DecodedHistoryItem | undefined;
139
+ switch (record.type) {
140
+ case "session_meta":
141
+ if (p.subagent_history_start_ordinal != null) item = context(record, `Codex copied subagent inference prefix omitted: child-local history starts at native ordinal ${String(p.subagent_history_start_ordinal)}. Copied model context does not prove original parent event addresses.`);
142
+ break;
143
+ case "response_item": {
144
+ item = response(record, facts);
145
+ if (p.id != null) responseIdsSeen.add(callKey(record, str(p.id, "response item id")));
146
+ if (item.role === "tool_call" && item.toolCallId) {
147
+ if (callsSeen.has(item.toolCallId)) throw new Error(`Unavailable Codex history: duplicate native call ID ${item.toolCallId}`);
148
+ callsSeen.add(item.toolCallId);
149
+ }
150
+ break;
151
+ }
152
+ case "compacted": item = context(record, `Codex compaction boundary\n${JSON.stringify({ message: p.message, window_number: p.window_number, first_window_id: p.first_window_id, previous_window_id: p.previous_window_id, window_id: p.window_id, replacement_history_items: Array.isArray(p.replacement_history) ? p.replacement_history.length : null })}\nreplacement_history is an inference checkpoint, not new conversation events.`); break;
153
+ case "event_msg": {
154
+ const type = str(p.type, "event_msg.type");
155
+ if (DISPLAY_COPIES.has(type)) break;
156
+ // A rollback changes the native selected window retrospectively. Until its
157
+ // turn semantics are decoded, don't return stale-but-plausible boot facts.
158
+ if (type === "thread_rolled_back") throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
159
+ if (type === "patch_apply_end" && callsSeen.has(callKey(record, str(p.call_id, "patch call_id")))) break;
160
+ if (type === "mcp_tool_call_end") {
161
+ const call = callKey(record, str(p.call_id, "MCP call_id"));
162
+ if (!callsSeen.has(call)) item = host(record, "MCP completion without a recorded raw call", p);
163
+ break;
164
+ }
165
+ if (type === "item_completed") {
166
+ const display = obj(p.item, "ItemCompleted.item"), kind = str(display.type, "TurnItem.type");
167
+ if (ITEM_COPIES.has(kind)) break;
168
+ if (toolDisplay(display) && callsSeen.has(callKey(record, str(display.id, "TurnItem.id")))) break;
169
+ if (kind === "CommandExecution" || kind === "McpToolCall") {
170
+ item = standaloneTool(record, display);
171
+ } else if (kind === "FunctionCallOutput") {
172
+ // hook_runtime.rs record_pending_input persists raw output FIRST,
173
+ // then emits this presentation copy with the SAME response-item ID.
174
+ if (!responseIdsSeen.has(callKey(record, str(display.id, "FunctionCallOutput.id")))) item = host(record, "FunctionCallOutput display without raw output", display);
175
+ } else if (HOST_ITEMS.has(kind) || kind === "DynamicToolCall") item = host(record, kind, display);
176
+ else throw new Error(`Unsupported Codex TurnItem: ${kind}`);
177
+ } else if (HOST_EVENTS.has(type)) {
178
+ // Lifecycle's repeated final answer isn't a second assistant message.
179
+ const { last_agent_message: _displayCopy, ...facts } = p;
180
+ item = host(record, type, facts);
181
+ }
182
+ else throw new Error(`Unsupported Codex persisted event: ${type}`);
183
+ break;
184
+ }
185
+ case "turn_context": case "token_usage_record": case "security_risk_score": case "inter_agent_communication_metadata": break;
186
+ case "world_state": item = context(record, "Codex world_state snapshot/patch omitted from the text projection; not a newly spoken message."); break;
187
+ case "inter_agent_communication": item = host(record, "inter-agent communication", { author: p.author, recipient: p.recipient, content: p.encrypted_content == null ? p.content : "[encrypted content unavailable]", trigger_turn: p.trigger_turn }); break;
188
+ case "retained_context": case "realtime_item": item = context(record, `Codex ${record.type} omitted from text projection; native structured/retained context is not newly spoken dialogue.`); break;
189
+ }
190
+ if (item) addWindow(record.windowId!).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
191
+ }
192
+ return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
193
+ }
@@ -0,0 +1,69 @@
1
+ /** A read-only history corpus: identity/discovery is separate from loading a projection. */
2
+ import { failure, success, type Outcome } from "../tools/result.js";
3
+ import type { HistoryProjection } from "./history.js";
4
+
5
+ export type HistoryHarness = "pi" | "claude" | "codex" | "dsh";
6
+ export type HistorySessionData = { projection: HistoryProjection; notice?: string };
7
+ export type HistorySession = {
8
+ harness: HistoryHarness;
9
+ id: string;
10
+ modifiedAt: number;
11
+ load(): Promise<HistorySessionData>;
12
+ };
13
+ export type HistoryCorpus = {
14
+ currentHarness: HistoryHarness;
15
+ sessions(harness?: HistoryHarness): Promise<HistorySession[]>;
16
+ };
17
+ /** A lazy current projection preserves native host checks, without requiring it for a foreign read. */
18
+ export type HistoryContext = HistoryProjection | { current(): HistoryProjection | Promise<HistoryProjection>; corpus: HistoryCorpus };
19
+ export type SessionSelector = { harness?: HistoryHarness; id: string; wildcard: boolean };
20
+ const HARNESSES = new Set<string>(["pi", "claude", "codex", "dsh"]);
21
+
22
+ export function sessionIdentity(session: Pick<HistorySession, "harness" | "id">): string {
23
+ return `${session.harness}:${session.id}`;
24
+ }
25
+
26
+ export function parseSessionSelector(value: string): Outcome<SessionSelector> {
27
+ const colon = value.indexOf(":");
28
+ const harness = colon < 0 ? undefined : value.slice(0, colon);
29
+ const id = colon < 0 ? value : value.slice(colon + 1);
30
+ if (id.length === 0 || id.includes(":") || (harness !== undefined && !HARNESSES.has(harness))) {
31
+ return failure("invalid_session", "Pass a session ID or prefix, optionally prefixed by pi:, claude:, codex:, or dsh:.");
32
+ }
33
+ return success({ ...(harness === undefined ? {} : { harness: harness as HistoryHarness }), id, wildcard: id.includes("*") });
34
+ }
35
+
36
+ /** '*' is the only metacharacter; all other characters match literally. */
37
+ export function matchesSession(session: HistorySession, selector: SessionSelector): boolean {
38
+ if (selector.harness !== undefined && selector.harness !== session.harness) return false;
39
+ const escaped = selector.id.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*");
40
+ return new RegExp(`^${escaped}$`).test(session.id);
41
+ }
42
+
43
+ export async function resolveSession(corpus: HistoryCorpus | undefined, selector: SessionSelector): Promise<Outcome<HistorySession>> {
44
+ if (corpus === undefined) return failure("unknown_session", "This host supplied no cross-session history corpus.");
45
+ const matching = (pool: HistorySession[]) => {
46
+ const exact = pool.filter((session) => session.id === selector.id);
47
+ return exact.length ? exact : pool.filter((session) => session.id.startsWith(selector.id));
48
+ };
49
+ let matches: HistorySession[];
50
+ if (selector.harness !== undefined) matches = matching((await corpus.sessions(selector.harness)).filter((session) => session.harness === selector.harness));
51
+ else {
52
+ matches = matching((await corpus.sessions(corpus.currentHarness)).filter((session) => session.harness === corpus.currentHarness));
53
+ if (matches.length === 0) matches = matching((await corpus.sessions()).filter((session) => session.harness !== corpus.currentHarness));
54
+ }
55
+ if (matches.length === 0) return failure("unknown_session", `No local session matches ${JSON.stringify(selector.harness ? `${selector.harness}:${selector.id}` : selector.id)}.`);
56
+ if (matches.length > 1) 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.`);
57
+ return success(matches[0]!);
58
+ }
59
+
60
+ export async function loadHistorySession(session: HistorySession): Promise<Outcome<HistorySessionData>> {
61
+ try { return success(await session.load()); }
62
+ catch (error) {
63
+ return failure("history_unavailable", `Cannot read session ${sessionIdentity(session)}: ${error instanceof Error ? error.message : String(error)}`);
64
+ }
65
+ }
66
+
67
+ export function currentHistory(context: HistoryContext): HistoryProjection | Promise<HistoryProjection> {
68
+ return "current" in context ? context.current() : context;
69
+ }
@@ -45,8 +45,8 @@ export type HistoryWindow = { windowId: string; createdAt?: string; items: Histo
45
45
 
46
46
  /** Paired result seqs stay on the branch but redirect readers to the call's event. */
47
47
  export type HistoryProjection = { windows: HistoryWindow[]; highestSeq: number; branchSeqs: Set<number>; pairedResults: Map<number, number> };
48
- /** The filters one selection applies before paging: as-given window and roles, seq bounds, and parsed epoch-ms time bounds. */
49
- export type HistoryFilter = { window_id?: string | null; roles?: HistoryRole[] | null; after_seq?: number; before_seq?: number; sinceMs?: number; untilMs?: number };
48
+ /** The filters one selection applies before paging: roles, seq bounds, and parsed epoch-ms time bounds. */
49
+ export type HistoryFilter = { roles?: HistoryRole[] | null; after_seq?: number; before_seq?: number; sinceMs?: number; untilMs?: number };
50
50
 
51
51
  /** Native entries after the adapter allocates seqs and selects the active branch. */
52
52
  export type DecodedHistoryItem = {
@@ -209,8 +209,8 @@ export function nestedCallSummary(event: HistoryEvent): { nested_calls?: Static<
209
209
 
210
210
  /** Stable identity and a verbatim preview, starting at the search match when present. */
211
211
  export const HistoryPageItemSchema = Type.Object({
212
+ session: Type.Optional(Type.String()),
212
213
  seq: Type.Integer({ minimum: 1 }),
213
- window_id: Type.String(),
214
214
  role: HistoryRoleSchema,
215
215
  created_at: Type.Union([Type.String(), Type.Null()]),
216
216
  ...ToolSummarySchema.properties,
@@ -222,6 +222,7 @@ export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
222
222
 
223
223
  /** A run of tool/context events the conversation view replaces with counts. */
224
224
  export const HistoryFoldedRowSchema = Type.Object({
225
+ session: Type.Optional(Type.String()),
225
226
  folded: Type.Literal(true),
226
227
  first_seq: Type.Integer({ minimum: 1 }),
227
228
  last_seq: Type.Integer({ minimum: 1 }),
@@ -246,7 +247,6 @@ export function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?:
246
247
  const truncated = start > 0 || start + limit < chars.length;
247
248
  return {
248
249
  seq: event.seq,
249
- window_id: event.windowId,
250
250
  role: event.role,
251
251
  created_at: event.createdAt ?? null,
252
252
  ...toolSummary(event),
@@ -260,19 +260,12 @@ export function allItems(projection: HistoryProjection): HistoryEvent[] {
260
260
  return projection.windows.flatMap((current) => current.items);
261
261
  }
262
262
 
263
- export function unknownWindowId(projection: HistoryProjection, params: HistoryFilter): { message: string; known: string[] } | undefined {
264
- if (typeof params.window_id !== "string") return undefined;
265
- const known = projection.windows.map((current) => current.windowId);
266
- return known.includes(params.window_id) ? undefined : { message: `No window "${params.window_id}" in this session`, known };
267
- }
268
-
269
263
  /**
270
- * Whether one event is inside the selection: its window, its seq bounds, and a half-open
264
+ * Whether one event is inside the selection: its seq bounds, and a half-open
271
265
  * [sinceMs, untilMs) window on created_at. A bounded time window drops events with no recorded
272
266
  * time or a time that cannot be read.
273
267
  */
274
268
  export function inSelection(event: HistoryEvent, params: HistoryFilter): boolean {
275
- if (typeof params.window_id === "string" && params.window_id !== event.windowId) return false;
276
269
  if (params.after_seq !== undefined && event.seq <= params.after_seq) return false;
277
270
  if (params.before_seq !== undefined && event.seq >= params.before_seq) return false;
278
271
  if (params.sinceMs === undefined && params.untilMs === undefined) return true;
@@ -0,0 +1,93 @@
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, type HistoryCorpus, type HistoryHarness, type HistorySession, type HistorySessionData } from "./corpus.js";
9
+
10
+ export type LocalHistoryRoots = Partial<Record<"pi" | "claude" | "codex", string | null>>;
11
+ export type LocalHistoryOptions = {
12
+ current: { harness: HistoryHarness; id: string; load(): Promise<HistorySessionData> };
13
+ /** Undefined uses the harness default; null disables that harness's filesystem discovery. */
14
+ roots?: LocalHistoryRoots;
15
+ home?: string;
16
+ env?: NodeJS.ProcessEnv;
17
+ /** Available only inside DSH; descriptors load through ctx.sessionQuery.readSession. */
18
+ dshSessions?: () => Promise<HistorySession[]>;
19
+ };
20
+
21
+ function rootsFor(options: LocalHistoryOptions): LocalHistoryRoots {
22
+ const env = options.env ?? process.env;
23
+ const home = options.home ?? env.HOME ?? homedir();
24
+ return {
25
+ pi: options.roots?.pi !== undefined ? options.roots.pi : env.NOTESOUP_HISTORY_PI_ROOT ?? join(env.PI_CODING_AGENT_DIR ?? join(home, ".pi", "agent"), "sessions"),
26
+ claude: options.roots?.claude !== undefined ? options.roots.claude : env.NOTESOUP_HISTORY_CLAUDE_ROOT ?? join(env.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "projects"),
27
+ codex: options.roots?.codex !== undefined ? options.roots.codex : env.NOTESOUP_HISTORY_CODEX_ROOT ?? join(env.CODEX_HOME ?? join(home, ".codex"), "sessions"),
28
+ };
29
+ }
30
+
31
+ /** Match the native layouts, without following symlinks or wandering into subagent/attachment stores. */
32
+ async function filesAt(root: string, depth: number): Promise<string[]> {
33
+ let entries;
34
+ try { entries = await readdir(root, { withFileTypes: true }); }
35
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
36
+ const paths: string[] = [];
37
+ for (const entry of entries) {
38
+ const path = join(root, entry.name);
39
+ if (entry.isDirectory() && depth > 0) paths.push(...await filesAt(path, depth - 1));
40
+ else if (entry.isFile() && depth === 0) paths.push(path);
41
+ }
42
+ return paths;
43
+ }
44
+
45
+ async function localSessions(harness: "pi" | "claude" | "codex", root: string): Promise<HistorySession[]> {
46
+ const paths = await filesAt(root, harness === "codex" ? 3 : 1);
47
+ const sessions: HistorySession[] = [];
48
+ for (const path of paths) {
49
+ const name = path.split(/[\\/]/).at(-1)!;
50
+ const id = harness === "pi" ? /^.+_(.+)\.jsonl$/.exec(name)?.[1]
51
+ : harness === "claude" ? /^(.+)\.jsonl$/.exec(name)?.[1]
52
+ : /^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];
53
+ if (!id) continue;
54
+ let modifiedAt: number;
55
+ try { modifiedAt = (await stat(path)).mtimeMs; }
56
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
57
+ sessions.push({
58
+ harness, id, modifiedAt,
59
+ async load() {
60
+ if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
61
+ const text = await readFile(path, "utf8");
62
+ if (harness === "pi") return { projection: piHistoryFromJsonl(text, id) };
63
+ const projection = claudeHistoryFromJsonl(text, { sessionId: id, headUuid: offlineClaudeHead(text) });
64
+ const missing = projection.missingAncestors;
65
+ 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` }) };
66
+ },
67
+ });
68
+ }
69
+ return sessions;
70
+ }
71
+
72
+ /** Fresh discovery per call; a live binding wins over its persisted descriptor. No transcript writes. */
73
+ export function localHistoryCorpus(options: LocalHistoryOptions): HistoryCorpus {
74
+ return {
75
+ currentHarness: options.current.harness,
76
+ async sessions(onlyHarness) {
77
+ const roots = rootsFor(options);
78
+ const discovered: HistorySession[] = [];
79
+ for (const harness of ["pi", "claude", "codex"] as const) {
80
+ if (onlyHarness !== undefined && onlyHarness !== harness) continue;
81
+ const root = roots[harness];
82
+ if (root != null) discovered.push(...await localSessions(harness, root));
83
+ }
84
+ if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
85
+ discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
86
+ const unique = new Map<string, HistorySession>();
87
+ for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
88
+ const current = { ...options.current, modifiedAt: Date.now() };
89
+ if (onlyHarness === undefined || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
90
+ return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
91
+ },
92
+ };
93
+ }
@@ -0,0 +1,199 @@
1
+ /** Pi's persisted entry/message wire format, independent of the Pi SDK. */
2
+ import { contentText, projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection, type RecordedNestedCalls, type ToolCallStatus } from "./history.js";
3
+
4
+ type ToolCall = { type: "toolCall"; id: string; name: string; arguments: Record<string, unknown> };
5
+ /** Structural views also accept native SDK values without converting or allocating seqs twice. */
6
+ type Message = {
7
+ role: string; content?: unknown; output?: string; summary?: string; command?: string;
8
+ cancelled?: boolean; exitCode?: number; truncated?: boolean; fullOutputPath?: string;
9
+ toolName?: string; toolCallId?: string; isError?: boolean; nestedCalls?: RecordedNestedCalls;
10
+ };
11
+ export type PiHistoryEntry = {
12
+ type: string; id: string; parentId?: string | null; timestamp?: string;
13
+ message?: Message; summary?: string; customType?: string; data?: unknown; content?: unknown;
14
+ };
15
+
16
+ function mapRole(role: string): DecodedHistoryItem["role"] | undefined {
17
+ if (role === "user" || role === "assistant") return role;
18
+ if (role === "toolResult" || role === "bashExecution") return "tool";
19
+ if (role === "custom") return "developer";
20
+ if (role === "compactionSummary" || role === "branchSummary") return "system";
21
+ return undefined;
22
+ }
23
+
24
+ function isToolCall(part: unknown): part is ToolCall {
25
+ return typeof part === "object" && part !== null && (part as { type?: unknown }).type === "toolCall";
26
+ }
27
+
28
+ /** Seq allocation depends on entry kind and role, never on visible content. */
29
+ export function piSequenceCount(entry: Pick<PiHistoryEntry, "type" | "message">): number {
30
+ if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message") return 1;
31
+ if (entry.type !== "message" || !entry.message || mapRole(entry.message.role) === undefined) return 0;
32
+ if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content)) return 1;
33
+ return 1 + entry.message.content.filter(isToolCall).length;
34
+ }
35
+
36
+ function messageContent(message: Message): string {
37
+ switch (message.role) {
38
+ case "bashExecution":
39
+ return message.output ?? "";
40
+ case "branchSummary":
41
+ case "compactionSummary":
42
+ return message.summary ?? "";
43
+ default:
44
+ return contentText(message.content);
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Pass the host's nested-call record through as recorded. It is evidence about calls this run made,
50
+ * not a second transcript: the host stores no nested results, and this lane invents none.
51
+ */
52
+ function nestedCallsOf(message: Message): RecordedNestedCalls | undefined {
53
+ if (message.role !== "toolResult" || message.nestedCalls === undefined) return undefined;
54
+ return { calls: message.nestedCalls.calls, complete: message.nestedCalls.complete };
55
+ }
56
+
57
+ function toolInfo(message: Message): Pick<DecodedHistoryItem, "toolName" | "arguments" | "outputTruncated" | "fullOutputPath" | "toolError" | "toolCallId" | "nestedCalls" | "recordedStatus"> {
58
+ if (message.role === "bashExecution") {
59
+ // A standalone bash run records its own outcome, so its status is read here rather than
60
+ // inferred from a result message that will never arrive: a cancelled or nonzero run is an
61
+ // error, and a run with no recorded exit code stays unknown instead of being called ok.
62
+ const status: ToolCallStatus = message.cancelled === true ? "error" : typeof message.exitCode === "number" ? (message.exitCode === 0 ? "ok" : "error") : "unfinished";
63
+ // A truncated run is only half the record without the on-disk path: surface both.
64
+ return { toolName: "bash", arguments: { command: message.command }, recordedStatus: status, outputTruncated: message.truncated || undefined, fullOutputPath: message.truncated ? message.fullOutputPath : undefined };
65
+ }
66
+ if (message.role !== "toolResult") return {};
67
+ const nestedCalls = nestedCallsOf(message);
68
+ return {
69
+ toolName: message.toolName,
70
+ toolCallId: message.toolCallId,
71
+ toolError: message.isError === true ? true : undefined,
72
+ ...(nestedCalls ? { nestedCalls } : {}),
73
+ };
74
+ }
75
+
76
+ function toolCallItems(windowId: string, entry: { id: string; timestamp?: string }, message: Message, entrySeq: number): DecodedHistoryItem[] {
77
+ if (message.role !== "assistant" || !Array.isArray(message.content)) return [];
78
+ const items: DecodedHistoryItem[] = [];
79
+ let callIndex = 0;
80
+ for (const part of message.content) {
81
+ if (!isToolCall(part)) continue;
82
+ items.push({
83
+ seq: entrySeq + callIndex + 1,
84
+ windowId,
85
+ role: "tool_call",
86
+ text: "",
87
+ createdAt: entry.timestamp,
88
+ toolName: part.name,
89
+ toolCallId: part.id,
90
+ arguments: part.arguments,
91
+ });
92
+ callIndex += 1;
93
+ }
94
+ return items;
95
+ }
96
+
97
+ /** Build stable internal addresses, then project the active branch into public events. */
98
+ export function piHistoryFromEntries(sessionId: string, entries: readonly PiHistoryEntry[], branch: readonly PiHistoryEntry[]): HistoryProjection {
99
+ const seqByEntryId = new Map<string, number>();
100
+ let nextSeq = 1;
101
+ for (const entry of entries) {
102
+ const count = piSequenceCount(entry);
103
+ if (count === 0) continue;
104
+ seqByEntryId.set(entry.id, nextSeq);
105
+ nextSeq += count;
106
+ }
107
+ const highestSeq = nextSeq - 1;
108
+
109
+ let window: DecodedHistoryWindow = { windowId: `pcw:${sessionId.slice(0, 8)}:root`, items: [] };
110
+ const rawWindows = [window];
111
+ const branchSeqs = new Set<number>();
112
+
113
+ for (const entry of branch) {
114
+ 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) {
115
+ window = { windowId: entry.data.windowId, createdAt: entry.timestamp, items: [] };
116
+ rawWindows.push(window);
117
+ continue;
118
+ }
119
+ const entrySeq = seqByEntryId.get(entry.id);
120
+ if (entrySeq === undefined) continue;
121
+ branchSeqs.add(entrySeq);
122
+
123
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
124
+ window.items.push({ seq: entrySeq, windowId: window.windowId, role: "system", text: entry.summary ?? "", createdAt: entry.timestamp });
125
+ continue;
126
+ }
127
+ if (entry.type === "message" && entry.message) {
128
+ const role = mapRole(entry.message.role);
129
+ if (!role) continue;
130
+ window.items.push({
131
+ seq: entrySeq,
132
+ windowId: window.windowId,
133
+ role,
134
+ text: messageContent(entry.message),
135
+ createdAt: entry.timestamp,
136
+ ...toolInfo(entry.message),
137
+ });
138
+ const calls = toolCallItems(window.windowId, entry, entry.message, entrySeq);
139
+ for (const call of calls) branchSeqs.add(call.seq);
140
+ window.items.push(...calls);
141
+ continue;
142
+ }
143
+ if (entry.type === "custom_message") {
144
+ window.items.push({
145
+ seq: entrySeq,
146
+ windowId: window.windowId,
147
+ role: "developer",
148
+ text: contentText(entry.content),
149
+ createdAt: entry.timestamp,
150
+ });
151
+ }
152
+ }
153
+
154
+ return projectHistory(rawWindows, highestSeq, branchSeqs);
155
+ }
156
+
157
+ /** Offline files persist append order and parent links; select the final tree entry's ancestry. */
158
+ export function piHistoryFromJsonl(text: string, sessionId: string): HistoryProjection {
159
+ const lines = text.split("\n");
160
+ const entries: PiHistoryEntry[] = [];
161
+ let header = false;
162
+ for (let index = 0; index < lines.length; index++) {
163
+ const line = lines[index]!;
164
+ if (line.trim() === "") continue;
165
+ let row: PiHistoryEntry;
166
+ try { row = JSON.parse(line) as PiHistoryEntry; }
167
+ catch {
168
+ if (index === lines.length - 1 && !text.endsWith("\n")) break;
169
+ throw new Error(`malformed Pi transcript JSON at line ${index + 1}`);
170
+ }
171
+ if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string") throw new Error("invalid Pi transcript entry");
172
+ if (!header) {
173
+ if (row.type !== "session" || row.id !== sessionId) throw new Error("Pi transcript belongs to a different session or has no header");
174
+ header = true;
175
+ continue;
176
+ }
177
+ if (row.parentId !== null && typeof row.parentId !== "string") throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
178
+ if (row.type === "message" && (!row.message || typeof row.message.role !== "string")) throw new Error("invalid Pi transcript message");
179
+ entries.push(row);
180
+ }
181
+ if (!header) throw new Error("Pi transcript has no session header");
182
+ const byId = new Map<string, PiHistoryEntry>();
183
+ for (const entry of entries) {
184
+ if (byId.has(entry.id)) throw new Error(`duplicate Pi entry ID: ${entry.id}`);
185
+ byId.set(entry.id, entry);
186
+ }
187
+ const branch: PiHistoryEntry[] = [], seen = new Set<string>();
188
+ let cursor = entries.at(-1);
189
+ while (cursor) {
190
+ if (seen.has(cursor.id)) throw new Error("cyclic Pi transcript ancestry");
191
+ seen.add(cursor.id);
192
+ branch.push(cursor);
193
+ if (cursor.parentId === null) break;
194
+ const parent = byId.get(cursor.parentId!);
195
+ if (!parent) throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
196
+ cursor = parent;
197
+ }
198
+ return piHistoryFromEntries(sessionId, entries, branch.reverse());
199
+ }