forked from doctly/switchboard
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli-session-state.js
More file actions
228 lines (205 loc) · 6.46 KB
/
Copy pathcli-session-state.js
File metadata and controls
228 lines (205 loc) · 6.46 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
// see .ai/contexts/cli-session-state.md
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
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 GET_STATUS_PROBE_THROTTLE_MS = 5000;
let dir = DEFAULT_DIR;
let activeSessions = null;
let onIdle = null;
let log = null;
let isProcessAlive = defaultIsProcessAlive;
let now = Date.now;
let watcher = null;
let flushTimer = 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();
const lastProbeAt = new Map();
function defaultIsProcessAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === 'EPERM';
}
}
function init(ctx) {
dir = ctx.dir || DEFAULT_DIR;
activeSessions = ctx.activeSessions;
onIdle = ctx.onIdle;
log = ctx.log || { info() {}, debug() {}, warn() {}, error() {} };
isProcessAlive = ctx.isProcessAlive || defaultIsProcessAlive;
now = ctx.now || Date.now;
stop();
}
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,
procStart: raw.procStart == null ? null : String(raw.procStart),
};
}
function findSession(sessionId) {
if (!activeSessions) return null;
for (const [key, session] of activeSessions) {
if (!session || session.exited || session.isPlainTerminal || !session.projectFolder) continue;
const effectiveId = session.realSessionId || key;
if (effectiveId === sessionId) return { sessionId: effectiveId, session };
}
return null;
}
function handleFile(name) {
let text;
try {
text = fs.readFileSync(path.join(dir, name), 'utf8');
} catch {
const stale = known.get(name);
if (stale && stale.sessionId) forgetSession(stale.sessionId);
known.delete(name);
return;
}
const state = parseState(text);
if (!state) return;
const prev = known.get(name);
if (prev && prev.sessionId && prev.sessionId !== state.sessionId) forgetSession(prev.sessionId);
known.set(name, { procStart: state.procStart, status: state.status, sessionId: state.sessionId });
if (isProcessAlive(state.pid)) {
statusBySession.set(state.sessionId, { status: state.status, statusUpdatedAt: state.statusUpdatedAt, pid: state.pid });
} else {
forgetSession(state.sessionId);
}
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(match.sessionId) || 0;
if (now - last < MIN_RESCAN_INTERVAL_MS) return;
lastRescanAt.set(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();
for (const name of batch) handleFile(name);
}
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) {
known.set(name, { procStart: state.procStart, status: state.status, sessionId: state.sessionId });
if (isProcessAlive(state.pid)) {
statusBySession.set(state.sessionId, { status: state.status, statusUpdatedAt: state.statusUpdatedAt, pid: state.pid });
}
}
}
}
function forgetSession(sessionId) {
statusBySession.delete(sessionId);
lastProbeAt.delete(sessionId);
}
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;
}
log.info(`[cli-state] watching ${dir}`);
return true;
}
function stop() {
if (watcher) {
try { watcher.close(); } catch {}
watcher = null;
}
if (flushTimer) {
clearTimeout(flushTimer);
flushTimer = null;
}
pending.clear();
known.clear();
statusBySession.clear();
lastRescanAt.clear();
lastProbeAt.clear();
}
// 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 entry = statusBySession.get(sessionId);
if (!entry) return undefined;
const t = now();
const last = lastProbeAt.get(sessionId) || 0;
if (t - last >= GET_STATUS_PROBE_THROTTLE_MS) {
lastProbeAt.set(sessionId, t);
if (!isProcessAlive(entry.pid)) {
forgetSession(sessionId);
return undefined;
}
}
return { status: entry.status, statusUpdatedAt: entry.statusUpdatedAt };
}
module.exports = {
init,
ensureWatching,
stop,
parseState,
getStatus,
KNOWN_STATUSES,
DEFAULT_DIR,
FLUSH_MS,
MIN_RESCAN_INTERVAL_MS,
};