@oh-my-pi-zen/omp-stats 16.3.6-zen.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 (120) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/README.md +82 -0
  3. package/build.ts +95 -0
  4. package/dist/client/index.css +1 -0
  5. package/dist/client/index.html +24 -0
  6. package/dist/client/index.js +257 -0
  7. package/dist/client/styles.css +1656 -0
  8. package/dist/types/aggregator.d.ts +87 -0
  9. package/dist/types/client/App.d.ts +1 -0
  10. package/dist/types/client/api.d.ts +21 -0
  11. package/dist/types/client/app/AppLayout.d.ts +16 -0
  12. package/dist/types/client/app/NavRail.d.ts +7 -0
  13. package/dist/types/client/app/RangeControl.d.ts +7 -0
  14. package/dist/types/client/app/SyncButton.d.ts +14 -0
  15. package/dist/types/client/app/ThemeToggle.d.ts +1 -0
  16. package/dist/types/client/app/TopBar.d.ts +15 -0
  17. package/dist/types/client/app/routes.d.ts +12 -0
  18. package/dist/types/client/components/AgentTokenShare.d.ts +5 -0
  19. package/dist/types/client/components/chart-shared.d.ts +173 -0
  20. package/dist/types/client/components/models-table-shared.d.ts +175 -0
  21. package/dist/types/client/components/range-meta.d.ts +21 -0
  22. package/dist/types/client/data/charts.d.ts +1 -0
  23. package/dist/types/client/data/formatters.d.ts +8 -0
  24. package/dist/types/client/data/useHashRoute.d.ts +8 -0
  25. package/dist/types/client/data/useResource.d.ts +13 -0
  26. package/dist/types/client/data/view-models.d.ts +67 -0
  27. package/dist/types/client/index.d.ts +2 -0
  28. package/dist/types/client/routes/BehaviorRoute.d.ts +7 -0
  29. package/dist/types/client/routes/CostsRoute.d.ts +7 -0
  30. package/dist/types/client/routes/ErrorsRoute.d.ts +8 -0
  31. package/dist/types/client/routes/GainRoute.d.ts +7 -0
  32. package/dist/types/client/routes/ModelsRoute.d.ts +7 -0
  33. package/dist/types/client/routes/OverviewRoute.d.ts +8 -0
  34. package/dist/types/client/routes/ProjectsRoute.d.ts +7 -0
  35. package/dist/types/client/routes/RequestsRoute.d.ts +8 -0
  36. package/dist/types/client/routes/ToolsRoute.d.ts +7 -0
  37. package/dist/types/client/routes/index.d.ts +9 -0
  38. package/dist/types/client/types.d.ts +63 -0
  39. package/dist/types/client/ui/AsyncBoundary.d.ts +12 -0
  40. package/dist/types/client/ui/DataTable.d.ts +17 -0
  41. package/dist/types/client/ui/EmptyState.d.ts +7 -0
  42. package/dist/types/client/ui/ErrorState.d.ts +6 -0
  43. package/dist/types/client/ui/JsonBlock.d.ts +7 -0
  44. package/dist/types/client/ui/MetricCluster.d.ts +5 -0
  45. package/dist/types/client/ui/Panel.d.ts +7 -0
  46. package/dist/types/client/ui/RequestDrawer.d.ts +5 -0
  47. package/dist/types/client/ui/SegmentedControl.d.ts +12 -0
  48. package/dist/types/client/ui/Skeleton.d.ts +8 -0
  49. package/dist/types/client/ui/StatusPill.d.ts +7 -0
  50. package/dist/types/client/ui/index.d.ts +11 -0
  51. package/dist/types/client/useSystemTheme.d.ts +11 -0
  52. package/dist/types/db.d.ts +144 -0
  53. package/dist/types/embedded-client.d.ts +18 -0
  54. package/dist/types/gain-aggregator.d.ts +26 -0
  55. package/dist/types/index.d.ts +7 -0
  56. package/dist/types/parser.d.ts +53 -0
  57. package/dist/types/server.d.ts +7 -0
  58. package/dist/types/shared-types.d.ts +301 -0
  59. package/dist/types/sync-worker.d.ts +31 -0
  60. package/dist/types/types.d.ts +164 -0
  61. package/dist/types/user-metrics.d.ts +72 -0
  62. package/package.json +95 -0
  63. package/src/aggregator.ts +501 -0
  64. package/src/client/App.tsx +109 -0
  65. package/src/client/api.ts +102 -0
  66. package/src/client/app/AppLayout.tsx +93 -0
  67. package/src/client/app/NavRail.tsx +44 -0
  68. package/src/client/app/RangeControl.tsx +39 -0
  69. package/src/client/app/SyncButton.tsx +75 -0
  70. package/src/client/app/ThemeToggle.tsx +37 -0
  71. package/src/client/app/TopBar.tsx +73 -0
  72. package/src/client/app/routes.ts +69 -0
  73. package/src/client/components/AgentTokenShare.tsx +68 -0
  74. package/src/client/components/chart-shared.tsx +257 -0
  75. package/src/client/components/models-table-shared.tsx +255 -0
  76. package/src/client/components/range-meta.ts +73 -0
  77. package/src/client/css.d.ts +1 -0
  78. package/src/client/data/charts.ts +14 -0
  79. package/src/client/data/formatters.ts +45 -0
  80. package/src/client/data/useHashRoute.ts +87 -0
  81. package/src/client/data/useResource.ts +154 -0
  82. package/src/client/data/view-models.ts +251 -0
  83. package/src/client/index.tsx +10 -0
  84. package/src/client/routes/BehaviorRoute.tsx +623 -0
  85. package/src/client/routes/CostsRoute.tsx +234 -0
  86. package/src/client/routes/ErrorsRoute.tsx +118 -0
  87. package/src/client/routes/GainRoute.tsx +226 -0
  88. package/src/client/routes/ModelsRoute.tsx +430 -0
  89. package/src/client/routes/OverviewRoute.tsx +342 -0
  90. package/src/client/routes/ProjectsRoute.tsx +163 -0
  91. package/src/client/routes/RequestsRoute.tsx +123 -0
  92. package/src/client/routes/ToolsRoute.tsx +463 -0
  93. package/src/client/routes/index.ts +9 -0
  94. package/src/client/styles.css +1330 -0
  95. package/src/client/types.ts +80 -0
  96. package/src/client/ui/AsyncBoundary.tsx +54 -0
  97. package/src/client/ui/DataTable.tsx +122 -0
  98. package/src/client/ui/EmptyState.tsx +16 -0
  99. package/src/client/ui/ErrorState.tsx +25 -0
  100. package/src/client/ui/JsonBlock.tsx +75 -0
  101. package/src/client/ui/MetricCluster.tsx +67 -0
  102. package/src/client/ui/Panel.tsx +24 -0
  103. package/src/client/ui/RequestDrawer.tsx +208 -0
  104. package/src/client/ui/SegmentedControl.tsx +36 -0
  105. package/src/client/ui/Skeleton.tsx +17 -0
  106. package/src/client/ui/StatusPill.tsx +15 -0
  107. package/src/client/ui/index.ts +11 -0
  108. package/src/client/useSystemTheme.ts +87 -0
  109. package/src/db.ts +1530 -0
  110. package/src/embedded-client.generated.txt +0 -0
  111. package/src/embedded-client.ts +26 -0
  112. package/src/gain-aggregator.ts +281 -0
  113. package/src/index.ts +194 -0
  114. package/src/parser.ts +450 -0
  115. package/src/server.ts +352 -0
  116. package/src/shared-types.ts +323 -0
  117. package/src/sync-worker.ts +40 -0
  118. package/src/types.ts +171 -0
  119. package/src/user-metrics.ts +685 -0
  120. package/tailwind.config.js +40 -0
