agent-sh 0.14.8 → 0.14.9

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 (49) hide show
  1. package/dist/agent/agent-loop.d.ts +0 -4
  2. package/dist/agent/agent-loop.js +8 -166
  3. package/dist/agent/entry-format.d.ts +5 -0
  4. package/dist/agent/entry-format.js +9 -0
  5. package/dist/agent/extensions/rolling-history/constants.d.ts +1 -0
  6. package/dist/agent/extensions/rolling-history/constants.js +1 -0
  7. package/dist/agent/extensions/rolling-history/index.d.ts +4 -0
  8. package/dist/agent/extensions/rolling-history/index.js +203 -0
  9. package/dist/agent/extensions/rolling-history/recall.d.ts +4 -0
  10. package/dist/agent/extensions/rolling-history/recall.js +122 -0
  11. package/dist/agent/extensions/rolling-history/strategy.d.ts +70 -0
  12. package/dist/agent/extensions/rolling-history/strategy.js +336 -0
  13. package/dist/agent/host-types.d.ts +0 -3
  14. package/dist/agent/index.js +44 -5
  15. package/dist/agent/live-view.d.ts +57 -0
  16. package/dist/agent/live-view.js +238 -0
  17. package/dist/agent/llm-client.d.ts +1 -0
  18. package/dist/agent/llm-client.js +1 -1
  19. package/dist/agent/session-store.d.ts +90 -0
  20. package/dist/agent/session-store.js +288 -0
  21. package/dist/agent/store.d.ts +74 -0
  22. package/dist/agent/store.js +284 -0
  23. package/dist/agent/subagent.js +2 -2
  24. package/dist/agent/tool-protocol.d.ts +11 -11
  25. package/dist/cli/index.js +4 -2
  26. package/dist/core/index.d.ts +0 -1
  27. package/dist/core/index.js +0 -1
  28. package/dist/core/settings.d.ts +5 -1
  29. package/dist/core/settings.js +62 -1
  30. package/dist/extensions/index.d.ts +1 -0
  31. package/dist/shell/events.d.ts +1 -0
  32. package/dist/shell/input-handler.js +4 -0
  33. package/dist/shell/tui-renderer.js +5 -2
  34. package/dist/utils/diff-renderer.js +9 -7
  35. package/examples/extensions/ash-acp-bridge/src/index.ts +1 -2
  36. package/examples/extensions/ashi/package.json +2 -2
  37. package/examples/extensions/ashi/src/capture.ts +1 -1
  38. package/examples/extensions/ashi/src/cli.ts +3 -4
  39. package/examples/extensions/ashi/src/compaction.ts +6 -2
  40. package/examples/extensions/ashi/src/frontend.ts +13 -13
  41. package/examples/extensions/ashi/src/multi-session-store.ts +35 -12
  42. package/examples/extensions/ashi/src/session-commands.ts +1 -1
  43. package/examples/extensions/ashi/src/user-shell-intents.ts +17 -0
  44. package/package.json +13 -1
  45. package/dist/agent/conversation-state.d.ts +0 -142
  46. package/dist/agent/conversation-state.js +0 -788
  47. package/dist/agent/history-file.d.ts +0 -81
  48. package/dist/agent/history-file.js +0 -271
  49. package/examples/extensions/ashi/src/session-store.ts +0 -363
