sidekick-shared 0.26.1 → 0.26.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.
@@ -136,6 +136,8 @@ class ClaudeCodeReader {
136
136
  sessionPath;
137
137
  parser;
138
138
  filePosition = 0;
139
+ /** Cursor after the last complete line, safe to persist across restarts. */
140
+ committedPosition = 0;
139
141
  events = [];
140
142
  _wasTruncated = false;
141
143
  decoder = new string_decoder_1.StringDecoder('utf8');
@@ -165,6 +167,7 @@ class ClaudeCodeReader {
165
167
  if (currentSize < this.filePosition) {
166
168
  this._wasTruncated = true;
167
169
  this.filePosition = 0;
170
+ this.committedPosition = 0;
168
171
  this.parser.reset();
169
172
  this.decoder = new string_decoder_1.StringDecoder('utf8');
170
173
  }
@@ -183,7 +186,11 @@ class ClaudeCodeReader {
183
186
  finally {
184
187
  fs.closeSync(fd);
185
188
  }
186
- const chunk = this.decoder.write(buffer.subarray(0, bytesRead));
189
+ const bytes = buffer.subarray(0, bytesRead);
190
+ const newline = bytes.lastIndexOf(0x0a);
191
+ if (newline >= 0)
192
+ this.committedPosition = this.filePosition + newline + 1;
193
+ const chunk = this.decoder.write(bytes);
187
194
  this.parser.processChunk(chunk);
188
195
  this.filePosition += bytesRead;
189
196
  }
@@ -198,6 +205,7 @@ class ClaudeCodeReader {
198
205
  }
199
206
  reset() {
200
207
  this.filePosition = 0;
208
+ this.committedPosition = 0;
201
209
  this.parser.reset();
202
210
  this.decoder = new string_decoder_1.StringDecoder('utf8');
203
211
  this._wasTruncated = false;
@@ -213,10 +221,11 @@ class ClaudeCodeReader {
213
221
  this.decoder = new string_decoder_1.StringDecoder('utf8');
214
222
  }
215
223
  getPosition() {
216
- return this.filePosition;
224
+ return this.committedPosition;
217
225
  }
218
226
  seekTo(position) {
219
227
  this.filePosition = position;
228
+ this.committedPosition = position;
220
229
  this.parser.reset();
221
230
  this.decoder = new string_decoder_1.StringDecoder('utf8');
222
231
  }
@@ -473,6 +473,8 @@ class CodexReader {
473
473
  onTokenUsage;
474
474
  parser;
475
475
  filePosition = 0;
476
+ /** Cursor after the last complete line, safe to persist across restarts. */
477
+ committedPosition = 0;
476
478
  lineBuffer = '';
477
479
  _wasTruncated = false;
478
480
  decoder = new string_decoder_1.StringDecoder('utf8');
@@ -487,18 +489,19 @@ class CodexReader {
487
489
  getSessionMeta() {
488
490
  return this.parser.getSessionMeta();
489
491
  }
490
- readNew() {
492
+ readNew(endPosition) {
491
493
  this._wasTruncated = false;
492
494
  const events = [];
493
495
  try {
494
496
  if (!fs.existsSync(this.rolloutPath))
495
497
  return [];
496
498
  const stats = fs.statSync(this.rolloutPath);
497
- const currentSize = stats.size;
499
+ const currentSize = Math.min(stats.size, endPosition ?? stats.size);
498
500
  // Handle truncation
499
501
  if (currentSize < this.filePosition) {
500
502
  this._wasTruncated = true;
501
503
  this.filePosition = 0;
504
+ this.committedPosition = 0;
502
505
  this.lineBuffer = '';
503
506
  this.parser.reset();
504
507
  this.decoder = new string_decoder_1.StringDecoder('utf8');
@@ -517,7 +520,11 @@ class CodexReader {
517
520
  finally {
518
521
  fs.closeSync(fd);
519
522
  }
520
- const chunk = this.decoder.write(buffer.subarray(0, bytesRead));
523
+ const bytes = buffer.subarray(0, bytesRead);
524
+ const newline = bytes.lastIndexOf(0x0a);
525
+ if (newline >= 0)
526
+ this.committedPosition = this.filePosition + newline + 1;
527
+ const chunk = this.decoder.write(bytes);
521
528
  this.filePosition += bytesRead;
522
529
  // Process lines
523
530
  const text = this.lineBuffer + chunk;
@@ -583,6 +590,7 @@ class CodexReader {
583
590
  }
584
591
  reset() {
585
592
  this.filePosition = 0;
593
+ this.committedPosition = 0;
586
594
  this.lineBuffer = '';
587
595
  this.parser.reset();
588
596
  this.decoder = new string_decoder_1.StringDecoder('utf8');
@@ -606,12 +614,14 @@ class CodexReader {
606
614
  this.decoder = new string_decoder_1.StringDecoder('utf8');
607
615
  }
608
616
  getPosition() {
609
- return this.filePosition;
617
+ return this.committedPosition;
610
618
  }
611
619
  seekTo(position) {
612
- this.filePosition = position;
613
- this.lineBuffer = '';
614
- this.decoder = new string_decoder_1.StringDecoder('utf8');
620
+ // Rebuild model, turn, and cumulative-token context before resuming.
621
+ // The prefix is parsed only; its events are already in the consumer snapshot.
622
+ this.reset();
623
+ if (position > 0)
624
+ this.readNew(position);
615
625
  }
616
626
  wasTruncated() {
617
627
  return this._wasTruncated;
@@ -1,6 +1,4 @@
1
- /**
2
- * Provider-aware cross-session search.
3
- */
1
+ /** Provider-aware cross-session search. */
4
2
  import type { SessionProviderBase, ProviderId } from '../providers/types';
5
3
  export interface SearchResult {
6
4
  providerId: ProviderId;
@@ -10,7 +8,13 @@ export interface SearchResult {
10
8
  eventType: string;
11
9
  timestamp: string;
12
10
  }
13
- export declare function searchSessions(provider: SessionProviderBase, query: string, opts?: {
11
+ export interface SessionSearchOptions {
12
+ /** Workspace path, resolved canonically. Takes precedence over projectSlug. */
13
+ projectPath?: string;
14
+ /** Legacy provider-encoded project identifier. */
14
15
  projectSlug?: string;
15
16
  maxResults?: number;
16
- }): Promise<SearchResult[]>;
17
+ /** Stop obsolete interactive searches between session reads. */
18
+ signal?: AbortSignal;
19
+ }
20
+ export declare function searchSessions(provider: SessionProviderBase, query: string, options?: SessionSearchOptions): Promise<SearchResult[]>;
@@ -1,98 +1,69 @@
1
1
  "use strict";
2
- /**
3
- * Provider-aware cross-session search.
4
- */
5
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- var desc = Object.getOwnPropertyDescriptor(m, k);
8
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
- desc = { enumerable: true, get: function() { return m[k]; } };
10
- }
11
- Object.defineProperty(o, k2, desc);
12
- }) : (function(o, m, k, k2) {
13
- if (k2 === undefined) k2 = k;
14
- o[k2] = m[k];
15
- }));
16
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
- Object.defineProperty(o, "default", { enumerable: true, value: v });
18
- }) : function(o, v) {
19
- o["default"] = v;
20
- });
21
- var __importStar = (this && this.__importStar) || (function () {
22
- var ownKeys = function(o) {
23
- ownKeys = Object.getOwnPropertyNames || function (o) {
24
- var ar = [];
25
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
- return ar;
27
- };
28
- return ownKeys(o);
29
- };
30
- return function (mod) {
31
- if (mod && mod.__esModule) return mod;
32
- var result = {};
33
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
- __setModuleDefault(result, mod);
35
- return result;
36
- };
37
- })();
2
+ /** Provider-aware cross-session search. */
38
3
  Object.defineProperty(exports, "__esModule", { value: true });
39
4
  exports.searchSessions = searchSessions;
40
- const fs = __importStar(require("fs"));
41
- const path = __importStar(require("path"));
42
- async function searchSessions(provider, query, opts) {
43
- const maxResults = opts?.maxResults ?? 50;
5
+ const paths_1 = require("../paths");
6
+ async function enumerateSessions(provider, options) {
7
+ const workspace = options.projectPath
8
+ ? (0, paths_1.resolveProjectIdentity)(options.projectPath).resolvedCwd
9
+ : undefined;
10
+ if (!options.projectSlug || workspace) {
11
+ if (provider.listSessionFilesAsync)
12
+ return provider.listSessionFilesAsync(workspace);
13
+ if (workspace) {
14
+ return provider
15
+ .findAllSessions(workspace)
16
+ .map((path) => ({ path, mtime: new Date(0), workspacePath: workspace }));
17
+ }
18
+ if (provider.listAllSessionFiles)
19
+ return provider.listAllSessionFiles();
20
+ }
21
+ // Older/custom providers can expose virtual project directories. Let the
22
+ // provider enumerate them instead of assuming a particular on-disk layout.
23
+ const files = [];
24
+ for (const folder of provider.getAllProjectFolders()) {
25
+ if (options.signal?.aborted)
26
+ break;
27
+ if (options.projectSlug && folder.encodedName !== options.projectSlug)
28
+ continue;
29
+ const paths = provider.id === 'codex'
30
+ ? provider.findAllSessions(folder.name)
31
+ : provider.findSessionsInDirectory(folder.dir);
32
+ files.push(...paths.map((path) => ({ path, mtime: folder.lastModified, workspacePath: folder.name })));
33
+ }
34
+ return files;
35
+ }
36
+ async function searchSessions(provider, query, options = {}) {
37
+ const maxResults = options.maxResults ?? 50;
44
38
  const results = [];
45
- const baseDir = provider.getProjectsBaseDir();
46
- try {
47
- if (!fs.existsSync(baseDir))
48
- return results;
49
- // Get all project folders
50
- const folders = provider.getAllProjectFolders();
51
- for (const folder of folders) {
52
- if (results.length >= maxResults)
53
- break;
54
- // If projectSlug specified, filter by encoded name
55
- if (opts?.projectSlug && folder.encodedName !== opts.projectSlug)
56
- continue;
57
- // Get session files in this folder
58
- let sessionFiles = [];
59
- try {
60
- const dir = folder.dir;
61
- if (fs.existsSync(dir)) {
62
- const entries = fs
63
- .readdirSync(dir)
64
- .filter((f) => f.endsWith('.jsonl') || f.endsWith('.json'));
65
- sessionFiles = entries.map((f) => path.join(dir, f));
66
- }
67
- }
68
- catch {
69
- /* skip */
70
- }
71
- // If no files found from dir scan, try findAllSessions with the folder name
72
- if (sessionFiles.length === 0) {
73
- // Let canonical directory discovery handle synthetic DB-backed paths.
74
- sessionFiles = provider.findSessionsInDirectory(folder.dir);
75
- }
76
- for (const sessionPath of sessionFiles) {
77
- if (results.length >= maxResults)
78
- break;
79
- const remaining = maxResults - results.length;
80
- const hits = provider.searchInSession(sessionPath, query, remaining);
81
- for (const hit of hits) {
82
- results.push({
83
- providerId: provider.id,
84
- projectPath: hit.projectPath || folder.name,
85
- sessionPath: hit.sessionPath,
86
- snippet: hit.line,
87
- eventType: hit.eventType,
88
- timestamp: hit.timestamp,
89
- });
90
- }
39
+ if (maxResults <= 0 || !query.trim() || options.signal?.aborted)
40
+ return results;
41
+ const files = await enumerateSessions(provider, options);
42
+ const seen = new Set();
43
+ files.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
44
+ for (const file of files) {
45
+ if (results.length >= maxResults || options.signal?.aborted)
46
+ break;
47
+ if (seen.has(file.path))
48
+ continue;
49
+ seen.add(file.path);
50
+ try {
51
+ const hits = provider.searchInSession(file.path, query, maxResults - results.length);
52
+ for (const hit of hits.slice(0, maxResults - results.length)) {
53
+ results.push({
54
+ providerId: provider.id,
55
+ projectPath: hit.projectPath || file.workspacePath || '',
56
+ sessionPath: hit.sessionPath,
57
+ snippet: hit.line,
58
+ eventType: hit.eventType,
59
+ timestamp: hit.timestamp,
60
+ });
91
61
  }
92
62
  }
63
+ catch {
64
+ // An unreadable session must not hide matches in the remaining sessions.
65
+ }
66
+ await new Promise((resolve) => setImmediate(resolve));
93
67
  }
94
- catch {
95
- /* skip */
96
- }
97
- return results.slice(0, maxResults);
68
+ return results;
98
69
  }
@@ -38,17 +38,11 @@ var __importStar = (this && this.__importStar) || (function () {
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.resolveSessionPath = resolveSessionPath;
40
40
  exports.createWatcher = createWatcher;
41
- const os = __importStar(require("os"));
42
41
  const path = __importStar(require("path"));
42
+ const openCode_1 = require("../providers/openCode");
43
43
  const jsonlWatcher_1 = require("./jsonlWatcher");
44
44
  const providerReaderWatcher_1 = require("./providerReaderWatcher");
45
45
  const sqliteWatcher_1 = require("./sqliteWatcher");
46
- function getOpenCodeDataDir() {
47
- const xdg = process.env.XDG_DATA_HOME;
48
- if (xdg)
49
- return path.join(xdg, 'opencode');
50
- return path.join(os.homedir(), '.local', 'share', 'opencode');
51
- }
52
46
  /**
53
47
  * Resolve the session a command should act on: an exact or unique-prefix
54
48
  * match of `sessionId` among the workspace's sessions, or the most recent
@@ -94,7 +88,7 @@ function createWatcherForProvider(provider, sessionPath, callbacks) {
94
88
  case 'codex':
95
89
  return new providerReaderWatcher_1.ProviderReaderSessionWatcher(provider, sessionPath, callbacks);
96
90
  case 'opencode': {
97
- const dataDir = getOpenCodeDataDir();
91
+ const dataDir = (0, openCode_1.getOpenCodeDataDir)();
98
92
  const dbPath = path.join(dataDir, 'opencode.db');
99
93
  // Session ID is the basename without extension
100
94
  const sid = path.basename(sessionPath, '.json');
@@ -42,6 +42,26 @@ const fs = __importStar(require("fs"));
42
42
  const jsonl_1 = require("../parsers/jsonl");
43
43
  const DEFAULT_DEBOUNCE_MS = 100;
44
44
  const DEFAULT_CATCHUP_INTERVAL_MS = 30_000;
45
+ /** Skip old complete events while retaining an in-progress final line. */
46
+ function lastCompleteLineOffset(filePath) {
47
+ const fd = fs.openSync(filePath, 'r');
48
+ try {
49
+ let end = fs.fstatSync(fd).size;
50
+ const buffer = Buffer.alloc(64 * 1024);
51
+ while (end > 0) {
52
+ const start = Math.max(0, end - buffer.length);
53
+ const count = fs.readSync(fd, buffer, 0, end - start, start);
54
+ const newline = buffer.subarray(0, count).lastIndexOf(0x0a);
55
+ if (newline >= 0)
56
+ return start + newline + 1;
57
+ end = start;
58
+ }
59
+ return 0;
60
+ }
61
+ finally {
62
+ fs.closeSync(fd);
63
+ }
64
+ }
45
65
  function createJsonlTail(options) {
46
66
  return new JsonlTailReader(options);
47
67
  }
@@ -79,7 +99,7 @@ class JsonlTailReader {
79
99
  this.active = true;
80
100
  if (this.options.startAtEnd && this.options.startOffset === undefined) {
81
101
  try {
82
- this.readOffset = fs.statSync(this.options.path).size;
102
+ this.readOffset = lastCompleteLineOffset(this.options.path);
83
103
  }
84
104
  catch {
85
105
  this.readOffset = 0;
@@ -179,7 +199,11 @@ class JsonlTailReader {
179
199
  this.fsWatcher = fs.watch(this.options.path, { persistent: false }, () => {
180
200
  this.debouncedRead();
181
201
  });
182
- this.fsWatcher.on('error', (error) => this.options.onError?.(error));
202
+ this.fsWatcher.on('error', (error) => {
203
+ this.fsWatcher?.close();
204
+ this.fsWatcher = null;
205
+ this.options.onError?.(error);
206
+ });
183
207
  }
184
208
  catch {
185
209
  // Polling still covers filesystems where fs.watch is unavailable.
@@ -5,26 +5,20 @@
5
5
  import type { ProviderId } from '../providers/types';
6
6
  import type { SessionWatcher, SessionWatcherCallbacks } from './types';
7
7
  export declare class JsonlSessionWatcher implements SessionWatcher {
8
- private _isActive;
9
- private filePosition;
10
- private fsWatcher;
11
- private catchupTimer;
12
- private debounceTimer;
13
- private codexInPlanMode;
14
- private readonly parser;
15
8
  private readonly providerId;
16
9
  private readonly sessionPath;
17
10
  private readonly callbacks;
11
+ private tail;
12
+ private startOffset;
13
+ private codexInPlanMode;
18
14
  constructor(providerId: ProviderId, sessionPath: string, callbacks: SessionWatcherCallbacks);
19
15
  get isActive(): boolean;
20
- /** Seek to a byte offset. Must be called before start(). */
16
+ /** Seek to a committed byte offset before starting replay. */
21
17
  seekTo(position: number): void;
22
- /** Get the current byte position. */
18
+ /** Position after the last complete JSONL line. */
23
19
  getPosition(): number;
24
20
  start(replay: boolean): void;
25
21
  stop(): void;
26
- private debouncedRead;
27
- private readNewBytes;
28
22
  private handleRawEvent;
29
23
  private normalizeCodexEvent;
30
24
  }
@@ -3,47 +3,11 @@
3
3
  * JSONL session watcher for Claude Code and Codex.
4
4
  * Uses byte-offset tracking + fs.watch with debounce + catch-up polling.
5
5
  */
6
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
- if (k2 === undefined) k2 = k;
8
- var desc = Object.getOwnPropertyDescriptor(m, k);
9
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
- desc = { enumerable: true, get: function() { return m[k]; } };
11
- }
12
- Object.defineProperty(o, k2, desc);
13
- }) : (function(o, m, k, k2) {
14
- if (k2 === undefined) k2 = k;
15
- o[k2] = m[k];
16
- }));
17
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
- Object.defineProperty(o, "default", { enumerable: true, value: v });
19
- }) : function(o, v) {
20
- o["default"] = v;
21
- });
22
- var __importStar = (this && this.__importStar) || (function () {
23
- var ownKeys = function(o) {
24
- ownKeys = Object.getOwnPropertyNames || function (o) {
25
- var ar = [];
26
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
- return ar;
28
- };
29
- return ownKeys(o);
30
- };
31
- return function (mod) {
32
- if (mod && mod.__esModule) return mod;
33
- var result = {};
34
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
- __setModuleDefault(result, mod);
36
- return result;
37
- };
38
- })();
39
6
  Object.defineProperty(exports, "__esModule", { value: true });
40
7
  exports.JsonlSessionWatcher = void 0;
41
- const fs = __importStar(require("fs"));
42
- const jsonl_1 = require("../parsers/jsonl");
8
+ const jsonlTail_1 = require("./jsonlTail");
43
9
  const codexParser_1 = require("../parsers/codexParser");
44
10
  const toolSummary_1 = require("../formatters/toolSummary");
45
- const DEBOUNCE_MS = 100;
46
- const CATCHUP_INTERVAL_MS = 30_000;
47
11
  // ── Normalizers ──
48
12
  function normalizeClaudeCodeEvent(raw) {
49
13
  const events = [];
@@ -220,139 +184,46 @@ function truncate(text, maxLen) {
220
184
  }
221
185
  // ── Watcher ──
222
186
  class JsonlSessionWatcher {
223
- _isActive = false;
224
- filePosition = 0;
225
- fsWatcher = null;
226
- catchupTimer = null;
227
- debounceTimer = null;
228
- codexInPlanMode = false;
229
- parser;
230
187
  providerId;
231
188
  sessionPath;
232
189
  callbacks;
190
+ tail;
191
+ startOffset;
192
+ codexInPlanMode = false;
233
193
  constructor(providerId, sessionPath, callbacks) {
234
194
  this.providerId = providerId;
235
195
  this.sessionPath = sessionPath;
236
196
  this.callbacks = callbacks;
237
- this.parser = new jsonl_1.JsonlParser({
238
- onEvent: (event) => this.handleRawEvent(event),
239
- onError: (err) => callbacks.onError?.(err),
240
- });
241
197
  }
242
198
  get isActive() {
243
- return this._isActive;
199
+ return this.tail?.isActive ?? false;
244
200
  }
245
- /** Seek to a byte offset. Must be called before start(). */
201
+ /** Seek to a committed byte offset before starting replay. */
246
202
  seekTo(position) {
247
- this.filePosition = position;
248
- this.parser.reset();
203
+ this.startOffset = Math.max(0, position);
204
+ this.tail?.seekTo(this.startOffset);
249
205
  }
250
- /** Get the current byte position. */
206
+ /** Position after the last complete JSONL line. */
251
207
  getPosition() {
252
- return this.filePosition;
208
+ return this.tail?.getOffset() ?? this.startOffset ?? 0;
253
209
  }
254
210
  start(replay) {
255
- if (this._isActive)
211
+ if (this.isActive)
256
212
  return;
257
- this._isActive = true;
258
- if (replay) {
259
- // Read entire file from offset 0
260
- this.readNewBytes();
261
- }
262
- else {
263
- // Skip to end of file
264
- try {
265
- const stat = fs.statSync(this.sessionPath);
266
- this.filePosition = stat.size;
267
- }
268
- catch {
269
- this.filePosition = 0;
270
- }
271
- }
272
- // Watch for changes
273
- try {
274
- this.fsWatcher = fs.watch(this.sessionPath, { persistent: false }, () => {
275
- this.debouncedRead();
276
- });
277
- this.fsWatcher.on('error', (error) => {
278
- // Degrade to catch-up polling without killing the live session.
279
- this.fsWatcher?.close();
280
- this.fsWatcher = null;
281
- this.callbacks.onError?.(error);
282
- });
283
- }
284
- catch {
285
- // fs.watch not available, rely on polling only
286
- }
287
- // Catch-up polling
288
- this.catchupTimer = setInterval(() => {
289
- if (this._isActive)
290
- this.readNewBytes();
291
- }, CATCHUP_INTERVAL_MS);
213
+ this.tail = (0, jsonlTail_1.createJsonlTail)({
214
+ path: this.sessionPath,
215
+ startOffset: replay ? this.getPosition() : undefined,
216
+ startAtEnd: !replay,
217
+ onEvent: (event) => this.handleRawEvent(event),
218
+ onBatchComplete: () => this.callbacks.onBatchComplete?.(),
219
+ onError: (error) => this.callbacks.onError?.(error),
220
+ });
221
+ this.tail.start();
292
222
  }
293
223
  stop() {
294
- if (!this._isActive)
295
- return;
296
- this._isActive = false;
297
- if (this.debounceTimer) {
298
- clearTimeout(this.debounceTimer);
299
- this.debounceTimer = null;
300
- }
301
- if (this.fsWatcher) {
302
- this.fsWatcher.close();
303
- this.fsWatcher = null;
304
- }
305
- if (this.catchupTimer) {
306
- clearInterval(this.catchupTimer);
307
- this.catchupTimer = null;
308
- }
309
- this.parser.flush();
224
+ this.tail?.stop();
310
225
  this.codexInPlanMode = false;
311
226
  }
312
- debouncedRead() {
313
- if (this.debounceTimer)
314
- clearTimeout(this.debounceTimer);
315
- this.debounceTimer = setTimeout(() => {
316
- this.readNewBytes();
317
- }, DEBOUNCE_MS);
318
- }
319
- readNewBytes() {
320
- if (!this._isActive)
321
- return;
322
- let fd = null;
323
- try {
324
- const stat = fs.statSync(this.sessionPath);
325
- // Handle file truncation (shouldn't happen with append-only, but be safe)
326
- if (stat.size < this.filePosition) {
327
- this.filePosition = 0;
328
- this.parser.reset();
329
- }
330
- if (stat.size <= this.filePosition)
331
- return;
332
- fd = fs.openSync(this.sessionPath, 'r');
333
- const bytesToRead = stat.size - this.filePosition;
334
- const buffer = Buffer.alloc(bytesToRead);
335
- const bytesRead = fs.readSync(fd, buffer, 0, bytesToRead, this.filePosition);
336
- fs.closeSync(fd);
337
- fd = null;
338
- if (bytesRead > 0) {
339
- this.filePosition += bytesRead;
340
- const chunk = buffer.toString('utf-8', 0, bytesRead);
341
- this.parser.processChunk(chunk);
342
- }
343
- }
344
- catch (err) {
345
- if (fd !== null) {
346
- try {
347
- fs.closeSync(fd);
348
- }
349
- catch {
350
- /* ignore */
351
- }
352
- }
353
- this.callbacks.onError?.(err instanceof Error ? err : new Error(String(err)));
354
- }
355
- }
356
227
  handleRawEvent(event) {
357
228
  // For codex, raw events don't match RawSessionEvent shape exactly, but
358
229
  // JsonlParser parses any JSON object. Cast to Record for codex normalizer.
@@ -112,12 +112,13 @@ class ProviderReaderSessionWatcher {
112
112
  clearInterval(this.catchupTimer);
113
113
  this.catchupTimer = null;
114
114
  }
115
- this.reader.flush();
115
+ // Keep unfinished input buffered so a later start can resume losslessly.
116
116
  }
117
117
  seekToEnd() {
118
118
  try {
119
- const stat = fs.statSync(this.sessionPath);
120
- this.reader.seekTo(stat.size);
119
+ // Consume existing complete records to retain parser context and any
120
+ // unfinished line, without emitting historical events.
121
+ this.reader.readNew();
121
122
  }
122
123
  catch {
123
124
  this.reader.reset();
@@ -143,6 +144,7 @@ class ProviderReaderSessionWatcher {
143
144
  this.callbacks.onEvent(followEvent);
144
145
  }
145
146
  }
147
+ this.callbacks.onBatchComplete?.();
146
148
  }
147
149
  catch (err) {
148
150
  this.callbacks.onError?.(err instanceof Error ? err : new Error(String(err)));
@@ -312,6 +312,7 @@ class SqliteSessionWatcher {
312
312
  if (part.time_updated > this.lastPartTime)
313
313
  this.lastPartTime = part.time_updated;
314
314
  }
315
+ this.callbacks.onBatchComplete?.();
315
316
  }
316
317
  catch (err) {
317
318
  this.callbacks.onError?.(err instanceof Error ? err : new Error(String(err)));
@@ -46,6 +46,8 @@ export interface FollowEvent {
46
46
  }
47
47
  export interface SessionWatcherCallbacks {
48
48
  onEvent: (event: FollowEvent) => void;
49
+ /** All events in this read have been delivered; the cursor can now be checkpointed. */
50
+ onBatchComplete?: () => void;
49
51
  onError?: (error: Error) => void;
50
52
  }
51
53
  export interface SessionWatcher {