officepals 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +122 -2
- package/bin/officepals.mjs +196 -0
- package/package.json +39 -4
- package/src/hook.mjs +370 -0
- package/src/install.mjs +197 -0
- package/src/paths.mjs +20 -0
- package/src/server.mjs +289 -0
- package/src/sessions.mjs +73 -0
- package/src/state.mjs +295 -0
- package/src/stats.mjs +72 -0
- package/src/title.mjs +100 -0
- package/web/index.html +2946 -0
- package/web/tool-kinds.js +43 -0
- package/web/vendor/three/CSS2DRenderer.js +238 -0
- package/web/vendor/three/LICENSE +21 -0
- package/web/vendor/three/OrbitControls.js +1523 -0
- package/web/vendor/three/README.md +5 -0
- package/web/vendor/three/RoundedBoxGeometry.js +155 -0
- package/web/vendor/three/three.module.min.js +6 -0
package/src/server.mjs
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// The local officepals server: hook events in, live office state out.
|
|
2
|
+
//
|
|
3
|
+
// POST /hooks events from the hook relay (token-checked)
|
|
4
|
+
// GET /events Server-Sent Events: a snapshot, then every update
|
|
5
|
+
// GET /* the office web page (web/)
|
|
6
|
+
//
|
|
7
|
+
// Listens on 127.0.0.1 only and refuses requests whose Host isn't loopback,
|
|
8
|
+
// so neither the network nor a DNS-rebinding web page can reach it.
|
|
9
|
+
import * as crypto from 'node:crypto';
|
|
10
|
+
import * as fs from 'node:fs';
|
|
11
|
+
import * as http from 'node:http';
|
|
12
|
+
import * as path from 'node:path';
|
|
13
|
+
|
|
14
|
+
import { codexIndexPath, serverFile, statsFile } from './paths.mjs';
|
|
15
|
+
import { runningSessions, registryDir } from './sessions.mjs';
|
|
16
|
+
import { adopt, apply, createState, prune, setTitle } from './state.mjs';
|
|
17
|
+
import { createStats, dayKey, loadStats, record, saveStats, today } from './stats.mjs';
|
|
18
|
+
import { readCodexTitle, readTitle } from './title.mjs';
|
|
19
|
+
|
|
20
|
+
const MAX_BODY = 16 * 1024;
|
|
21
|
+
const PRUNE_EVERY_MS = 60_000;
|
|
22
|
+
const HEARTBEAT_MS = 15_000;
|
|
23
|
+
/** Re-read a session's title at most this often, plus at the moments it changes. */
|
|
24
|
+
const TITLE_EVERY_MS = 20_000;
|
|
25
|
+
const TITLE_EVENTS = new Set(['SessionStart', 'UserPromptSubmit', 'Stop']);
|
|
26
|
+
/** How often to check which sessions are running. A tracked session leaves
|
|
27
|
+
* after missing from two checks in a row (a file mid-write reads as missing). */
|
|
28
|
+
const RUNNING_EVERY_MS = 4_000;
|
|
29
|
+
const MISSES_TO_LEAVE = 2;
|
|
30
|
+
/** A session that just said goodbye isn't let back in while its process exits. */
|
|
31
|
+
const ENDED_GRACE_MS = 60_000;
|
|
32
|
+
/** A rename lands in a file; react this soon after it changes (debounced). */
|
|
33
|
+
const WATCH_DEBOUNCE_MS = 120;
|
|
34
|
+
/** Stats are written this long after the last change (and on close). */
|
|
35
|
+
const SAVE_STATS_AFTER_MS = 2_000;
|
|
36
|
+
const TYPES = {
|
|
37
|
+
'.html': 'text/html; charset=utf-8',
|
|
38
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
39
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
40
|
+
'.css': 'text/css; charset=utf-8',
|
|
41
|
+
'.svg': 'image/svg+xml',
|
|
42
|
+
'.png': 'image/png',
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function loopbackHost(hostHeader, port) {
|
|
46
|
+
const allowed = [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`];
|
|
47
|
+
return allowed.includes(String(hostHeader).toLowerCase());
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function startServer({ port, webDir, log = () => {}, writeServerFile = true, sessionsDir = registryDir(), stats: statsPath = statsFile(), codexIndex = codexIndexPath() }) {
|
|
51
|
+
const token = crypto.randomBytes(24).toString('hex');
|
|
52
|
+
const state = createState();
|
|
53
|
+
// Daily stats: loaded from disk, saved shortly after each change.
|
|
54
|
+
const stats = statsPath ? loadStats(statsPath) : createStats();
|
|
55
|
+
let statsDay = dayKey(Date.now());
|
|
56
|
+
let saveTimer = null;
|
|
57
|
+
const saveNow = () => {
|
|
58
|
+
clearTimeout(saveTimer);
|
|
59
|
+
saveTimer = null;
|
|
60
|
+
if (!statsPath) return;
|
|
61
|
+
try {
|
|
62
|
+
saveStats(statsPath, stats);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
log(`couldn't save stats: ${err.message}`);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const statsUpdate = () => ({ type: 'stats', today: today(stats, Date.now()) });
|
|
68
|
+
const clients = new Set();
|
|
69
|
+
const titleReadAt = new Map(); // session id -> last read
|
|
70
|
+
const misses = new Map(); // tracked session id -> checks it was missing from
|
|
71
|
+
const registryName = new Map(); // session id -> the name Claude Code lists it under
|
|
72
|
+
const endedAt = new Map(); // session id -> when SessionEnd arrived
|
|
73
|
+
|
|
74
|
+
/** Let in sessions that are running but not here yet; see off those whose
|
|
75
|
+
* process has stopped. Announces a fresh snapshot when anything changed. */
|
|
76
|
+
function syncRunning() {
|
|
77
|
+
const running = sessionsDir ? runningSessions(sessionsDir) : null;
|
|
78
|
+
if (!running) return; // unknown: change nothing
|
|
79
|
+
const now = Date.now();
|
|
80
|
+
for (const [id, t] of endedAt) if (now - t > ENDED_GRACE_MS) endedAt.delete(id);
|
|
81
|
+
let changed = false;
|
|
82
|
+
const ids = new Set();
|
|
83
|
+
for (const r of running) {
|
|
84
|
+
if (endedAt.has(r.id)) continue;
|
|
85
|
+
ids.add(r.id);
|
|
86
|
+
misses.delete(r.id);
|
|
87
|
+
if (adopt(state, r, now)) {
|
|
88
|
+
changed = true;
|
|
89
|
+
log(`found running session · ${r.project ?? r.id.slice(0, 8)}`);
|
|
90
|
+
}
|
|
91
|
+
// Renamed in Claude Code: the list has the new name at once.
|
|
92
|
+
if (r.name && registryName.get(r.id) !== r.name) {
|
|
93
|
+
registryName.set(r.id, r.name);
|
|
94
|
+
if (setTitle(state, r.id, r.name) && !changed) announceTitle(r.id);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
for (const [id, s] of Object.entries(state.sessions)) {
|
|
98
|
+
if (!s.tracked || ids.has(id)) continue;
|
|
99
|
+
const n = (misses.get(id) ?? 0) + 1;
|
|
100
|
+
if (n < MISSES_TO_LEAVE) {
|
|
101
|
+
misses.set(id, n);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
misses.delete(id);
|
|
105
|
+
titleReadAt.delete(id);
|
|
106
|
+
registryName.delete(id);
|
|
107
|
+
delete state.sessions[id];
|
|
108
|
+
changed = true;
|
|
109
|
+
log(`session gone · ${s.project ?? id.slice(0, 8)}`);
|
|
110
|
+
}
|
|
111
|
+
if (changed) broadcast(snapshot());
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Read the session's title from its log now and then, and announce changes. */
|
|
115
|
+
async function refreshTitle(ev) {
|
|
116
|
+
const s = state.sessions[ev.session];
|
|
117
|
+
const codex = ev.provider === 'codex';
|
|
118
|
+
if (!s || (!codex && !ev.transcript)) return;
|
|
119
|
+
if (registryName.has(ev.session)) return; // Claude Code's own list has the current name
|
|
120
|
+
const last = titleReadAt.get(ev.session) ?? 0;
|
|
121
|
+
if (s.title && !TITLE_EVENTS.has(ev.event) && Date.now() - last < TITLE_EVERY_MS) return;
|
|
122
|
+
titleReadAt.set(ev.session, Date.now());
|
|
123
|
+
const title = codex ? await readCodexTitle(ev.session) : await readTitle(ev.transcript);
|
|
124
|
+
if (title && setTitle(state, ev.session, title)) {
|
|
125
|
+
broadcast({ type: 'update', ts: Date.now(), event: { session: ev.session, event: 'TitleChanged' }, session: state.sessions[ev.session] });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const announceTitle = (id) =>
|
|
130
|
+
broadcast({ type: 'update', ts: Date.now(), event: { session: id, event: 'TitleChanged' }, session: state.sessions[id] });
|
|
131
|
+
|
|
132
|
+
/** Codex's session index changed (a rename, a new title): re-read its sessions' titles. */
|
|
133
|
+
async function refreshCodexTitles() {
|
|
134
|
+
for (const [id, s] of Object.entries(state.sessions)) {
|
|
135
|
+
if (s.provider !== 'codex') continue;
|
|
136
|
+
const title = await readCodexTitle(id, codexIndex);
|
|
137
|
+
if (title && setTitle(state, id, title)) announceTitle(id);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Watch a folder for changes (to one file, if named), debounced; null if it can't be watched. */
|
|
142
|
+
function watch(dir, file, onChange) {
|
|
143
|
+
let timer = null;
|
|
144
|
+
try {
|
|
145
|
+
const w = fs.watch(dir, (_, name) => {
|
|
146
|
+
if (file && name && name !== file) return;
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
timer = setTimeout(onChange, WATCH_DEBOUNCE_MS);
|
|
149
|
+
});
|
|
150
|
+
w.on('error', () => w.close());
|
|
151
|
+
return { close: () => { clearTimeout(timer); w.close(); } };
|
|
152
|
+
} catch {
|
|
153
|
+
return null; // missing folder: the timers still catch changes, just later
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const send = (res, msg) => res.write(`data: ${JSON.stringify(msg)}\n\n`);
|
|
158
|
+
const broadcast = (msg) => clients.forEach((res) => send(res, msg));
|
|
159
|
+
const snapshot = () => ({ type: 'snapshot', now: Date.now(), sessions: state.sessions, stats: today(stats, Date.now()) });
|
|
160
|
+
|
|
161
|
+
function serveStatic(req, res) {
|
|
162
|
+
const url = new URL(req.url, 'http://x');
|
|
163
|
+
const rel = url.pathname === '/' ? 'index.html' : decodeURIComponent(url.pathname).replace(/^\/+/, '');
|
|
164
|
+
const file = path.resolve(webDir, rel);
|
|
165
|
+
if (!file.startsWith(path.resolve(webDir) + path.sep)) return void res.writeHead(404).end();
|
|
166
|
+
fs.readFile(file, (err, data) => {
|
|
167
|
+
if (err) return void res.writeHead(404).end('not found');
|
|
168
|
+
res.writeHead(200, {
|
|
169
|
+
'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream',
|
|
170
|
+
'cache-control': 'no-store',
|
|
171
|
+
'x-content-type-options': 'nosniff',
|
|
172
|
+
});
|
|
173
|
+
res.end(data);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function receiveHook(req, res) {
|
|
178
|
+
if (req.headers['x-officepals-token'] !== token) return void res.writeHead(401).end();
|
|
179
|
+
let body = '';
|
|
180
|
+
req.on('data', (chunk) => {
|
|
181
|
+
body += chunk;
|
|
182
|
+
if (body.length > MAX_BODY) req.destroy();
|
|
183
|
+
});
|
|
184
|
+
req.on('end', () => {
|
|
185
|
+
res.writeHead(204).end();
|
|
186
|
+
let ev;
|
|
187
|
+
try {
|
|
188
|
+
ev = JSON.parse(body);
|
|
189
|
+
} catch {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const ts = Date.now();
|
|
193
|
+
const facts = [];
|
|
194
|
+
apply(state, ev, ts, facts);
|
|
195
|
+
broadcast({ type: 'update', ts, event: ev, session: state.sessions[ev.session] ?? null });
|
|
196
|
+
if (facts.some((f) => record(stats, f, ts))) {
|
|
197
|
+
broadcast(statsUpdate());
|
|
198
|
+
if (statsPath && !saveTimer) saveTimer = setTimeout(saveNow, SAVE_STATS_AFTER_MS);
|
|
199
|
+
}
|
|
200
|
+
log(`${ev.event}${ev.tool ? ' ' + ev.tool : ''} · ${ev.project ?? ev.session.slice(0, 8)}`);
|
|
201
|
+
if (ev.event === 'SessionEnd') {
|
|
202
|
+
titleReadAt.delete(ev.session);
|
|
203
|
+
misses.delete(ev.session);
|
|
204
|
+
endedAt.set(ev.session, ts);
|
|
205
|
+
} else {
|
|
206
|
+
endedAt.delete(ev.session); // back again (a resumed session)
|
|
207
|
+
refreshTitle(ev);
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function streamEvents(req, res) {
|
|
213
|
+
res.writeHead(200, {
|
|
214
|
+
'content-type': 'text/event-stream',
|
|
215
|
+
'cache-control': 'no-store',
|
|
216
|
+
connection: 'keep-alive',
|
|
217
|
+
});
|
|
218
|
+
send(res, snapshot());
|
|
219
|
+
clients.add(res);
|
|
220
|
+
req.on('close', () => clients.delete(res));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const server = http.createServer((req, res) => {
|
|
224
|
+
if (!loopbackHost(req.headers.host, actualPort)) return void res.writeHead(403).end();
|
|
225
|
+
if (req.method === 'POST' && req.url === '/hooks') return receiveHook(req, res);
|
|
226
|
+
if (req.method === 'GET' && req.url === '/events') return streamEvents(req, res);
|
|
227
|
+
if (req.method === 'GET') return serveStatic(req, res);
|
|
228
|
+
res.writeHead(405).end();
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
let actualPort = port;
|
|
232
|
+
await new Promise((resolve, reject) => {
|
|
233
|
+
server.once('error', reject);
|
|
234
|
+
server.listen(port, '127.0.0.1', () => {
|
|
235
|
+
actualPort = server.address().port;
|
|
236
|
+
resolve();
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
if (writeServerFile) {
|
|
241
|
+
fs.mkdirSync(path.dirname(serverFile()), { recursive: true, mode: 0o700 });
|
|
242
|
+
fs.writeFileSync(serverFile(), JSON.stringify({ port: actualPort, token, pid: process.pid }), { mode: 0o600 });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
syncRunning();
|
|
246
|
+
// Renames show up at once: watch the files the names live in.
|
|
247
|
+
const watchers = [
|
|
248
|
+
sessionsDir && watch(sessionsDir, null, syncRunning),
|
|
249
|
+
codexIndex && watch(path.dirname(codexIndex), path.basename(codexIndex), refreshCodexTitles),
|
|
250
|
+
].filter(Boolean);
|
|
251
|
+
const timers = [
|
|
252
|
+
setInterval(syncRunning, RUNNING_EVERY_MS),
|
|
253
|
+
setInterval(() => {
|
|
254
|
+
const before = Object.keys(state.sessions).length;
|
|
255
|
+
prune(state, Date.now());
|
|
256
|
+
if (Object.keys(state.sessions).length !== before) broadcast(snapshot());
|
|
257
|
+
// Past midnight: a new day's (empty) numbers.
|
|
258
|
+
if (dayKey(Date.now()) !== statsDay) {
|
|
259
|
+
statsDay = dayKey(Date.now());
|
|
260
|
+
broadcast(statsUpdate());
|
|
261
|
+
}
|
|
262
|
+
}, PRUNE_EVERY_MS),
|
|
263
|
+
setInterval(() => clients.forEach((res) => res.write(': ping\n\n')), HEARTBEAT_MS),
|
|
264
|
+
];
|
|
265
|
+
|
|
266
|
+
return {
|
|
267
|
+
port: actualPort,
|
|
268
|
+
token,
|
|
269
|
+
state,
|
|
270
|
+
syncRunning, // checks now (tests; it also runs on a timer)
|
|
271
|
+
refreshCodexTitles,
|
|
272
|
+
stats,
|
|
273
|
+
close() {
|
|
274
|
+
timers.forEach(clearInterval);
|
|
275
|
+
watchers.forEach((w) => w.close());
|
|
276
|
+
if (saveTimer) saveNow();
|
|
277
|
+
clients.forEach((res) => res.end());
|
|
278
|
+
if (writeServerFile) {
|
|
279
|
+
try {
|
|
280
|
+
const s = JSON.parse(fs.readFileSync(serverFile(), 'utf-8'));
|
|
281
|
+
if (s.pid === process.pid) fs.unlinkSync(serverFile());
|
|
282
|
+
} catch {
|
|
283
|
+
/* already gone */
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return new Promise((resolve) => server.close(resolve));
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
package/src/sessions.mjs
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Which Claude Code sessions are running right now.
|
|
2
|
+
//
|
|
3
|
+
// Claude Code keeps one small file per running session in ~/.claude/sessions
|
|
4
|
+
// (<pid>.json: the process id, session id, folder, name and busy/idle). The
|
|
5
|
+
// office reads it so that sessions already open when it starts walk in at
|
|
6
|
+
// once, and sessions whose process has gone (a closed terminal sends no
|
|
7
|
+
// SessionEnd) leave within seconds instead of half an hour.
|
|
8
|
+
//
|
|
9
|
+
// Best effort: the folder is Claude Code's own and may be missing (older
|
|
10
|
+
// versions) or change shape. Anything unexpected reads as "unknown", and the
|
|
11
|
+
// office then falls back to hook events alone. Only <pid>.json files are read
|
|
12
|
+
// (never the .key files next to them), and only the fields below are kept.
|
|
13
|
+
import * as fs from 'node:fs';
|
|
14
|
+
import * as os from 'node:os';
|
|
15
|
+
import * as path from 'node:path';
|
|
16
|
+
|
|
17
|
+
const MAX_FILE = 64 * 1024;
|
|
18
|
+
const MAX_NAME = 40;
|
|
19
|
+
|
|
20
|
+
export function registryDir() {
|
|
21
|
+
return process.env.OFFICEPALS_CLAUDE_SESSIONS || path.join(os.homedir(), '.claude', 'sessions');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Is a process with this id running? (EPERM: it is, but it isn't ours.) */
|
|
25
|
+
export function processAlive(pid) {
|
|
26
|
+
try {
|
|
27
|
+
process.kill(pid, 0);
|
|
28
|
+
return true;
|
|
29
|
+
} catch (err) {
|
|
30
|
+
return err.code === 'EPERM';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const clip = (s) => {
|
|
35
|
+
const one = s.replace(/\s+/g, ' ').trim();
|
|
36
|
+
return one.length > MAX_NAME ? one.slice(0, MAX_NAME - 1) + '…' : one;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The running sessions, or null when the registry can't be read (then nobody
|
|
41
|
+
* should be sent home on its account).
|
|
42
|
+
* @returns {null | Array<{ pid: number, id: string, project: string | null, name: string | null, busy: boolean, startedAt: number | null }>}
|
|
43
|
+
*/
|
|
44
|
+
export function runningSessions(dir = registryDir(), alive = processAlive) {
|
|
45
|
+
let files;
|
|
46
|
+
try {
|
|
47
|
+
files = fs.readdirSync(dir).filter((f) => /^\d+\.json$/.test(f));
|
|
48
|
+
} catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
const out = [];
|
|
52
|
+
for (const f of files) {
|
|
53
|
+
let d;
|
|
54
|
+
try {
|
|
55
|
+
const file = path.join(dir, f);
|
|
56
|
+
if (fs.statSync(file).size > MAX_FILE) continue;
|
|
57
|
+
d = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
58
|
+
} catch {
|
|
59
|
+
continue; // being written, or not what we expect
|
|
60
|
+
}
|
|
61
|
+
if (!d || !Number.isInteger(d.pid) || typeof d.sessionId !== 'string' || !d.sessionId) continue;
|
|
62
|
+
if (String(d.pid) + '.json' !== f || !alive(d.pid)) continue; // left behind by a crash
|
|
63
|
+
out.push({
|
|
64
|
+
pid: d.pid,
|
|
65
|
+
id: d.sessionId,
|
|
66
|
+
project: typeof d.cwd === 'string' && d.cwd ? path.basename(d.cwd) : null,
|
|
67
|
+
name: typeof d.name === 'string' && d.name.trim() ? clip(d.name) : null,
|
|
68
|
+
busy: d.status === 'busy',
|
|
69
|
+
startedAt: Number.isFinite(d.startedAt) ? d.startedAt : null,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
package/src/state.mjs
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
// The office's view of every Claude Code session, built from hook events.
|
|
2
|
+
// Pure: `apply(state, event, ts)` mutates and returns `state`; nothing here does I/O.
|
|
3
|
+
//
|
|
4
|
+
// A session (the main agent) and each of its sub-agents are "workers":
|
|
5
|
+
// tool the tool call in flight (null between calls)
|
|
6
|
+
// label a short label for it (a file name, a host, a query)
|
|
7
|
+
// cmd for a shell command, its kind: test, build, install, git or look
|
|
8
|
+
// waiting null, or { kind: 'permission' | 'question' | 'plan', tool, label, since }
|
|
9
|
+
// A session also has a `phase`: 'working' during a turn, 'idle' between turns,
|
|
10
|
+
// `turnTools` (tool calls this turn, by tool), `waits` (how often and how long
|
|
11
|
+
// it has waited on you), `title` (the name Claude Code gave the conversation, read from its log by
|
|
12
|
+
// the server), `tracked` (its process is being watched; see adopt), `plan`
|
|
13
|
+
// and `steps` (its to-do list, and each step's status for the whiteboard), `task` (the to-do step in progress, when the session uses the
|
|
14
|
+
// task tools) and `lastTurnMs` (how long the turn that just ended took).
|
|
15
|
+
|
|
16
|
+
/** Tools that are themselves a request for the user's input. */
|
|
17
|
+
export const QUESTION_TOOLS = { AskUserQuestion: 'question', ExitPlanMode: 'plan' };
|
|
18
|
+
|
|
19
|
+
/** Sessions with no events for this long (and not waiting on you) leave the office. */
|
|
20
|
+
export const STALE_MS = 30 * 60_000;
|
|
21
|
+
|
|
22
|
+
export function createState() {
|
|
23
|
+
return { sessions: {} };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function worker(extra = {}) {
|
|
27
|
+
return { tool: null, label: null, cmd: null, waiting: null, ...extra };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function ensureSession(state, ev, ts) {
|
|
31
|
+
let s = state.sessions[ev.session];
|
|
32
|
+
if (!s) {
|
|
33
|
+
s = state.sessions[ev.session] = {
|
|
34
|
+
id: ev.session,
|
|
35
|
+
project: ev.project ?? null,
|
|
36
|
+
provider: ev.provider ?? 'claude',
|
|
37
|
+
phase: 'idle',
|
|
38
|
+
firstSeen: ts,
|
|
39
|
+
lastSeen: ts,
|
|
40
|
+
title: null,
|
|
41
|
+
task: null,
|
|
42
|
+
tasks: {},
|
|
43
|
+
taskStates: {},
|
|
44
|
+
plan: null,
|
|
45
|
+
steps: [],
|
|
46
|
+
turnStart: null,
|
|
47
|
+
lastTurnMs: null,
|
|
48
|
+
turnTools: {},
|
|
49
|
+
waits: { count: 0, ms: 0 },
|
|
50
|
+
...worker(),
|
|
51
|
+
subagents: {},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
s.lastSeen = ts;
|
|
55
|
+
if (ev.project) s.project = ev.project;
|
|
56
|
+
return s;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The worker an event belongs to: the session itself, or one of its sub-agents. */
|
|
60
|
+
function target(s, ev, ts) {
|
|
61
|
+
if (!ev.agent) return s;
|
|
62
|
+
if (!s.subagents[ev.agent]) s.subagents[ev.agent] = worker({ id: ev.agent, type: ev.agentType ?? null, since: ts });
|
|
63
|
+
return s.subagents[ev.agent];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Anything that shows the agent at work starts a turn if none is running. */
|
|
67
|
+
function work(s, ts) {
|
|
68
|
+
if (s.phase !== 'working') {
|
|
69
|
+
s.phase = 'working';
|
|
70
|
+
s.turnStart = ts;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const MAX_TASKS = 50;
|
|
75
|
+
|
|
76
|
+
const STEP_STATUS = new Set(['pending', 'in_progress', 'completed']);
|
|
77
|
+
|
|
78
|
+
/** Apply a change to the to-do list: next step, some done / one started, or all done. */
|
|
79
|
+
function stepPlan(plan, { advance, done, start, finish }) {
|
|
80
|
+
if (finish) for (const p of plan) p.s = 'completed';
|
|
81
|
+
if (advance) {
|
|
82
|
+
const cur = plan.find((p) => p.s === 'in_progress');
|
|
83
|
+
if (cur) cur.s = 'completed';
|
|
84
|
+
const next = plan.find((p) => p.s === 'pending');
|
|
85
|
+
if (next) next.s = 'in_progress';
|
|
86
|
+
}
|
|
87
|
+
if (Array.isArray(done)) for (const n of done) if (plan[n - 1]) plan[n - 1].s = 'completed';
|
|
88
|
+
if (Number.isInteger(start) && plan[start - 1]) {
|
|
89
|
+
for (const p of plan) if (p.s === 'in_progress') p.s = 'pending';
|
|
90
|
+
plan[start - 1].s = 'in_progress';
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Track the to-do list (and the step in progress) from whichever task tool the session uses. */
|
|
95
|
+
function trackTask(s, ev) {
|
|
96
|
+
if (ev.todo) s.task = ev.todo;
|
|
97
|
+
// A whole list (TodoWrite, the Claude app's task list), or a change to it.
|
|
98
|
+
if (Array.isArray(ev.plan)) {
|
|
99
|
+
s.plan = ev.plan.slice(0, MAX_TASKS).map((p) => ({ t: typeof p?.t === 'string' ? p.t : '', s: STEP_STATUS.has(p?.s) ? p.s : 'pending' }));
|
|
100
|
+
} else if (ev.planStep && s.plan) {
|
|
101
|
+
stepPlan(s.plan, ev.planStep);
|
|
102
|
+
}
|
|
103
|
+
if (ev.plan || ev.planStep) {
|
|
104
|
+
const cur = s.plan?.find((p) => p.s === 'in_progress');
|
|
105
|
+
if (!ev.todo) s.task = cur?.t || null;
|
|
106
|
+
}
|
|
107
|
+
// Task tools: created, started, completed one at a time.
|
|
108
|
+
if (ev.event === 'TaskCreated' && ev.taskId && ev.taskSubject) {
|
|
109
|
+
s.tasks[ev.taskId] = ev.taskSubject;
|
|
110
|
+
s.taskStates[ev.taskId] ??= 'pending';
|
|
111
|
+
const ids = Object.keys(s.tasks);
|
|
112
|
+
if (ids.length > MAX_TASKS) {
|
|
113
|
+
delete s.tasks[ids[0]];
|
|
114
|
+
delete s.taskStates[ids[0]];
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (ev.event === 'PreToolUse' && ev.tool === 'TaskUpdate') {
|
|
118
|
+
const subject = ev.taskSubject ?? (ev.taskId ? s.tasks[ev.taskId] : undefined);
|
|
119
|
+
if (ev.taskId && STEP_STATUS.has(ev.taskStatus)) s.taskStates[ev.taskId] = ev.taskStatus;
|
|
120
|
+
if (ev.taskStatus === 'in_progress' && subject) s.task = subject;
|
|
121
|
+
if (ev.taskStatus === 'completed' && subject && s.task === subject) s.task = null;
|
|
122
|
+
}
|
|
123
|
+
if (ev.event === 'TaskCompleted') {
|
|
124
|
+
const subject = ev.taskSubject ?? (ev.taskId ? s.tasks[ev.taskId] : undefined);
|
|
125
|
+
if (ev.taskId) s.taskStates[ev.taskId] = 'completed';
|
|
126
|
+
if (subject && s.task === subject) s.task = null;
|
|
127
|
+
}
|
|
128
|
+
// What the whiteboard shows: each step's status, from the list or the task tools.
|
|
129
|
+
s.steps = s.plan ? s.plan.map((p) => p.s) : Object.values(s.taskStates);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const MAX_TOOL_KINDS = 40;
|
|
133
|
+
|
|
134
|
+
/** Count a tool call in this turn (shell commands by kind: "Bash:test"). */
|
|
135
|
+
function countTool(s, ev) {
|
|
136
|
+
if (!ev.tool) return;
|
|
137
|
+
const key = ev.tool === 'Bash' && ev.cmd ? `Bash:${ev.cmd}` : ev.tool;
|
|
138
|
+
if (key in s.turnTools || Object.keys(s.turnTools).length < MAX_TOOL_KINDS) s.turnTools[key] = (s.turnTools[key] ?? 0) + 1;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Facts for the daily stats (see apply's `facts`).
|
|
142
|
+
let facts = null;
|
|
143
|
+
|
|
144
|
+
/** A wait is over (answered or abandoned): add it to the session's tally. */
|
|
145
|
+
function endWait(s, w, ts) {
|
|
146
|
+
if (!w.waiting) return;
|
|
147
|
+
const ms = Math.max(0, ts - w.waiting.since);
|
|
148
|
+
s.waits.count++;
|
|
149
|
+
s.waits.ms += ms;
|
|
150
|
+
facts?.push({ type: 'wait', ms });
|
|
151
|
+
w.waiting = null;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function wait(w, kind, ev, ts) {
|
|
155
|
+
if (!w.waiting) {
|
|
156
|
+
w.waiting = { kind, tool: ev.tool ?? w.tool, label: ev.label ?? w.label, cmd: ev.cmd ?? null, risk: ev.risk ?? null, since: ts };
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Apply a hook event. `out`, when given, collects facts for the daily stats:
|
|
162
|
+
* { type: 'wait', ms } when a wait on you ends, { type: 'turn', ms } when a turn does.
|
|
163
|
+
*/
|
|
164
|
+
export function apply(state, ev, ts, out = null) {
|
|
165
|
+
facts = out;
|
|
166
|
+
try {
|
|
167
|
+
return applyEvent(state, ev, ts);
|
|
168
|
+
} finally {
|
|
169
|
+
facts = null;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function applyEvent(state, ev, ts) {
|
|
174
|
+
if (!ev || typeof ev.session !== 'string' || typeof ev.event !== 'string') return state;
|
|
175
|
+
|
|
176
|
+
if (ev.event === 'SessionEnd') {
|
|
177
|
+
delete state.sessions[ev.session];
|
|
178
|
+
return state;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const s = ensureSession(state, ev, ts);
|
|
182
|
+
trackTask(s, ev);
|
|
183
|
+
switch (ev.event) {
|
|
184
|
+
case 'SessionStart':
|
|
185
|
+
s.phase = 'idle';
|
|
186
|
+
break;
|
|
187
|
+
|
|
188
|
+
case 'UserPromptSubmit':
|
|
189
|
+
s.phase = 'working';
|
|
190
|
+
s.turnStart = ts;
|
|
191
|
+
endWait(s, s, ts);
|
|
192
|
+
s.turnTools = {};
|
|
193
|
+
// A finished list comes off the whiteboard when the next request starts.
|
|
194
|
+
if (s.steps.length && s.steps.every((x) => x === 'completed')) {
|
|
195
|
+
s.plan = null;
|
|
196
|
+
s.taskStates = {};
|
|
197
|
+
s.steps = [];
|
|
198
|
+
}
|
|
199
|
+
break;
|
|
200
|
+
|
|
201
|
+
case 'PreToolUse': {
|
|
202
|
+
const w = target(s, ev, ts);
|
|
203
|
+
endWait(s, w, ts); // moving on means whatever it waited for was answered
|
|
204
|
+
countTool(s, ev);
|
|
205
|
+
w.tool = ev.tool ?? null;
|
|
206
|
+
w.label = ev.label ?? null;
|
|
207
|
+
w.cmd = ev.cmd ?? null; // the kind of shell command (test, git, …)
|
|
208
|
+
work(s, ts);
|
|
209
|
+
const kind = QUESTION_TOOLS[ev.tool];
|
|
210
|
+
if (kind) wait(w, kind, ev, ts);
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
case 'PermissionRequest':
|
|
215
|
+
wait(target(s, ev, ts), 'permission', ev, ts);
|
|
216
|
+
work(s, ts);
|
|
217
|
+
break;
|
|
218
|
+
|
|
219
|
+
case 'Notification':
|
|
220
|
+
// Older CLIs announce permission prompts only as a notification.
|
|
221
|
+
if (ev.notification === 'permission_prompt') wait(target(s, ev, ts), 'permission', ev, ts);
|
|
222
|
+
break;
|
|
223
|
+
|
|
224
|
+
case 'PostToolUse':
|
|
225
|
+
case 'PostToolUseFailure': {
|
|
226
|
+
const w = target(s, ev, ts);
|
|
227
|
+
endWait(s, w, ts);
|
|
228
|
+
w.tool = null;
|
|
229
|
+
w.cmd = null;
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
case 'SubagentStart':
|
|
234
|
+
target(s, ev, ts);
|
|
235
|
+
break;
|
|
236
|
+
|
|
237
|
+
case 'SubagentStop':
|
|
238
|
+
if (ev.agent) delete s.subagents[ev.agent];
|
|
239
|
+
break;
|
|
240
|
+
|
|
241
|
+
case 'Stop':
|
|
242
|
+
s.lastTurnMs = s.turnStart === null ? null : ts - s.turnStart;
|
|
243
|
+
if (s.lastTurnMs !== null) facts?.push({ type: 'turn', ms: s.lastTurnMs });
|
|
244
|
+
s.turnStart = null;
|
|
245
|
+
s.phase = 'idle';
|
|
246
|
+
s.tool = null;
|
|
247
|
+
endWait(s, s, ts);
|
|
248
|
+
break;
|
|
249
|
+
|
|
250
|
+
default:
|
|
251
|
+
break;
|
|
252
|
+
}
|
|
253
|
+
return state;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Set a session's title (read from its log); true when it changed. */
|
|
257
|
+
export function setTitle(state, sessionId, title) {
|
|
258
|
+
const s = state.sessions[sessionId];
|
|
259
|
+
if (!s || !title || s.title === title) return false;
|
|
260
|
+
s.title = title;
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* A session found running in Claude Code's session list rather than through a
|
|
266
|
+
* hook event (it was open before the office started). Adds it when new and
|
|
267
|
+
* marks it `tracked`: its process is watched, so it stays while that runs,
|
|
268
|
+
* however quiet, and leaves when it stops. True when it was added.
|
|
269
|
+
*/
|
|
270
|
+
export function adopt(state, { id, project, name, busy, startedAt }, ts) {
|
|
271
|
+
let s = state.sessions[id];
|
|
272
|
+
const added = !s;
|
|
273
|
+
if (added) {
|
|
274
|
+
s = ensureSession(state, { session: id, project, provider: 'claude' }, ts);
|
|
275
|
+
s.firstSeen = Math.min(startedAt ?? ts, ts); // keeps desks in the order sessions opened
|
|
276
|
+
if (busy) {
|
|
277
|
+
s.phase = 'working';
|
|
278
|
+
s.turnStart = ts;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
s.tracked = true;
|
|
282
|
+
if (name && !s.title) s.title = name;
|
|
283
|
+
return added;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Drop sessions that have gone quiet, unless they are still waiting on you.
|
|
287
|
+
* Tracked sessions are left alone: their process says when they're gone. */
|
|
288
|
+
export function prune(state, now, staleMs = STALE_MS) {
|
|
289
|
+
for (const [id, s] of Object.entries(state.sessions)) {
|
|
290
|
+
if (s.tracked) continue;
|
|
291
|
+
const waiting = s.waiting || Object.values(s.subagents).some((a) => a.waiting);
|
|
292
|
+
if (!waiting && now - s.lastSeen > staleMs) delete state.sessions[id];
|
|
293
|
+
}
|
|
294
|
+
return state;
|
|
295
|
+
}
|