package/src/parser.ts ADDED
@@ -0,0 +1,450 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import {
4
+ type AssistantMessage,
5
+ coerceServiceTierByFamily,
6
+ getPriorityPremiumRequests,
7
+ resolveModelServiceTier,
8
+ type ServiceTierByFamily,
9
+ type ToolResultMessage,
10
+ } from "@oh-my-pi-zen/pi-ai";
11
+ import { getSessionsDir, isEnoent } from "@oh-my-pi-zen/pi-utils";
12
+ import type {
13
+ AgentType,
14
+ MessageStats,
15
+ SessionEntry,
16
+ SessionMessageEntry,
17
+ SessionServiceTierChangeEntry,
18
+ ToolCallStats,
19
+ ToolResultLink,
20
+ UserMessageLink,
21
+ UserMessageStats,
22
+ } from "./types";
23
+ import { computeUserMessageMetrics } from "./user-metrics";
24
+
25
+ /** Basename of an advisor agent's transcript inside a session artifacts dir. */
26
+ const ADVISOR_TRANSCRIPT_BASENAME = "__advisor.jsonl";
27
+
28
+ /**
29
+ * Classify which agent produced a transcript from its path within the sessions
30
+ * directory. Layout: `<sessionsDir>/<project>/<file>.jsonl` is the `main`
31
+ * agent; subagent and advisor transcripts live nested one level deeper inside
32
+ * the session's artifacts dir (`<project>/<session>/<id>.jsonl`,
33
+ * `<project>/<session>/__advisor.jsonl`). Any advisor transcript
34
+ * (`__advisor.jsonl` or `__advisor.<slug>.jsonl`) — at any depth, including a
35
+ * subagent's own advisor — counts as `advisor`; every other nested transcript
36
+ * is a task `subagent`.
37
+ */
38
+ export function classifyAgentType(sessionPath: string): AgentType {
39
+ const base = path.basename(sessionPath);
40
+ if (base === ADVISOR_TRANSCRIPT_BASENAME || (base.startsWith("__advisor.") && base.endsWith(".jsonl"))) {
41
+ return "advisor";
42
+ }
43
+ const rel = path.relative(getSessionsDir(), sessionPath);
44
+ // `<project>/<file>.jsonl` -> 2 segments. Deeper nesting is a subagent.
45
+ return rel.split(path.sep).length <= 2 ? "main" : "subagent";
46
+ }
47
+
48
+ /**
49
+ * Extract folder name from session filename.
50
+ * Session files are named like: --work--pi--/timestamp_uuid.jsonl
51
+ * The folder part uses -- as path separator.
52
+ */
53
+ function extractFolderFromPath(sessionPath: string): string {
54
+ const sessionsDir = getSessionsDir();
55
+ const rel = path.relative(sessionsDir, sessionPath);
56
+ const projectDir = rel.split(path.sep)[0];
57
+ // Convert --work--pi-- to /work/pi
58
+ return projectDir.replace(/^--/, "/").replace(/--/g, "/");
59
+ }
60
+
61
+ /**
62
+ * Check if an entry is an assistant message.
63
+ */
64
+ function isAssistantMessage(entry: SessionEntry): entry is SessionMessageEntry {
65
+ if (entry.type !== "message") return false;
66
+ const msgEntry = entry as SessionMessageEntry;
67
+ // Legacy sessions (pre-id tracking) recorded message entries without an `id`.
68
+ // They're not linkable and would violate the messages.entry_id NOT NULL
69
+ // constraint, so skip them at the parser boundary.
70
+ if (typeof msgEntry.id !== "string" || msgEntry.id.length === 0) return false;
71
+ return msgEntry.message?.role === "assistant";
72
+ }
73
+
74
+ /**
75
+ * Check if an entry is a user message (non-toolResult).
76
+ */
77
+ function isUserMessage(entry: SessionEntry): entry is SessionMessageEntry {
78
+ if (entry.type !== "message") return false;
79
+ const msgEntry = entry as SessionMessageEntry;
80
+ if (typeof msgEntry.id !== "string" || msgEntry.id.length === 0) return false;
81
+ return msgEntry.message?.role === "user";
82
+ }
83
+
84
+ /**
85
+ * Check if an entry is a service-tier change.
86
+ */
87
+ function isServiceTierChange(entry: SessionEntry): entry is SessionServiceTierChangeEntry {
88
+ return entry.type === "service_tier_change";
89
+ }
90
+
91
+ /**
92
+ * Check if an entry is a tool-result message.
93
+ */
94
+ function isToolResultMessage(entry: SessionEntry): entry is SessionMessageEntry {
95
+ if (entry.type !== "message") return false;
96
+ return (entry as SessionMessageEntry).message?.role === "toolResult";
97
+ }
98
+
99
+ /**
100
+ * Extract plain text from a user message content payload.
101
+ */
102
+ function extractUserText(content: unknown): string {
103
+ if (typeof content === "string") return content;
104
+ if (!Array.isArray(content)) return "";
105
+ const parts: string[] = [];
106
+ for (const block of content) {
107
+ if (block && typeof block === "object" && (block as { type?: unknown }).type === "text") {
108
+ const text = (block as { text?: unknown }).text;
109
+ if (typeof text === "string") parts.push(text);
110
+ }
111
+ }
112
+ return parts.join("");
113
+ }
114
+
115
+ /**
116
+ * Build user-message stats from an entry. Returns null for empty/synthetic content.
117
+ */
118
+ function extractUserStats(sessionFile: string, folder: string, entry: SessionMessageEntry): UserMessageStats | null {
119
+ const msg = entry.message as { role: "user"; content?: unknown; synthetic?: boolean };
120
+ if (msg.role !== "user" || msg.synthetic) return null;
121
+ const text = extractUserText(msg.content);
122
+ if (!text.trim()) return null;
123
+ const metrics = computeUserMessageMetrics(text);
124
+ const ts = Date.parse(entry.timestamp);
125
+ return {
126
+ sessionFile,
127
+ entryId: entry.id,
128
+ folder,
129
+ timestamp: Number.isFinite(ts) ? ts : 0,
130
+ model: null,
131
+ provider: null,
132
+ chars: metrics.chars,
133
+ words: metrics.words,
134
+ yelling: metrics.yelling,
135
+ profanity: metrics.profanity,
136
+ anguish: metrics.anguish,
137
+ negation: metrics.negation,
138
+ repetition: metrics.repetition,
139
+ blame: metrics.blame,
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Extract stats from an assistant message entry.
145
+ */
146
+ function extractStats(
147
+ sessionFile: string,
148
+ folder: string,
149
+ entry: SessionMessageEntry,
150
+ currentServiceTier: ServiceTierByFamily | undefined,
151
+ agentType: AgentType,
152
+ ): MessageStats | null {
153
+ const msg = entry.message as AssistantMessage;
154
+ if (msg?.role !== "assistant") return null;
155
+
156
+ // Backfill: when the session recorded `priority` as the active service tier
157
+ // at this point but the AI usage payload was captured before priority
158
+ // requests were folded into `premiumRequests`, derive the count here so the
159
+ // "Premium Reqs" stat aggregates priority traffic on re-sync. Trust any
160
+ // non-zero value already in `usage.premiumRequests` (Copilot multipliers or
161
+ // the new AI code path) and only synthesise when the field is missing/zero.
162
+ const recorded = msg.usage.premiumRequests ?? 0;
163
+ const model = { provider: msg.provider, api: msg.api, id: msg.model };
164
+ const tier = resolveModelServiceTier(currentServiceTier, model);
165
+ const derived = recorded > 0 ? recorded : getPriorityPremiumRequests(tier, model);
166
+ const usage = derived === recorded ? msg.usage : { ...msg.usage, premiumRequests: derived };
167
+
168
+ return {
169
+ sessionFile,
170
+ entryId: entry.id,
171
+ folder,
172
+ model: msg.model,
173
+ provider: msg.provider,
174
+ api: msg.api,
175
+ timestamp: msg.timestamp,
176
+ duration: msg.duration ?? null,
177
+ ttft: msg.ttft ?? null,
178
+ stopReason: msg.stopReason,
179
+ errorMessage: msg.errorMessage ?? null,
180
+ usage,
181
+ agentType,
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Extract one {@link ToolCallStats} per `toolCall` content block of an
187
+ * assistant message. Returns an empty array for turns without tool calls.
188
+ */
189
+ function extractToolCalls(
190
+ sessionFile: string,
191
+ folder: string,
192
+ entry: SessionMessageEntry,
193
+ agentType: AgentType,
194
+ ): ToolCallStats[] {
195
+ const msg = entry.message as AssistantMessage;
196
+ if (msg?.role !== "assistant" || !Array.isArray(msg.content)) return [];
197
+
198
+ const blocks = msg.content.filter(block => block.type === "toolCall");
199
+ if (blocks.length === 0) return [];
200
+
201
+ return blocks.map(block => {
202
+ let argsChars = 0;
203
+ try {
204
+ argsChars = JSON.stringify(block.arguments ?? {}).length;
205
+ } catch {
206
+ // Non-serializable arguments (shouldn't happen in persisted JSONL); size unknown.
207
+ }
208
+ return {
209
+ sessionFile,
210
+ entryId: entry.id,
211
+ toolCallId: block.id,
212
+ folder,
213
+ toolName: block.name,
214
+ model: msg.model,
215
+ provider: msg.provider,
216
+ timestamp: msg.timestamp,
217
+ agentType,
218
+ callsInTurn: blocks.length,
219
+ argsChars,
220
+ };
221
+ });
222
+ }
223
+
224
+ /**
225
+ * Build the result linkage for a `toolResult` entry: text characters fed back
226
+ * into context plus the error flag, keyed to the originating call.
227
+ */
228
+ function extractToolResultLink(sessionFile: string, entry: SessionMessageEntry): ToolResultLink | null {
229
+ const msg = entry.message as ToolResultMessage;
230
+ if (msg.role !== "toolResult" || typeof msg.toolCallId !== "string" || msg.toolCallId.length === 0) return null;
231
+ let resultChars = 0;
232
+ if (Array.isArray(msg.content)) {
233
+ for (const block of msg.content) {
234
+ if (block.type === "text" && typeof block.text === "string") resultChars += block.text.length;
235
+ }
236
+ }
237
+ return {
238
+ sessionFile,
239
+ toolCallId: msg.toolCallId,
240
+ resultChars,
241
+ isError: msg.isError === true,
242
+ };
243
+ }
244
+
245
+ const LF = 0x0a;
246
+ const CR = 0x0d;
247
+ const jsonLineDecoder = new TextDecoder();
248
+
249
+ function parseJsonLine(bytes: Uint8Array, start: number, end: number): SessionEntry | null {
250
+ while (end > start && bytes[end - 1] === CR) end--;
251
+ if (end <= start) return null;
252
+ try {
253
+ return JSON.parse(jsonLineDecoder.decode(bytes.subarray(start, end))) as SessionEntry;
254
+ } catch {
255
+ return null;
256
+ }
257
+ }
258
+
259
+ function visitSessionEntriesLenient(bytes: Uint8Array, visit: (entry: SessionEntry) => void): number {
260
+ let cursor = 0;
261
+ let read = 0;
262
+
263
+ while (cursor < bytes.length) {
264
+ const newline = bytes.indexOf(LF, cursor);
265
+ const hasNewline = newline !== -1;
266
+ const lineEnd = hasNewline ? newline : bytes.length;
267
+ const entry = parseJsonLine(bytes, cursor, lineEnd);
268
+ if (entry) {
269
+ visit(entry);
270
+ read = hasNewline ? newline + 1 : lineEnd;
271
+ } else if (hasNewline) {
272
+ read = newline + 1;
273
+ } else {
274
+ break;
275
+ }
276
+ cursor = hasNewline ? newline + 1 : lineEnd;
277
+ }
278
+
279
+ return read;
280
+ }
281
+
282
+ function parseSessionEntriesLenient(bytes: Uint8Array): { entries: SessionEntry[]; read: number } {
283
+ const entries: SessionEntry[] = [];
284
+ const read = visitSessionEntriesLenient(bytes, entry => entries.push(entry));
285
+ return { entries, read };
286
+ }
287
+
288
+ function scanLastServiceTier(bytes: Uint8Array): ServiceTierByFamily | undefined {
289
+ let currentServiceTier: ServiceTierByFamily | undefined;
290
+ visitSessionEntriesLenient(bytes, entry => {
291
+ if (isServiceTierChange(entry)) currentServiceTier = coerceServiceTierByFamily(entry.serviceTier);
292
+ });
293
+ return currentServiceTier;
294
+ }
295
+ /**
296
+ * Parse a session file and extract all assistant message stats.
297
+ * Uses incremental reading with offset tracking.
298
+ *
299
+ * Service-tier carry-over: `currentServiceTier` is a session-scoped piece of
300
+ * state derived from `service_tier_change` entries that affects whether
301
+ * subsequent OpenAI assistant replies count as premium requests. Incremental
302
+ * syncs that resume past the most-recent tier change would otherwise lose
303
+ * that state and silently record `premiumRequests = 0` for priority traffic
304
+ * (the coding-agent stopped folding the tier into `usage.premiumRequests`
305
+ * after 13f59162e — the parser is now the sole source of truth). When
306
+ * `fromOffset > 0` we therefore scan the bytes preceding `fromOffset`
307
+ * for the latest service-tier value before parsing the unprocessed tail.
308
+ * The scan only keeps the current tier and does not materialize prefix
309
+ * entries, preserving offset-based memory behavior for large sessions.
310
+ */
311
+ export interface ParseSessionResult {
312
+ stats: MessageStats[];
313
+ userStats: UserMessageStats[];
314
+ userLinks: UserMessageLink[];
315
+ toolCalls: ToolCallStats[];
316
+ toolResults: ToolResultLink[];
317
+ newOffset: number;
318
+ }
319
+ export async function parseSessionFile(sessionPath: string, fromOffset = 0): Promise<ParseSessionResult> {
320
+ let bytes: Uint8Array;
321
+ try {
322
+ bytes = await Bun.file(sessionPath).bytes();
323
+ } catch (err) {
324
+ if (isEnoent(err))
325
+ return { stats: [], userStats: [], userLinks: [], toolCalls: [], toolResults: [], newOffset: fromOffset };
326
+ throw err;
327
+ }
328
+
329
+ const folder = extractFolderFromPath(sessionPath);
330
+ const agentType = classifyAgentType(sessionPath);
331
+ const stats: MessageStats[] = [];
332
+ const userStats: UserMessageStats[] = [];
333
+ const userLinks: UserMessageLink[] = [];
334
+ const toolCalls: ToolCallStats[] = [];
335
+ const toolResults: ToolResultLink[] = [];
336
+ const userByEntryId = new Map<string, UserMessageStats>();
337
+ const start = Math.max(0, Math.min(fromOffset, bytes.length));
338
+ const unprocessed = bytes.subarray(start);
339
+ const { entries, read } = parseSessionEntriesLenient(unprocessed);
340
+ let currentServiceTier: ServiceTierByFamily | undefined;
341
+ if (start > 0) {
342
+ currentServiceTier = scanLastServiceTier(bytes.subarray(0, start));
343
+ }
344
+ for (const entry of entries) {
345
+ if (isServiceTierChange(entry)) {
346
+ currentServiceTier = coerceServiceTierByFamily(entry.serviceTier);
347
+ continue;
348
+ }
349
+ if (isUserMessage(entry)) {
350
+ const userMsg = extractUserStats(sessionPath, folder, entry);
351
+ if (userMsg) {
352
+ userStats.push(userMsg);
353
+ userByEntryId.set(entry.id, userMsg);
354
+ }
355
+ continue;
356
+ }
357
+ if (isToolResultMessage(entry)) {
358
+ const link = extractToolResultLink(sessionPath, entry);
359
+ if (link) toolResults.push(link);
360
+ continue;
361
+ }
362
+ if (isAssistantMessage(entry)) {
363
+ const msgStats = extractStats(sessionPath, folder, entry, currentServiceTier, agentType);
364
+ if (msgStats) stats.push(msgStats);
365
+ toolCalls.push(...extractToolCalls(sessionPath, folder, entry, agentType));
366
+ // Link assistant's responding model back to the user message it answered.
367
+ const parentId = (entry as SessionMessageEntry).parentId;
368
+ if (parentId) {
369
+ const msg = entry.message as AssistantMessage;
370
+ if (msg.model && msg.provider) {
371
+ // Emit unconditionally. The aggregator's UPDATE is guarded by
372
+ // `model IS NULL` so this is idempotent: a no-op for already
373
+ // linked rows, a fix-up for fresh inserts (which start NULL
374
+ // because the user row is recorded before its reply lands) and
375
+ // for cross-pass orphans whose parent was committed by an
376
+ // earlier incremental sync.
377
+ userLinks.push({
378
+ sessionFile: sessionPath,
379
+ entryId: parentId,
380
+ model: msg.model,
381
+ provider: msg.provider,
382
+ });
383
+ }
384
+ }
385
+ }
386
+ }
387
+
388
+ return { stats, userStats, userLinks, toolCalls, toolResults, newOffset: start + read };
389
+ }
390
+
391
+ /**
392
+ * List all session directories (folders).
393
+ */
394
+ export async function listSessionFolders(): Promise<string[]> {
395
+ try {
396
+ const sessionsDir = getSessionsDir();
397
+ const entries = await fs.readdir(sessionsDir, { withFileTypes: true });
398
+ return entries.filter(e => e.isDirectory()).map(e => path.join(sessionsDir, e.name));
399
+ } catch {
400
+ return [];
401
+ }
402
+ }
403
+
404
+ /**
405
+ * List all session files in a folder.
406
+ */
407
+ export async function listSessionFiles(folderPath: string): Promise<string[]> {
408
+ try {
409
+ const entries = await fs.readdir(folderPath, { recursive: true, withFileTypes: true });
410
+ return entries.filter(e => e.isFile() && e.name.endsWith(".jsonl")).map(e => path.join(e.parentPath, e.name));
411
+ } catch {
412
+ return [];
413
+ }
414
+ }
415
+
416
+ /**
417
+ * List all session files across all folders.
418
+ */
419
+ export async function listAllSessionFiles(): Promise<string[]> {
420
+ const folders = await listSessionFolders();
421
+ const allFiles: string[] = [];
422
+
423
+ for (const folder of folders) {
424
+ const files = await listSessionFiles(folder);
425
+ allFiles.push(...files);
426
+ }
427
+
428
+ return allFiles;
429
+ }
430
+
431
+ /**
432
+ * Find a specific entry in a session file.
433
+ */
434
+ export async function getSessionEntry(sessionPath: string, entryId: string): Promise<SessionEntry | null> {
435
+ let bytes: Uint8Array;
436
+ try {
437
+ bytes = await Bun.file(sessionPath).bytes();
438
+ } catch (err) {
439
+ if (isEnoent(err)) return null;
440
+ throw err;
441
+ }
442
+
443
+ const { entries } = parseSessionEntriesLenient(bytes);
444
+ for (const entry of entries) {
445
+ if ("id" in entry && entry.id === entryId) {
446
+ return entry;
447
+ }
448
+ }
449
+ return null;
450
+ }