@a-t-h-i/bot-lobby 0.6.2 → 0.6.3

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.
@@ -2,10 +2,12 @@
2
2
  * Other sessions' conversations, read from their saved pi session files. A
3
3
  * task another terminal drives has no live feed in this window, so the lobby
4
4
  * shows what its session file holds: the current branch's user and assistant
5
- * messages, reread whenever the file changes.
5
+ * messages. Files are read as they grow — only the bytes appended since the
6
+ * last look — and only what the conversation needs is kept: each entry's
7
+ * parent, and the text of user and assistant messages (never tool output).
6
8
  */
7
- import { readFileSync, statSync } from "node:fs";
8
- import { chatFromEntries, MAX_CHAT, type ChatEntry } from "./feed.ts";
9
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
10
+ import { chatFromEntries, chatText, CLEARED_NOTE, isClearedMark, MAX_CHAT, textOf, type ChatEntry } from "./feed.ts";
9
11
 
10
12
  interface EntryLike {
11
13
  type?: string;
@@ -51,22 +53,151 @@ export function chatFromFile(text: string, max = MAX_CHAT): ChatEntry[] {
51
53
  return chatFromEntries(currentBranch(parseEntries(text)), max).map((line, index) => ({ id: index + 1, at: line.at ?? 0, role: line.role, text: line.text }));
52
54
  }
53
55
 
56
+ /** What a session log keeps of one entry: its parent, and its conversation lines if it is a message. */
57
+ interface LogNode {
58
+ parentId?: string;
59
+ chat?: ChatEntry[];
60
+ }
61
+
62
+ /** Bytes read at most per look, so a huge file is caught up over a few frames rather than in one. */
63
+ const READ_CHUNK = 4 * 1024 * 1024;
64
+
65
+ let logIds = 0;
66
+
67
+ /**
68
+ * One session file, followed as it grows. Its entries form a tree (pi
69
+ * branches); the conversation is the branch that ends at the newest entry.
70
+ * The newest messages are kept ready; the whole history is walked only when
71
+ * asked for.
72
+ */
73
+ export class SessionLog {
74
+ readonly path: string;
75
+ private offset = 0;
76
+ private leaf?: string;
77
+ private readonly nodes = new Map<string, LogNode>();
78
+ private recentCache?: { max: number; entries: ChatEntry[]; older: boolean };
79
+
80
+ constructor(path: string) {
81
+ this.path = path;
82
+ }
83
+
84
+ /** Read what was appended since the last look; true when the conversation may have changed. */
85
+ update(): boolean {
86
+ let size: number;
87
+ try {
88
+ size = statSync(this.path).size;
89
+ } catch {
90
+ return false;
91
+ }
92
+ if (size < this.offset) this.reset();
93
+ if (size === this.offset) return false;
94
+ let changed = false;
95
+ let fd: number | undefined;
96
+ try {
97
+ fd = openSync(this.path, "r");
98
+ while (this.offset < size) {
99
+ const length = Math.min(READ_CHUNK, size - this.offset);
100
+ const buffer = Buffer.alloc(length);
101
+ const read = readSync(fd, buffer, 0, length, this.offset);
102
+ // Only whole lines: a line still being written (or a character cut in two) waits for the next look.
103
+ const end = buffer.lastIndexOf(0x0a, read - 1);
104
+ if (end < 0) break;
105
+ for (const line of buffer.toString("utf8", 0, end).split("\n")) changed = this.add(line) || changed;
106
+ this.offset += end + 1;
107
+ if (length === READ_CHUNK) break;
108
+ }
109
+ } catch {
110
+ // Unreadable for now; the next look tries again.
111
+ } finally {
112
+ if (fd !== undefined) closeSync(fd);
113
+ }
114
+ if (changed) this.recentCache = undefined;
115
+ return changed;
116
+ }
117
+
118
+ private reset(): void {
119
+ this.offset = 0;
120
+ this.leaf = undefined;
121
+ this.nodes.clear();
122
+ this.recentCache = undefined;
123
+ }
124
+
125
+ private add(line: string): boolean {
126
+ if (!line.trim()) return false;
127
+ let entry: { type?: string; id?: unknown; parentId?: unknown; timestamp?: unknown; message?: { role?: string; content?: unknown } };
128
+ try {
129
+ entry = JSON.parse(line);
130
+ } catch {
131
+ return false;
132
+ }
133
+ if (typeof entry?.id !== "string") return false;
134
+ const node: LogNode = typeof entry.parentId === "string" ? { parentId: entry.parentId } : {};
135
+ const role = entry.message?.role;
136
+ const parsed = typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN;
137
+ const at = Number.isFinite(parsed) ? parsed : 0;
138
+ if (entry.type === "message" && (role === "user" || role === "assistant")) {
139
+ const chat = chatText(role, textOf(entry.message?.content)).map((part) => ({ id: ++logIds, at, role: part.role, text: part.text }));
140
+ if (chat.length > 0) node.chat = chat;
141
+ } else if (isClearedMark(entry)) {
142
+ node.chat = [{ id: ++logIds, at, role: "note", text: CLEARED_NOTE }];
143
+ }
144
+ this.nodes.set(entry.id, node);
145
+ this.leaf = entry.id;
146
+ return true;
147
+ }
148
+
149
+ /** The conversation's messages from the newest back, visiting at most `max`; whether any are left before them. */
150
+ private walk(max: number): { entries: ChatEntry[]; older: boolean } {
151
+ const parts: ChatEntry[][] = [];
152
+ let count = 0;
153
+ let older = false;
154
+ const seen = new Set<string>();
155
+ for (let id = this.leaf; id && !seen.has(id); id = this.nodes.get(id)?.parentId) {
156
+ seen.add(id);
157
+ const chat = this.nodes.get(id)?.chat;
158
+ if (!chat) continue;
159
+ if (count >= max) {
160
+ older = true;
161
+ break;
162
+ }
163
+ parts.push(chat);
164
+ count += chat.length;
165
+ }
166
+ const entries = parts.reverse().flat();
167
+ return { entries: entries.length > max ? entries.slice(-max) : entries, older: older || entries.length > max };
168
+ }
169
+
170
+ /** The newest `max` messages (kept until the file changes), and whether earlier ones exist. */
171
+ recent(max = MAX_CHAT): { entries: ChatEntry[]; older: boolean } {
172
+ if (this.recentCache?.max !== max) this.recentCache = { max, ...this.walk(max) };
173
+ return this.recentCache;
174
+ }
175
+
176
+ /** Every message of the conversation, oldest first (for scrolling back through it). */
177
+ history(): ChatEntry[] {
178
+ return this.walk(Number.POSITIVE_INFINITY).entries;
179
+ }
180
+ }
181
+
54
182
  /** How the cache finds session files: pi's session list, id → path. */
55
183
  export type SessionLister = () => Promise<ReadonlyArray<{ id: string; path: string }>>;
56
184
 
57
185
  /** How often the id → path map is refreshed while someone looks. */
58
186
  export const LIST_REFRESH_MS = 5000;
59
187
 
188
+ /** Session files followed at once; the least recently looked at is let go past this. */
189
+ export const MAX_LOGS = 8;
190
+
60
191
  /**
61
- * Chats of sessions by id, cached per file and reread only when its size or
62
- * mtime changes. Finding a file is async (pi lists sessions from disk), so the
192
+ * Chats of sessions by id, each followed through a `SessionLog` (only new
193
+ * bytes read). Finding a file is async (pi lists sessions from disk), so the
63
194
  * first look returns nothing and `onChange` fires once new files are known.
64
195
  */
65
196
  export class SessionChats {
66
197
  private paths = new Map<string, string>();
67
198
  private listing?: Promise<void>;
68
199
  private listedAt = Number.NEGATIVE_INFINITY;
69
- private readonly chats = new Map<string, { stamp: string; chat: ChatEntry[] }>();
200
+ private readonly logs = new Map<string, SessionLog>();
70
201
 
71
202
  private readonly list: SessionLister;
72
203
  private readonly onChange: () => void;
@@ -95,30 +226,36 @@ export class SessionChats {
95
226
  this.paths.set(sessionId, path);
96
227
  }
97
228
 
98
- chat(sessionId: string): ChatEntry[] {
229
+ /** The session's log, following its file (the least recently used let go past `MAX_LOGS`). */
230
+ private log(sessionId: string): SessionLog | undefined {
99
231
  const path = this.paths.get(sessionId);
100
232
  if (!path) {
101
233
  // A file's path never changes, so pi's list is only read (at most every few seconds) for sessions not found yet.
102
234
  if (this.now() - this.listedAt >= LIST_REFRESH_MS) this.refresh();
103
- return [];
104
- }
105
- let stamp: string;
106
- try {
107
- const stat = statSync(path);
108
- stamp = `${stat.size}:${stat.mtimeMs}`;
109
- } catch {
110
- return this.chats.get(sessionId)?.chat ?? [];
111
- }
112
- const cached = this.chats.get(sessionId);
113
- if (cached?.stamp === stamp) return cached.chat;
114
- let chat: ChatEntry[];
115
- try {
116
- chat = chatFromFile(readFileSync(path, "utf8"));
117
- } catch {
118
- return cached?.chat ?? [];
235
+ return undefined;
119
236
  }
120
- this.chats.set(sessionId, { stamp, chat });
121
- return chat;
237
+ let log = this.logs.get(sessionId);
238
+ if (!log || log.path !== path) log = new SessionLog(path);
239
+ this.logs.delete(sessionId);
240
+ this.logs.set(sessionId, log);
241
+ if (this.logs.size > MAX_LOGS) this.logs.delete(this.logs.keys().next().value!);
242
+ log.update();
243
+ return log;
244
+ }
245
+
246
+ /** The newest messages of a session's conversation (the same objects until its file grows). */
247
+ chat(sessionId: string): ChatEntry[] {
248
+ return this.log(sessionId)?.recent().entries ?? [];
249
+ }
250
+
251
+ /** Whether the session has messages earlier than `chat` returns. */
252
+ hasOlder(sessionId: string): boolean {
253
+ return this.log(sessionId)?.recent().older ?? false;
254
+ }
255
+
256
+ /** The session's whole conversation, oldest first. */
257
+ history(sessionId: string): ChatEntry[] {
258
+ return this.log(sessionId)?.history() ?? [];
122
259
  }
123
260
 
124
261
  private refresh(): void {
@@ -190,14 +190,14 @@ export class BackgroundSession {
190
190
 
191
191
  /** Split stdout into JSON lines (LF only, as pi's RPC framing requires) and handle each. */
192
192
  private receive(chunk: string): void {
193
- this.buffer += chunk;
194
- let newline = this.buffer.indexOf("\n");
195
- while (newline >= 0) {
196
- const line = this.buffer.slice(0, newline).replace(/\r$/, "");
197
- this.buffer = this.buffer.slice(newline + 1);
193
+ const text = this.buffer + chunk;
194
+ let start = 0;
195
+ for (let newline = text.indexOf("\n"); newline >= 0; newline = text.indexOf("\n", start)) {
196
+ const line = text.slice(start, newline).replace(/\r$/, "");
197
+ start = newline + 1;
198
198
  if (line.trim()) this.handle(line);
199
- newline = this.buffer.indexOf("\n");
200
199
  }
200
+ this.buffer = text.slice(start);
201
201
  }
202
202
 
203
203
  private handle(line: string): void {
@@ -280,7 +280,10 @@ export const launchPi: SessionLauncher = (args, cwd) => {
280
280
  return proc as unknown as SessionProcess;
281
281
  };
282
282
 
283
- /** Every background session this window started, oldest first. */
283
+ /** Ended background sessions kept in the list (with their feeds); older ones are let go. */
284
+ export const MAX_ENDED = 6;
285
+
286
+ /** Every background session this window started, oldest first (ended ones beyond the newest few let go). */
284
287
  export class SessionRegistry {
285
288
  readonly sessions: BackgroundSession[] = [];
286
289
  private readonly launcher: SessionLauncher;
@@ -295,10 +298,21 @@ export class SessionRegistry {
295
298
  const proc = this.launcher(sessionArgs(start.name, model), cwd);
296
299
  const session = new BackgroundSession(proc, start, this.onChange);
297
300
  this.sessions.push(session);
301
+ this.prune();
298
302
  this.onChange();
299
303
  return session;
300
304
  }
301
305
 
306
+ /** Let go of all but the newest `MAX_ENDED` sessions that have ended (their conversations stay in their session files). */
307
+ private prune(): void {
308
+ let ended = 0;
309
+ for (let index = this.sessions.length - 1; index >= 0; index -= 1) {
310
+ if (this.sessions[index]!.alive) continue;
311
+ ended += 1;
312
+ if (ended > MAX_ENDED) this.sessions.splice(index, 1);
313
+ }
314
+ }
315
+
302
316
  get(key: string): BackgroundSession | undefined {
303
317
  return this.sessions.find((session) => session.key === key);
304
318
  }