@@ -0,0 +1,238 @@
1
+ import { stripMeta } from "./llm-client.js";
2
+ export class LiveView {
3
+ messages = [];
4
+ messagesDirty = true;
5
+ cachedMessagesJson = null;
6
+ instanceId;
7
+ handlers;
8
+ lastApiTokenCount = null;
9
+ lastApiMessageCount = 0;
10
+ // Mid-tool-pair user/system messages are buffered and flushed after
11
+ // the trailing tool_result — splicing into the gap breaks
12
+ // reasoning_content pairing on strict providers.
13
+ pendingMessages = [];
14
+ constructor(handlers, instanceId = "0000") {
15
+ this.handlers = handlers ?? null;
16
+ this.instanceId = instanceId;
17
+ }
18
+ getMessagesJson() {
19
+ if (this.messagesDirty || this.cachedMessagesJson === null) {
20
+ this.cachedMessagesJson = JSON.stringify(this.messages);
21
+ this.messagesDirty = false;
22
+ }
23
+ return this.cachedMessagesJson;
24
+ }
25
+ invalidateMessagesCache() {
26
+ this.messagesDirty = true;
27
+ this.cachedMessagesJson = null;
28
+ }
29
+ addUserMessage(text) {
30
+ this.messages.push({ role: "user", content: text });
31
+ this.invalidateMessagesCache();
32
+ }
33
+ addAssistantMessage(content, toolCalls, extras) {
34
+ const hasToolCalls = !!toolCalls?.length;
35
+ // Promote reasoning into content on reasoning-only turns; strict
36
+ // providers (DeepSeek native) reject content="" with no tool_calls.
37
+ if (!content && !hasToolCalls) {
38
+ const r = (extras?.reasoning_content ?? extras?.reasoning);
39
+ if (typeof r === "string" && r)
40
+ content = r;
41
+ }
42
+ if (!content && !hasToolCalls)
43
+ return;
44
+ const base = {
45
+ role: "assistant",
46
+ content: hasToolCalls ? (content ?? null) : content,
47
+ };
48
+ if (hasToolCalls) {
49
+ base.tool_calls = toolCalls.map((tc) => ({
50
+ id: tc.id,
51
+ type: "function",
52
+ function: tc.function,
53
+ }));
54
+ }
55
+ if (extras)
56
+ Object.assign(base, extras);
57
+ this.messages.push(base);
58
+ this.invalidateMessagesCache();
59
+ }
60
+ addToolResult(toolCallId, content, isError = false) {
61
+ if (typeof content === "string") {
62
+ this.messages.push({ role: "tool", tool_call_id: toolCallId, content });
63
+ }
64
+ else {
65
+ const parts = [];
66
+ for (const img of content) {
67
+ parts.push({ type: "image_url", image_url: { url: `data:${img.mimeType};base64,${img.data}` } });
68
+ }
69
+ const label = isError ? `Error: [${content.length} image(s)]` : `[${content.length} image(s)]`;
70
+ parts.unshift({ type: "text", text: label });
71
+ this.messages.push({ role: "tool", tool_call_id: toolCallId, content: parts });
72
+ }
73
+ this.invalidateMessagesCache();
74
+ this.flushPendingMessages();
75
+ }
76
+ addToolResultInline(content) {
77
+ this.messages.push({ role: "user", content });
78
+ this.invalidateMessagesCache();
79
+ this.flushPendingMessages();
80
+ }
81
+ /** Safe from any context: queues if mid-tool-pair, appends otherwise. */
82
+ addSystemNote(text) {
83
+ if (this.hasOpenToolCalls()) {
84
+ this.pendingMessages.push({ kind: "system", text });
85
+ return;
86
+ }
87
+ this.messages.push({ role: "user", content: text });
88
+ this.invalidateMessagesCache();
89
+ }
90
+ appendUserMessage(text) {
91
+ if (this.hasOpenToolCalls()) {
92
+ this.pendingMessages.push({ kind: "user", text });
93
+ return;
94
+ }
95
+ this.addUserMessage(text);
96
+ }
97
+ hasOpenToolCalls() {
98
+ for (let i = this.messages.length - 1; i >= 0; i--) {
99
+ const msg = this.messages[i];
100
+ if (msg.role === "tool")
101
+ continue;
102
+ if (msg.role !== "assistant")
103
+ return false;
104
+ if (!("tool_calls" in msg) || !msg.tool_calls)
105
+ return false;
106
+ const answered = new Set();
107
+ for (let j = i + 1; j < this.messages.length; j++) {
108
+ const m = this.messages[j];
109
+ if (m.role !== "tool")
110
+ break;
111
+ answered.add(m.tool_call_id);
112
+ }
113
+ return msg.tool_calls.some((tc) => !answered.has(tc.id));
114
+ }
115
+ return false;
116
+ }
117
+ flushPendingMessages() {
118
+ if (this.pendingMessages.length === 0)
119
+ return;
120
+ if (this.hasOpenToolCalls())
121
+ return;
122
+ const pending = this.pendingMessages;
123
+ this.pendingMessages = [];
124
+ for (const m of pending) {
125
+ if (m.kind === "user") {
126
+ this.addUserMessage(m.text);
127
+ }
128
+ else {
129
+ this.messages.push({ role: "user", content: m.text });
130
+ }
131
+ }
132
+ this.invalidateMessagesCache();
133
+ }
134
+ getMessages() {
135
+ return this.normalizeReasoningConsistency(this.stubDanglingToolCalls(this.dropOrphanToolMessages(this.messages)));
136
+ }
137
+ get() {
138
+ return this.messages;
139
+ }
140
+ forLLM() {
141
+ return this.getMessages().map(stripMeta);
142
+ }
143
+ replace(msgs) {
144
+ this.replaceMessages(msgs);
145
+ }
146
+ link(index, entryId) {
147
+ const m = this.messages[index];
148
+ if (!m)
149
+ throw new Error(`LiveView.link: no message at index ${index}`);
150
+ const am = m;
151
+ am.meta = { ...am.meta, entryId };
152
+ }
153
+ /** DeepSeek 400s on tool messages without a matching tool_call;
154
+ * compaction can leave such orphans. */
155
+ dropOrphanToolMessages(messages) {
156
+ const knownIds = new Set();
157
+ const result = [];
158
+ for (const msg of messages) {
159
+ if (msg.role === "assistant" && "tool_calls" in msg && msg.tool_calls) {
160
+ for (const tc of msg.tool_calls)
161
+ knownIds.add(tc.id);
162
+ }
163
+ if (msg.role === "tool" && !knownIds.has(msg.tool_call_id)) {
164
+ continue;
165
+ }
166
+ result.push(msg);
167
+ }
168
+ return result;
169
+ }
170
+ /** Stub missing tool results after a mid-execution interrupt so
171
+ * DeepSeek doesn't 400 on dangling tool_calls. */
172
+ stubDanglingToolCalls(messages) {
173
+ const result = [];
174
+ let i = 0;
175
+ while (i < messages.length) {
176
+ const msg = messages[i];
177
+ result.push(msg);
178
+ i++;
179
+ if (msg.role !== "assistant" || !("tool_calls" in msg) || !msg.tool_calls)
180
+ continue;
181
+ const seen = new Set();
182
+ while (i < messages.length && messages[i].role === "tool") {
183
+ const t = messages[i];
184
+ seen.add(t.tool_call_id);
185
+ result.push(t);
186
+ i++;
187
+ }
188
+ for (const tc of msg.tool_calls) {
189
+ if (!seen.has(tc.id)) {
190
+ result.push({ role: "tool", tool_call_id: tc.id, content: "[cancelled]" });
191
+ }
192
+ }
193
+ }
194
+ return result;
195
+ }
196
+ /** DeepSeek 400s if any assistant in a thinking-mode conversation
197
+ * is missing `reasoning_content`. Cross-alias `reasoning` (from
198
+ * OpenRouter) and stub gaps with "". */
199
+ normalizeReasoningConsistency(messages) {
200
+ const needsNormalize = messages.some((m) => m.role === "assistant" && (m.reasoning !== undefined ||
201
+ m.reasoning_content !== undefined ||
202
+ m.reasoning_details !== undefined));
203
+ if (!needsNormalize)
204
+ return messages;
205
+ return messages.map((m) => {
206
+ if (m.role !== "assistant")
207
+ return m;
208
+ const a = m;
209
+ if (a.reasoning_content !== undefined)
210
+ return m;
211
+ return { ...m, reasoning_content: a.reasoning ?? "" };
212
+ });
213
+ }
214
+ /** Invalidates the API token baseline since the new array's count is unknown. */
215
+ replaceMessages(messages) {
216
+ this.messages = messages;
217
+ this.invalidateMessagesCache();
218
+ this.lastApiTokenCount = null;
219
+ this.lastApiMessageCount = 0;
220
+ this.flushPendingMessages();
221
+ }
222
+ updateApiTokenCount(promptTokens) {
223
+ this.lastApiTokenCount = promptTokens;
224
+ this.lastApiMessageCount = this.messages.length;
225
+ }
226
+ estimatePromptTokens() {
227
+ if (this.lastApiTokenCount === null)
228
+ return this.estimateTokens();
229
+ const trailing = this.messages.length - this.lastApiMessageCount;
230
+ if (trailing <= 0)
231
+ return this.lastApiTokenCount;
232
+ const trailingMessages = this.messages.slice(this.lastApiMessageCount);
233
+ return this.lastApiTokenCount + Math.ceil(JSON.stringify(trailingMessages).length / 4);
234
+ }
235
+ estimateTokens() {
236
+ return Math.ceil(this.getMessagesJson().length / 4);
237
+ }
238
+ }
@@ -11,6 +11,7 @@ export type { ChatCompletionMessageParam, ChatCompletionTool };
11
11
  export type AgentShMessage = ChatCompletionMessageParam & {
12
12
  meta?: Record<string, unknown>;
13
13
  };
