sidekick-shared 0.24.4 → 0.25.0

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 (98) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +200 -52
  3. package/dist/accountChangeSignal.d.ts +3 -0
  4. package/dist/accountChangeSignal.js +19 -0
  5. package/dist/accountChanges.d.ts +21 -0
  6. package/dist/accountChanges.js +151 -0
  7. package/dist/accountManager.d.ts +13 -0
  8. package/dist/accountManager.js +60 -32
  9. package/dist/accountRegistry.d.ts +3 -1
  10. package/dist/accountRegistry.js +64 -41
  11. package/dist/accounts.js +40 -19
  12. package/dist/autoSwitch.d.ts +2 -1
  13. package/dist/autoSwitch.js +32 -7
  14. package/dist/browser.d.ts +10 -3
  15. package/dist/browser.js +17 -1
  16. package/dist/codexProfiles.d.ts +14 -0
  17. package/dist/codexProfiles.js +268 -116
  18. package/dist/codexQuotaWatcher.d.ts +6 -0
  19. package/dist/codexQuotaWatcher.js +101 -47
  20. package/dist/context/sessionContext.js +2 -4
  21. package/dist/ensureDefaultAccounts.js +4 -4
  22. package/dist/index.d.ts +32 -15
  23. package/dist/index.js +54 -9
  24. package/dist/modelAliases.d.ts +13 -0
  25. package/dist/modelAliases.js +58 -0
  26. package/dist/modelCatalog.d.ts +32 -0
  27. package/dist/modelCatalog.js +145 -0
  28. package/dist/modelContext.d.ts +36 -3
  29. package/dist/modelContext.js +109 -34
  30. package/dist/modelInfo.d.ts +30 -1
  31. package/dist/modelInfo.js +116 -26
  32. package/dist/multiProviderQuotaService.d.ts +8 -0
  33. package/dist/multiProviderQuotaService.js +64 -3
  34. package/dist/node.d.ts +8 -2
  35. package/dist/node.js +11 -1
  36. package/dist/observedContextWindows.d.ts +13 -0
  37. package/dist/observedContextWindows.js +13 -0
  38. package/dist/observedSessionCollector.d.ts +75 -4
  39. package/dist/observedSessionCollector.js +452 -42
  40. package/dist/parsers/codexHistory.d.ts +32 -0
  41. package/dist/parsers/codexHistory.js +125 -0
  42. package/dist/parsers/mcpToolName.d.ts +26 -0
  43. package/dist/parsers/mcpToolName.js +31 -0
  44. package/dist/parsers/sessionActivityDetector.d.ts +6 -0
  45. package/dist/parsers/sessionActivityDetector.js +17 -0
  46. package/dist/parsers/sessionPathResolver.d.ts +11 -4
  47. package/dist/parsers/sessionPathResolver.js +11 -4
  48. package/dist/paths.d.ts +7 -3
  49. package/dist/paths.js +7 -3
  50. package/dist/providerIds.d.ts +11 -0
  51. package/dist/providerIds.js +9 -0
  52. package/dist/providerQuota.d.ts +3 -1
  53. package/dist/providerQuota.js +3 -0
  54. package/dist/providers/claudeCode.d.ts +11 -1
  55. package/dist/providers/claudeCode.js +222 -39
  56. package/dist/providers/codex.d.ts +39 -1
  57. package/dist/providers/codex.js +326 -39
  58. package/dist/providers/codexDatabase.d.ts +9 -0
  59. package/dist/providers/codexDatabase.js +107 -2
  60. package/dist/providers/diagnostics.d.ts +13 -0
  61. package/dist/providers/diagnostics.js +88 -0
  62. package/dist/providers/factory.d.ts +14 -0
  63. package/dist/providers/factory.js +57 -0
  64. package/dist/providers/openCode.d.ts +20 -1
  65. package/dist/providers/openCode.js +361 -11
  66. package/dist/providers/openCodeDatabase.d.ts +10 -0
  67. package/dist/providers/openCodeDatabase.js +69 -0
  68. package/dist/providers/types.d.ts +57 -2
  69. package/dist/providers/types.js +4 -0
  70. package/dist/quota.d.ts +4 -1
  71. package/dist/quota.js +3 -7
  72. package/dist/quotaHistory.d.ts +3 -2
  73. package/dist/quotaHistory.js +2 -2
  74. package/dist/quotaPoller.d.ts +13 -1
  75. package/dist/quotaPoller.js +65 -3
  76. package/dist/quotaSnapshots.js +8 -77
  77. package/dist/schemas/accountManager.d.ts +2 -2
  78. package/dist/schemas/accountManager.js +2 -4
  79. package/dist/schemas/accountStatus.d.ts +3 -0
  80. package/dist/schemas/accountStatus.js +1 -0
  81. package/dist/schemas/index.d.ts +1 -0
  82. package/dist/schemas/index.js +7 -2
  83. package/dist/schemas/observedSessionV1.d.ts +27 -26
  84. package/dist/schemas/observedSessionV1.js +6 -4
  85. package/dist/schemas/quota.d.ts +2 -2
  86. package/dist/schemas/quota.js +3 -6
  87. package/dist/schemas/quotaHistory.d.ts +2 -2
  88. package/dist/schemas/tokenEstimation.d.ts +1 -1
  89. package/dist/sessionMonitor.d.ts +15 -0
  90. package/dist/sessionMonitor.js +142 -0
  91. package/dist/sessionPreviews.d.ts +85 -0
  92. package/dist/sessionPreviews.js +549 -0
  93. package/dist/sessionTranscripts.js +10 -4
  94. package/dist/types/observedSessionV1.d.ts +6 -2
  95. package/dist/types/observedSessionV1.js +14 -8
  96. package/dist/writers/atomic.d.ts +20 -0
  97. package/dist/writers/atomic.js +190 -19
  98. package/package.json +22 -1
