officepals 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.mjs ADDED
@@ -0,0 +1,244 @@
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 { 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
+ /** Stats are written this long after the last change (and on close). */
33
+ const SAVE_STATS_AFTER_MS = 2_000;
34
+ const TYPES = {
35
+ '.html': 'text/html; charset=utf-8',
36
+ '.js': 'text/javascript; charset=utf-8',
37
+ '.mjs': 'text/javascript; charset=utf-8',
38
+ '.css': 'text/css; charset=utf-8',
39
+ '.svg': 'image/svg+xml',
40
+ '.png': 'image/png',
41
+ };
42
+
43
+ function loopbackHost(hostHeader, port) {
44
+ const allowed = [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`];
45
+ return allowed.includes(String(hostHeader).toLowerCase());
46
+ }
47
+
48
+ export async function startServer({ port, webDir, log = () => {}, writeServerFile = true, sessionsDir = registryDir(), stats: statsPath = statsFile() }) {
49
+ const token = crypto.randomBytes(24).toString('hex');
50
+ const state = createState();
51
+ // Daily stats: loaded from disk, saved shortly after each change.
52
+ const stats = statsPath ? loadStats(statsPath) : createStats();
53
+ let statsDay = dayKey(Date.now());
54
+ let saveTimer = null;
55
+ const saveNow = () => {
56
+ clearTimeout(saveTimer);
57
+ saveTimer = null;
58
+ if (!statsPath) return;
59
+ try {
60
+ saveStats(statsPath, stats);
61
+ } catch (err) {
62
+ log(`couldn't save stats: ${err.message}`);
63
+ }
64
+ };
65
+ const statsUpdate = () => ({ type: 'stats', today: today(stats, Date.now()) });
66
+ const clients = new Set();
67
+ const titleReadAt = new Map(); // session id -> last read
68
+ const misses = new Map(); // tracked session id -> checks it was missing from
69
+ const endedAt = new Map(); // session id -> when SessionEnd arrived
70
+
71
+ /** Let in sessions that are running but not here yet; see off those whose
72
+ * process has stopped. Announces a fresh snapshot when anything changed. */
73
+ function syncRunning() {
74
+ const running = sessionsDir ? runningSessions(sessionsDir) : null;
75
+ if (!running) return; // unknown: change nothing
76
+ const now = Date.now();
77
+ for (const [id, t] of endedAt) if (now - t > ENDED_GRACE_MS) endedAt.delete(id);
78
+ let changed = false;
79
+ const ids = new Set();
80
+ for (const r of running) {
81
+ if (endedAt.has(r.id)) continue;
82
+ ids.add(r.id);
83
+ misses.delete(r.id);
84
+ if (adopt(state, r, now)) {
85
+ changed = true;
86
+ log(`found running session · ${r.project ?? r.id.slice(0, 8)}`);
87
+ }
88
+ }
89
+ for (const [id, s] of Object.entries(state.sessions)) {
90
+ if (!s.tracked || ids.has(id)) continue;
91
+ const n = (misses.get(id) ?? 0) + 1;
92
+ if (n < MISSES_TO_LEAVE) {
93
+ misses.set(id, n);
94
+ continue;
95
+ }
96
+ misses.delete(id);
97
+ titleReadAt.delete(id);
98
+ delete state.sessions[id];
99
+ changed = true;
100
+ log(`session gone · ${s.project ?? id.slice(0, 8)}`);
101
+ }
102
+ if (changed) broadcast(snapshot());
103
+ }
104
+
105
+ /** Read the session's title from its log now and then, and announce changes. */
106
+ async function refreshTitle(ev) {
107
+ const s = state.sessions[ev.session];
108
+ const codex = ev.provider === 'codex';
109
+ if (!s || (!codex && !ev.transcript)) return;
110
+ const last = titleReadAt.get(ev.session) ?? 0;
111
+ if (s.title && !TITLE_EVENTS.has(ev.event) && Date.now() - last < TITLE_EVERY_MS) return;
112
+ titleReadAt.set(ev.session, Date.now());
113
+ const title = codex ? await readCodexTitle(ev.session) : await readTitle(ev.transcript);
114
+ if (title && setTitle(state, ev.session, title)) {
115
+ broadcast({ type: 'update', ts: Date.now(), event: { session: ev.session, event: 'TitleChanged' }, session: state.sessions[ev.session] });
116
+ }
117
+ }
118
+
119
+ const send = (res, msg) => res.write(`data: ${JSON.stringify(msg)}\n\n`);
120
+ const broadcast = (msg) => clients.forEach((res) => send(res, msg));
121
+ const snapshot = () => ({ type: 'snapshot', now: Date.now(), sessions: state.sessions, stats: today(stats, Date.now()) });
122
+
123
+ function serveStatic(req, res) {
124
+ const url = new URL(req.url, 'http://x');
125
+ const rel = url.pathname === '/' ? 'index.html' : decodeURIComponent(url.pathname).replace(/^\/+/, '');
126
+ const file = path.resolve(webDir, rel);
127
+ if (!file.startsWith(path.resolve(webDir) + path.sep)) return void res.writeHead(404).end();
128
+ fs.readFile(file, (err, data) => {
129
+ if (err) return void res.writeHead(404).end('not found');
130
+ res.writeHead(200, {
131
+ 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream',
132
+ 'cache-control': 'no-store',
133
+ 'x-content-type-options': 'nosniff',
134
+ });
135
+ res.end(data);
136
+ });
137
+ }
138
+
139
+ function receiveHook(req, res) {
140
+ if (req.headers['x-officepals-token'] !== token) return void res.writeHead(401).end();
141
+ let body = '';
142
+ req.on('data', (chunk) => {
143
+ body += chunk;
144
+ if (body.length > MAX_BODY) req.destroy();
145
+ });
146
+ req.on('end', () => {
147
+ res.writeHead(204).end();
148
+ let ev;
149
+ try {
150
+ ev = JSON.parse(body);
151
+ } catch {
152
+ return;
153
+ }
154
+ const ts = Date.now();
155
+ const facts = [];
156
+ apply(state, ev, ts, facts);
157
+ broadcast({ type: 'update', ts, event: ev, session: state.sessions[ev.session] ?? null });
158
+ if (facts.some((f) => record(stats, f, ts))) {
159
+ broadcast(statsUpdate());
160
+ if (statsPath && !saveTimer) saveTimer = setTimeout(saveNow, SAVE_STATS_AFTER_MS);
161
+ }
162
+ log(`${ev.event}${ev.tool ? ' ' + ev.tool : ''} · ${ev.project ?? ev.session.slice(0, 8)}`);
163
+ if (ev.event === 'SessionEnd') {
164
+ titleReadAt.delete(ev.session);
165
+ misses.delete(ev.session);
166
+ endedAt.set(ev.session, ts);
167
+ } else {
168
+ endedAt.delete(ev.session); // back again (a resumed session)
169
+ refreshTitle(ev);
170
+ }
171
+ });
172
+ }
173
+
174
+ function streamEvents(req, res) {
175
+ res.writeHead(200, {
176
+ 'content-type': 'text/event-stream',
177
+ 'cache-control': 'no-store',
178
+ connection: 'keep-alive',
179
+ });
180
+ send(res, snapshot());
181
+ clients.add(res);
182
+ req.on('close', () => clients.delete(res));
183
+ }
184
+
185
+ const server = http.createServer((req, res) => {
186
+ if (!loopbackHost(req.headers.host, actualPort)) return void res.writeHead(403).end();
187
+ if (req.method === 'POST' && req.url === '/hooks') return receiveHook(req, res);
188
+ if (req.method === 'GET' && req.url === '/events') return streamEvents(req, res);
189
+ if (req.method === 'GET') return serveStatic(req, res);
190
+ res.writeHead(405).end();
191
+ });
192
+
193
+ let actualPort = port;
194
+ await new Promise((resolve, reject) => {
195
+ server.once('error', reject);
196
+ server.listen(port, '127.0.0.1', () => {
197
+ actualPort = server.address().port;
198
+ resolve();
199
+ });
200
+ });
201
+
202
+ if (writeServerFile) {
203
+ fs.mkdirSync(path.dirname(serverFile()), { recursive: true, mode: 0o700 });
204
+ fs.writeFileSync(serverFile(), JSON.stringify({ port: actualPort, token, pid: process.pid }), { mode: 0o600 });
205
+ }
206
+
207
+ syncRunning();
208
+ const timers = [
209
+ setInterval(syncRunning, RUNNING_EVERY_MS),
210
+ setInterval(() => {
211
+ const before = Object.keys(state.sessions).length;
212
+ prune(state, Date.now());
213
+ if (Object.keys(state.sessions).length !== before) broadcast(snapshot());
214
+ // Past midnight: a new day's (empty) numbers.
215
+ if (dayKey(Date.now()) !== statsDay) {
216
+ statsDay = dayKey(Date.now());
217
+ broadcast(statsUpdate());
218
+ }
219
+ }, PRUNE_EVERY_MS),
220
+ setInterval(() => clients.forEach((res) => res.write(': ping\n\n')), HEARTBEAT_MS),
221
+ ];
222
+
223
+ return {
224
+ port: actualPort,
225
+ token,
226
+ state,
227
+ syncRunning, // checks now (tests; it also runs on a timer)
228
+ stats,
229
+ close() {
230
+ timers.forEach(clearInterval);
231
+ if (saveTimer) saveNow();
232
+ clients.forEach((res) => res.end());
233
+ if (writeServerFile) {
234
+ try {
235
+ const s = JSON.parse(fs.readFileSync(serverFile(), 'utf-8'));
236
+ if (s.pid === process.pid) fs.unlinkSync(serverFile());
237
+ } catch {
238
+ /* already gone */
239
+ }
240
+ }
241
+ return new Promise((resolve) => server.close(resolve));
242
+ },
243
+ };
244
+ }
@@ -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
+ }
package/src/stats.mjs ADDED
@@ -0,0 +1,72 @@
1
+ // Daily stats, kept on disk (~/.officepals/stats.json) so they survive a
2
+ // reload and a restart: how often and how long your agents waited on you, and
3
+ // how many turns they finished. Counts only; nothing about what was done.
4
+ import * as fs from 'node:fs';
5
+ import * as path from 'node:path';
6
+
7
+ /** Days kept on disk. */
8
+ export const KEEP_DAYS = 60;
9
+
10
+ const pad = (n) => String(n).padStart(2, '0');
11
+
12
+ /** The local calendar day of a time, "2026-11-30". */
13
+ export function dayKey(ts) {
14
+ const d = new Date(ts);
15
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
16
+ }
17
+
18
+ const emptyDay = () => ({ waits: 0, waitMs: 0, longestWaitMs: 0, turns: 0, workMs: 0 });
19
+
20
+ export function createStats(days = {}) {
21
+ return { days };
22
+ }
23
+
24
+ /** Add a fact from the session state: a wait that ended, or a turn that did. */
25
+ export function record(stats, fact, ts) {
26
+ const key = dayKey(ts);
27
+ const d = (stats.days[key] ??= emptyDay());
28
+ const ms = Math.max(0, Math.round(Number(fact.ms) || 0));
29
+ if (fact.type === 'wait') {
30
+ d.waits++;
31
+ d.waitMs += ms;
32
+ d.longestWaitMs = Math.max(d.longestWaitMs, ms);
33
+ } else if (fact.type === 'turn') {
34
+ d.turns++;
35
+ d.workMs += ms;
36
+ } else {
37
+ return false;
38
+ }
39
+ const keys = Object.keys(stats.days).sort();
40
+ for (const old of keys.slice(0, Math.max(0, keys.length - KEEP_DAYS))) delete stats.days[old];
41
+ return true;
42
+ }
43
+
44
+ /** Today's numbers (zeros on a fresh day), with the day they're for. */
45
+ export function today(stats, ts) {
46
+ const key = dayKey(ts);
47
+ return { day: key, ...(stats.days[key] ?? emptyDay()) };
48
+ }
49
+
50
+ /** Read the stats file; anything missing or odd starts afresh. */
51
+ export function loadStats(file) {
52
+ try {
53
+ const data = JSON.parse(fs.readFileSync(file, 'utf-8'));
54
+ const days = {};
55
+ for (const [key, d] of Object.entries(data?.days ?? {})) {
56
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || !d || typeof d !== 'object') continue;
57
+ const day = emptyDay();
58
+ for (const k of Object.keys(day)) if (Number.isFinite(d[k]) && d[k] >= 0) day[k] = d[k];
59
+ days[key] = day;
60
+ }
61
+ return createStats(days);
62
+ } catch {
63
+ return createStats();
64
+ }
65
+ }
66
+
67
+ export function saveStats(file, stats) {
68
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
69
+ const tmp = `${file}.tmp`;
70
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, days: stats.days }, null, 2) + '\n', { mode: 0o600 });
71
+ fs.renameSync(tmp, file);
72
+ }