14
+ export declare function stripMeta(m: ChatCompletionMessageParam): ChatCompletionMessageParam;
14
15
  export interface LlmClientConfig {
15
16
  apiKey: string;
16
17
  baseURL?: string;
@@ -6,7 +6,7 @@
6
6
  * (command suggestions, completions).
7
7
  */
8
8
  import OpenAI from "openai";
9
- function stripMeta(m) {
9
+ export function stripMeta(m) {
10
10
  if (!("meta" in m))
11
11
  return m;
12
12
  const { meta: _meta, ...rest } = m;
@@ -0,0 +1,90 @@
1
+ import type { AgentShMessage } from "./llm-client.js";
2
+ export type { AgentShMessage } from "./llm-client.js";
3
+ export interface SessionHeaderEntry {
4
+ type: "session";
5
+ id: string;
6
+ parentId: null;
7
+ timestamp: number;
8
+ cwd: string;
9
+ version: 1;
10
+ }
11
+ export interface MessageEntry {
12
+ type: "message";
13
+ id: string;
14
+ parentId: string;
15
+ timestamp: number;
16
+ message: AgentShMessage;
17
+ }
18
+ export interface CompactionEntry {
19
+ type: "compaction";
20
+ id: string;
21
+ parentId: string;
22
+ timestamp: number;
23
+ firstKeptId: string;
24
+ tokensBefore: number;
25
+ summary?: string;
26
+ }
27
+ /** Omitted from buildMessages — the agent already saw it via <shell_events>. */
28
+ export interface ShellExchangeEntry {
29
+ type: "shell-exchange";
30
+ id: string;
31
+ parentId: string;
32
+ timestamp: number;
33
+ command: string;
34
+ output: string;
35
+ exitCode: number | null;
36
+ cwd?: string;
37
+ private?: boolean;
38
+ }
39
+ export type SessionEntry = SessionHeaderEntry | MessageEntry | CompactionEntry | ShellExchangeEntry;
40
+ export declare function newEntryId(): string;
41
+ export declare function summarizeMessage(m: AgentShMessage): string;
42
+ /** For displayed user text. Loops because both wrappers can stack at the head. */
43
+ export declare function stripContextWrappers(content: string): string;
44
+ export declare function renderEvictedSummary(evicted: AgentShMessage[]): string;
45
+ export declare class SessionStore {
46
+ private entriesPath;
47
+ private leafPath;
48
+ private entries;
49
+ private rootId;
50
+ private activeLeaf;
51
+ private pendingHeader;
52
+ readonly id: string;
53
+ constructor(filePath: string, opts?: {
54
+ create?: {
55
+ cwd: string;
56
+ sessionId: string;
57
+ };
58
+ });
59
+ /** Deferred so an opened-but-unused session leaves no files on disk. */
60
+ private flushHeader;
61
+ getActiveLeaf(): string;
62
+ setActiveLeaf(id: string): void;
63
+ getRootId(): string;
64
+ getEntry(id: string): SessionEntry | undefined;
65
+ getAllEntries(): SessionEntry[];
66
+ appendMessages(messages: AgentShMessage[]): Promise<string[]>;
67
+ appendShellExchange(e: {
68
+ command: string;
69
+ output: string;
70
+ exitCode: number | null;
71
+ cwd?: string;
72
+ private?: boolean;
73
+ }): Promise<string>;
74
+ appendCompaction(firstKeptId: string, tokensBefore: number, summary?: string): Promise<string>;
75
+ /** Returns oldest-first. */
76
+ getBranch(leafId?: string): SessionEntry[];
77
+ /** Latest compaction on the branch replaces the evicted prefix with
78
+ * its stored summary, or a rendered one if no summary was stored. */
79
+ buildMessages(leafId?: string): AgentShMessage[];
80
+ /** Parallel entryIds array — null for the synthetic compaction-summary
81
+ * slot — so callers can map message indices back to on-disk ids. */
82
+ buildBranchWithIds(leafId?: string): {
83
+ messages: AgentShMessage[];
84
+ entryIds: (string | null)[];
85
+ };
86
+ getPreview(): string;
87
+ private load;
88
+ private lastEntryId;
89
+ private persistLeaf;
90
+ }
@@ -0,0 +1,288 @@
1
+ import * as fs from "node:fs";
2
+ import * as fsp from "node:fs/promises";
3
+ import * as path from "node:path";
4
+ import * as crypto from "node:crypto";
5
+ export function newEntryId() {
6
+ return crypto.randomBytes(4).toString("hex");
7
+ }
8
+ function extractText(content) {
9
+ if (typeof content === "string")
10
+ return content;
11
+ if (Array.isArray(content)) {
12
+ return content.map((p) => {
13
+ if (typeof p === "string")
14
+ return p;
15
+ const part = p;
16
+ return part?.text ?? part?.content ?? "";
17
+ }).join(" ");
18
+ }
19
+ return "";
20
+ }
21
+ function snippet(text, max) {
22
+ const cleaned = String(text ?? "").replace(/\s+/g, " ").trim();
23
+ if (cleaned.length <= max)
24
+ return cleaned || "(empty)";
25
+ return cleaned.slice(0, max) + "…";
26
+ }
27
+ export function summarizeMessage(m) {
28
+ const role = m.role ?? "?";
29
+ if (role === "assistant") {
30
+ const tc = m.tool_calls;
31
+ if (Array.isArray(tc) && tc.length > 0) {
32
+ const tools = tc.map((t) => {
33
+ const name = t.function?.name ?? "tool";
34
+ const args = t.function?.arguments;
35
+ return args ? `${name}(${snippet(args, 200)})` : name;
36
+ }).join(", ");
37
+ const text = extractText(m.content);
38
+ const prefix = text ? `${snippet(text, 400)} → ` : "";
39
+ return `assistant: ${prefix}called ${tools}`;
40
+ }
41
+ }
42
+ if (role === "tool") {
43
+ const text = typeof m.content === "string" ? m.content : extractText(m.content);
44
+ const isErr = /^error\b|: error\b/i.test(text.slice(0, 200));
45
+ return `tool result: ${snippet(text, isErr ? 1000 : 400)}`;
46
+ }
47
+ if (role === "user") {
48
+ return `user: ${snippet(extractText(m.content), 1000)}`;
49
+ }
50
+ return `${role}: ${snippet(extractText(m.content), 500)}`;
51
+ }
52
+ /** For displayed user text. Loops because both wrappers can stack at the head. */
53
+ export function stripContextWrappers(content) {
54
+ let out = content;
55
+ for (;;) {
56
+ const next = out.replace(/^\s*<(query_context|dynamic_context)>[\s\S]*?<\/\1>\s*/, "");
57
+ if (next === out)
58
+ return out;
59
+ out = next;
60
+ }
61
+ }
62
+ export function renderEvictedSummary(evicted) {
63
+ const lines = evicted.map((m) => `- ${summarizeMessage(m)}`);
64
+ return `${lines.length} message(s) elided\n${lines.join("\n")}`;
65
+ }
66
+ export class SessionStore {
67
+ entriesPath;
68
+ leafPath;
69
+ entries = new Map();
70
+ rootId = "";
71
+ activeLeaf = "";
72
+ pendingHeader = null;
73
+ id;
74
+ constructor(filePath, opts) {
75
+ this.entriesPath = filePath;
76
+ this.leafPath = filePath + ".leaf";
77
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
78
+ if (opts?.create) {
79
+ this.id = opts.create.sessionId;
80
+ const header = {
81
+ type: "session",
82
+ id: opts.create.sessionId,
83
+ parentId: null,
84
+ timestamp: Date.now(),
85
+ cwd: opts.create.cwd,
86
+ version: 1,
87
+ };
88
+ this.entries.set(header.id, header);
89
+ this.rootId = header.id;
90
+ this.activeLeaf = header.id;
91
+ this.pendingHeader = header;
92
+ }
93
+ else {
94
+ this.id = "";
95
+ this.load();
96
+ if (!this.rootId)
97
+ throw new Error(`session file lacks a session header: ${filePath}`);
98
+ this.id = this.rootId;
99
+ }
100
+ }
101
+ /** Deferred so an opened-but-unused session leaves no files on disk. */
102
+ flushHeader() {
103
+ if (!this.pendingHeader)
104
+ return;
105
+ const headerLine = JSON.stringify(this.pendingHeader) + "\n";
106
+ this.pendingHeader = null;
107
+ fs.writeFileSync(this.entriesPath, headerLine);
108
+ this.persistLeaf();
109
+ }
110
+ getActiveLeaf() { return this.activeLeaf; }
111
+ setActiveLeaf(id) {
112
+ if (!this.entries.has(id))
113
+ throw new Error(`unknown entry: ${id}`);
114
+ this.activeLeaf = id;
115
+ this.persistLeaf();
116
+ }
117
+ getRootId() { return this.rootId; }
118
+ getEntry(id) { return this.entries.get(id); }
119
+ getAllEntries() { return [...this.entries.values()]; }
120
+ async appendMessages(messages) {
121
+ if (messages.length === 0)
122
+ return [];
123
+ this.flushHeader();
124
+ let parent = this.activeLeaf;
125
+ const lines = [];
126
+ const newIds = [];
127
+ for (const m of messages) {
128
+ const e = {
129
+ type: "message",
130
+ id: newEntryId(),
131
+ parentId: parent,
132
+ timestamp: Date.now(),
133
+ message: m,
134
+ };
135
+ this.entries.set(e.id, e);
136
+ lines.push(JSON.stringify(e));
137
+ newIds.push(e.id);
138
+ parent = e.id;
139
+ }
140
+ this.activeLeaf = parent;
141
+ await fsp.appendFile(this.entriesPath, lines.join("\n") + "\n");
142
+ this.persistLeaf();
143
+ return newIds;
144
+ }
145
+ async appendShellExchange(e) {
146
+ this.flushHeader();
147
+ const entry = {
148
+ type: "shell-exchange",
149
+ id: newEntryId(),
150
+ parentId: this.activeLeaf,
151
+ timestamp: Date.now(),
152
+ command: e.command,
153
+ output: e.output,
154
+ exitCode: e.exitCode,
155
+ ...(e.cwd !== undefined ? { cwd: e.cwd } : {}),
156
+ ...(e.private ? { private: true } : {}),
157
+ };
158
+ this.entries.set(entry.id, entry);
159
+ this.activeLeaf = entry.id;
160
+ await fsp.appendFile(this.entriesPath, JSON.stringify(entry) + "\n");
161
+ this.persistLeaf();
162
+ return entry.id;
163
+ }
164
+ async appendCompaction(firstKeptId, tokensBefore, summary) {
165
+ if (!this.entries.has(firstKeptId))
166
+ throw new Error(`firstKeptId unknown: ${firstKeptId}`);
167
+ this.flushHeader();
168
+ const e = {
169
+ type: "compaction",
170
+ id: newEntryId(),
171
+ parentId: this.activeLeaf,
172
+ timestamp: Date.now(),
173
+ firstKeptId,
174
+ tokensBefore,
175
+ ...(summary !== undefined ? { summary } : {}),
176
+ };
177
+ this.entries.set(e.id, e);
178
+ this.activeLeaf = e.id;
179
+ await fsp.appendFile(this.entriesPath, JSON.stringify(e) + "\n");
180
+ this.persistLeaf();
181
+ return e.id;
182
+ }
183
+ /** Returns oldest-first. */
184
+ getBranch(leafId = this.activeLeaf) {
185
+ const out = [];
186
+ const seen = new Set();
187
+ let cur = leafId;
188
+ while (cur && !seen.has(cur)) {
189
+ seen.add(cur);
190
+ const e = this.entries.get(cur);
191
+ if (!e)
192
+ break;
193
+ out.push(e);
194
+ cur = e.parentId;
195
+ }
196
+ return out.reverse();
197
+ }
198
+ /** Latest compaction on the branch replaces the evicted prefix with
199
+ * its stored summary, or a rendered one if no summary was stored. */
200
+ buildMessages(leafId = this.activeLeaf) {
201
+ return this.buildBranchWithIds(leafId).messages;
202
+ }
203
+ /** Parallel entryIds array — null for the synthetic compaction-summary
204
+ * slot — so callers can map message indices back to on-disk ids. */
205
+ buildBranchWithIds(leafId = this.activeLeaf) {
206
+ const branch = this.getBranch(leafId);
207
+ let compactionIdx = -1;
208
+ for (let i = branch.length - 1; i >= 0; i--) {
209
+ if (branch[i].type === "compaction") {
210
+ compactionIdx = i;
211
+ break;
212
+ }
213
+ }
214
+ const messages = [];
215
+ const entryIds = [];
216
+ let startIdx = 0;
217
+ if (compactionIdx >= 0) {
218
+ const c = branch[compactionIdx];
219
+ const firstKeptIdx = branch.findIndex((e) => e.id === c.firstKeptId);
220
+ startIdx = firstKeptIdx >= 0 ? firstKeptIdx : 0;
221
+ const summary = c.summary ?? renderEvictedSummary(branch.slice(0, startIdx)
222
+ .filter((e) => e.type === "message")
223
+ .map((e) => e.message));
224
+ messages.push({ role: "user", content: `[Compacted conversation summary]\n${summary}` });
225
+ entryIds.push(null);
226
+ }
227
+ for (let i = startIdx; i < branch.length; i++) {
228
+ const e = branch[i];
229
+ if (e.type === "message") {
230
+ messages.push(e.message);
231
+ entryIds.push(e.id);
232
+ }
233
+ }
234
+ return { messages, entryIds };
235
+ }
236
+ getPreview() {
237
+ for (const e of this.entries.values()) {
238
+ if (e.type === "message" && e.message.role === "user") {
239
+ const raw = typeof e.message.content === "string" ? e.message.content : "";
240
+ const txt = stripContextWrappers(raw);
241
+ if (txt)
242
+ return txt.slice(0, 80);
243
+ }
244
+ }
245
+ return "(empty)";
246
+ }
247
+ load() {
248
+ let raw;
249
+ try {
250
+ raw = fs.readFileSync(this.entriesPath, "utf-8");
251
+ }
252
+ catch {
253
+ return;
254
+ }
255
+ for (const line of raw.split("\n")) {
256
+ if (!line)
257
+ continue;
258
+ try {
259
+ const e = JSON.parse(line);
260
+ if (!e.id)
261
+ continue;
262
+ this.entries.set(e.id, e);
263
+ if (e.type === "session")
264
+ this.rootId = e.id;
265
+ }
266
+ catch { /* skip malformed */ }
267
+ }
268
+ try {
269
+ this.activeLeaf = fs.readFileSync(this.leafPath, "utf-8").trim();
270
+ if (!this.entries.has(this.activeLeaf))
271
+ this.activeLeaf = this.rootId;
272
+ }
273
+ catch {
274
+ this.activeLeaf = this.lastEntryId();
275
+ }
276
+ }
277
+ lastEntryId() {
278
+ let lastId = this.rootId;
279
+ for (const e of this.entries.values())
280
+ lastId = e.id;
281
+ return lastId;
282
+ }
283
+ persistLeaf() {
284
+ if (this.pendingHeader)
285
+ return;
286
+ fs.writeFileSync(this.leafPath, this.activeLeaf);
287
+ }
288
+ }