Repository navigation
Expand file tree
/
Copy pathcli-session-state.js
More file actions
1334 lines (1240 loc) · 52.9 KB
/
Copy pathcli-session-state.js
File metadata and controls
1334 lines (1240 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// see .ai/contexts/cli-session-state.md
'use strict';
const fs = require('fs');
const { execFile } = require('child_process');
const os = require('os');
const path = require('path');
const { bridgeSessionKey } = require('./bridge-session-id');
const { procStartMatches, toCreated, WINDOWS_FILETIME_RE, PROC_START_TOLERANCE } = require('./src/main/cli/proc-start');
const DEFAULT_DIR = path.join(os.homedir(), '.claude', 'sessions');
const STATE_FILE_RE = /^\d+\.json$/;
const KNOWN_STATUSES = new Set(['busy', 'idle', 'waiting', 'shell']);
const RESCAN_STATUS = 'idle';
const FLUSH_MS = 150;
const MIN_RESCAN_INTERVAL_MS = 1000;
const MAX_SEEDED_FILES = 200;
const MAX_LIVE_QUERY_IDS = 200;
const GET_STATUS_PROBE_THROTTLE_MS = 5000;
const MAX_PROBE_PIDS = 64;
const PROBE_TIMEOUT_MS = 5000;
const PROCESS_TABLE_TIMEOUT_MS = 15000;
const PROCESS_TABLE_TTL_MS = 3000;
const PROCESS_TABLE_MAX_BUFFER = 4 << 20;
const PROCESS_TABLE_LOG_WINDOW_MS = 60000;
let dir = DEFAULT_DIR;
let activeSessions = null;
let onIdle = null;
let onOwnerExit = null;
let log = null;
let isProcessAlive = defaultIsProcessAlive;
let readProcStart = defaultReadProcStart;
let readProcStartMany = defaultReadProcStartMany;
let readParentPid = defaultReadParentPid;
let readCliProcess = defaultReadCliProcess;
let readRealpath = fs.realpathSync;
let readProcessTable = defaultReadProcessTable;
let processTableEnabled = false;
let processTableEpoch = 0;
let processTable = null;
let processTableInFlight = null;
let processTableFailureLoggedAt = -Infinity;
const rosterOwnership = new Map();
let probeWindow = null;
let probeWindowTimer = null;
let probeWindowEpoch = 0;
let scheduleProbeWindow = setTimeout;
let cancelProbeWindow = clearTimeout;
let ownPid = process.pid;
let now = Date.now;
let platform = process.platform;
let deliveryInitialized = false;
let watcher = null;
let flushTimer = null;
let livenessTimer = null;
const pending = new Set();
const known = new Map();
const lastRescanAt = new Map();
// sessionId -> { status, statusUpdatedAt, pid } for live pids only -- see .ai/contexts/cli-session-state.md
const statusBySession = new Map();
let staleSidebarIdentity = '[]';
const lastProbeAt = new Map();
const statusKey = (sessionId) => String(sessionId).toLowerCase();
const MAX_DESCRIPTOR_SCAN = 1000;
// Listeners told "the directory changed" after each flushed batch -- see .ai/contexts/bg-agents.md
const descriptorListeners = new Set();
const statusListeners = new Set();
const pendingOwnerDeaths = new Map();
const scheduledRuns = new Map();
let v1Reader;
function liveElsewhereV1Checked(id, hasPty, ptyPids, options = {}) {
if (Object.hasOwn(options, 'processTable')) options = { ...options,
processTable: { ...options.processTable, expiresAt: (options.processTable?.at ?? -Infinity) + PROCESS_TABLE_TTL_MS } };
return v1Reader ? v1Reader.liveElsewhereV1Checked(id, hasPty, ptyPids, options) : Promise.resolve({ known: false, reason: 'reader not initialized' });
}
function observeTabWriterV1(binding) {
return v1Reader ? v1Reader.observeTabWriterV1(binding) : { uncertain: true };
}
async function readStatusEvidence(id, deadline, options = {}) {
const bounded = async fn => {
let timer;
try { return await Promise.race([Promise.resolve().then(fn), new Promise(resolve => {
timer = setTimeout(() => resolve(null), Math.max(0, deadline - now()));
})]); } finally { clearTimeout(timer); }
};
if (now() >= deadline) return null;
const read = () => bounded(() => liveElsewhereV1Checked(id, () => false, () => [], { deadline, requireUnique: true, ...options }));
let result = await read();
if (now() >= deadline) return null;
if (result?.known && !result.live && !result.ambiguous) return result;
if (Object.hasOwn(options, 'processTable')) return result?.known || result?.ambiguous ? result : null;
if (platform === 'win32') {
await bounded(() => refreshProcessTable());
const evidence = readWorkerProcessEvidence();
if (!evidence.processTableFresh || now() - evidence.observedAt >= PROCESS_TABLE_TTL_MS || now() >= deadline) return null;
result = await read();
}
if (now() >= deadline || platform === 'win32' && (!processTableFresh()
|| now() - processTable.observedAt >= PROCESS_TABLE_TTL_MS)) return null;
if (result?.ambiguous) return result;
if (!result?.known || result.live && (!result.live.procStart || platform === 'linux' && !result.live.namespace)) return null;
return result;
}
function trackScheduleRun(sessionId, child, cwd, scheduleName) {
const key = sessionId.toLowerCase();
const live = { kind: 'schedule', pid: child.pid, cwd, startedAt: Date.now(), scheduleName };
scheduledRuns.set(key, live);
notifyStatusesChanged();
const release = () => {
if (scheduledRuns.get(key) !== live) return;
scheduledRuns.delete(key);
notifyStatusesChanged();
};
child.once('exit', release);
child.once('error', release);
}
function isScheduleRunLive(sessionId) {
return scheduledRuns.has(sessionId.toLowerCase());
}
function getScheduleRunSnapshot() {
return Array.from(scheduledRuns, ([sessionId, run]) => ({ sessionId, ...run }));
}
function annotateScheduleRuns(projects) {
for (const project of projects) for (const session of project.sessions) {
const ids = [...new Set([session.sessionId, session.headSessionId, ...(session.mergedMemberIds || [])].filter(Boolean))];
const live = project.remoteAlias || session.remoteAlias ? [] : ids.filter(id => scheduledRuns.has(id.toLowerCase()));
if (live.length) session.runningScheduleIds = live;
else delete session.runningScheduleIds;
}
return projects;
}
function defaultIsProcessAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === 'EPERM';
}
}
function defaultReadParentPid(pid) {
if (processTableEnabled) return tableEntry(pid) ? (tableEntry(pid).ppid ?? null) : null;
if (process.platform !== 'linux') return null;
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
return Number.isInteger(ppid) && ppid > 0 ? ppid : null;
} catch {
return null;
}
}
const TABLE_LINE_RE = /^\s*(\d+)\s+(\d+)(?:\s+(\d+))?\s*(?:\t(.*))?$/;
const TABLE_LSTART_RE = /^\s*(\d+)\s+(\d+)\s+([A-Za-z]{3}\s+[A-Za-z]{3}\s+\d+\s+[\d:]+\s+\d{4})\s*$/;
function parseProcessTable(text) {
const out = new Map();
for (const line of String(text).split(/\r?\n/)) {
let m = TABLE_LINE_RE.exec(line);
if (m) { out.set(Number(m[1]), { ppid: Number(m[2]), created: toCreated(m[3]), ...(m[4] === undefined ? {} : { commandLine: m[4] }) }); continue; }
m = TABLE_LSTART_RE.exec(line);
if (m) {
const ms = Date.parse(m[3]);
out.set(Number(m[1]), { ppid: Number(m[2]), created: Number.isFinite(ms) ? BigInt(ms) : null });
}
}
return out;
}
function probeProcessTable(plat = process.platform, timeoutMs = PROCESS_TABLE_TIMEOUT_MS, exec = execFile, signal) {
return new Promise((resolve, reject) => {
const opts = { timeout: timeoutMs, windowsHide: true, maxBuffer: PROCESS_TABLE_MAX_BUFFER, ...(signal ? { signal } : {}) };
const done = (err, stdout, stderr) => {
if (err) { err.stderr = String(stderr || '').slice(0, 300); err.timedOut = err.killed === true && err.signal === 'SIGTERM'; reject(err); return; }
resolve(parseProcessTable(stdout));
};
if (plat === 'win32') {
const script = 'Get-CimInstance -ClassName Win32_Process | ForEach-Object { $t = if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { "" }; "$($_.ProcessId) $($_.ParentProcessId) $t`t$($_.CommandLine)" }';
const exe = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
exec(exe, ['-NoProfile', '-NonInteractive', '-Command', script], opts, done);
} else if (plat === 'darwin') {
exec('/bin/ps', ['-A', '-o', 'pid=,ppid=,lstart='], opts, done);
} else {
resolve(new Map());
}
});
}
function defaultReadProcessTable(timeoutMs, { signal } = {}) {
return probeProcessTable(process.platform, timeoutMs, execFile, signal);
}
function processTableFresh() {
return !!processTable && now() - processTable.at < PROCESS_TABLE_TTL_MS;
}
function deliveryProcessTableFresh() {
return !processTableEnabled || (processTableFresh() && !!processTable.map);
}
function normaliseProcessTable(read) {
if (!(read instanceof Map) || read.size === 0) return null;
const out = new Map();
for (const [pid, value] of read) {
if (typeof value === 'number') out.set(pid, { ppid: value, created: null });
else if (value && typeof value === 'object') out.set(pid, { ppid: value.ppid, created: toCreated(value.created), ...(value.commandLine === undefined ? {} : { commandLine: value.commandLine }) });
}
return out.size > 0 ? out : null;
}
function flushProbeWindow() {
const window = probeWindow;
if (probeWindowTimer) cancelProbeWindow(probeWindowTimer);
probeWindowTimer = null;
probeWindow = null;
if (!window || !(window.timeout || window.error || window.caller.timeout || window.caller.error || window.aborted)) return;
const durations = window.durations.sort((a, b) => a - b);
log.info?.(`[cli-state] process table probes: windowMs=${PROCESS_TABLE_LOG_WINDOW_MS} timeoutBudgetMs=${PROCESS_TABLE_TIMEOUT_MS}`
+ ` ok=${window.ok} timeout=${window.timeout} error=${window.error} maxMs=${durations.at(-1) ?? 'n/a'} p95Ms=${durations[Math.ceil(durations.length * 0.95) - 1] ?? 'n/a'}`
+ ` callerOk=${window.caller.ok} callerTimeout=${window.caller.timeout} callerError=${window.caller.error} aborted=${window.aborted}`);
}
function recordProcessTableProbe(outcome, duration, timeoutMs) {
if (probeWindow && now() - probeWindow.at >= PROCESS_TABLE_LOG_WINDOW_MS) flushProbeWindow();
if (!probeWindow) {
probeWindow = { at: now(), ok: 0, timeout: 0, error: 0, durations: [], caller: { ok: 0, timeout: 0, error: 0 }, aborted: 0 };
probeWindowTimer = scheduleProbeWindow(flushProbeWindow, PROCESS_TABLE_LOG_WINDOW_MS);
probeWindowTimer.unref?.();
}
if (outcome === 'aborted') probeWindow.aborted++;
else if (timeoutMs === PROCESS_TABLE_TIMEOUT_MS) {
probeWindow[outcome]++;
probeWindow.durations.push(duration);
} else probeWindow.caller[outcome]++;
}
function measureProcessTable(timeoutMs, options) {
const epoch = probeWindowEpoch;
const started = now();
return (map, err) => {
let outcome = map ? 'ok' : 'error';
if (err?.code === 'ABORT_ERR' || err?.name === 'AbortError') outcome = 'aborted';
else if (err?.timedOut === true) outcome = 'timeout';
if (options?.signal?.aborted) outcome = 'aborted';
if (epoch === probeWindowEpoch) recordProcessTableProbe(outcome, Math.max(0, now() - started), timeoutMs);
};
}
function refreshProcessTable({ force = false, deadline = Infinity } = {}) {
if (!processTableEnabled) return Promise.resolve(null);
if (!force && processTableFresh()) return Promise.resolve(processTable.map);
if (processTableInFlight) return processTableInFlight;
const epoch = processTableEpoch;
const observedAt = now();
const inFlight = (async () => {
let map = null;
let error;
const timeoutMs = Math.max(1, Math.min(PROCESS_TABLE_TIMEOUT_MS, deadline - now()));
const record = measureProcessTable(timeoutMs);
try {
map = normaliseProcessTable(await readProcessTable(timeoutMs));
} catch (err) {
error = err;
if (now() - processTableFailureLoggedAt >= PROCESS_TABLE_LOG_WINDOW_MS) {
processTableFailureLoggedAt = now();
log.debug(`[cli-state] process table unreadable: exit=${err?.code ?? 'unknown'} timeout=${err?.timedOut === true} stderr=${JSON.stringify(String(err?.stderr || '').slice(0, 300))}`);
}
} finally { record(map, error); }
if (epoch === processTableEpoch) {
processTable = { at: now(), observedAt, map };
processTableInFlight = null;
if (map) {
for (const pid of rosterOwnership.keys()) if (!map.has(pid)) rosterOwnership.delete(pid);
const stale = JSON.stringify([...known.values()].filter(entry => sidebarDescriptorIsStale(statusKey(entry.sessionId), entry))
.map(entry => [statusKey(entry.sessionId), entry.pid]).sort());
const sidebarChanged = stale !== staleSidebarIdentity;
staleSidebarIdentity = stale;
if (sidebarChanged) notifyStatusesChanged();
notifyDescriptorsChanged();
}
}
return map;
})();
processTableInFlight = inFlight;
return inFlight;
}
async function readProcessTableSnapshot(deadline, { fresh = false, signal } = {}) {
if (!processTableEnabled) return undefined;
if (fresh) {
const observedAt = now();
let map = null;
if (!signal?.aborted && observedAt < deadline) {
const timeoutMs = Math.min(PROCESS_TABLE_TIMEOUT_MS, deadline - observedAt);
const record = measureProcessTable(timeoutMs, { signal });
let error;
try { map = normaliseProcessTable(await readProcessTable(timeoutMs, { signal })); }
catch (err) { error = err; }
finally { record(map, error); }
}
if (signal?.aborted || now() >= deadline) map = null;
const at = now();
return { at, observedAt, map, expiresAt: at + PROCESS_TABLE_TTL_MS };
}
await refreshProcessTable({ deadline });
return processTable ? { ...processTable, expiresAt: processTable.at + PROCESS_TABLE_TTL_MS } : { map: null };
}
function startProcessTableRefresh() {
if (!processTableEnabled || processTableFresh() || processTableInFlight) return;
refreshProcessTable().catch(() => {});
}
function tableEntry(pid) {
return processTable && processTable.map ? processTable.map.get(pid) : undefined;
}
function readWorkerProcessEvidence() {
const table = processTable?.map;
return { processTableFresh: processTableFresh() && !!table, observedAt: processTable?.observedAt,
tableEntry: pid => table?.get(pid) };
}
function chainReaches(pid, isAnchor, strict) {
let current = pid;
for (let depth = 0; depth < 64 && current && current > 1; depth++) {
if (isAnchor(current)) return true;
const parent = readParentPid(current);
if (!parent) return false;
if (processTableEnabled) {
const child = tableEntry(current);
const above = tableEntry(parent);
const known = !!child && !!above && child.created != null && above.created != null;
if (strict && !known) return false;
if (known && child.created < above.created) return false;
}
current = parent;
}
return false;
}
// see .ai/contexts/cli-session-state.md ("Live elsewhere")
function descendsFromThisProcess(pid, own = null) {
return chainReaches(pid, (current) => current === ownPid || (own !== null && own.has(current)), false);
}
function leafIsTheDescriptorWriter(raw) {
const leaf = tableEntry(raw.pid);
if (!leaf || leaf.created == null) return false;
return raw.pidDomain === 'win32:anchor'
&& procStartMatches(leaf.created, raw.procStart);
}
function conversationOwns(raw, own) {
if (own.size === 0) return false;
if (!processTableEnabled) return own.has(raw.pid) || chainReaches(raw.pid, (current) => own.has(current), false);
return leafIsTheDescriptorWriter(raw) && chainReaches(raw.pid, (current) => own.has(current), true);
}
function defaultReadProcStart(pid) {
if (process.platform !== 'linux') return null;
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
return fields[19] || null;
} catch {
return null;
}
}
// see .ai/contexts/trigger-watcher.md
function defaultReadCliProcess(pid) {
let args;
if (processTableEnabled) {
const commandLine = processTableFresh() ? tableEntry(pid)?.commandLine : null;
if (!commandLine) return null;
const executable = /^"([^"]*)"|^((?:[A-Za-z]:[\\/]|\\\\)[^"\r\n]*?\.exe)(?=\s|$)|^(\S+)/i.exec(commandLine.trim());
if (!executable) return null;
args = [executable[1] ?? executable[2] ?? executable[3]];
const rest = commandLine.trim().slice(executable[0].length);
const tokens = /"([^"]*)"|((?:[A-Za-z]:[\\/]|\\\\)[^"\r\n]*?\.(?:[cm]?js))(?=\s|$)|(\S+)/gi;
args.push(...[...rest.matchAll(tokens)].map(match => match[1] ?? match[2] ?? match[3]));
} else {
if (platform !== 'linux') return null;
try { args = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').filter(Boolean); } catch { return null; }
}
if (!args.length) return null;
const name = value => value.replaceAll('\\', '/').split('/').pop().toLowerCase();
if (/^claude(?:\.exe)?$/.test(name(args[0]))) return true;
const script = args.slice(1).find(arg => !arg.startsWith('-'));
if (!/^node(?:\.exe)?$/.test(name(args[0])) || typeof script !== 'string') return false;
const cliScript = /(?:^|[\\/])@anthropic-ai[\\/]claude-code[\\/]cli\.js$/i;
if (cliScript.test(script)) return true;
try { return cliScript.test(readRealpath(script)); } catch { return false; }
}
// see .ai/contexts/cli-session-state.md
function probeProcStartWindows(pids, timeoutMs = PROBE_TIMEOUT_MS, exec = execFile) {
const ids = [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);
if (ids.length === 0) return Promise.resolve(new Map());
const script = `Get-Process -Id ${ids.join(',')} -ErrorAction SilentlyContinue | ForEach-Object { try { "$($_.Id) $($_.StartTime.ToFileTimeUtc())" } catch {} }; exit 0`;
const exe = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
return new Promise((resolve, reject) => {
exec(exe, ['-NoProfile', '-NonInteractive', '-Command', script],
{ timeout: timeoutMs, windowsHide: true, maxBuffer: 1 << 20 },
(err, stdout) => {
if (err && (err.killed || typeof err.code !== 'number')) { reject(err); return; }
const out = new Map();
for (const line of String(stdout).split(/\r?\n/)) {
const m = /^(\d+) (\d+)$/.exec(line.trim());
if (m) out.set(Number(m[1]), m[2]);
}
resolve(out);
});
});
}
async function defaultReadProcStartMany(pids) {
if (process.platform === 'win32') return probeProcStartWindows(pids);
const out = new Map();
if (process.platform !== 'linux') return out;
for (const pid of pids) {
const start = defaultReadProcStart(pid);
if (start != null) out.set(pid, start);
}
return out;
}
function init(ctx) {
deliveryInitialized = true;
dir = ctx.dir || DEFAULT_DIR;
activeSessions = ctx.activeSessions;
onIdle = ctx.onIdle;
onOwnerExit = ctx.onOwnerExit || null;
log = ctx.log || { info() {}, debug() {}, warn() {}, error() {} };
isProcessAlive = ctx.isProcessAlive || defaultIsProcessAlive;
readProcStart = ctx.readProcStart || defaultReadProcStart;
readProcStartMany = ctx.readProcStartMany
|| (ctx.readProcStart
? async (pids) => new Map(pids.map((pid) => [pid, ctx.readProcStart(pid)]))
: defaultReadProcStartMany);
now = ctx.now || Date.now;
platform = ctx.platform || process.platform;
readParentPid = ctx.readParentPid || defaultReadParentPid;
readCliProcess = ctx.readCliProcess || defaultReadCliProcess;
readRealpath = ctx.readRealpath || fs.realpathSync;
ownPid = ctx.ownPid || process.pid;
v1Reader = require('./src/main/cli/session-state-v1').createV1Reader({ dir, parseDescriptor, parseState,
platform, now, procFs: ctx.v1ProcFs, descriptorFs: ctx.v1DescriptorFs,
readProcStartMany: ctx.readProcStartMany || ctx.readProcStart ? readProcStartMany
: (pids, deadline) => platform === 'win32'
? probeProcStartWindows(pids, Math.max(1, Math.min(PROBE_TIMEOUT_MS, deadline - now()))) : readProcStartMany(pids),
readParentPid, readCliProcess, scheduledRuns, procStartMatches, isProcessAlive });
processTableEnabled = !ctx.readParentPid && (platform === 'win32' || platform === 'darwin');
readProcessTable = ctx.readProcessTable || defaultReadProcessTable;
processTableEpoch++;
processTable = null;
staleSidebarIdentity = '[]';
processTableInFlight = null;
stop();
processTableFailureLoggedAt = -Infinity;
scheduleProbeWindow = ctx.schedule || setTimeout;
cancelProbeWindow = ctx.cancel || clearTimeout;
}
function parseState(text) {
let raw;
try { raw = JSON.parse(text); } catch { return null; }
if (!raw || typeof raw !== 'object') return null;
if (!Number.isInteger(raw.pid) || raw.pid <= 0) return null;
if (typeof raw.sessionId !== 'string' || !raw.sessionId) return null;
if (typeof raw.status !== 'string' || !KNOWN_STATUSES.has(raw.status)) return null;
return {
pid: raw.pid,
sessionId: raw.sessionId,
status: raw.status,
statusUpdatedAt: Number.isInteger(raw.statusUpdatedAt) ? raw.statusUpdatedAt : null,
waitingFor: typeof raw.waitingFor === 'string' && raw.waitingFor ? raw.waitingFor : null,
procStart: raw.procStart == null ? null : String(raw.procStart),
};
}
// The descriptor subset the agents view reads -- see .ai/contexts/bg-agents.md
function parseDescriptor(text) {
let raw;
try { raw = JSON.parse(text); } catch { return null; }
if (!raw || typeof raw !== 'object') return null;
if (!Number.isInteger(raw.pid) || raw.pid <= 0) return null;
if (typeof raw.sessionId !== 'string' || !raw.sessionId) return null;
const s = (v) => (typeof v === 'string' && v ? v : null);
return {
pid: raw.pid,
sessionId: raw.sessionId,
kind: s(raw.kind),
bridgeSessionId: s(raw.bridgeSessionId),
jobId: s(raw.jobId),
agent: s(raw.agent),
name: s(raw.name),
...(s(raw.nameSource) ? { nameSource: s(raw.nameSource) } : {}),
cwd: s(raw.cwd),
status: KNOWN_STATUSES.has(raw.status) ? raw.status : null,
startedAt: Number.isFinite(raw.startedAt) ? raw.startedAt : null,
};
}
function readAllDescriptors() {
startProcessTableRefresh();
let names;
try { names = fs.readdirSync(dir); } catch { return []; }
const out = [];
let seen = 0;
for (const name of names) {
if (!STATE_FILE_RE.test(name)) continue;
if (++seen > MAX_DESCRIPTOR_SCAN) break;
let text;
try { text = fs.readFileSync(path.join(dir, name), 'utf8'); } catch { continue; }
const d = parseDescriptor(text);
if (!d || !isProcessAlive(d.pid)) continue;
let raw;
try {
raw = JSON.parse(text);
raw.descriptorMtimeMs = fs.statSync(path.join(dir, name)).mtimeMs;
} catch { continue; }
if (deliveryProcessIdentity(raw) !== 'stale') out.push(d);
}
return out;
}
// see .ai/contexts/session-state.md ("Proven continuation re-key")
function getDescriptorIdentity(snapshot = {}) {
Object.assign(snapshot, readWriterDescriptors());
if (!snapshot.descriptors) return null;
return JSON.stringify([...new Set([...snapshot.descriptors.values()].map(d => JSON.stringify([d.sessionId, d.pid])))].sort());
}
function onDescriptorsChanged(listener) {
descriptorListeners.add(listener);
return () => { descriptorListeners.delete(listener); };
}
function notifyDescriptorsChanged() {
for (const listener of descriptorListeners) {
try { listener(); } catch (err) { log.warn(`[cli-state] descriptor listener failed: ${err.message}`); }
}
}
function onStatusesChanged(listener) {
statusListeners.add(listener);
return () => { statusListeners.delete(listener); };
}
function notifyStatusesChanged() {
for (const listener of statusListeners) {
try { listener(); } catch (err) { log.warn('[cli-state] status listener failed: ' + err.message); }
}
}
function notifyOwnerExit(sessionId, pid) {
for (const entry of known.values()) {
if (entry.pid === pid && statusKey(entry.sessionId) === statusKey(sessionId)) entry.exited = true;
}
if (!onOwnerExit) return;
const key = statusKey(sessionId);
if (pendingOwnerDeaths.has(key)) return;
const callback = onOwnerExit;
pendingOwnerDeaths.set(key, pid);
queueMicrotask(() => {
if (!pendingOwnerDeaths.has(key)) return;
pendingOwnerDeaths.delete(key);
const current = statusBySession.get(key);
const currentExited = current && [...known.values()].some(entry => entry.exited
&& entry.pid === current.pid && statusKey(entry.sessionId) === key);
if (current && !currentExited && isProcessAlive(current.pid)) return;
if ([...known.values()].some(entry => statusKey(entry.sessionId) === key && !entry.exited && isProcessAlive(entry.pid))) return;
if (currentExited) {
forgetSession(key, current.pid);
notifyDescriptorsChanged();
notifyStatusesChanged();
}
try { callback(key); } catch (err) { log.warn(`[cli-state] owner-exit callback failed: ${err.message}`); }
});
}
function findSession(sessionId) {
if (!activeSessions) return null;
for (const [key, session] of activeSessions) {
if (!session || session.exited || session.isPlainTerminal || session.isAttach || !session.projectFolder) continue;
const effectiveId = session.realSessionId || key;
if (statusKey(effectiveId) === statusKey(sessionId)) return { sessionId: effectiveId, session };
}
return null;
}
function retainAfterMiss(name, deleted) {
const stale = known.get(name);
if (!stale) return;
if (deleted && !isProcessAlive(stale.pid)) {
notifyOwnerExit(stale.sessionId, stale.pid);
forgetSession(stale.sessionId, stale.pid);
known.delete(name);
return;
}
stale.missedProbes ??= 0;
}
function handleFile(name) {
let text;
try {
text = fs.readFileSync(path.join(dir, name), 'utf8');
} catch (err) {
retainAfterMiss(name, err.code === 'ENOENT');
return;
}
const state = parseState(text);
if (!state) {
retainAfterMiss(name, false);
return;
}
const prev = known.get(name);
const identity = { ...parseDescriptor(text), ...state, pidDomain: JSON.parse(text).pidDomain };
try { identity.descriptorMtimeMs = fs.statSync(path.join(dir, name)).mtimeMs; } catch {}
known.set(name, identity);
if (prev && prev.sessionId && statusKey(prev.sessionId) !== statusKey(state.sessionId)) forgetSession(prev.sessionId, prev.pid);
if (isProcessAlive(state.pid)) {
rememberStatus(identity);
} else {
notifyOwnerExit(state.sessionId, state.pid);
forgetSession(state.sessionId, state.pid);
}
const reused = !!prev && prev.procStart !== state.procStart;
if (!prev || reused) return;
if (prev.status === state.status) return;
if (state.status !== RESCAN_STATUS) return;
if (!isProcessAlive(state.pid)) return;
const match = findSession(state.sessionId);
if (!match) {
log.debug(`[cli-state] no active session for ${state.sessionId} (pid ${state.pid})`);
return;
}
const now = Date.now();
const last = lastRescanAt.get(statusKey(match.sessionId)) || 0;
if (now - last < MIN_RESCAN_INTERVAL_MS) return;
lastRescanAt.set(statusKey(match.sessionId), now);
try {
onIdle(match.sessionId, match.session);
} catch (err) {
log.warn(`[cli-state] rescan failed for ${match.sessionId}: ${err.message}`);
}
}
function flush() {
flushTimer = null;
const batch = [...pending];
pending.clear();
const previous = new Map(statusBySession);
for (const name of batch) handleFile(name);
armLivenessProbe();
if (previous.size !== statusBySession.size || [...statusBySession].some(([id, entry]) => {
const prev = previous.get(id);
return sidebarStateChanged(prev, entry);
})) notifyStatusesChanged();
if (batch.length > 0) notifyDescriptorsChanged();
}
function armLivenessProbe() {
if (livenessTimer || !watcher || statusBySession.size === 0) return;
livenessTimer = setTimeout(() => {
livenessTimer = null;
const previous = new Map(statusBySession);
for (const [name, stale] of known) {
if (stale.missedProbes == null || !statusBySession.has(statusKey(stale.sessionId))) continue;
handleFile(name);
const retained = known.get(name);
if (retained && retained.missedProbes != null && ++retained.missedProbes >= 2) {
forgetSession(retained.sessionId, retained.pid);
known.delete(name);
}
}
for (const [id, entry] of statusBySession) {
if (!isProcessAlive(entry.pid)) {
notifyOwnerExit(id, entry.pid);
forgetSession(id, entry.pid);
}
}
if (previous.size !== statusBySession.size || [...statusBySession].some(([id, entry]) => {
const prev = previous.get(id);
return sidebarStateChanged(prev, entry);
})) {
notifyDescriptorsChanged();
notifyStatusesChanged();
}
armLivenessProbe();
}, GET_STATUS_PROBE_THROTTLE_MS);
if (typeof livenessTimer.unref === 'function') livenessTimer.unref();
}
function seed() {
let names;
try { names = fs.readdirSync(dir); } catch { return; }
const files = names.filter(n => STATE_FILE_RE.test(n));
if (files.length > MAX_SEEDED_FILES) return;
for (const name of files) {
let text;
try { text = fs.readFileSync(path.join(dir, name), 'utf8'); } catch { continue; }
const state = parseState(text);
if (state) {
const identity = { ...parseDescriptor(text), ...state, pidDomain: JSON.parse(text).pidDomain };
try { identity.descriptorMtimeMs = fs.statSync(path.join(dir, name)).mtimeMs; } catch {}
known.set(name, identity);
if (isProcessAlive(state.pid)) {
rememberStatus(identity);
} else {
notifyOwnerExit(state.sessionId, state.pid);
}
}
}
}
function rememberStatus(state) {
const key = statusKey(state.sessionId);
if (deliveryProcessIdentity(state) === 'stale') return;
statusBySession.set(key, { ...parseDescriptor(JSON.stringify(state)),
statusUpdatedAt: state.statusUpdatedAt, waitingFor: state.waitingFor });
}
function forgetSession(sessionId, pid) {
const key = statusKey(sessionId);
if (statusBySession.get(key)?.pid !== pid) return;
statusBySession.delete(key);
lastProbeAt.delete(key);
}
function ensureWatching() {
if (watcher) return true;
if (!onIdle || !activeSessions) return false;
try {
if (!fs.statSync(dir).isDirectory()) return false;
} catch {
return false;
}
seed();
try {
watcher = fs.watch(dir, (_eventType, filename) => {
if (!filename || !STATE_FILE_RE.test(filename)) return;
pending.add(filename);
if (flushTimer) return;
flushTimer = setTimeout(flush, FLUSH_MS);
if (typeof flushTimer.unref === 'function') flushTimer.unref();
});
watcher.on('error', (err) => {
log.warn(`[cli-state] watcher error: ${err.message}`);
stop();
});
} catch (err) {
watcher = null;
log.warn(`[cli-state] cannot watch ${dir}: ${err.message}`);
return false;
}
armLivenessProbe();
log.info(`[cli-state] watching ${dir}`);
return true;
}
function stop() {
probeWindowEpoch++;
if (probeWindowTimer) cancelProbeWindow(probeWindowTimer);
probeWindowTimer = null;
probeWindow = null;
rosterOwnership.clear();
pendingOwnerDeaths.clear();
const hadStatus = statusBySession.size > 0;
if (watcher) {
try { watcher.close(); } catch {}
watcher = null;
}
if (flushTimer) {
clearTimeout(flushTimer);
flushTimer = null;
}
if (livenessTimer) {
clearTimeout(livenessTimer);
livenessTimer = null;
}
pending.clear();
known.clear();
statusBySession.clear();
staleSidebarIdentity = '[]';
lastRescanAt.clear();
lastProbeAt.clear();
if (hadStatus) {
notifyDescriptorsChanged();
notifyStatusesChanged();
}
}
// Lookup + throttled lazy liveness re-probe -- see .ai/contexts/cli-session-state.md ("the one invariant" still holds: never arms onIdle).
function getStatus(sessionId) {
const key = statusKey(sessionId);
let entry = statusBySession.get(key);
if (!entry) return undefined;
if ([...known.values()].some(writer => writer.exited && writer.pid === entry.pid && statusKey(writer.sessionId) === key)) {
notifyOwnerExit(sessionId, entry.pid);
forgetSession(sessionId, entry.pid);
notifyDescriptorsChanged();
notifyStatusesChanged();
return undefined;
}
if (sidebarDescriptorIsStale(key, entry)) {
const replacement = liveKnownDescriptors().find(state => statusKey(state.sessionId) === key);
if (!replacement) return undefined;
forgetSession(sessionId, entry.pid);
rememberStatus(replacement);
entry = statusBySession.get(key);
}
const t = now();
const last = lastProbeAt.get(key) || 0;
if (t - last >= GET_STATUS_PROBE_THROTTLE_MS) {
lastProbeAt.set(key, t);
if (!isProcessAlive(entry.pid)) {
notifyOwnerExit(sessionId, entry.pid);
forgetSession(sessionId, entry.pid);
notifyDescriptorsChanged();
notifyStatusesChanged();
return undefined;
}
}
return { status: entry.status, statusUpdatedAt: entry.statusUpdatedAt, waitingFor: entry.waitingFor };
}
function sidebarStateChanged(previous, entry) {
return !previous || ['status', 'waitingFor', 'pid', 'kind', 'jobId', 'name', 'nameSource', 'cwd'].some(field => previous[field] !== entry[field]);
}
function liveKnownDescriptors() {
return [...known.values()].filter(entry => {
if (entry.exited) return false;
if (!isProcessAlive(entry.pid)) {
entry.exited = true;
return false;
}
return !sidebarDescriptorIsStale(statusKey(entry.sessionId), entry);
})
.sort((a, b) => (a.startedAt ?? Infinity) - (b.startedAt ?? Infinity) || a.pid - b.pid);
}
function getSidebarDescriptors({ allWriters = false } = {}) {
startProcessTableRefresh();
if (allWriters) return liveKnownDescriptors().map(entry => ({ ...parseDescriptor(JSON.stringify(entry)),
statusUpdatedAt: entry.statusUpdatedAt, waitingFor: entry.waitingFor }));
const descriptors = [];
for (const id of [...statusBySession.keys()]) {
if (!getStatus(id)) continue;
const current = statusBySession.get(id);
if (!sidebarDescriptorIsStale(id, current)) descriptors.push({ ...current });
}
return descriptors;
}
function sidebarDescriptorIsStale(id, entry) {
const writer = [...known.values()].find(s => s.pid === entry.pid && statusKey(s.sessionId) === id);
if (!writer) return true;
if (processTableEnabled && (!processTableFresh() || !processTable.map)) {
return JSON.parse(staleSidebarIdentity).some(([sessionId, pid]) => sessionId === id && pid === entry.pid);
}
return deliveryProcessIdentity(writer) === 'stale';
}
function canCompareProcStart(raw) {
if (raw.procStart == null) return false;
const windowsDescriptor = typeof raw.pidDomain === 'string' && raw.pidDomain.startsWith('win32:');
if (platform === 'win32' || windowsDescriptor) {
return raw.pidDomain === 'win32:anchor'
&& typeof raw.procStart === 'string'
&& WINDOWS_FILETIME_RE.test(raw.procStart);
}
return true;
}
// On-demand scan, independent of the watcher -- see .ai/contexts/cli-session-state.md ("Live elsewhere")
async function scanLiveProcessesChecked(sessionIds, exclude) {
const found = new Map();
if (sessionIds.size === 0) return { found, unreadable: null };
let names;
try { names = fs.readdirSync(dir).sort(); } catch (err) {
return { found, unreadable: err && err.code === 'ENOENT' ? null : `cannot read ${dir}: ${err && err.message}` };
}
let unreadable = null;
const alive = [];
for (const name of names) {
if (!STATE_FILE_RE.test(name)) continue;
let raw;
try { raw = JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')); } catch (err) {
if (!(err && err.code === 'ENOENT')) unreadable = unreadable || `cannot read ${path.join(dir, name)}`;
continue;
}
if (!raw || typeof raw !== 'object' || typeof raw.sessionId !== 'string') continue;
const keys = [...sessionIds].filter(key => raw.sessionId.toLowerCase() === key
|| (bridgeSessionKey(key) !== null && bridgeSessionKey(key) === bridgeSessionKey(raw.bridgeSessionId)));
if (!keys.length) continue;
if (!Number.isInteger(raw.pid) || raw.pid <= 0) continue;
if (!isProcessAlive(raw.pid)) continue;
alive.push({ ...raw, keys });
}
if (typeof exclude.needsProcessTable === 'function' && alive.some((raw) => raw.keys.some((key) => exclude.needsProcessTable(key)))) await refreshProcessTable();
const candidates = alive.filter((raw) => !raw.keys.every((key) => exclude(raw.pid, raw, key)));
const comparable = [...new Set(candidates.filter(canCompareProcStart).map((raw) => raw.pid))];
const toProbe = platform === 'win32' ? comparable.slice(0, MAX_PROBE_PIDS) : comparable;
let actualByPid = new Map();
if (toProbe.length > 0) {
try {
const probed = await readProcStartMany(toProbe);
if (probed instanceof Map) actualByPid = probed;
} catch {}
}
for (const raw of candidates) {
if (canCompareProcStart(raw) && toProbe.includes(raw.pid)) {
const actual = actualByPid.get(raw.pid);
if (actual != null && String(actual) !== String(raw.procStart)) continue;
}
const live = {
pid: raw.pid,
cwd: typeof raw.cwd === 'string' ? raw.cwd : null,
startedAt: Number.isFinite(raw.startedAt) ? raw.startedAt : null,
kind: typeof raw.kind === 'string' && raw.kind ? raw.kind : null,
jobId: typeof raw.jobId === 'string' && raw.jobId ? raw.jobId : null,
};
for (const key of raw.keys) if (!found.has(key)) found.set(key, live);
}
return { found, unreadable };
}
async function scanLiveProcesses(sessionIds, exclude) {
return (await scanLiveProcessesChecked(sessionIds, exclude)).found;
}
async function findLiveProcess(sessionId, { exclude = () => false } = {}) {
if (typeof sessionId !== 'string' || !sessionId) return null;
const key = sessionId.toLowerCase();
return (await scanLiveProcesses(new Set([key]), exclude)).get(key) || null;
}
// see .ai/contexts/cli-session-state.md ("Owner of a /clear transcript")
function clearOwner(sessionId, ptyPid, { closestWriter = false, descriptorSnapshot } = {}) {
if (typeof sessionId !== 'string' || !sessionId || !Number.isInteger(ptyPid)) return 'pending';
if (closestWriter) return closestWriterOwner(sessionId, ptyPid,
descriptorSnapshot && descriptorSnapshot.descriptors ? descriptorSnapshot : readWriterDescriptors());
let names;
try { names = fs.readdirSync(dir); } catch { return 'pending'; }
const key = sessionId.toLowerCase();
let pid = null;
let found = null;
for (const name of names) {
if (!STATE_FILE_RE.test(name)) continue;
let raw;
try { raw = JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')); } catch { continue; }
if (!raw || typeof raw.sessionId !== 'string' || raw.sessionId.toLowerCase() !== key) continue;
if (!Number.isInteger(raw.pid) || raw.pid <= 0) continue;
if (!isProcessAlive(raw.pid)) continue;
pid = raw.pid;
found = raw;
break;
}
if (pid == null) return 'pending';
if (processTableEnabled) {
startProcessTableRefresh();
if (!tableEntry(pid)) return 'pending';
return conversationOwns(found, new Set([ptyPid])) ? 'mine' : 'other';
}
let current = pid;
for (let depth = 0; depth < 64 && current && current > 1; depth++) {
if (current === ptyPid) return 'mine';
const parent = readParentPid(current);
if (parent == null) return depth === 0 ? 'unknown' : 'other';
current = parent;
}
return 'other';
}
// see .ai/contexts/session-state.md ("Proven continuation re-key")