@@ -0,0 +1,549 @@
1
+ "use strict";
2
+ /**
3
+ * Cheap, bounded previews of provider-native session files (Node-only).
4
+ *
5
+ * `listRecentSessions` answers "what happened in this workspace" but labels
6
+ * every discovered session before applying its limit, so its cost scales with
7
+ * total session count. This module inverts the order of operations: enumerate
8
+ * with stats only, sort by mtime, apply `since`/`limit`, and only then do
9
+ * bounded content reads for the survivors. That keeps a "recent sessions"
10
+ * surface cheap even against a machine with thousands of accumulated sessions.
11
+ *
12
+ * Prompt extraction delegates to each provider's `extractSessionLabel` (Claude
13
+ * Code reads only the first 8 KiB; Codex prefers the sqlite thread title, else
14
+ * a bounded first-user-message scan that skips injected context). The first
15
+ * timestamp and workspace path come from one generic prefix parse in this
16
+ * module. A session whose opening events are larger than the prefix budget
17
+ * yields `null` fields rather than an error.
18
+ *
19
+ * @module sessionPreviews
20
+ */
21
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ var desc = Object.getOwnPropertyDescriptor(m, k);
24
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
25
+ desc = { enumerable: true, get: function() { return m[k]; } };
26
+ }
27
+ Object.defineProperty(o, k2, desc);
28
+ }) : (function(o, m, k, k2) {
29
+ if (k2 === undefined) k2 = k;
30
+ o[k2] = m[k];
31
+ }));
32
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
33
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
34
+ }) : function(o, v) {
35
+ o["default"] = v;
36
+ });
37
+ var __importStar = (this && this.__importStar) || (function () {
38
+ var ownKeys = function(o) {
39
+ ownKeys = Object.getOwnPropertyNames || function (o) {
40
+ var ar = [];
41
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
42
+ return ar;
43
+ };
44
+ return ownKeys(o);
45
+ };
46
+ return function (mod) {
47
+ if (mod && mod.__esModule) return mod;
48
+ var result = {};
49
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
50
+ __setModuleDefault(result, mod);
51
+ return result;
52
+ };
53
+ })();
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.readSessionPreview = readSessionPreview;
56
+ exports.readSessionPreviewAsync = readSessionPreviewAsync;
57
+ exports.listSessionPreviews = listSessionPreviews;
58
+ exports.listSessionPreviewsAsync = listSessionPreviewsAsync;
59
+ const fs = __importStar(require("fs"));
60
+ const DEFAULT_PREFIX_BYTES = 16 * 1024;
61
+ const DEFAULT_LIMIT = 50;
62
+ const DEFAULT_CONCURRENCY = 4;
63
+ const MAX_CONCURRENCY = 16;
64
+ /**
65
+ * Reads a bounded preview of one session file. Returns `null` when the file is
66
+ * missing or unreadable; malformed content degrades to `null` fields instead
67
+ * of throwing.
68
+ */
69
+ function readSessionPreview(provider, sessionPath, options = {}) {
70
+ let sizeBytes;
71
+ let modifiedAt;
72
+ try {
73
+ const stats = fs.statSync(sessionPath);
74
+ sizeBytes = stats.size;
75
+ // Inside the try: an out-of-range mtime RangeErrors on serialization,
76
+ // and this function's contract is to degrade, not throw.
77
+ modifiedAt = stats.mtime.toISOString();
78
+ }
79
+ catch {
80
+ let metadata;
81
+ try {
82
+ metadata = provider.getSessionMetadata?.(sessionPath);
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ if (!metadata)
88
+ return null;
89
+ sizeBytes = 0;
90
+ try {
91
+ modifiedAt = metadata.mtime.toISOString();
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ let firstUserPrompt = null;
98
+ try {
99
+ firstUserPrompt = provider.extractSessionLabel(sessionPath);
100
+ }
101
+ catch {
102
+ // Label extraction is best-effort.
103
+ }
104
+ let sessionId = '';
105
+ try {
106
+ sessionId = provider.getSessionId(sessionPath);
107
+ }
108
+ catch {
109
+ // A provider that cannot identify the file still yields a usable preview.
110
+ }
111
+ const prefix = scanPrefix(sessionPath, options.maxPrefixBytes ?? DEFAULT_PREFIX_BYTES);
112
+ return {
113
+ provider: provider.id,
114
+ sessionId,
115
+ filePath: sessionPath,
116
+ modifiedAt,
117
+ sizeBytes,
118
+ firstUserPrompt,
119
+ firstTimestamp: prefix.firstTimestamp,
120
+ workspacePath: prefix.workspacePath,
121
+ };
122
+ }
123
+ /** Event-loop-safe counterpart to readSessionPreview with per-call degradation status. */
124
+ async function readSessionPreviewAsync(provider, sessionPath, options = {}) {
125
+ let labels;
126
+ const diagnostics = [];
127
+ try {
128
+ labels = await extractLabelsAsync(provider, [sessionPath], options);
129
+ }
130
+ catch {
131
+ labels = new Map([[sessionPath, null]]);
132
+ diagnostics.push({
133
+ providerId: provider.id,
134
+ kind: 'read_failed',
135
+ severity: 'warning',
136
+ phase: 'read',
137
+ message: `${provider.id} session label was unavailable.`,
138
+ });
139
+ }
140
+ const info = await statSessionFileAsync(provider, sessionPath);
141
+ if (!info) {
142
+ return {
143
+ preview: null,
144
+ diagnostics: dedupeDiagnostics([...diagnostics, ...providerDiagnostics(provider)]),
145
+ };
146
+ }
147
+ const preview = await readSessionPreviewFromInfoAsync(provider, info, labels.get(sessionPath) ?? null, options);
148
+ return {
149
+ preview,
150
+ diagnostics: dedupeDiagnostics([...diagnostics, ...providerDiagnostics(provider)]),
151
+ };
152
+ }
153
+ /**
154
+ * Lists previews across providers, newest first. Enumeration is stat-only;
155
+ * content is read only for the post-`limit` survivors.
156
+ */
157
+ function listSessionPreviews(providers, options = {}) {
158
+ const limit = Math.max(0, options.limit ?? DEFAULT_LIMIT);
159
+ const sinceMs = resolveSinceMs(options.since);
160
+ const candidates = [];
161
+ for (const provider of providers) {
162
+ for (const file of enumerateSessionFiles(provider, options.workspacePath)) {
163
+ const mtimeMs = file.mtime.getTime();
164
+ if (sinceMs !== null && mtimeMs <= sinceMs)
165
+ continue;
166
+ candidates.push({ provider, path: file.path, mtimeMs });
167
+ }
168
+ }
169
+ candidates.sort((left, right) => right.mtimeMs - left.mtimeMs);
170
+ const previews = [];
171
+ for (const candidate of candidates.slice(0, limit)) {
172
+ const preview = readSessionPreview(candidate.provider, candidate.path, options);
173
+ if (preview)
174
+ previews.push(preview);
175
+ }
176
+ return previews;
177
+ }
178
+ /**
179
+ * Lists previews without blocking the caller loop on corpus-wide synchronous
180
+ * work. SQLite-backed providers perform at most one subprocess per call.
181
+ */
182
+ async function listSessionPreviewsAsync(providers, options = {}) {
183
+ const limit = Math.max(0, options.limit ?? DEFAULT_LIMIT);
184
+ const sinceMs = resolveSinceMs(options.since);
185
+ const candidates = [];
186
+ const operationDiagnostics = [];
187
+ await Promise.all(providers.map(async (provider) => {
188
+ let files = [];
189
+ try {
190
+ files = provider.listSessionFilesAsync
191
+ ? await provider.listSessionFilesAsync(options.workspacePath)
192
+ : await enumerateSessionFilesAsyncFallback(provider, options.workspacePath, options);
193
+ }
194
+ catch {
195
+ files = [];
196
+ operationDiagnostics.push({
197
+ providerId: provider.id,
198
+ kind: 'read_failed',
199
+ severity: 'error',
200
+ phase: 'enumerate',
201
+ message: `${provider.id} session enumeration failed.`,
202
+ });
203
+ }
204
+ for (const info of files) {
205
+ const mtimeMs = info.mtime.getTime();
206
+ if (sinceMs !== null && mtimeMs <= sinceMs)
207
+ continue;
208
+ candidates.push({ provider, info });
209
+ }
210
+ }));
211
+ candidates.sort((left, right) => right.info.mtime.getTime() - left.info.mtime.getTime());
212
+ const selected = candidates.slice(0, limit);
213
+ const labels = new Map();
214
+ await Promise.all(providers.map(async (provider) => {
215
+ const paths = selected
216
+ .filter((item) => item.provider === provider)
217
+ .map((item) => item.info.path);
218
+ if (paths.length === 0)
219
+ return;
220
+ try {
221
+ labels.set(provider, await extractLabelsAsync(provider, paths, options));
222
+ }
223
+ catch {
224
+ labels.set(provider, new Map(paths.map((sessionPath) => [sessionPath, null])));
225
+ operationDiagnostics.push({
226
+ providerId: provider.id,
227
+ kind: 'read_failed',
228
+ severity: 'warning',
229
+ phase: 'read',
230
+ message: `${provider.id} session labels were unavailable.`,
231
+ });
232
+ }
233
+ }));
234
+ const previews = await mapWithConcurrency(selected, async ({ provider, info }) => {
235
+ const preview = await readSessionPreviewFromInfoAsync(provider, info, labels.get(provider)?.get(info.path) ?? info.label ?? null, options);
236
+ await yieldControl(options);
237
+ return preview;
238
+ }, concurrency(options));
239
+ return {
240
+ previews: previews.filter((preview) => preview !== null),
241
+ diagnostics: dedupeDiagnostics([
242
+ ...operationDiagnostics,
243
+ ...providers.flatMap(providerDiagnostics),
244
+ ]),
245
+ };
246
+ }
247
+ function resolveSinceMs(since) {
248
+ if (since === undefined)
249
+ return null;
250
+ const ms = since instanceof Date ? since.getTime() : Date.parse(since);
251
+ return Number.isFinite(ms) ? ms : null;
252
+ }
253
+ function enumerateSessionFiles(provider, workspacePath) {
254
+ try {
255
+ if (workspacePath) {
256
+ return provider
257
+ .findAllSessions(workspacePath)
258
+ .map(statSessionFile)
259
+ .filter((info) => info !== null);
260
+ }
261
+ if (provider.listAllSessionFiles)
262
+ return provider.listAllSessionFiles();
263
+ // Best-effort global fallback for providers without listAllSessionFiles:
264
+ // correct for project-folder-shaped providers, empty otherwise.
265
+ const results = [];
266
+ const seen = new Set();
267
+ for (const folder of provider.getAllProjectFolders()) {
268
+ for (const sessionPath of provider.findSessionsInDirectory(folder.dir)) {
269
+ if (seen.has(sessionPath))
270
+ continue;
271
+ seen.add(sessionPath);
272
+ const info = statSessionFile(sessionPath);
273
+ if (info)
274
+ results.push(info);
275
+ }
276
+ }
277
+ return results;
278
+ }
279
+ catch {
280
+ return [];
281
+ }
282
+ }
283
+ function statSessionFile(sessionPath) {
284
+ try {
285
+ return { path: sessionPath, mtime: fs.statSync(sessionPath).mtime };
286
+ }
287
+ catch {
288
+ return null;
289
+ }
290
+ }
291
+ async function statSessionFileAsync(provider, sessionPath) {
292
+ try {
293
+ const stat = await fs.promises.stat(sessionPath);
294
+ return {
295
+ path: sessionPath,
296
+ mtime: stat.mtime,
297
+ sizeBytes: stat.size,
298
+ sessionId: safeSessionId(provider, sessionPath),
299
+ };
300
+ }
301
+ catch {
302
+ let metadata = null;
303
+ try {
304
+ // Async first: for DB-backed synthetic paths the sync variant can spawn
305
+ // a blocking sqlite3 subprocess, defeating this API's event-loop safety.
306
+ if (provider.getSessionMetadataAsync) {
307
+ metadata = await provider.getSessionMetadataAsync(sessionPath);
308
+ }
309
+ else {
310
+ metadata = provider.getSessionMetadata?.(sessionPath) ?? null;
311
+ }
312
+ }
313
+ catch {
314
+ metadata = null;
315
+ }
316
+ if (!metadata)
317
+ return null;
318
+ return {
319
+ path: sessionPath,
320
+ mtime: metadata.mtime,
321
+ sizeBytes: 0,
322
+ sessionId: safeSessionId(provider, sessionPath),
323
+ };
324
+ }
325
+ }
326
+ async function extractLabelsAsync(provider, sessionPaths, options) {
327
+ if (provider.extractSessionLabelsAsync) {
328
+ // Callers deliberately do not retry through the synchronous provider path
329
+ // if this batch fails: DB-backed providers could otherwise spawn once per
330
+ // session after their single async batch failed.
331
+ return provider.extractSessionLabelsAsync(sessionPaths);
332
+ }
333
+ const values = new Map();
334
+ for (const sessionPath of sessionPaths) {
335
+ values.set(sessionPath, await extractLabelWithYield(provider, sessionPath, options));
336
+ }
337
+ return values;
338
+ }
339
+ async function enumerateSessionFilesAsyncFallback(provider, workspacePath, options) {
340
+ await yieldControl(options);
341
+ const paths = workspacePath
342
+ ? provider.findAllSessions(workspacePath)
343
+ : provider.listAllSessionFiles
344
+ ? provider.listAllSessionFiles().map((item) => item.path)
345
+ : provider
346
+ .getAllProjectFolders()
347
+ .flatMap((folder) => provider.findSessionsInDirectory(folder.dir));
348
+ return (await mapWithConcurrency([...new Set(paths)], async (sessionPath) => {
349
+ const info = await statSessionFileAsync(provider, sessionPath);
350
+ await yieldControl(options);
351
+ return info;
352
+ }, concurrency(options))).filter((item) => item !== null);
353
+ }
354
+ async function readSessionPreviewFromInfoAsync(provider, info, firstUserPrompt, options) {
355
+ let modifiedAt;
356
+ try {
357
+ modifiedAt = info.mtime.toISOString();
358
+ }
359
+ catch {
360
+ return null;
361
+ }
362
+ const prefix = await scanPrefixAsync(info.path, options.maxPrefixBytes ?? DEFAULT_PREFIX_BYTES);
363
+ return {
364
+ provider: provider.id,
365
+ sessionId: info.sessionId ?? safeSessionId(provider, info.path),
366
+ filePath: info.path,
367
+ modifiedAt,
368
+ sizeBytes: info.sizeBytes ?? 0,
369
+ firstUserPrompt,
370
+ firstTimestamp: prefix.firstTimestamp ?? info.createdAt?.toISOString() ?? null,
371
+ workspacePath: prefix.workspacePath ?? info.workspacePath ?? null,
372
+ };
373
+ }
374
+ async function extractLabelWithYield(provider, sessionPath, options) {
375
+ await yieldControl(options);
376
+ try {
377
+ return provider.extractSessionLabel(sessionPath);
378
+ }
379
+ catch {
380
+ return null;
381
+ }
382
+ }
383
+ function safeSessionId(provider, sessionPath) {
384
+ try {
385
+ return provider.getSessionId(sessionPath);
386
+ }
387
+ catch {
388
+ return '';
389
+ }
390
+ }
391
+ function concurrency(options) {
392
+ const requested = options.concurrency ?? DEFAULT_CONCURRENCY;
393
+ if (!Number.isFinite(requested))
394
+ return DEFAULT_CONCURRENCY;
395
+ return Math.min(MAX_CONCURRENCY, Math.max(1, Math.floor(requested)));
396
+ }
397
+ async function yieldControl(options) {
398
+ if (options.yieldBetweenReads) {
399
+ await options.yieldBetweenReads();
400
+ return;
401
+ }
402
+ await new Promise((resolve) => setImmediate(resolve));
403
+ }
404
+ async function mapWithConcurrency(values, mapper, maxConcurrency) {
405
+ const results = new Array(values.length);
406
+ let cursor = 0;
407
+ await Promise.all(Array.from({ length: Math.min(maxConcurrency, values.length) }, async () => {
408
+ while (true) {
409
+ const index = cursor++;
410
+ if (index >= values.length)
411
+ return;
412
+ results[index] = await mapper(values[index]);
413
+ }
414
+ }));
415
+ return results;
416
+ }
417
+ function providerDiagnostics(provider) {
418
+ try {
419
+ return [...(provider.getLastOperationStatus?.().diagnostics ?? [])];
420
+ }
421
+ catch {
422
+ return [];
423
+ }
424
+ }
425
+ function dedupeDiagnostics(diagnostics) {
426
+ const seen = new Set();
427
+ return diagnostics.filter((diagnostic) => {
428
+ const key = `${diagnostic.providerId}\0${diagnostic.kind}\0${diagnostic.phase}`;
429
+ if (seen.has(key))
430
+ return false;
431
+ seen.add(key);
432
+ return true;
433
+ });
434
+ }
435
+ /**
436
+ * Parses complete JSONL lines out of the first `maxPrefixBytes` of a file,
437
+ * taking the first top-level `timestamp` string and the first workspace path
438
+ * (top-level `cwd`, or `payload.cwd` on a Codex `session_meta` row). Partial
439
+ * trailing lines and malformed rows are skipped; never throws.
440
+ */
441
+ function scanPrefix(sessionPath, maxPrefixBytes) {
442
+ const result = { firstTimestamp: null, workspacePath: null };
443
+ let content;
444
+ let sawWholeFile;
445
+ try {
446
+ const descriptor = fs.openSync(sessionPath, 'r');
447
+ try {
448
+ const size = fs.fstatSync(descriptor).size;
449
+ const readBytes = Math.min(size, Math.max(1, maxPrefixBytes));
450
+ const buffer = Buffer.alloc(readBytes);
451
+ fs.readSync(descriptor, buffer, 0, readBytes, 0);
452
+ content = buffer.toString('utf8');
453
+ sawWholeFile = readBytes >= size;
454
+ }
455
+ finally {
456
+ fs.closeSync(descriptor);
457
+ }
458
+ }
459
+ catch {
460
+ return result;
461
+ }
462
+ const lines = content.split('\n');
463
+ // The final chunk after the last newline is a partial line unless the whole
464
+ // file fit in the prefix.
465
+ const completeLines = sawWholeFile ? lines : lines.slice(0, -1);
466
+ for (const line of completeLines) {
467
+ const trimmed = line.trim();
468
+ if (!trimmed)
469
+ continue;
470
+ let parsed;
471
+ try {
472
+ parsed = JSON.parse(trimmed);
473
+ }
474
+ catch {
475
+ continue;
476
+ }
477
+ if (parsed === null || typeof parsed !== 'object')
478
+ continue;
479
+ if (result.firstTimestamp === null && typeof parsed.timestamp === 'string') {
480
+ result.firstTimestamp = parsed.timestamp;
481
+ }
482
+ if (result.workspacePath === null) {
483
+ if (typeof parsed.cwd === 'string' && parsed.cwd) {
484
+ result.workspacePath = parsed.cwd;
485
+ }
486
+ else if (parsed.type === 'session_meta') {
487
+ const payload = parsed.payload;
488
+ if (payload && typeof payload.cwd === 'string' && payload.cwd) {
489
+ result.workspacePath = payload.cwd;
490
+ }
491
+ }
492
+ }
493
+ if (result.firstTimestamp !== null && result.workspacePath !== null)
494
+ break;
495
+ }
496
+ return result;
497
+ }
498
+ async function scanPrefixAsync(sessionPath, maxPrefixBytes) {
499
+ const result = { firstTimestamp: null, workspacePath: null };
500
+ let handle = null;
501
+ try {
502
+ handle = await fs.promises.open(sessionPath, 'r');
503
+ const stats = await handle.stat();
504
+ const readBytes = Math.min(stats.size, Math.max(1, maxPrefixBytes));
505
+ const buffer = Buffer.alloc(readBytes);
506
+ const { bytesRead } = await handle.read(buffer, 0, readBytes, 0);
507
+ parsePrefixInto(result, buffer.toString('utf8', 0, bytesRead), bytesRead >= stats.size);
508
+ }
509
+ catch {
510
+ return result;
511
+ }
512
+ finally {
513
+ await handle?.close().catch(() => undefined);
514
+ }
515
+ return result;
516
+ }
517
+ function parsePrefixInto(result, content, sawWholeFile) {
518
+ const lines = content.split('\n');
519
+ const completeLines = sawWholeFile ? lines : lines.slice(0, -1);
520
+ for (const line of completeLines) {
521
+ const trimmed = line.trim();
522
+ if (!trimmed)
523
+ continue;
524
+ let parsed;
525
+ try {
526
+ parsed = JSON.parse(trimmed);
527
+ }
528
+ catch {
529
+ continue;
530
+ }
531
+ if (parsed === null || typeof parsed !== 'object')
532
+ continue;
533
+ if (result.firstTimestamp === null && typeof parsed.timestamp === 'string') {
534
+ result.firstTimestamp = parsed.timestamp;
535
+ }
536
+ if (result.workspacePath === null) {
537
+ if (typeof parsed.cwd === 'string' && parsed.cwd)
538
+ result.workspacePath = parsed.cwd;
539
+ else if (parsed.type === 'session_meta') {
540
+ const payload = parsed.payload;
541
+ if (payload && typeof payload.cwd === 'string' && payload.cwd) {
542
+ result.workspacePath = payload.cwd;
543
+ }
544
+ }
545
+ }
546
+ if (result.firstTimestamp !== null && result.workspacePath !== null)
547
+ break;
548
+ }
549
+ }
@@ -7,17 +7,23 @@ const transcript_1 = require("./transcript");
7
7
  /** List recent sessions using the provider's existing discovery and metadata APIs. */
8
8
  function listRecentSessions(provider, workspacePath, options = {}) {
9
9
  const limit = Math.max(0, options.limit ?? 20);
10
+ // Sort on mtime alone first so labels — the only per-file content read —
11
+ // are extracted just for the returned slice, not every discovered session.
10
12
  return provider
11
13
  .findAllSessions(workspacePath)
12
14
  .map((sessionPath) => ({
13
- provider: provider.id,
14
- sessionId: provider.getSessionId(sessionPath),
15
15
  sessionPath,
16
- label: provider.extractSessionLabel(sessionPath),
17
16
  modifiedAt: sessionModifiedAt(provider, sessionPath).toISOString(),
18
17
  }))
19
18
  .sort((left, right) => right.modifiedAt.localeCompare(left.modifiedAt))
20
- .slice(0, limit);
19
+ .slice(0, limit)
20
+ .map(({ sessionPath, modifiedAt }) => ({
21
+ provider: provider.id,
22
+ sessionId: provider.getSessionId(sessionPath),
23
+ sessionPath,
24
+ label: provider.extractSessionLabel(sessionPath),
25
+ modifiedAt,
26
+ }));
21
27
  }
22
28
  function sessionModifiedAt(provider, sessionPath) {
23
29
  const metadata = provider.getSessionMetadata?.(sessionPath);
@@ -45,6 +45,8 @@ export interface ObservedAgentSessionV1 {
45
45
  costUsd: ObservedValueV1<number | null>;
46
46
  };
47
47
  pendingUserRequest: PendingUserRequestV1 | null;
48
+ /** When model/usage content was last read; unchanged on collector cache hits. */
49
+ contentObservedAt?: string;
48
50
  observedAt: string;
49
51
  }
50
52
  export interface ProviderCapabilitiesV1 {
@@ -67,6 +69,8 @@ export interface ProviderSessionAdapterV1 {
67
69
  dispose(): void;
68
70
  }
69
71
  export declare function derivePendingUserRequestV1(provider: ProviderId, sessionId: string, sourcePath: string, events: SessionEvent[]): PendingUserRequestV1 | null;
70
- export declare function createProviderSessionAdapterV1(sessionProvider: SessionProviderBase, options?: {
72
+ export interface ProviderSessionAdapterV1Options {
71
73
  pollIntervalMs?: number;
72
- }): ProviderSessionAdapterV1;
74
+ observationOnly?: boolean;
75
+ }
76
+ export declare function createProviderSessionAdapterV1(sessionProvider: SessionProviderBase, options?: ProviderSessionAdapterV1Options): ProviderSessionAdapterV1;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.derivePendingUserRequestV1 = derivePendingUserRequestV1;
4
4
  exports.createProviderSessionAdapterV1 = createProviderSessionAdapterV1;
5
5
  const transcript_1 = require("../transcript");
6
+ const sessionActivityDetector_1 = require("../parsers/sessionActivityDetector");
6
7
  function evidence(provider, sessionId, sourcePath, event, eventIndex) {
7
8
  return [
8
9
  {
@@ -98,13 +99,13 @@ function waitingToolPrompt(input, toolName) {
98
99
  return 'Approve the proposed plan?';
99
100
  return null;
100
101
  }
101
- function providerCapabilities(provider) {
102
+ function providerCapabilities(provider, observationOnly) {
102
103
  const refs = [];
103
104
  const known = (value) => observed(value, 'inferred', 1, refs);
104
105
  return {
105
106
  schemaVersion: 1,
106
107
  provider,
107
- resume: known(true),
108
+ resume: known(!observationOnly),
108
109
  forkLineage: known(provider !== 'opencode'),
109
110
  quotaSource: known(provider === 'claude-code' ? 'api' : provider === 'codex' ? 'mixed' : 'none'),
110
111
  assetExtraction: known(true),
@@ -115,7 +116,7 @@ function createProviderSessionAdapterV1(sessionProvider, options = {}) {
115
116
  const adapter = {
116
117
  schemaVersion: 1,
117
118
  provider: sessionProvider.id,
118
- capabilities: providerCapabilities(sessionProvider.id),
119
+ capabilities: providerCapabilities(sessionProvider.id, options.observationOnly === true),
119
120
  async discover(cwd) {
120
121
  return Promise.all(sessionProvider.findAllSessions(cwd).map((sessionPath) => adapter.read(sessionPath, cwd)));
121
122
  },
@@ -129,11 +130,15 @@ function createProviderSessionAdapterV1(sessionProvider, options = {}) {
129
130
  });
130
131
  const refs = evidence(sessionProvider.id, stats.sessionId, sessionPath);
131
132
  const model = Object.entries(stats.modelUsage).sort((left, right) => right[1].calls - left[1].calls)[0]?.[0] ?? null;
132
- const metadata = sessionProvider.getSessionMetadata?.(sessionPath);
133
- const modifiedAt = metadata?.mtime.getTime() ?? Date.parse(stats.endTime);
134
- const recent = Number.isFinite(modifiedAt) && Date.now() - modifiedAt < 2 * 60_000;
133
+ const activityResult = (0, sessionActivityDetector_1.detectSessionActivity)(sessionPath);
134
+ const activity = activityResult.state === 'ongoing'
135
+ ? 'active'
136
+ : activityResult.state === 'stale'
137
+ ? 'idle'
138
+ : 'ended';
135
139
  const allCostsReported = transcript.usage.costs.length > 0 &&
136
140
  transcript.usage.costs.every((cost) => cost.source === 'provider-reported');
141
+ const observedAt = new Date().toISOString();
137
142
  return {
138
143
  schemaVersion: 1,
139
144
  identity: {
@@ -143,7 +148,7 @@ function createProviderSessionAdapterV1(sessionProvider, options = {}) {
143
148
  },
144
149
  cwd: observed(cwd, 'inferred', cwd ? 0.95 : 0.4, refs),
145
150
  model: observed(model, model ? 'reported' : 'inferred', model ? 1 : 0.2, refs),
146
- activity: observed(recent ? 'active' : 'idle', 'inferred', 0.8, refs),
151
+ activity: observed(activity, 'inferred', 0.85, refs),
147
152
  usage: {
148
153
  inputTokens: observed(stats.tokens.input, 'reported', 1, refs),
149
154
  outputTokens: observed(stats.tokens.output, 'reported', 1, refs),
@@ -157,7 +162,8 @@ function createProviderSessionAdapterV1(sessionProvider, options = {}) {
157
162
  : 'estimated', allCostsReported ? 1 : transcript.usage.totalCostUsd === null ? 0.5 : 0.9, refs),
158
163
  },
159
164
  pendingUserRequest: derivePendingUserRequestV1(sessionProvider.id, stats.sessionId, sessionPath, events),
160
- observedAt: new Date().toISOString(),
165
+ contentObservedAt: observedAt,
166
+ observedAt,
161
167
  };
162
168
  },
163
169
  watch(sessionPath, listener, cwd) {
@@ -1,4 +1,24 @@
1
1
  export declare function atomicWriteJson(filePath: string, value: unknown): Promise<void>;
2
2
  export declare function atomicWriteJsonSync(filePath: string, value: unknown): void;
3
+ /** Raw-string sibling of {@link atomicWriteJsonSync} for non-JSON payloads. */
4
+ export declare function atomicWriteFileSync(filePath: string, content: string, mode?: number): void;
3
5
  /** Serializes read-modify-write cycles across Sidekick processes. */
4
6
  export declare function updateJsonStoreAtomic<T>(filePath: string, createEmpty: () => T, update: (latest: T) => T | Promise<T>): Promise<T>;
7
+ /**
8
+ * Synchronous counterpart of {@link acquireLock}, sharing its lock-file
9
+ * protocol so sync and async waiters exclude each other across processes.
10
+ *
11
+ * Two timeout rules apply instead of one: the same progress-based budget as the
12
+ * async path (a token that never changes trips it in LOCK_NO_PROGRESS_MS), plus
13
+ * an absolute {@link SYNC_LOCK_MAX_WAIT_MS} ceiling, because a sync waiter
14
+ * blocks its event loop while queued. Sync holders take no heartbeat — their
15
+ * critical sections must stay well under LOCK_STALE_MS (in-repo users are
16
+ * local-filesystem read-modify-writes, plus keychain reads behind the
17
+ * auth-swap locks that can take a few seconds).
18
+ *
19
+ * The caller must ensure `dirname(lockPath)` exists — a missing parent
20
+ * surfaces as a raw ENOENT, not a timeout.
21
+ */
22
+ export declare function withFileLockSync<T>(lockPath: string, operation: () => T): T;
23
+ /** Synchronous mirror of {@link updateJsonStoreAtomic}. */
24
+ export declare function updateJsonStoreAtomicSync<T>(filePath: string, createEmpty: () => T, update: (latest: T) => T): T;