agenthall 0.0.0-stage → 1.0.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/server.js ADDED
@@ -0,0 +1,2613 @@
1
+ 'use strict';
2
+
3
+ // Agent Hall server: spawns agents in PTYs, tracks their status through
4
+ // Claude Code hooks and serves the office UI. Listens on 127.0.0.1 only.
5
+
6
+ const http = require('http');
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const crypto = require('crypto');
11
+ const { execFileSync, execFile } = require('child_process');
12
+ const { WebSocketServer } = require('ws');
13
+ const pty = require('@lydell/node-pty');
14
+ const I18N = require('./public/i18n.js');
15
+
16
+ const HOST = '127.0.0.1';
17
+ const PORT = Number(process.env.PORT) || 4321;
18
+ const HOME = process.env.AGENT_OFFICE_HOME || path.join(os.homedir(), '.agent-office');
19
+ const STATE_FILE = path.join(HOME, 'state.json');
20
+ const SETTINGS_DIR = path.join(HOME, 'settings');
21
+ const PUBLIC_DIR = path.join(__dirname, 'public');
22
+ const IS_WIN = process.platform === 'win32';
23
+ const SCROLLBACK_LIMIT = 512 * 1024;
24
+
25
+ const ROLES = ['lead', 'senior', 'mid', 'junior', 'intern'];
26
+ const ROLE_LABELS = { lead: 'Team Lead', senior: 'Senior', mid: 'Mid-level', junior: 'Junior', intern: 'Intern' };
27
+
28
+ // Errors carry a translation key so API responses follow the caller's language.
29
+ class OfficeError extends Error {
30
+ constructor(key, params) {
31
+ super(I18N.translate('en', key, params));
32
+ this.key = key;
33
+ this.params = params;
34
+ }
35
+ }
36
+ const errText = (lang, e) => (e && e.key ? I18N.translate(lang, e.key, e.params) : String((e && e.message) || e));
37
+ const reqLang = (req) => {
38
+ const l = String(req.headers['x-lang'] || '').slice(0, 5);
39
+ return I18N.LANGS.includes(l) ? l : 'en';
40
+ };
41
+ const COLORS = ['#e76f51', '#2a9d8f', '#e9c46a', '#8ab17d', '#9b5de5', '#f15bb5', '#00bbf9', '#f4a261', '#43aa8b', '#ef476f', '#118ab2', '#ffd166'];
42
+
43
+ fs.mkdirSync(SETTINGS_DIR, { recursive: true });
44
+
45
+ // ---------------------------------------------------------------- state
46
+
47
+ function loadState() {
48
+ try {
49
+ const s = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
50
+ return { projects: s.projects || [], agents: s.agents || [], external: s.external || {}, game: s.game, resumeOnBoot: s.resumeOnBoot, roomOrder: s.roomOrder || [], buildings: s.buildings, token: s.token, tasks: s.tasks || [], workday: s.workday, meetings: s.meetings || [] };
51
+ } catch {
52
+ return { projects: [], agents: [], external: {}, roomOrder: [], tasks: [], meetings: [] };
53
+ }
54
+ }
55
+
56
+ const db = loadState();
57
+ if (!db.token) db.token = crypto.randomBytes(16).toString('hex');
58
+
59
+ let saveTimer = null;
60
+ function save() {
61
+ clearTimeout(saveTimer);
62
+ saveTimer = setTimeout(() => {
63
+ fs.writeFileSync(STATE_FILE, JSON.stringify(db, null, 2));
64
+ }, 200);
65
+ }
66
+ save();
67
+
68
+ // Runtime-only data per agent id.
69
+ const runtime = new Map();
70
+ function rt(id) {
71
+ if (!runtime.has(id)) {
72
+ runtime.set(id, {
73
+ status: 'offline', // offline | starting | idle | working | waiting
74
+ pty: null,
75
+ buffer: '',
76
+ task: '',
77
+ tool: '',
78
+ lastOutputAt: 0,
79
+ lastHookAt: 0,
80
+ startedAt: 0,
81
+ visit: null, // { targetId, until }
82
+ transcriptPath: null,
83
+ note: '',
84
+ });
85
+ }
86
+ return runtime.get(id);
87
+ }
88
+
89
+ // Rooms keep the order the boss arranged (temporary rooms included, by id).
90
+ function orderRooms(list) {
91
+ const order = db.roomOrder || [];
92
+ const rank = (p, i) => {
93
+ const k = order.indexOf(p.id);
94
+ return k >= 0 ? k : order.length + i;
95
+ };
96
+ return list.map((p, i) => [rank(p, i), p]).sort((a, b) => a[0] - b[0]).map(([, p]) => p);
97
+ }
98
+
99
+ // Buildings (offices / teams) of the city. "main" is the HQ with the boss's
100
+ // office; the boss adds any other building from the empty lot in the city.
101
+ db.buildings = db.buildings && db.buildings.length ? db.buildings : [
102
+ { id: 'main', name: 'Agent Hall', company: 'Getir', tool: 'claude', color: '#3b3447', createdAt: 0 },
103
+ ];
104
+ // The HQ kept the product's old name until the boss renamed it.
105
+ for (const b of db.buildings) if (b.id === 'main' && b.name === 'Agent Office') b.name = 'Agent Hall';
106
+ // Earlier versions created an empty "Partner" building by default; drop it unless rooms moved in.
107
+ db.buildings = db.buildings.filter((b) => b.id !== 'partner' || db.projects.some((p) => p.building === 'partner'));
108
+ const findBuilding = (id) => db.buildings.find((b) => b.id === id);
109
+ const BUILDING_COLORS = ['#3b3447', '#2f3d4f', '#3d4a3a', '#4a3a3a', '#3a3f55', '#4a4334', '#2f4a4a', '#47354a'];
110
+
111
+ function publicState() {
112
+ const ext = [...externals.values()];
113
+ const autoRooms = new Map();
114
+ for (const e of ext) {
115
+ if (findProject(e.projectId) || autoRooms.has(e.projectId)) continue;
116
+ autoRooms.set(e.projectId, { id: e.projectId, name: path.basename(e.cwd), path: e.cwd, color: COLORS[hashStr(e.cwd) % COLORS.length], auto: true, createdAt: 0 });
117
+ }
118
+ return {
119
+ buildings: db.buildings,
120
+ roles: ROLES,
121
+ projects: orderRooms([...db.projects, ...autoRooms.values()]),
122
+ agents: [
123
+ ...ext.map(({ transcript, ...e }) => ({ ...e, game: gameView(e) })),
124
+ ...db.agents.map((a) => {
125
+ const r = rt(a.id);
126
+ return {
127
+ ...a,
128
+ status: r.status,
129
+ task: r.task,
130
+ tool: r.tool,
131
+ note: r.note,
132
+ ask: r.ask,
133
+ stuck: r.stuck,
134
+ meeting: r.meeting || null,
135
+ visit: r.visit,
136
+ startedAt: r.startedAt,
137
+ tool: toolOf(a),
138
+ game: gameView({ ...a, status: r.status }),
139
+ };
140
+ }),
141
+ ],
142
+ game: gameSummary(),
143
+ tasks: db.tasks,
144
+ workday: db.workday,
145
+ usage: usageToday,
146
+ conflicts: activeConflicts(),
147
+ meetings: db.meetings,
148
+ };
149
+ }
150
+
151
+ // ---------------------------------------------------------------- broadcast
152
+
153
+ const clients = new Set();
154
+ let stateTimer = null;
155
+ function broadcastState() {
156
+ if (stateTimer) return;
157
+ stateTimer = setTimeout(() => {
158
+ stateTimer = null;
159
+ const msg = JSON.stringify({ t: 'state', state: publicState() });
160
+ for (const c of clients) if (c.readyState === 1) c.send(msg);
161
+ }, 50);
162
+ }
163
+ function broadcast(obj) {
164
+ const msg = JSON.stringify(obj);
165
+ for (const c of clients) if (c.readyState === 1) c.send(msg);
166
+ }
167
+
168
+ function setStatus(id, status, extra = {}) {
169
+ const r = rt(id);
170
+ const prev = r.status;
171
+ r.status = status;
172
+ Object.assign(r, extra);
173
+ if (status !== 'working' && status !== 'waiting') r.tool = '';
174
+ if (status !== 'waiting') r.ask = null;
175
+ if (status !== 'working' && status !== 'waiting') {
176
+ r.stuck = null;
177
+ r.calls = [];
178
+ }
179
+ if (prev !== status) boardOnStatus(id, prev, status);
180
+ if (prev !== status) meetingOnStatus(id, prev, status);
181
+ if (prev !== status) {
182
+ const a = findAgent(id);
183
+ const credited = onStatusChange(id, prev, status);
184
+ if (a && status === 'waiting') broadcast({ t: 'toast', kind: 'warn', agentId: id, key: 'srv.waiting', params: { name: a.name } });
185
+ if (a && credited) broadcast({ t: 'toast', kind: 'ok', agentId: id, key: 'srv.finished', params: { name: a.name } });
186
+ }
187
+ broadcastState();
188
+ }
189
+
190
+ // ---------------------------------------------------------------- helpers
191
+
192
+ const findAgent = (id) => db.agents.find((a) => a.id === id);
193
+ const findProject = (id) => db.projects.find((p) => p.id === id);
194
+ const newId = () => crypto.randomBytes(6).toString('hex');
195
+ const hashStr = (str) => crypto.createHash('sha1').update(String(str)).digest().readUInt32BE(0);
196
+ const findAny = (id) => findAgent(id) || externals.get(id);
197
+
198
+ // Resolve the user's login shell PATH once so agents start with the same
199
+ // environment as a regular terminal even when launched from elsewhere.
200
+ let shellPath = process.env.PATH || '';
201
+ if (!IS_WIN) {
202
+ try {
203
+ const sh = process.env.SHELL || '/bin/bash';
204
+ const out = execFileSync(sh, ['-ilc', 'printf "__AO__%s__AO__" "$PATH"'], {
205
+ timeout: 5000,
206
+ encoding: 'utf8',
207
+ stdio: ['ignore', 'pipe', 'ignore'],
208
+ });
209
+ const m = out.match(/__AO__(.*)__AO__/s);
210
+ if (m && m[1]) shellPath = m[1];
211
+ } catch {
212
+ /* keep process PATH */
213
+ }
214
+ }
215
+
216
+ function which(cmd) {
217
+ if (path.isAbsolute(cmd)) return cmd;
218
+ const exts = IS_WIN ? ['.exe', '.cmd', '.bat', ''] : [''];
219
+ for (const dir of shellPath.split(path.delimiter)) {
220
+ for (const ext of exts) {
221
+ const p = path.join(dir, cmd + ext);
222
+ try {
223
+ fs.accessSync(p, fs.constants.X_OK);
224
+ if (fs.statSync(p).isFile()) return p;
225
+ } catch {
226
+ /* next */
227
+ }
228
+ }
229
+ }
230
+ return null;
231
+ }
232
+
233
+ // Agent CLIs the office can run. Only Claude Code reports its status through
234
+ // hooks; the others are tracked from terminal activity.
235
+ const TOOLS = {
236
+ claude: { label: 'Claude Code', cmd: 'claude', icon: '✳' },
237
+ cursor: { label: 'Cursor Agent', cmd: 'cursor-agent', icon: '◆', model: (m) => ['--model', m], prompt: (t) => [t], plan: ['--mode', 'plan'], yolo: ['--force'] },
238
+ codex: { label: 'Codex CLI', cmd: 'codex', icon: '◎', model: (m) => ['-m', m], prompt: (t) => [t] },
239
+ gemini: { label: 'Gemini CLI', cmd: 'gemini', icon: '✦', model: (m) => ['-m', m] },
240
+ aider: { label: 'Aider', cmd: 'aider', icon: '▲', model: (m) => ['--model', m] },
241
+ opencode: { label: 'OpenCode', cmd: 'opencode', icon: '▣' },
242
+ custom: { label: 'Custom', cmd: '', icon: '⚙' },
243
+ };
244
+ const toolOf = (agent) => (agent.tool && TOOLS[agent.tool] ? agent.tool : path.basename(agent.command || 'claude').replace(/\.(exe|cmd)$/i, '') === 'claude' ? 'claude' : 'custom');
245
+
246
+ function isClaude(agent) {
247
+ return toolOf(agent) === 'claude';
248
+ }
249
+
250
+ // Small `office` wrapper on every agent's PATH (see office-cli.js).
251
+ const OFFICE_BIN = path.join(HOME, 'bin');
252
+ function writeOfficeCommand() {
253
+ fs.mkdirSync(OFFICE_BIN, { recursive: true });
254
+ const cli = path.join(__dirname, 'office-cli.js');
255
+ if (IS_WIN) fs.writeFileSync(path.join(OFFICE_BIN, 'office.cmd'), `@"${process.execPath}" "${cli}" %*\r\n`);
256
+ else {
257
+ const f = path.join(OFFICE_BIN, 'office');
258
+ fs.writeFileSync(f, `#!/bin/sh\nexec "${process.execPath}" "${cli}" "$@"\n`);
259
+ fs.chmodSync(f, 0o755);
260
+ }
261
+ }
262
+ writeOfficeCommand();
263
+
264
+ function writeHookSettings(agent) {
265
+ const relay = path.join(__dirname, 'hook-relay.js');
266
+ const cmd = (event) =>
267
+ `"${process.execPath}" "${relay}" ${PORT} ${agent.id} ${event} ${db.token}`;
268
+ const entry = (event, matcher) => {
269
+ const e = { hooks: [{ type: 'command', command: cmd(event), timeout: 5 }] };
270
+ if (matcher) e.matcher = matcher;
271
+ return [e];
272
+ };
273
+ const settings = {
274
+ hooks: {
275
+ SessionStart: entry('SessionStart'),
276
+ UserPromptSubmit: entry('UserPromptSubmit'),
277
+ PreToolUse: entry('PreToolUse', '*'),
278
+ PostToolUse: entry('PostToolUse', '*'),
279
+ Notification: entry('Notification'),
280
+ Stop: entry('Stop'),
281
+ },
282
+ };
283
+ const file = path.join(SETTINGS_DIR, `${agent.id}.json`);
284
+ fs.writeFileSync(file, JSON.stringify(settings, null, 2));
285
+ return file;
286
+ }
287
+
288
+ const OFFICE_HELP =
289
+ 'The office is a small city of buildings (teams and offices); some run Claude Code agents, others run other AI tools such as Cursor, Codex or Gemini. ' +
290
+ 'You can talk to any colleague with the `office` shell command: `office who` lists everyone, `office send "<name>" "<message>"` delivers a message to their terminal. ' +
291
+ 'Messages from colleagues start with [MESSAGE from ...]; answer them with `office send` when a reply is useful.';
292
+
293
+ function identityPrompt(agent, project) {
294
+ return [
295
+ `You are ${agent.name}, a ${ROLE_LABELS[agent.role] || agent.role} engineer working in "Agent Hall" on the project "${project.name}".`,
296
+ 'The person talking to you is your boss.',
297
+ 'Messages that start with [ANNOUNCEMENT] are broadcast by the boss to the whole team in your room: read them, act if they concern you, and reply briefly.',
298
+ 'Messages that start with [VISIT] mean the boss sent you to talk with a colleague; the colleague\'s recent context is included.',
299
+ OFFICE_HELP,
300
+ ].join(' ');
301
+ }
302
+
303
+ // ---------------------------------------------------------------- agents
304
+
305
+ // ---- worktrees: an agent can work in its own git worktree on its own branch,
306
+ // so agents in the same repo never edit each other's files. Worktrees live
307
+ // inside the repo (under .claude/worktrees, like Claude Code's own, so the
308
+ // folder trust carries over) and are kept out of `git status` locally.
309
+ const git = (cwd, args) => execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 20000 }).trim();
310
+ const slugOf = (agent) =>
311
+ (agent.name.toLocaleLowerCase('tr').replace(/ı/g, 'i').normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'agent') + '-' + agent.id.slice(0, 4);
312
+
313
+ function gitRoot(dir) {
314
+ try {
315
+ return git(dir, ['rev-parse', '--show-toplevel']);
316
+ } catch {
317
+ return null;
318
+ }
319
+ }
320
+
321
+ function ensureWorktree(agent, project) {
322
+ const root = gitRoot(project.path);
323
+ if (!root) return null; // not a git repo: work in the room's folder
324
+ const slug = slugOf(agent);
325
+ const wt = path.join(root, '.claude', 'worktrees', 'agent-' + slug);
326
+ const branch = 'office/' + slug;
327
+ if (!fs.existsSync(path.join(wt, '.git'))) {
328
+ try {
329
+ const exists = (() => {
330
+ try {
331
+ git(root, ['rev-parse', '--verify', '--quiet', 'refs/heads/' + branch]);
332
+ return true;
333
+ } catch {
334
+ return false;
335
+ }
336
+ })();
337
+ git(root, exists ? ['worktree', 'add', wt, branch] : ['worktree', 'add', '-b', branch, wt, 'HEAD']);
338
+ const exclude = path.join(git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']), 'info', 'exclude');
339
+ const rule = '/.claude/worktrees/';
340
+ const has = fs.existsSync(exclude) && fs.readFileSync(exclude, 'utf8').split('\n').includes(rule);
341
+ if (!has) {
342
+ fs.mkdirSync(path.dirname(exclude), { recursive: true });
343
+ fs.appendFileSync(exclude, `\n# Agent Hall worktrees\n${rule}\n`);
344
+ }
345
+ } catch (e) {
346
+ throw new OfficeError('err.worktree', { error: String(e.stderr || e.message).trim().split('\n')[0] });
347
+ }
348
+ }
349
+ agent.worktreePath = wt;
350
+ agent.branch = branch;
351
+ save();
352
+ // a room on a subfolder of the repo works in the same subfolder of the worktree
353
+ return path.join(wt, path.relative(root, project.path));
354
+ }
355
+
356
+ function agentCwd(agent, project) {
357
+ return (agent.worktree && ensureWorktree(agent, project)) || project.path;
358
+ }
359
+
360
+ // When an agent leaves: remove its worktree if nothing is left uncommitted.
361
+ // The branch stays, with whatever was committed on it.
362
+ function dropWorktree(agent) {
363
+ const wt = agent.worktreePath;
364
+ if (!wt || !fs.existsSync(wt)) return null;
365
+ try {
366
+ if (git(wt, ['status', '--porcelain'])) return { kept: wt };
367
+ const root = path.dirname(path.dirname(path.dirname(wt)));
368
+ git(root, ['worktree', 'remove', wt]);
369
+ return { removed: wt };
370
+ } catch {
371
+ return { kept: wt };
372
+ }
373
+ }
374
+
375
+ function startAgent(agent, initialPrompt) {
376
+ const r = rt(agent.id);
377
+ if (r.pty) return;
378
+ const project = findProject(agent.projectId);
379
+ if (!project) throw new OfficeError('err.projectNotFound');
380
+ if (!fs.existsSync(project.path)) throw new OfficeError('err.projectFolderMissing', { path: project.path });
381
+ const cwd = agentCwd(agent, project);
382
+
383
+ const command = agent.command || 'claude';
384
+ const resolved = which(command);
385
+ if (!resolved) throw new OfficeError('err.commandNotFound', { command });
386
+
387
+ const args = [];
388
+ let resumed = false;
389
+ if (isClaude(agent)) {
390
+ const bad = claudeConfigProblem();
391
+ if (bad) throw new OfficeError('err.claudeConfigUnreadable', bad);
392
+ args.push('--settings', writeHookSettings(agent));
393
+ args.push('--append-system-prompt', identityPrompt(agent, project));
394
+ if (agent.model) args.push('--model', agent.model);
395
+ if (agent.permissionMode && agent.permissionMode !== 'default') args.push('--permission-mode', agent.permissionMode);
396
+ if (agent.hasConversation && agent.sessionId) {
397
+ args.push('--resume', agent.sessionId);
398
+ if (agent.forkOnce) args.push('--fork-session');
399
+ delete agent.forkOnce;
400
+ resumed = true;
401
+ } else {
402
+ agent.sessionId = crypto.randomUUID();
403
+ args.push('--session-id', agent.sessionId);
404
+ }
405
+ args.push('--name', `${agent.name} (${project.name})`);
406
+ if (initialPrompt) args.push(initialPrompt);
407
+ } else {
408
+ const tool = TOOLS[toolOf(agent)];
409
+ if (agent.model && tool.model) args.push(...tool.model(agent.model));
410
+ if (agent.permissionMode === 'plan' && tool.plan) args.push(...tool.plan);
411
+ if (agent.permissionMode === 'bypassPermissions' && tool.yolo) args.push(...tool.yolo);
412
+ if (agent.args) args.push(...agent.args);
413
+ // Other tools get the office introduction together with their first task.
414
+ if (initialPrompt) {
415
+ const intro = `${initialPrompt}\n\n(You are ${agent.name}, working in Agent Hall on "${project.name}". ${OFFICE_HELP})`;
416
+ if (tool.prompt) args.push(...tool.prompt(intro));
417
+ else setTimeout(() => rt(agent.id).pty && sendToAgent(agent, intro), 6000);
418
+ }
419
+ }
420
+
421
+ const env = {
422
+ ...process.env,
423
+ PATH: OFFICE_BIN + path.delimiter + shellPath,
424
+ AGENT_OFFICE_AGENT: agent.id,
425
+ AGENT_OFFICE_PORT: String(PORT),
426
+ AGENT_OFFICE_TOKEN: db.token,
427
+ TERM: 'xterm-256color',
428
+ COLORTERM: 'truecolor',
429
+ };
430
+ // Allow a clean launch even when the office itself was started from inside Claude Code.
431
+ for (const k of ['CLAUDECODE', 'CLAUDE_CODE_CHILD_SESSION', 'CLAUDE_CODE_ENTRYPOINT', 'CLAUDE_CODE_SSE_PORT']) delete env[k];
432
+ let file = resolved;
433
+ let argv = args;
434
+ if (IS_WIN && /\.(cmd|bat)$/i.test(resolved)) {
435
+ file = process.env.ComSpec || 'cmd.exe';
436
+ argv = ['/c', resolved, ...args];
437
+ }
438
+
439
+ const p = pty.spawn(file, argv, { name: 'xterm-256color', cols: 120, rows: 34, cwd, env });
440
+ r.pty = p;
441
+ r.buffer = '';
442
+ r.startedAt = Date.now();
443
+ r.promptSinceStart = false;
444
+ r.task = initialPrompt ? initialPrompt.slice(0, 240) : r.task;
445
+ r.note = '';
446
+ setStatus(agent.id, initialPrompt ? 'working' : 'starting');
447
+ save();
448
+
449
+ p.onData((data) => {
450
+ r.buffer += data;
451
+ if (r.buffer.length > SCROLLBACK_LIMIT) r.buffer = r.buffer.slice(-SCROLLBACK_LIMIT);
452
+ r.lastOutputAt = Date.now();
453
+ const msg = JSON.stringify({ t: 'out', id: agent.id, data });
454
+ for (const c of clients) if (c.readyState === 1 && c.attached === agent.id) c.send(msg);
455
+ });
456
+
457
+ p.onExit(({ exitCode }) => {
458
+ r.pty = null;
459
+ // A resume that dies right away usually means the session is gone: start fresh next time.
460
+ if (resumed && Date.now() - r.startedAt < 8000 && exitCode !== 0) {
461
+ agent.hasConversation = false;
462
+ r.note = { key: 'srv.resumeFailed' };
463
+ save();
464
+ }
465
+ r.visit = null;
466
+ setStatus(agent.id, 'offline');
467
+ broadcast({ t: 'exit', id: agent.id, code: exitCode });
468
+ });
469
+
470
+ // No hook after boot usually means Claude is blocked on a prompt (e.g. the
471
+ // folder trust question) that the boss has to answer in the terminal.
472
+ setTimeout(() => {
473
+ if (r.pty !== p) return;
474
+ if (isClaude(agent) && r.lastHookAt < r.startedAt) {
475
+ setStatus(agent.id, 'waiting', { note: { key: 'srv.blockedPrompt' } });
476
+ } else if (r.status === 'starting') setStatus(agent.id, 'idle');
477
+ }, 7000);
478
+ }
479
+
480
+ function stopAgent(agent) {
481
+ const r = rt(agent.id);
482
+ if (!r.pty) return;
483
+ try {
484
+ r.pty.kill();
485
+ } catch {
486
+ /* already gone */
487
+ }
488
+ }
489
+
490
+ // Type text into the agent's TUI as a paste, then press enter.
491
+ function sendToAgent(agent, text) {
492
+ const r = rt(agent.id);
493
+ if (!r.pty) throw new OfficeError('err.offline', { name: agent.name });
494
+ const p = r.pty;
495
+ const multi = text.includes('\n');
496
+ p.write(multi ? `\x1b[200~${text}\x1b[201~` : text);
497
+ setTimeout(() => {
498
+ if (r.pty === p) p.write('\r');
499
+ }, multi ? 400 : 150);
500
+ if (r.status === 'idle' || r.status === 'starting') setStatus(agent.id, 'working', { task: text.slice(0, 240) });
501
+ }
502
+
503
+ // Short, readable summary of the last conversation turns from a transcript.
504
+ function recentContext(agent, maxChars = 4000) {
505
+ const file = agent.external ? agent.transcript : rt(agent.id).transcriptPath;
506
+ const lines = conversation(transcriptEntries(file), 60)
507
+ .filter((m) => m.who !== 'tool')
508
+ .map((m) => `${m.who === 'user' ? 'Boss/User' : agent.name}: ${m.text}`);
509
+ let out = lines.join('\n\n');
510
+ if (!out && !agent.external) {
511
+ // eslint-disable-next-line no-control-regex
512
+ out = rt(agent.id).buffer.replace(/\x1b\[(\d*)C/g, (_, n) => ' '.repeat(Number(n) || 1)).replace(/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07|\x1b[=>()][0-9A-Za-z]?/g, '').replace(/\r/g, '');
513
+ out = out.split('\n').map((x) => x.trimEnd()).filter(Boolean).join('\n');
514
+ }
515
+ return out.slice(-maxChars);
516
+ }
517
+
518
+ // ---------------------------------------------------------------- transcripts
519
+
520
+ const CLAUDE_DIR = path.join(os.homedir(), '.claude');
521
+
522
+ // Claude Code keeps its login and onboarding state in ~/.claude.json. If it is
523
+ // unreadable (typically left owned by root after `sudo claude`), every agent
524
+ // boots into the first-run theme picker and asks to log in again.
525
+ function claudeConfigProblem() {
526
+ const file = path.join(process.env.CLAUDE_CONFIG_DIR || os.homedir(), '.claude.json');
527
+ try {
528
+ fs.accessSync(file, fs.constants.R_OK | fs.constants.W_OK);
529
+ return null;
530
+ } catch (e) {
531
+ return e.code === 'ENOENT' ? null : { path: file };
532
+ }
533
+ }
534
+
535
+ // Read only the end of a (possibly huge) transcript file.
536
+ function readTail(file, bytes = 384 * 1024) {
537
+ const fd = fs.openSync(file, 'r');
538
+ try {
539
+ const { size } = fs.fstatSync(fd);
540
+ const start = Math.max(0, size - bytes);
541
+ const buf = Buffer.alloc(size - start);
542
+ fs.readSync(fd, buf, 0, buf.length, start);
543
+ let str = buf.toString('utf8');
544
+ if (start > 0) str = str.slice(str.indexOf('\n') + 1);
545
+ return str;
546
+ } finally {
547
+ fs.closeSync(fd);
548
+ }
549
+ }
550
+
551
+ const entryCache = new Map(); // file -> { mtime, size, entries }
552
+ function transcriptEntries(file) {
553
+ if (!file) return [];
554
+ let st;
555
+ try {
556
+ st = fs.statSync(file);
557
+ } catch {
558
+ return [];
559
+ }
560
+ const c = entryCache.get(file);
561
+ if (c && c.mtime === st.mtimeMs && c.size === st.size) return c.entries;
562
+ const entries = [];
563
+ let raw;
564
+ try {
565
+ raw = readTail(file);
566
+ } catch {
567
+ // e.g. a transcript owned by another user (session started with sudo)
568
+ return [];
569
+ }
570
+ for (const line of raw.split('\n')) {
571
+ let e;
572
+ try {
573
+ e = JSON.parse(line);
574
+ } catch {
575
+ continue;
576
+ }
577
+ if ((e.type !== 'user' && e.type !== 'assistant') || e.isMeta || !e.message) continue;
578
+ const content = e.message.content;
579
+ const item = { type: e.type, ts: e.timestamp, stop: e.message.stop_reason, text: '', tools: [], results: [] };
580
+ if (typeof content === 'string') item.text = content;
581
+ else if (Array.isArray(content)) {
582
+ for (const part of content) {
583
+ if (part.type === 'text') item.text += (item.text ? '\n' : '') + part.text;
584
+ else if (part.type === 'tool_use') item.tools.push({ id: part.id, name: part.name, input: part.input });
585
+ else if (part.type === 'tool_result') item.results.push(part.tool_use_id);
586
+ }
587
+ }
588
+ item.text = item.text.trim();
589
+ entries.push(item);
590
+ }
591
+ entryCache.set(file, { mtime: st.mtimeMs, size: st.size, entries });
592
+ return entries;
593
+ }
594
+
595
+ // Prompts typed by a person, as opposed to command output and injected context.
596
+ const isHumanText = (t) => t && !t.startsWith('<') && !t.startsWith('Caveat:');
597
+
598
+ function conversation(entries, max = 80) {
599
+ const out = [];
600
+ for (const e of entries) {
601
+ if (e.type === 'user' && isHumanText(e.text)) out.push({ who: 'user', text: e.text, ts: e.ts });
602
+ if (e.type === 'assistant') {
603
+ if (e.text) out.push({ who: 'agent', text: e.text, ts: e.ts });
604
+ for (const t of e.tools) out.push({ who: 'tool', text: summarizeTool(t.name, t.input), ts: e.ts });
605
+ }
606
+ }
607
+ return out.slice(-max);
608
+ }
609
+
610
+ function digest(entries) {
611
+ let task = '';
612
+ let tool = '';
613
+ const done = new Set();
614
+ for (let i = entries.length - 1; i >= 0; i--) {
615
+ const e = entries[i];
616
+ e.results.forEach((id) => done.add(id));
617
+ if (!tool && e.type === 'assistant') {
618
+ const open = e.tools.find((t) => !done.has(t.id));
619
+ if (open) tool = summarizeTool(open.name, open.input);
620
+ }
621
+ if (!task && e.type === 'user' && isHumanText(e.text)) task = e.text.slice(0, 240);
622
+ if (task && (tool || i < entries.length - 40)) break;
623
+ }
624
+ return { task, tool };
625
+ }
626
+
627
+ function transcriptFile(cwd, sessionId) {
628
+ const direct = path.join(CLAUDE_DIR, 'projects', cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`);
629
+ if (fs.existsSync(direct)) return direct;
630
+ try {
631
+ for (const d of fs.readdirSync(path.join(CLAUDE_DIR, 'projects'))) {
632
+ const f = path.join(CLAUDE_DIR, 'projects', d, `${sessionId}.jsonl`);
633
+ if (fs.existsSync(f)) return f;
634
+ }
635
+ } catch {
636
+ /* none */
637
+ }
638
+ return null;
639
+ }
640
+
641
+ // ---------------------------------------------------------------- task board
642
+
643
+ // Each room has a board of cards. An idle agent in the room takes the oldest
644
+ // card; the card is done when the agent finishes that turn.
645
+ const BOARD_IDLE_MS = 5000;
646
+ const DONE_KEEP_MS = 3 * 24 * 60 * 60 * 1000;
647
+ db.tasks = db.tasks.filter((t) => t.status !== 'done' || Date.now() - t.doneAt < DONE_KEEP_MS);
648
+ // Nobody is working on a card across a restart.
649
+ for (const t of db.tasks) if (t.status === 'doing') Object.assign(t, { status: 'todo', agentId: null });
650
+
651
+ // Put an agent's card back at the front of the queue.
652
+ function boardReturn(agentId) {
653
+ const r = rt(agentId);
654
+ const task = db.tasks.find((x) => x.id === r.boardTask);
655
+ r.boardTask = null;
656
+ if (!task || task.status !== 'doing') return;
657
+ Object.assign(task, { status: 'todo', agentId: null });
658
+ save();
659
+ }
660
+
661
+ function boardOnStatus(id, prev, status) {
662
+ const r = rt(id);
663
+ if (status === 'working' && prev === 'idle') r.boardHold = false;
664
+ if (!r.boardTask) return;
665
+ if (status === 'offline') return boardReturn(id);
666
+ if (status !== 'idle' || (prev !== 'working' && prev !== 'waiting') || gl(id).declined) return;
667
+ const task = db.tasks.find((x) => x.id === r.boardTask);
668
+ r.boardTask = null;
669
+ if (!task) return;
670
+ Object.assign(task, { status: 'done', doneAt: Date.now() });
671
+ save();
672
+ const a = findAgent(id);
673
+ if (a) broadcast({ t: 'toast', kind: 'ok', agentId: id, key: 'srv.boardDone', params: { name: a.name, task: task.text.slice(0, 60) } });
674
+ }
675
+
676
+ function boardTick() {
677
+ const now = Date.now();
678
+ const todo = db.tasks.filter((t) => t.status === 'todo').sort((p, q) => p.createdAt - q.createdAt);
679
+ let changed = false;
680
+ for (const task of todo) {
681
+ const agent = db.agents.find((a) => {
682
+ const r = rt(a.id);
683
+ const l = gl(a.id);
684
+ return a.projectId === task.projectId && r.pty && r.status === 'idle' && !r.boardTask && !r.boardHold && !r.visit && !r.meeting && !l.oneOnOne && now - (l.idleSince || now) >= BOARD_IDLE_MS;
685
+ });
686
+ if (!agent) continue;
687
+ try {
688
+ sendToAgent(agent, `[BOARD TASK from the boss] ${task.text}`);
689
+ } catch {
690
+ continue;
691
+ }
692
+ Object.assign(task, { status: 'doing', agentId: agent.id, startedAt: now });
693
+ rt(agent.id).boardTask = task.id;
694
+ broadcast({ t: 'toast', kind: 'info', agentId: agent.id, key: 'srv.boardPicked', params: { name: agent.name, task: task.text.slice(0, 60) } });
695
+ changed = true;
696
+ }
697
+ if (changed) {
698
+ save();
699
+ broadcastState();
700
+ }
701
+ }
702
+ setInterval(boardTick, 3000);
703
+
704
+ // ---------------------------------------------------------------- meetings
705
+
706
+ // The boss picks a few idle Claude agents and a topic. Round 0: everyone gives
707
+ // their view; round 1: everyone answers the others; round 2: the first one
708
+ // (the chair) writes the summary for the boss. Nobody changes files.
709
+ const MEETING_MAX = 6;
710
+ const MEETINGS_KEEP = 20;
711
+ const MEETING_ROUND_MS = 5 * 60000;
712
+ db.meetings = db.meetings || [];
713
+ for (const m of db.meetings) if (m.status === 'running') m.status = 'cancelled'; // nobody is in a meeting after a restart
714
+
715
+ const meetingLine = (m, entry) => `${m.names[entry.agentId]}: ${entry.text}`;
716
+ function meetingPrompt(m, round, a) {
717
+ const others = m.participants.filter((id) => id !== a.id).map((id) => {
718
+ const x = findAgent(id);
719
+ const p = x && findProject(x.projectId);
720
+ return `${m.names[id]} (${ROLE_LABELS[x ? x.role : 'mid']}, project "${p ? p.name : '?'}")`;
721
+ });
722
+ const rules = 'Answer in the chat only: do not change any files, do not run commands that change anything.';
723
+ const lang = m.lang === 'tr' ? 'Turkish' : 'English';
724
+ if (round === 0) return `[MEETING] The boss called a meeting about: "${m.topic}". With you: ${others.join(', ')}. Give your view from your own project's side in at most 150 words, in ${lang}. ${rules}`;
725
+ if (round === 1) return `[MEETING] Round 2. What the others said:\n\n${m.rounds[0].filter((e) => e.agentId !== a.id).map((e) => meetingLine(m, e)).join('\n\n')}\n\nAnswer them: agree, disagree or add what is missing, in at most 120 words, in ${lang}. ${rules}`;
726
+ return `[MEETING] You chair this meeting about "${m.topic}". The whole discussion:\n\n${m.rounds.flat().map((e) => meetingLine(m, e)).join('\n\n')}\n\nWrite the summary for the boss in ${lang}: decisions, open questions, and action items with an owner each. At most 250 words. ${rules}`;
727
+ }
728
+
729
+ function meetingRound(m, round) {
730
+ m.round = round;
731
+ m.rounds[round] = m.rounds[round] || [];
732
+ m.roundAt = Date.now();
733
+ const who = round === 2 ? [m.participants[0]] : m.participants;
734
+ m.waiting = [];
735
+ for (const id of who) {
736
+ const a = findAgent(id);
737
+ const r = a && rt(a.id);
738
+ if (!a || !r.pty) {
739
+ m.rounds[round].push({ agentId: id, text: '(—)' });
740
+ continue;
741
+ }
742
+ r.meeting = m.id;
743
+ m.waiting.push(id);
744
+ try {
745
+ sendToAgent(a, meetingPrompt(m, round, a));
746
+ } catch {
747
+ m.waiting = m.waiting.filter((x) => x !== id);
748
+ m.rounds[round].push({ agentId: id, text: '(—)' });
749
+ }
750
+ }
751
+ save();
752
+ broadcastState();
753
+ if (!m.waiting.length) nextMeetingRound(m);
754
+ }
755
+
756
+ function lastAgentText(file) {
757
+ const entries = transcriptEntries(file);
758
+ for (let i = entries.length - 1; i >= 0; i--) {
759
+ const e = entries[i];
760
+ if (e.type === 'user' && isHumanText(e.text)) break;
761
+ if (e.type === 'assistant' && e.text) return e.text;
762
+ }
763
+ return '';
764
+ }
765
+
766
+ function meetingAnswer(m, id, text) {
767
+ if (!m.waiting.includes(id)) return;
768
+ m.waiting = m.waiting.filter((x) => x !== id);
769
+ if (m.round === 2) m.summary = text;
770
+ else m.rounds[m.round].push({ agentId: id, text });
771
+ save();
772
+ broadcastState();
773
+ if (!m.waiting.length) nextMeetingRound(m);
774
+ }
775
+
776
+ function nextMeetingRound(m) {
777
+ if (m.status !== 'running') return;
778
+ if (m.round < 2) return meetingRound(m, m.round + 1);
779
+ endMeeting(m, 'done');
780
+ }
781
+
782
+ function endMeeting(m, status) {
783
+ m.status = status;
784
+ m.endedAt = Date.now();
785
+ m.waiting = [];
786
+ for (const id of m.participants) if (rt(id).meeting === m.id) rt(id).meeting = null;
787
+ save();
788
+ broadcastState();
789
+ if (status === 'done') broadcast({ t: 'toast', kind: 'ok', key: 'srv.meetingDone', params: { topic: m.topic.slice(0, 60) } });
790
+ }
791
+
792
+ function meetingOnStatus(id, prev, status) {
793
+ const r = rt(id);
794
+ const m = r.meeting && db.meetings.find((x) => x.id === r.meeting);
795
+ if (!m || m.status !== 'running') return;
796
+ if (status === 'offline') return meetingAnswer(m, id, '(—)');
797
+ if (status !== 'idle' || (prev !== 'working' && prev !== 'waiting')) return;
798
+ gl(id).declined = true; // a meeting answer is not a finished task: no toast, no XP
799
+ // the transcript gets the last words a moment after the turn ends
800
+ setTimeout(() => meetingAnswer(m, id, lastAgentText(r.transcriptPath) || '(—)'), 1200);
801
+ }
802
+
803
+ setInterval(() => {
804
+ for (const m of db.meetings) {
805
+ if (m.status !== 'running' || Date.now() - m.roundAt < MEETING_ROUND_MS) continue;
806
+ for (const id of [...m.waiting]) meetingAnswer(m, id, '(—)');
807
+ }
808
+ }, 15 * 1000);
809
+
810
+ // ---------------------------------------------------------------- workday
811
+
812
+ // Agents with nothing to do go home after a while (the conversation is kept and
813
+ // resumed when they come back), and everyone idle goes home once the workday
814
+ // is over. A card on the board calls someone in when the room is empty.
815
+ const WORKDAY_DEFAULTS = { autoHome: true, idleMin: 45, endHour: null, autoWake: true };
816
+ db.workday = { ...WORKDAY_DEFAULTS, ...(db.workday || {}) };
817
+ const AFTER_HOURS_IDLE_MS = 60 * 1000;
818
+
819
+ function workdayOver(now = new Date()) {
820
+ const end = db.workday.endHour;
821
+ // the workday ends at endHour and starts again at 6 in the morning
822
+ return end !== null && end !== undefined && (now.getHours() >= end || now.getHours() < 6);
823
+ }
824
+
825
+ function workdayTick() {
826
+ const now = Date.now();
827
+ const w = db.workday;
828
+ const over = workdayOver();
829
+ if (w.autoHome || over) {
830
+ for (const a of db.agents) {
831
+ const r = rt(a.id);
832
+ const l = gl(a.id);
833
+ if (!r.pty || r.status !== 'idle' || r.boardTask || r.visit || r.meeting || l.oneOnOne) continue;
834
+ const idle = now - (l.idleSince || now);
835
+ const limit = over ? AFTER_HOURS_IDLE_MS : w.autoHome ? w.idleMin * 60000 : Infinity;
836
+ if (idle < limit) continue;
837
+ stopAgent(a);
838
+ broadcast({ t: 'toast', kind: 'info', agentId: a.id, key: over ? 'srv.homeEndOfDay' : 'srv.homeIdle', params: { name: a.name, n: w.idleMin } });
839
+ }
840
+ }
841
+ }
842
+ setInterval(workdayTick, 30 * 1000);
843
+
844
+ // Someone left a card in an empty room: call the first one at home in to work.
845
+ const wakeTried = new Map(); // projectId -> last attempt
846
+ function boardWake() {
847
+ if (!db.workday.autoWake) return;
848
+ const now = Date.now();
849
+ const rooms = new Set(db.tasks.filter((t) => t.status === 'todo').map((t) => t.projectId));
850
+ for (const pid of rooms) {
851
+ const team = db.agents.filter((a) => a.projectId === pid);
852
+ if (!team.length || team.some((a) => rt(a.id).pty)) continue;
853
+ if (now - (wakeTried.get(pid) || 0) < 5 * 60000) continue;
854
+ wakeTried.set(pid, now);
855
+ const a = team[0];
856
+ try {
857
+ startAgent(a);
858
+ broadcast({ t: 'toast', kind: 'info', agentId: a.id, key: 'srv.calledIn', params: { name: a.name } });
859
+ } catch (e) {
860
+ console.error(`Could not call ${a.name} in: ${e.message}`);
861
+ }
862
+ }
863
+ }
864
+ setInterval(boardWake, 5000);
865
+
866
+ // ---------------------------------------------------------------- end-of-day report
867
+
868
+ // What every Claude session did on one local day, read from the transcripts:
869
+ // tasks given, files changed, commits, pull requests and the last word.
870
+ // Covers office agents, the boss's own terminals and sessions closed since.
871
+ const PR_RE = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
872
+ // Lines Claude Code writes into the user's turn that nobody typed.
873
+ const NOT_A_TASK = /^(\[Request interrupted|This session is being continued|No response requested)/;
874
+ const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
875
+
876
+ // The subject line of a `git commit` in a shell command, or null if none.
877
+ function commitMessage(cmd) {
878
+ const c = String(cmd || '').match(/(?:^|[\s;&|(])git(?:\s+-C\s+\S+)?\s+commit\b([\s\S]*)/);
879
+ if (!c) return null;
880
+ const rest = c[1];
881
+ const heredoc = rest.match(/^[^\n]*<<-?\s*['"]?(\w+)['"]?[^\n]*\n\s*([^\n]+)/);
882
+ if (heredoc) return heredoc[2].trim();
883
+ const m = rest.match(/-m\s+(?:"([^"]+)"|'([^']+)')/);
884
+ return m ? (m[1] || m[2]).split('\n')[0].trim() : '';
885
+ }
886
+
887
+ function resultText(content) {
888
+ if (typeof content === 'string') return content;
889
+ if (Array.isArray(content)) return content.map((c) => (c && c.type === 'text' ? c.text : '')).join('\n');
890
+ return '';
891
+ }
892
+
893
+ // `seen` holds entry ids already counted: resumed and forked sessions start
894
+ // with a copy of the earlier conversation, which must not count twice.
895
+ // API list prices in $ per million tokens: input, output, cache read. Cache
896
+ // writes cost 1.25x input for 5 minutes and 2x for an hour; fast mode doubles
897
+ // it all. Longest prefix first. Subscriptions don't pay per token, so this is
898
+ // what the same work would cost on the API.
899
+ const PRICES = [
900
+ ['claude-fable-5-1', 10, 50, 0.25],
901
+ ['claude-fable-5', 10, 50, 1],
902
+ ['claude-mythos', 10, 50, 1],
903
+ ['claude-opus-5-5', 4, 20, 0.2],
904
+ ['claude-opus-5', 5, 25, 0.5],
905
+ ['claude-opus-4-8', 5, 25, 0.5],
906
+ ['claude-opus-4-7', 5, 25, 0.5],
907
+ ['claude-opus-4-6', 5, 25, 0.5],
908
+ ['claude-sonnet-5-5', 2, 10, 0.2],
909
+ ['claude-sonnet-5', 2, 10, 0.2],
910
+ ['claude-sonnet-4-6', 3, 15, 0.3],
911
+ ['claude-haiku-4-5', 1, 5, 0.1],
912
+ ];
913
+ const emptyUsage = () => ({ input: 0, output: 0, cacheWrite: 0, cacheRead: 0, cost: 0, unpriced: 0 });
914
+ function addUsage(u, model, x, speed) {
915
+ const cw5 = (x.cache_creation && x.cache_creation.ephemeral_5m_input_tokens) || 0;
916
+ const cw1h = (x.cache_creation && x.cache_creation.ephemeral_1h_input_tokens) || 0;
917
+ const cw = x.cache_creation_input_tokens || cw5 + cw1h;
918
+ const tokens = { input: x.input_tokens || 0, output: x.output_tokens || 0, cacheWrite: cw, cacheRead: x.cache_read_input_tokens || 0 };
919
+ for (const k of Object.keys(tokens)) u[k] += tokens[k];
920
+ const price = PRICES.find(([id]) => String(model).startsWith(id));
921
+ if (!price) {
922
+ u.unpriced += tokens.input + tokens.output + cw + tokens.cacheRead;
923
+ return;
924
+ }
925
+ const [, pin, pout, pread] = price;
926
+ // writes without the 5m/1h split are counted as 5-minute writes
927
+ const cw5m = cw5 + cw1h ? cw5 : cw;
928
+ const dollars = (tokens.input * pin + tokens.output * pout + tokens.cacheRead * pread + cw5m * pin * 1.25 + cw1h * pin * 2) / 1e6;
929
+ u.cost += speed === 'fast' ? dollars * 2 : dollars;
930
+ }
931
+ function mergeUsage(into, u) {
932
+ for (const k of Object.keys(into)) into[k] += u[k];
933
+ return into;
934
+ }
935
+
936
+ function sessionReport(file, from, to, seen, sub = false) {
937
+ let raw;
938
+ try {
939
+ raw = readTail(file, 8 * 1024 * 1024);
940
+ } catch {
941
+ return null;
942
+ }
943
+ const r = { cwd: '', tasks: [], files: new Set(), commits: [], prs: new Set(), last: '', first: 0, end: 0, tools: 0, usage: emptyUsage() };
944
+ for (const line of raw.split('\n')) {
945
+ let e;
946
+ try {
947
+ e = JSON.parse(line);
948
+ } catch {
949
+ continue;
950
+ }
951
+ if ((e.type !== 'user' && e.type !== 'assistant') || e.isMeta || !e.message) continue;
952
+ const ts = Date.parse(e.timestamp);
953
+ if (!(ts >= from && ts < to)) continue;
954
+ // One API message is written once per content block, each with the same usage.
955
+ const mid = e.type === 'assistant' && e.message.usage && e.message.id;
956
+ if (mid && !seen.has('m:' + mid)) {
957
+ seen.add('m:' + mid);
958
+ addUsage(r.usage, e.message.model, e.message.usage, e.message.usage.speed);
959
+ r.first = r.first || ts;
960
+ r.end = ts;
961
+ }
962
+ if (sub || e.isSidechain) continue;
963
+ if (e.uuid) {
964
+ if (seen.has(e.uuid)) continue;
965
+ seen.add(e.uuid);
966
+ }
967
+ if (e.cwd) r.cwd = e.cwd;
968
+ r.first = r.first || ts;
969
+ r.end = ts;
970
+ const content = typeof e.message.content === 'string' ? [{ type: 'text', text: e.message.content }] : e.message.content || [];
971
+ for (const part of content) {
972
+ if (!part) continue;
973
+ if (part.type === 'text' && part.text) {
974
+ const t = part.text.trim();
975
+ if (e.type === 'user' && isHumanText(t) && !NOT_A_TASK.test(t)) r.tasks.push(t.replace(/\s+/g, ' ').slice(0, 200));
976
+ if (e.type === 'assistant' && t) r.last = t.slice(0, 600);
977
+ for (const u of t.match(PR_RE) || []) r.prs.add(u);
978
+ } else if (part.type === 'tool_use') {
979
+ r.tools++;
980
+ const input = part.input || {};
981
+ if (EDIT_TOOLS.has(part.name) && (input.file_path || input.notebook_path)) {
982
+ const f = input.file_path || input.notebook_path;
983
+ r.files.add(r.cwd && f.startsWith(r.cwd + '/') ? f.slice(r.cwd.length + 1) : f);
984
+ }
985
+ const msg = part.name === 'Bash' ? commitMessage(input.command) : null;
986
+ if (msg !== null) r.commits.push(msg || '(commit)');
987
+ } else if (part.type === 'tool_result') {
988
+ for (const u of resultText(part.content).match(PR_RE) || []) r.prs.add(u);
989
+ }
990
+ }
991
+ }
992
+ if (!r.tasks.length && !r.tools && !r.end) return null;
993
+ return { ...r, files: [...r.files], prs: [...r.prs] };
994
+ }
995
+
996
+ function dayReport(day) {
997
+ const from = new Date(`${day}T00:00:00`).getTime();
998
+ const to = from + 24 * 60 * 60 * 1000;
999
+ const base = path.join(CLAUDE_DIR, 'projects');
1000
+ const out = [];
1001
+ const candidates = [];
1002
+ let dirs = [];
1003
+ try {
1004
+ dirs = fs.readdirSync(base, { withFileTypes: true }).filter((d) => d.isDirectory());
1005
+ } catch {
1006
+ return { day, sessions: out };
1007
+ }
1008
+ for (const d of dirs) {
1009
+ let files = [];
1010
+ try {
1011
+ files = fs.readdirSync(path.join(base, d.name)).filter((f) => f.endsWith('.jsonl'));
1012
+ } catch {
1013
+ continue;
1014
+ }
1015
+ const add = (file, sessionId, sub) => {
1016
+ try {
1017
+ const st = fs.statSync(file);
1018
+ if (st.mtimeMs >= from) candidates.push({ file, sessionId, sub, born: st.birthtimeMs || st.ctimeMs });
1019
+ } catch {
1020
+ /* gone */
1021
+ }
1022
+ };
1023
+ for (const f of files) {
1024
+ const sessionId = f.slice(0, -6);
1025
+ add(path.join(base, d.name, f), sessionId, false);
1026
+ // subagents (interns) keep their own transcripts next to the session
1027
+ const subDir = path.join(base, d.name, sessionId, 'subagents');
1028
+ let subs = [];
1029
+ try {
1030
+ subs = fs.readdirSync(subDir).filter((x) => x.endsWith('.jsonl'));
1031
+ } catch {
1032
+ /* none */
1033
+ }
1034
+ for (const x of subs) add(path.join(subDir, x), sessionId, true);
1035
+ }
1036
+ }
1037
+ // Oldest first, so copied history is credited to the session it began in;
1038
+ // sessions before their subagents.
1039
+ candidates.sort((a, b) => a.sub - b.sub || a.born - b.born);
1040
+ const seen = new Set();
1041
+ const bySession = new Map();
1042
+ for (const { file, sessionId, sub } of candidates) {
1043
+ const rep = sessionReport(file, from, to, seen, sub);
1044
+ if (!rep) continue;
1045
+ const parent = bySession.get(sessionId);
1046
+ if (sub && parent) {
1047
+ mergeUsage(parent.usage, rep.usage);
1048
+ parent.first = Math.min(parent.first, rep.first);
1049
+ parent.end = Math.max(parent.end, rep.end);
1050
+ continue;
1051
+ }
1052
+ const agent = db.agents.find((a) => a.sessionId === sessionId);
1053
+ const ext = [...externals.values()].find((x) => x.sessionId === sessionId);
1054
+ const meta = db.external[sessionId];
1055
+ const row = {
1056
+ sessionId,
1057
+ agentId: agent ? agent.id : ext ? ext.id : null,
1058
+ name: (agent && agent.name) || (ext && ext.name) || (meta && meta.name) || '',
1059
+ office: !!agent,
1060
+ room: (agent && findProject(agent.projectId)?.name) || (rep.cwd ? path.basename(rep.cwd) : ''),
1061
+ ...rep,
1062
+ };
1063
+ bySession.set(sessionId, row);
1064
+ out.push(row);
1065
+ }
1066
+ out.sort((a, b) => b.end - a.end);
1067
+ return { day, sessions: out, usage: out.reduce((u, r) => mergeUsage(u, r.usage), emptyUsage()) };
1068
+ }
1069
+
1070
+ // Today's usage per agent and in total, refreshed every minute for the UI.
1071
+ let usageToday = { day: '', total: emptyUsage(), agents: {} };
1072
+ let usageAt = 0;
1073
+ function refreshUsage() {
1074
+ if (!clients.size) return;
1075
+ usageAt = Date.now();
1076
+ const day = localDay();
1077
+ const rep = dayReport(day);
1078
+ const agents = {};
1079
+ for (const r of rep.sessions) if (r.agentId) agents[r.agentId] = mergeUsage(agents[r.agentId] || emptyUsage(), r.usage);
1080
+ usageToday = { day, total: rep.usage, agents };
1081
+ broadcastState();
1082
+ }
1083
+ setInterval(refreshUsage, 60 * 1000);
1084
+ setTimeout(refreshUsage, 3000);
1085
+
1086
+ function localDay(d = new Date()) {
1087
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
1088
+ }
1089
+
1090
+ // ---------------------------------------------------------------- external sessions
1091
+
1092
+ // Claude Code sessions started outside the office (in the boss's own terminals),
1093
+ // discovered through ~/.claude/sessions/<pid>.json. They are shown read-only.
1094
+ const externals = new Map();
1095
+ // Pids of fired outside sessions: skipped until the process is gone.
1096
+ const firedPids = new Set();
1097
+ const EXT_STATUS = { busy: 'working', working: 'working', running: 'working', idle: 'idle', waiting: 'waiting', blocked: 'waiting' };
1098
+
1099
+ function pidAlive(pid) {
1100
+ try {
1101
+ process.kill(pid, 0);
1102
+ return true;
1103
+ } catch (e) {
1104
+ return e.code === 'EPERM';
1105
+ }
1106
+ }
1107
+
1108
+ function projectFor(cwd) {
1109
+ let best = null;
1110
+ for (const p of db.projects) {
1111
+ if (cwd === p.path || cwd.startsWith(p.path + path.sep)) {
1112
+ if (!best || p.path.length > best.path.length) best = p;
1113
+ }
1114
+ }
1115
+ return best ? best.id : 'auto-' + hashStr(cwd).toString(16);
1116
+ }
1117
+
1118
+ function scanExternal() {
1119
+ const dir = path.join(CLAUDE_DIR, 'sessions');
1120
+ let files = [];
1121
+ try {
1122
+ files = fs.readdirSync(dir).filter((f) => /^\d+\.json$/.test(f));
1123
+ } catch {
1124
+ /* no sessions dir */
1125
+ }
1126
+ // Only a running office agent owns its session; a stopped one must not hide it.
1127
+ const ourSessions = new Set(db.agents.filter((a) => rt(a.id).pty).map((a) => a.sessionId).filter(Boolean));
1128
+ const ourPids = new Set([...runtime.values()].filter((r) => r.pty).map((r) => r.pty.pid));
1129
+ const seen = new Set();
1130
+ let changed = false;
1131
+ for (const f of files) {
1132
+ let info;
1133
+ try {
1134
+ info = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));
1135
+ } catch {
1136
+ continue;
1137
+ }
1138
+ if (!info.pid || !info.sessionId || !info.cwd) continue;
1139
+ if (!pidAlive(info.pid)) firedPids.delete(info.pid);
1140
+ if (ourSessions.has(info.sessionId) || ourPids.has(info.pid) || firedPids.has(info.pid) || !pidAlive(info.pid)) continue;
1141
+ const id = 'ext-' + info.sessionId;
1142
+ seen.add(id);
1143
+ const transcript = transcriptFile(info.cwd, info.sessionId);
1144
+ const entries = transcriptEntries(transcript);
1145
+ const { task, tool } = digest(entries);
1146
+ for (const e of entries.slice(-80)) {
1147
+ for (const t of e.tools) if (EDIT_TOOLS.has(t.name)) recordEdit(id, t.input && (t.input.file_path || t.input.notebook_path), Date.parse(e.ts));
1148
+ }
1149
+ let status = EXT_STATUS[info.status];
1150
+ if (!status) {
1151
+ let mtime = 0;
1152
+ try {
1153
+ mtime = transcript ? fs.statSync(transcript).mtimeMs : 0;
1154
+ } catch {
1155
+ /* gone */
1156
+ }
1157
+ status = Date.now() - mtime < 15000 ? 'working' : 'idle';
1158
+ }
1159
+ const meta = db.external[info.sessionId] || {};
1160
+ const prev = externals.get(id);
1161
+ const ext = {
1162
+ id,
1163
+ external: true,
1164
+ pid: info.pid,
1165
+ sessionId: info.sessionId,
1166
+ cwd: info.cwd,
1167
+ name: meta.name || info.name || path.basename(info.cwd),
1168
+ role: meta.role || 'mid',
1169
+ look: meta.look || 'auto',
1170
+ color: COLORS[hashStr(info.sessionId) % COLORS.length],
1171
+ createdAt: info.startedAt || 0,
1172
+ startedAt: info.startedAt || 0,
1173
+ projectId: projectFor(info.cwd),
1174
+ status,
1175
+ task,
1176
+ tool: status === 'working' || status === 'waiting' ? tool : '',
1177
+ note: '',
1178
+ visit: null,
1179
+ transcript,
1180
+ };
1181
+ if (!prev || JSON.stringify(prev) !== JSON.stringify(ext)) {
1182
+ if (!prev && status === 'idle') gl(id).idleSince = info.statusUpdatedAt || Date.now();
1183
+ const credited = prev && prev.status !== status && !ext.subagent ? onStatusChange(id, prev.status, status) : false;
1184
+ if (prev && prev.status !== status) {
1185
+ if (status === 'waiting') broadcast({ t: 'toast', kind: 'warn', agentId: id, key: 'srv.waitingExternal', params: { name: ext.name } });
1186
+ if (credited) broadcast({ t: 'toast', kind: 'ok', agentId: id, key: 'srv.finished', params: { name: ext.name } });
1187
+ }
1188
+ externals.set(id, ext);
1189
+ changed = true;
1190
+ }
1191
+ }
1192
+ if (scanSubagents(seen)) changed = true;
1193
+ for (const id of [...externals.keys()]) {
1194
+ if (!seen.has(id)) {
1195
+ externals.delete(id);
1196
+ changed = true;
1197
+ }
1198
+ }
1199
+ if (changed) broadcastState();
1200
+ }
1201
+ setInterval(() => {
1202
+ try {
1203
+ scanExternal();
1204
+ } catch (e) {
1205
+ console.error('Scanning outside sessions failed:', e.message);
1206
+ }
1207
+ }, 2000);
1208
+
1209
+ // Subagents a session spawned (Agent/Task tool) live in <transcript>/subagents/.
1210
+ // Running ones sit at intern desks in their parent's room; finished ones take a
1211
+ // short break in the garden and then leave.
1212
+ const SUBAGENT_RECENT = 10 * 60 * 1000;
1213
+ const SUBAGENT_LINGER = 2 * 60 * 1000;
1214
+ const INTERN_NAMES = ['Ali', 'Ayla', 'Berk', 'Cem', 'Dila', 'Efe', 'Ela', 'Hakan', 'Işıl', 'Nil', 'Pelin', 'Rüzgar', 'Sarp', 'Tuna', 'Umut', 'Zehra', 'Bora', 'Ece', 'İpek', 'Oğuz'];
1215
+
1216
+ function scanSubagents(seen) {
1217
+ const parents = [];
1218
+ for (const e of externals.values()) {
1219
+ if (!e.subagent && seen.has(e.id) && e.transcript) parents.push({ id: e.id, name: e.name, projectId: e.projectId, cwd: e.cwd, transcript: e.transcript });
1220
+ }
1221
+ for (const a of db.agents) {
1222
+ const r = rt(a.id);
1223
+ const p = findProject(a.projectId);
1224
+ if (r.pty && r.transcriptPath) parents.push({ id: a.id, name: a.name, projectId: a.projectId, cwd: p ? p.path : '', transcript: r.transcriptPath });
1225
+ }
1226
+ const now = Date.now();
1227
+ let changed = false;
1228
+ for (const parent of parents) {
1229
+ const dir = path.join(parent.transcript.replace(/\.jsonl$/, ''), 'subagents');
1230
+ let files;
1231
+ try {
1232
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl'));
1233
+ } catch {
1234
+ continue;
1235
+ }
1236
+ for (const f of files) {
1237
+ const file = path.join(dir, f);
1238
+ let mtime;
1239
+ try {
1240
+ mtime = fs.statSync(file).mtimeMs;
1241
+ } catch {
1242
+ continue;
1243
+ }
1244
+ if (now - mtime > SUBAGENT_RECENT) continue;
1245
+ const entries = transcriptEntries(file);
1246
+ if (!entries.length) continue;
1247
+ const last = entries[entries.length - 1];
1248
+ const done = last.type === 'assistant' && last.stop === 'end_turn' && !last.tools.length;
1249
+ if (done && now - mtime > SUBAGENT_LINGER) continue;
1250
+ const agentId = f.replace(/^agent-/, '').replace(/\.jsonl$/, '');
1251
+ let meta = {};
1252
+ try {
1253
+ meta = JSON.parse(fs.readFileSync(file.replace(/\.jsonl$/, '.meta.json'), 'utf8'));
1254
+ } catch {
1255
+ /* optional */
1256
+ }
1257
+ const id = 'sub-' + agentId;
1258
+ seen.add(id);
1259
+ const firstTs = Date.parse(entries[0].ts) || mtime;
1260
+ const sub = {
1261
+ id,
1262
+ external: true,
1263
+ subagent: true,
1264
+ parentId: parent.id,
1265
+ parentName: parent.name,
1266
+ cwd: parent.cwd,
1267
+ name: INTERN_NAMES[hashStr(agentId) % INTERN_NAMES.length],
1268
+ role: 'intern',
1269
+ color: COLORS[hashStr(agentId + 'c') % COLORS.length],
1270
+ createdAt: firstTs,
1271
+ startedAt: firstTs,
1272
+ projectId: parent.projectId,
1273
+ status: done ? 'idle' : 'working',
1274
+ idleSince: done ? mtime : null,
1275
+ task: meta.description || (entries[0].text || '').slice(0, 240),
1276
+ tool: done ? '' : digest(entries).tool,
1277
+ note: '',
1278
+ visit: null,
1279
+ transcript: file,
1280
+ };
1281
+ const prev = externals.get(id);
1282
+ if (!prev || JSON.stringify(prev) !== JSON.stringify(sub)) {
1283
+ if (!prev && !done) broadcast({ t: 'toast', kind: 'info', agentId: id, key: 'srv.internHired', params: { parent: parent.name, name: sub.name, task: sub.task.slice(0, 60) } });
1284
+ if (prev && prev.status === 'working' && done) broadcast({ t: 'toast', kind: 'ok', agentId: id, key: 'srv.internDone', params: { name: sub.name, parent: parent.name } });
1285
+ externals.set(id, sub);
1286
+ changed = true;
1287
+ }
1288
+ }
1289
+ }
1290
+ return changed;
1291
+ }
1292
+
1293
+ // Turn a temporary room (shown for an outside session) into a saved project.
1294
+ function ensureProject(id) {
1295
+ const existing = findProject(id);
1296
+ if (existing) return existing;
1297
+ const ext = [...externals.values()].find((e) => e.projectId === id);
1298
+ if (!ext) return null;
1299
+ const project = { id, name: path.basename(ext.cwd), path: ext.cwd, color: COLORS[hashStr(ext.cwd) % COLORS.length], createdAt: Date.now() };
1300
+ db.projects.push(project);
1301
+ save();
1302
+ return project;
1303
+ }
1304
+
1305
+ function summarizeTool(name, input) {
1306
+ if (!input || typeof input !== 'object') return name;
1307
+ const target = input.file_path || input.path || input.pattern || input.command || input.url || input.description || '';
1308
+ const t = String(target).replace(/\s+/g, ' ');
1309
+ return t ? `${name}: ${t.length > 80 ? t.slice(0, 77) + '…' : t}` : name;
1310
+ }
1311
+
1312
+ // What a tool call is about, in enough detail for the boss to approve it from
1313
+ // the approval queue without opening the terminal.
1314
+ function describeTool(name, input) {
1315
+ if (!input || typeof input !== 'object') return '';
1316
+ const cut = (v, n = 1200) => {
1317
+ const t = String(v || '');
1318
+ return t.length > n ? t.slice(0, n - 1) + '…' : t;
1319
+ };
1320
+ if (input.command) return cut(input.command);
1321
+ if (name === 'Edit' && input.file_path) return cut(`${input.file_path}\n- ${input.old_string || ''}\n+ ${input.new_string || ''}`);
1322
+ if (name === 'Write' && input.file_path) return cut(`${input.file_path}\n${input.content || ''}`, 600);
1323
+ if (input.file_path || input.url) return cut(input.file_path || input.url);
1324
+ try {
1325
+ return cut(JSON.stringify(input, null, 1));
1326
+ } catch {
1327
+ return '';
1328
+ }
1329
+ }
1330
+
1331
+ // ---- conflicts: two agents changing the same file within EDIT_WINDOW_MS.
1332
+ const EDIT_WINDOW_MS = 30 * 60000;
1333
+ const edits = new Map(); // absolute file -> Map(agentId -> last edit time)
1334
+ const conflictsSeen = new Set();
1335
+
1336
+ function recordEdit(agentId, file, at = Date.now()) {
1337
+ if (!file || !at || Date.now() - at > EDIT_WINDOW_MS) return;
1338
+ const byAgent = edits.get(file) || new Map();
1339
+ edits.set(file, byAgent);
1340
+ if ((byAgent.get(agentId) || 0) >= at) return;
1341
+ byAgent.set(agentId, at);
1342
+ const ids = [...byAgent].filter(([id, t]) => Date.now() - t < EDIT_WINDOW_MS && findAny(id)).map(([id]) => id);
1343
+ if (ids.length < 2) return;
1344
+ const key = file + '|' + [...ids].sort().join(',');
1345
+ if (conflictsSeen.has(key)) return;
1346
+ conflictsSeen.add(key);
1347
+ const names = ids.map((id) => findAny(id).name);
1348
+ broadcast({ t: 'toast', kind: 'warn', agentId, key: 'srv.conflict', params: { names: names.join(', '), file: path.basename(file) } });
1349
+ broadcastState();
1350
+ }
1351
+
1352
+ function activeConflicts() {
1353
+ const now = Date.now();
1354
+ const out = [];
1355
+ for (const [file, byAgent] of edits) {
1356
+ const live = [...byAgent].filter(([id, t]) => now - t < EDIT_WINDOW_MS && findAny(id));
1357
+ if (live.length < 2) {
1358
+ if (!live.length) edits.delete(file);
1359
+ continue;
1360
+ }
1361
+ out.push({ file, agents: live.map(([id]) => id), at: Math.max(...live.map(([, t]) => t)) });
1362
+ }
1363
+ return out;
1364
+ }
1365
+
1366
+ // ---- stuck agents: one step running for STUCK_MS, or the same call made
1367
+ // LOOP_REPEATS times among the last LOOP_WINDOW calls of a turn.
1368
+ const STUCK_MS = (Number(process.env.AGENT_OFFICE_STUCK_MIN) || 10) * 60000;
1369
+ const LOOP_WINDOW = 12;
1370
+ const LOOP_REPEATS = 4;
1371
+
1372
+ function trackCall(agent, r, call) {
1373
+ const key = call.tool + '\n' + call.detail;
1374
+ r.calls = [...(r.calls || []), key].slice(-LOOP_WINDOW);
1375
+ const count = r.calls.filter((k) => k === key).length;
1376
+ if (count < LOOP_REPEATS || (r.stuck && r.stuck.kind === 'loop')) return;
1377
+ r.stuck = { kind: 'loop', since: Date.now(), tool: summarizeTool(call.tool, { command: call.detail.split('\n')[0] }), count };
1378
+ broadcast({ t: 'toast', kind: 'warn', agentId: agent.id, key: 'srv.stuckLoop', params: { name: agent.name, n: count } });
1379
+ }
1380
+
1381
+ setInterval(() => {
1382
+ const now = Date.now();
1383
+ for (const a of db.agents) {
1384
+ const r = rt(a.id);
1385
+ if (r.status !== 'working' || !isClaude(a) || r.stuck || !r.stepAt || now - r.stepAt < STUCK_MS) continue;
1386
+ r.stuck = { kind: 'slow', since: r.stepAt, tool: r.tool || '' };
1387
+ broadcast({ t: 'toast', kind: 'warn', agentId: a.id, key: 'srv.stuckSlow', params: { name: a.name, n: Math.round((now - r.stepAt) / 60000) } });
1388
+ broadcastState();
1389
+ }
1390
+ }, 30 * 1000);
1391
+
1392
+ function handleHook(agentId, event, payload) {
1393
+ const agent = findAgent(agentId);
1394
+ if (!agent) return;
1395
+ const r = rt(agentId);
1396
+ r.lastHookAt = Date.now();
1397
+ if (payload.session_id && payload.session_id !== agent.sessionId) {
1398
+ agent.sessionId = payload.session_id;
1399
+ save();
1400
+ }
1401
+ if (payload.transcript_path) r.transcriptPath = payload.transcript_path;
1402
+
1403
+ switch (event) {
1404
+ case 'SessionStart':
1405
+ if (!r.promptSinceStart) setStatus(agentId, 'idle', { note: '' });
1406
+ break;
1407
+ case 'UserPromptSubmit':
1408
+ r.stepAt = Date.now();
1409
+ r.calls = [];
1410
+ r.stuck = null;
1411
+ if (!agent.hasConversation) {
1412
+ agent.hasConversation = true;
1413
+ save();
1414
+ }
1415
+ r.promptSinceStart = true;
1416
+ setStatus(agentId, 'working', { task: String(payload.prompt || '').slice(0, 240), note: '' });
1417
+ break;
1418
+ case 'PreToolUse':
1419
+ if (EDIT_TOOLS.has(payload.tool_name)) recordEdit(agentId, payload.tool_input && (payload.tool_input.file_path || payload.tool_input.notebook_path));
1420
+ r.lastCall = { tool: String(payload.tool_name || ''), detail: describeTool(payload.tool_name, payload.tool_input) };
1421
+ r.stepAt = Date.now();
1422
+ trackCall(agent, r, r.lastCall);
1423
+ setStatus(agentId, 'working', { tool: summarizeTool(payload.tool_name, payload.tool_input) });
1424
+ break;
1425
+ case 'PostToolUse':
1426
+ r.stepAt = Date.now();
1427
+ if (r.stuck && r.stuck.kind === 'slow') r.stuck = null;
1428
+ if (r.status === 'waiting') setStatus(agentId, 'working');
1429
+ break;
1430
+ case 'Notification': {
1431
+ const msg = String(payload.message || '');
1432
+ const type = String(payload.notification_type || '');
1433
+ if (/permission/i.test(type) || /permission|approv/i.test(msg)) {
1434
+ setStatus(agentId, 'waiting', { note: msg, ask: { ...(r.lastCall || { tool: '', detail: '' }), message: msg, at: Date.now() } });
1435
+ }
1436
+ break;
1437
+ }
1438
+ case 'Stop':
1439
+ r.visit = null;
1440
+ setStatus(agentId, 'idle', { note: '' });
1441
+ break;
1442
+ }
1443
+ }
1444
+
1445
+ // Non-Claude commands have no hooks: infer status from terminal activity.
1446
+ setInterval(() => {
1447
+ const now = Date.now();
1448
+ for (const a of db.agents) {
1449
+ const r = rt(a.id);
1450
+ if (r.visit && r.visit.until < now) {
1451
+ r.visit = null;
1452
+ broadcastState();
1453
+ }
1454
+ if (!r.pty || isClaude(a)) continue;
1455
+ const busy = now - r.lastOutputAt < 4000;
1456
+ if (busy && r.status !== 'working') setStatus(a.id, 'working');
1457
+ if (!busy && (r.status === 'working' || r.status === 'starting')) setStatus(a.id, 'idle');
1458
+ }
1459
+ }, 1000);
1460
+
1461
+ // ---------------------------------------------------------------- project suggestions
1462
+
1463
+ // Projects where Claude Code has been used before, read from ~/.claude/projects.
1464
+ function suggestProjects() {
1465
+ const base = path.join(os.homedir(), '.claude', 'projects');
1466
+ const out = [];
1467
+ let dirs = [];
1468
+ try {
1469
+ dirs = fs.readdirSync(base, { withFileTypes: true }).filter((d) => d.isDirectory());
1470
+ } catch {
1471
+ return out;
1472
+ }
1473
+ for (const d of dirs) {
1474
+ const dir = path.join(base, d.name);
1475
+ let files;
1476
+ try {
1477
+ files = fs
1478
+ .readdirSync(dir)
1479
+ .filter((f) => f.endsWith('.jsonl'))
1480
+ .map((f) => ({ f, m: fs.statSync(path.join(dir, f)).mtimeMs }))
1481
+ .sort((a, b) => b.m - a.m);
1482
+ } catch {
1483
+ continue;
1484
+ }
1485
+ if (!files.length) continue;
1486
+ let cwd = null;
1487
+ try {
1488
+ const fd = fs.openSync(path.join(dir, files[0].f), 'r');
1489
+ const buf = Buffer.alloc(64 * 1024);
1490
+ const n = fs.readSync(fd, buf, 0, buf.length, 0);
1491
+ fs.closeSync(fd);
1492
+ for (const line of buf.slice(0, n).toString('utf8').split('\n')) {
1493
+ try {
1494
+ const e = JSON.parse(line);
1495
+ if (e.cwd) {
1496
+ cwd = e.cwd;
1497
+ break;
1498
+ }
1499
+ } catch {
1500
+ /* partial line */
1501
+ }
1502
+ }
1503
+ } catch {
1504
+ /* skip */
1505
+ }
1506
+ if (cwd && fs.existsSync(cwd)) out.push({ path: cwd, name: path.basename(cwd), lastUsed: files[0].m });
1507
+ }
1508
+ const seen = new Set();
1509
+ return out
1510
+ .sort((a, b) => b.lastUsed - a.lastUsed)
1511
+ .filter((p) => !seen.has(p.path) && seen.add(p.path) && !db.projects.some((x) => x.path === p.path))
1512
+ .slice(0, 40);
1513
+ }
1514
+
1515
+ // ---------------------------------------------------------------- gamification
1516
+
1517
+ // Idle agents stay at their desk for GARDEN_AFTER, then take a break in the
1518
+ // garden. After BORED_AFTER they get bored and walk up to the boss and ask for
1519
+ // work, then ask for a 1:1 up to three times. An agent asks at most once every
1520
+ // ASK_EVERY (12 hours, so twice a day), even across restarts. It stands at the
1521
+ // front for a minute, then goes back to the garden; its request stays open
1522
+ // (the card in the UI) for ASK_WINDOW. Ignored three times, it sulks.
1523
+ // Finished turns earn XP; praise and 1:1s lift morale.
1524
+ const GARDEN_AFTER = (Number(process.env.AGENT_OFFICE_GARDEN_MIN) || 5) * 60000;
1525
+ const BORED_AFTER = (Number(process.env.AGENT_OFFICE_BORED_MIN) || 15) * 60000;
1526
+ const ASK_EVERY = (Number(process.env.AGENT_OFFICE_ASK_MIN) || 12 * 60) * 60000;
1527
+ const ASK_WINDOW = Math.min(ASK_EVERY, (Number(process.env.AGENT_OFFICE_ASK_WINDOW_MIN) || 10) * 60000);
1528
+ const MAX_ASKS = 3;
1529
+ const PROMOTION_LEVEL = { intern: 2, junior: 3, mid: 4, senior: 6 };
1530
+
1531
+ db.game = db.game || {};
1532
+ db.game.agents = db.game.agents || {};
1533
+ db.game.counters = db.game.counters || {};
1534
+ db.game.achievements = db.game.achievements || [];
1535
+
1536
+ const ACHIEVEMENTS = [
1537
+ { id: 'first_hire', icon: '🧑‍💼', test: (c) => c.hires >= 1 },
1538
+ { id: 'team_5', icon: '👥', test: (c) => c.hires >= 5 },
1539
+ { id: 'megaphone', icon: '📢', test: (c) => c.announcements >= 1 },
1540
+ { id: 'tasks_10', icon: '✅', test: (c) => c.turns >= 10 },
1541
+ { id: 'tasks_100', icon: '🏭', test: (c) => c.turns >= 100 },
1542
+ { id: 'door_open', icon: '🚪', test: (c) => c.oneOnOnes >= 1 },
1543
+ { id: 'coach', icon: '🧭', test: (c) => c.oneOnOnes >= 10 },
1544
+ { id: 'kudos', icon: '👏', test: (c) => c.praises >= 10 },
1545
+ { id: 'promoter', icon: '⬆️', test: (c) => c.promotions >= 1 },
1546
+ { id: 'teamwork', icon: '🤝', test: (c) => c.visits >= 1 },
1547
+ { id: 'rescue', icon: '🛟', test: (c) => c.rescues >= 1 },
1548
+ { id: 'star', icon: '🌟', test: (c, x) => x.maxLevel >= 5 },
1549
+ { id: 'happy', icon: '😄', test: (c, x) => x.happy >= 3 },
1550
+ { id: 'driver', icon: '🚗', test: (c) => c.arcadeRuns >= 1 },
1551
+ { id: 'bridge', icon: '📨', test: (c) => c.messages >= 1 },
1552
+ { id: 'speedster', icon: '🏎', test: (c) => c.arcadeBest >= 1000 },
1553
+ ];
1554
+
1555
+ const levelOf = (xp) => Math.floor(Math.sqrt(xp / 40)) + 1;
1556
+ const xpForLevel = (lv) => 40 * (lv - 1) * (lv - 1);
1557
+
1558
+ function g(id) {
1559
+ return db.game.agents[id] || (db.game.agents[id] = { xp: 0, morale: 80, turns: 0 });
1560
+ }
1561
+ const gameLive = new Map(); // runtime: idleSince, workingSince, asks, lastAskAt, sulking, oneOnOne
1562
+ function gl(id) {
1563
+ if (!gameLive.has(id)) gameLive.set(id, { idleSince: null, workingSince: null, oneOnOne: false });
1564
+ return gameLive.get(id);
1565
+ }
1566
+
1567
+ function gameView(a) {
1568
+ if (a.subagent) return null;
1569
+ const s = g(a.id);
1570
+ const l = gl(a.id);
1571
+ const level = levelOf(s.xp);
1572
+ const need = PROMOTION_LEVEL[a.role];
1573
+ return {
1574
+ xp: s.xp,
1575
+ level,
1576
+ levelXp: xpForLevel(level),
1577
+ nextXp: xpForLevel(level + 1),
1578
+ morale: Math.round(s.morale),
1579
+ turns: s.turns,
1580
+ // The request is "live" only for a short window; afterwards the agent goes back to the garden.
1581
+ asking: a.status === 'idle' && !s.sulking && !l.oneOnOne && s.asks && Date.now() - (s.lastAskAt || 0) < ASK_WINDOW ? s.asks : 0,
1582
+ askedAt: s.lastAskAt || 0,
1583
+ sulking: !!s.sulking && a.status === 'idle',
1584
+ oneOnOne: l.oneOnOne,
1585
+ idleSince: a.status === 'idle' ? l.idleSince : null,
1586
+ promotable: !!need && level >= need,
1587
+ };
1588
+ }
1589
+
1590
+ function gameSummary() {
1591
+ const c = db.game.counters;
1592
+ const today = new Date().toISOString().slice(0, 10);
1593
+ return {
1594
+ counters: c,
1595
+ today: c.day === today ? c.today || 0 : 0,
1596
+ unlocked: db.game.achievements,
1597
+ gardenAfter: GARDEN_AFTER,
1598
+ achievements: ACHIEVEMENTS.map(({ test, ...a }) => a),
1599
+ };
1600
+ }
1601
+
1602
+ function bump(counter, n = 1) {
1603
+ db.game.counters[counter] = (db.game.counters[counter] || 0) + n;
1604
+ save();
1605
+ checkAchievements();
1606
+ }
1607
+
1608
+ function addXp(id, n) {
1609
+ const s = g(id);
1610
+ const before = levelOf(s.xp);
1611
+ s.xp += n;
1612
+ const after = levelOf(s.xp);
1613
+ if (after > before) {
1614
+ const a = findAny(id);
1615
+ broadcast({ t: 'levelup', agentId: id, level: after });
1616
+ if (a) broadcast({ t: 'toast', kind: 'ok', agentId: id, key: 'srv.levelUp', params: { name: a.name, level: after } });
1617
+ }
1618
+ save();
1619
+ checkAchievements();
1620
+ }
1621
+
1622
+ function addMorale(id, d) {
1623
+ const s = g(id);
1624
+ s.morale = Math.max(0, Math.min(100, s.morale + d));
1625
+ save();
1626
+ }
1627
+
1628
+ // Ask state is persisted so a restart does not trigger a new round of requests.
1629
+ // lastAskAt is kept on purpose: the 12-hour limit holds even after the agent worked.
1630
+ function resetAsks(id) {
1631
+ const s = g(id);
1632
+ if (!s.asks && !s.sulking) return;
1633
+ s.asks = 0;
1634
+ s.sulking = false;
1635
+ save();
1636
+ }
1637
+
1638
+ function onStatusChange(id, prev, next) {
1639
+ const l = gl(id);
1640
+ const now = Date.now();
1641
+ if (next === 'working' || next === 'waiting') {
1642
+ if (prev !== 'working' && prev !== 'waiting') {
1643
+ l.workingSince = now;
1644
+ l.fromStart = prev === 'starting' || prev === 'offline';
1645
+ }
1646
+ l.idleSince = null;
1647
+ resetAsks(id);
1648
+ } else if (next === 'idle') {
1649
+ l.idleSince = now;
1650
+ const dur = now - (l.workingSince || now);
1651
+ // The burst of output while an agent boots is not a finished task.
1652
+ // A declined request is not a finished task either.
1653
+ const declined = l.declined;
1654
+ l.declined = false;
1655
+ if ((prev === 'working' || prev === 'waiting') && !(l.fromStart && dur < 15000) && !declined) {
1656
+ g(id).turns++;
1657
+ addMorale(id, 2);
1658
+ const c = db.game.counters;
1659
+ const today = new Date().toISOString().slice(0, 10);
1660
+ if (c.day !== today) {
1661
+ c.day = today;
1662
+ c.today = 0;
1663
+ }
1664
+ c.today = (c.today || 0) + 1;
1665
+ bump('turns');
1666
+ addXp(id, 10 + (dur > 2 * 60000 ? 5 : 0) + (dur > 10 * 60000 ? 10 : 0));
1667
+ return true;
1668
+ }
1669
+ } else if (next === 'offline') {
1670
+ l.idleSince = null;
1671
+ l.oneOnOne = false;
1672
+ resetAsks(id);
1673
+ }
1674
+ }
1675
+
1676
+ function checkAchievements() {
1677
+ const present = [...db.agents.map((a) => a.id), ...[...externals.values()].filter((e) => !e.subagent).map((e) => e.id)];
1678
+ const x = {
1679
+ maxLevel: Math.max(1, ...Object.values(db.game.agents).map((s) => levelOf(s.xp))),
1680
+ happy: present.filter((id) => g(id).morale >= 85).length,
1681
+ };
1682
+ const c = db.game.counters;
1683
+ for (const a of ACHIEVEMENTS) {
1684
+ if (db.game.achievements.includes(a.id) || !a.test(c, x)) continue;
1685
+ db.game.achievements.push(a.id);
1686
+ save();
1687
+ broadcast({ t: 'achievement', id: a.id, icon: a.icon });
1688
+ }
1689
+ }
1690
+
1691
+ function gameCandidates() {
1692
+ const list = [];
1693
+ for (const a of db.agents) if (rt(a.id).pty) list.push({ id: a.id, name: a.name, status: rt(a.id).status });
1694
+ for (const e of externals.values()) if (!e.subagent) list.push({ id: e.id, name: e.name, status: e.status });
1695
+ return list;
1696
+ }
1697
+
1698
+ setInterval(() => {
1699
+ const now = Date.now();
1700
+ let changed = false;
1701
+ for (const a of gameCandidates()) {
1702
+ if (a.status !== 'idle') continue;
1703
+ const l = gl(a.id);
1704
+ if (l.oneOnOne) continue;
1705
+ if (!l.idleSince) l.idleSince = now;
1706
+ if (now - l.idleSince < BORED_AFTER) continue;
1707
+ const s = g(a.id);
1708
+ const asks = s.asks || 0;
1709
+ const last = s.lastAskAt || 0;
1710
+ if (asks < MAX_ASKS && now - last >= ASK_EVERY) {
1711
+ if (asks > 0) addMorale(a.id, -5); // the previous request was ignored
1712
+ s.asks = asks + 1;
1713
+ s.lastAskAt = now;
1714
+ save();
1715
+ broadcast({ t: 'ask', agentId: a.id, n: s.asks });
1716
+ changed = true;
1717
+ } else if (asks >= MAX_ASKS && !s.sulking && now - last >= ASK_WINDOW) {
1718
+ s.sulking = true;
1719
+ save();
1720
+ addMorale(a.id, -20);
1721
+ broadcast({ t: 'toast', kind: 'warn', agentId: a.id, key: 'srv.sulk', params: { name: a.name } });
1722
+ changed = true;
1723
+ }
1724
+ }
1725
+ // A request window closing changes what clients should show.
1726
+ const live = gameCandidates().filter((a) => {
1727
+ const s = g(a.id);
1728
+ return s.asks && now - (s.lastAskAt || 0) >= ASK_WINDOW && now - (s.lastAskAt || 0) < ASK_WINDOW + 5000;
1729
+ });
1730
+ if (changed || live.length) broadcastState();
1731
+ }, 5000);
1732
+
1733
+ // ---------------------------------------------------------------- native folder picker
1734
+
1735
+ function pickFolderNative(lang) {
1736
+ const prompt = I18N.translate(lang, 'dialog.pickFolder').replace(/["\\]/g, '');
1737
+ return new Promise((resolve, reject) => {
1738
+ let cmd;
1739
+ let args;
1740
+ if (process.platform === 'darwin') {
1741
+ // JXA run by osascript itself: no Apple Events to another app, so macOS
1742
+ // does not ask for automation permission; activate() brings it forward.
1743
+ cmd = 'osascript';
1744
+ args = [
1745
+ '-l',
1746
+ 'JavaScript',
1747
+ '-e',
1748
+ `const app = Application.currentApplication(); app.includeStandardAdditions = true; app.activate(); app.chooseFolder({ withPrompt: ${JSON.stringify(prompt)} }).toString();`,
1749
+ ];
1750
+ } else if (IS_WIN) {
1751
+ cmd = 'powershell.exe';
1752
+ args = [
1753
+ '-NoProfile',
1754
+ '-STA',
1755
+ '-Command',
1756
+ `Add-Type -AssemblyName System.Windows.Forms; $f = New-Object System.Windows.Forms.FolderBrowserDialog; $f.Description = "${prompt}"; $w = New-Object System.Windows.Forms.Form; $w.TopMost = $true; if ($f.ShowDialog($w) -eq "OK") { $f.SelectedPath }`,
1757
+ ];
1758
+ } else {
1759
+ cmd = 'zenity';
1760
+ args = ['--file-selection', '--directory', `--title=${prompt}`];
1761
+ }
1762
+ execFile(cmd, args, { timeout: 10 * 60 * 1000 }, (err, stdout, stderr) => {
1763
+ const picked = String(stdout || '').trim().replace(/\/$/, '');
1764
+ if (picked) return resolve({ path: picked });
1765
+ if (err && err.code === 'ENOENT') return reject(new Error('unsupported'));
1766
+ // Only a real cancel is silent; anything else falls back to the in-app browser.
1767
+ const cancelled = /-128|cancel/i.test(String(stderr || '')) || (IS_WIN && !err) || (!IS_WIN && process.platform !== 'darwin' && err && err.code === 1);
1768
+ if (cancelled) return resolve({ cancelled: true });
1769
+ reject(new Error(String(stderr || (err && err.message) || 'failed').trim().split('\n').pop()));
1770
+ });
1771
+ });
1772
+ }
1773
+
1774
+ // ---------------------------------------------------------------- HTTP
1775
+
1776
+ const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png' };
1777
+ const VENDOR = {
1778
+ '/vendor/xterm.js': require.resolve('@xterm/xterm/lib/xterm.js'),
1779
+ '/vendor/xterm.css': require.resolve('@xterm/xterm/css/xterm.css'),
1780
+ '/vendor/addon-fit.js': require.resolve('@xterm/addon-fit/lib/addon-fit.js'),
1781
+ };
1782
+
1783
+ const allowedHosts = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`]);
1784
+ const allowedOrigins = new Set([`http://127.0.0.1:${PORT}`, `http://localhost:${PORT}`]);
1785
+
1786
+ function send(res, code, body, type = 'application/json; charset=utf-8') {
1787
+ res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store' });
1788
+ res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body));
1789
+ }
1790
+
1791
+ function readBody(req) {
1792
+ return new Promise((resolve, reject) => {
1793
+ let data = '';
1794
+ req.on('data', (c) => {
1795
+ data += c;
1796
+ if (data.length > 2e6) req.destroy();
1797
+ });
1798
+ req.on('end', () => {
1799
+ try {
1800
+ resolve(data ? JSON.parse(data) : {});
1801
+ } catch (e) {
1802
+ reject(e);
1803
+ }
1804
+ });
1805
+ req.on('error', reject);
1806
+ });
1807
+ }
1808
+
1809
+ function cleanText(s, max = 20000) {
1810
+ return String(s || '').replace(/\r\n/g, '\n').trim().slice(0, max);
1811
+ }
1812
+
1813
+ async function api(req, res, url) {
1814
+ const parts = url.pathname.split('/').filter(Boolean); // ['api', ...]
1815
+ const method = req.method;
1816
+ const lang = reqLang(req);
1817
+ const fail = (code, key, params) => send(res, code, { error: I18N.translate(lang, key, params) });
1818
+
1819
+ // Hook relay from Claude Code (authenticated with the per-install token).
1820
+ if (parts[1] === 'hook' && method === 'POST') {
1821
+ if (req.headers['x-agent-office-token'] !== db.token) return send(res, 403, { error: 'bad token' });
1822
+ const body = await readBody(req).catch(() => ({}));
1823
+ handleHook(parts[2], parts[3], body || {});
1824
+ return send(res, 200, { ok: true });
1825
+ }
1826
+
1827
+ // `office` command from inside agent terminals.
1828
+ if (parts[1] === 'office') {
1829
+ if (req.headers['x-agent-office-token'] !== db.token) return send(res, 403, { error: 'bad token' });
1830
+ if (method === 'GET' && parts[2] === 'who') {
1831
+ const me = url.searchParams.get('me');
1832
+ const list = [...db.agents, ...[...externals.values()].filter((e) => !e.subagent)].map((a) => {
1833
+ const p = findProject(a.projectId);
1834
+ const r = a.external ? a : rt(a.id);
1835
+ return {
1836
+ name: a.name,
1837
+ role: ROLE_LABELS[a.role] || a.role,
1838
+ tool: a.external ? 'Claude Code (own terminal)' : TOOLS[toolOf(a)].label,
1839
+ building: (findBuilding(p ? p.building || 'main' : 'main') || {}).name || 'HQ',
1840
+ room: p ? p.name : path.basename(a.cwd || ''),
1841
+ status: r.status,
1842
+ reachable: !a.external && !!rt(a.id).pty,
1843
+ you: a.id === me,
1844
+ };
1845
+ });
1846
+ return send(res, 200, { agents: list });
1847
+ }
1848
+ if (method === 'POST' && parts[2] === 'send') {
1849
+ const body = await readBody(req).catch(() => ({}));
1850
+ const from = findAny(body.from);
1851
+ const name = String(body.to || '').trim().toLowerCase();
1852
+ const to = db.agents.find((a) => a.name.toLowerCase() === name) || db.agents.find((a) => a.name.toLowerCase().startsWith(name));
1853
+ if (!from) return send(res, 400, { error: 'unknown sender' });
1854
+ if (!to) return send(res, 404, { error: `no colleague named "${body.to}" (try: office who)` });
1855
+ if (!rt(to.id).pty) return send(res, 409, { error: `${to.name} is not at work right now` });
1856
+ const fp = findProject(from.projectId);
1857
+ const text = cleanText(body.text, 8000);
1858
+ const fb = findBuilding((fp && fp.building) || 'main');
1859
+ const where = `${fb ? fb.name : 'HQ'} building${fb && fb.company ? ', ' + fb.company : ''}`;
1860
+ sendToAgent(to, `[MESSAGE from ${from.name} (${where}, ${from.external ? 'Claude Code' : TOOLS[toolOf(from)].label})] ${text}\n(Reply with: office send "${from.name}" "<message>")`);
1861
+ broadcast({ t: 'mail', from: from.id, to: to.id, text: text.slice(0, 140) });
1862
+ bump('messages');
1863
+ return send(res, 200, { ok: true, to: to.name });
1864
+ }
1865
+ }
1866
+
1867
+ // Everything else comes from the UI: block cross-site requests.
1868
+ const origin = req.headers.origin;
1869
+ if (method !== 'GET' && (!origin || !allowedOrigins.has(origin))) return send(res, 403, { error: 'forbidden origin' });
1870
+ if (method !== 'GET' && !String(req.headers['content-type'] || '').startsWith('application/json')) {
1871
+ return send(res, 415, { error: 'json required' });
1872
+ }
1873
+
1874
+ const body = method === 'GET' ? {} : await readBody(req);
1875
+
1876
+ if (method === 'GET' && parts[1] === 'state') return send(res, 200, publicState());
1877
+ if (method === 'GET' && parts[1] === 'report') {
1878
+ const day = /^\d{4}-\d{2}-\d{2}$/.test(url.searchParams.get('day') || '') ? url.searchParams.get('day') : localDay();
1879
+ return send(res, 200, dayReport(day));
1880
+ }
1881
+ if (method === 'GET' && parts[1] === 'suggest-projects') return send(res, 200, suggestProjects());
1882
+ if (method === 'GET' && parts[1] === 'tools') {
1883
+ return send(res, 200, Object.entries(TOOLS).map(([id, t]) => ({ id, label: t.label, icon: t.icon, cmd: t.cmd, installed: !t.cmd || !!which(t.cmd), model: !!t.model || id === 'claude' })));
1884
+ }
1885
+
1886
+ // In-app folder browser (fallback when no native dialog is available).
1887
+ if (method === 'GET' && parts[1] === 'browse') {
1888
+ let dir = url.searchParams.get('path') || os.homedir();
1889
+ dir = path.resolve(dir.replace(/^~(?=$|\/|\\)/, os.homedir()));
1890
+ let entries = [];
1891
+ try {
1892
+ entries = fs
1893
+ .readdirSync(dir, { withFileTypes: true })
1894
+ .filter((d) => d.isDirectory() && !d.name.startsWith('.') && d.name !== 'node_modules')
1895
+ .map((d) => d.name)
1896
+ .sort((a, b) => a.localeCompare(b));
1897
+ } catch (e) {
1898
+ return fail(400, 'err.folderOpen', { code: e.code || e.message });
1899
+ }
1900
+ const isProject = ['.git', 'package.json', 'CLAUDE.md'].some((f) => fs.existsSync(path.join(dir, f)));
1901
+ return send(res, 200, { path: dir, parent: path.dirname(dir) !== dir ? path.dirname(dir) : null, home: os.homedir(), dirs: entries, isProject });
1902
+ }
1903
+
1904
+ // Native OS folder picker.
1905
+ if (method === 'POST' && parts[1] === 'pick-folder') {
1906
+ const picked = await pickFolderNative(lang).catch((e) => ({ error: e.message }));
1907
+ return send(res, 200, picked);
1908
+ }
1909
+
1910
+ if (parts[1] === 'tasks' && parts[2]) {
1911
+ const task = db.tasks.find((x) => x.id === parts[2]);
1912
+ if (!task) return fail(404, 'err.taskNotFound');
1913
+ if (method === 'DELETE') {
1914
+ if (task.status === 'doing' && task.agentId) rt(task.agentId).boardTask = null;
1915
+ db.tasks = db.tasks.filter((x) => x !== task);
1916
+ } else if (method === 'PATCH') {
1917
+ if (body.text && task.status === 'todo') task.text = cleanText(body.text, 4000);
1918
+ // Back on the board, e.g. a finished card that needs another round.
1919
+ if (body.status === 'todo' && task.status === 'done') Object.assign(task, { status: 'todo', agentId: null, createdAt: Date.now() });
1920
+ // First in line.
1921
+ if (body.top && task.status === 'todo') task.createdAt = Math.min(...db.tasks.map((x) => x.createdAt)) - 1;
1922
+ }
1923
+ save();
1924
+ broadcastState();
1925
+ setTimeout(boardTick, 300);
1926
+ return send(res, 200, { ok: true });
1927
+ }
1928
+
1929
+ if (parts[1] === 'projects') {
1930
+ if (method === 'POST' && parts.length === 2) {
1931
+ const p = path.resolve(String(body.path || '').replace(/^~(?=$|\/|\\)/, os.homedir()));
1932
+ if (!body.path || !fs.existsSync(p) || !fs.statSync(p).isDirectory()) return fail(400, 'err.folderNotFound');
1933
+ const project = {
1934
+ id: newId(),
1935
+ name: cleanText(body.name, 60) || path.basename(p),
1936
+ path: p,
1937
+ color: COLORS[db.projects.length % COLORS.length],
1938
+ building: findBuilding(body.building) ? body.building : 'main',
1939
+ createdAt: Date.now(),
1940
+ };
1941
+ db.projects.push(project);
1942
+ save();
1943
+ broadcastState();
1944
+ return send(res, 200, project);
1945
+ }
1946
+ // Room settings from the right-click menu; editing a temporary room keeps it.
1947
+ if (method === 'PATCH' && parts.length === 3) {
1948
+ const proj = findProject(parts[2]) || ensureProject(parts[2]);
1949
+ if (!proj) return fail(404, 'err.projectNotFound');
1950
+ if (body.name) proj.name = cleanText(body.name, 60);
1951
+ if (/^#[0-9a-f]{6}$/i.test(String(body.color || ''))) proj.color = body.color;
1952
+ if (body.extraDesks !== undefined) proj.extraDesks = Math.max(0, Math.min(24, Number(body.extraDesks) | 0));
1953
+ if (body.extraLeadDesks !== undefined) proj.extraLeadDesks = Math.max(0, Math.min(6, Number(body.extraLeadDesks) | 0));
1954
+ if (body.building && findBuilding(body.building)) proj.building = body.building;
1955
+ save();
1956
+ scanExternal();
1957
+ broadcastState();
1958
+ return send(res, 200, proj);
1959
+ }
1960
+ if (method === 'POST' && parts[3] === 'open-folder') {
1961
+ const proj = findProject(parts[2]) || [...externals.values()].map((e) => ({ id: e.projectId, path: e.cwd })).find((x) => x.id === parts[2]);
1962
+ if (!proj) return fail(404, 'err.projectNotFound');
1963
+ const opener = process.platform === 'darwin' ? 'open' : IS_WIN ? 'explorer.exe' : 'xdg-open';
1964
+ execFile(opener, [proj.path], () => {});
1965
+ return send(res, 200, { ok: true });
1966
+ }
1967
+ if (method === 'POST' && parts[3] === 'save') {
1968
+ const saved = ensureProject(parts[2]);
1969
+ if (!saved) return fail(404, 'err.projectNotFound');
1970
+ scanExternal();
1971
+ broadcastState();
1972
+ return send(res, 200, saved);
1973
+ }
1974
+ const project = findProject(parts[2]) || (method === 'POST' && parts[3] === 'announce' ? { id: parts[2], name: 'room' } : null);
1975
+ if (!project) return fail(404, 'err.projectNotFound');
1976
+ if (method === 'DELETE') {
1977
+ for (const a of db.agents.filter((x) => x.projectId === project.id)) stopAgent(a);
1978
+ db.agents = db.agents.filter((x) => x.projectId !== project.id);
1979
+ db.projects = db.projects.filter((x) => x.id !== project.id);
1980
+ db.tasks = db.tasks.filter((x) => x.projectId !== project.id);
1981
+ save();
1982
+ broadcastState();
1983
+ return send(res, 200, { ok: true });
1984
+ }
1985
+ if (method === 'POST' && parts[3] === 'tasks') {
1986
+ const text = cleanText(body.text, 4000);
1987
+ if (!text) return fail(400, 'err.emptyTask');
1988
+ const task = { id: newId(), projectId: project.id, text, status: 'todo', agentId: null, createdAt: Date.now() };
1989
+ db.tasks.push(task);
1990
+ save();
1991
+ broadcastState();
1992
+ setTimeout(boardTick, 300);
1993
+ return send(res, 200, task);
1994
+ }
1995
+ if (method === 'POST' && parts[3] === 'announce') {
1996
+ const text = cleanText(body.text);
1997
+ if (!text) return fail(400, 'err.emptyAnnouncement');
1998
+ const sent = [];
1999
+ for (const a of db.agents.filter((x) => x.projectId === project.id)) {
2000
+ if (!rt(a.id).pty) continue;
2001
+ sendToAgent(a, `[ANNOUNCEMENT from the boss to the ${project.name} team] ${text}`);
2002
+ sent.push(a.id);
2003
+ }
2004
+ broadcast({ t: 'bubble', ids: sent, text, kind: 'announce', projectId: project.id });
2005
+ bump('announcements');
2006
+ const skipped = [...externals.values()].filter((e) => e.projectId === project.id).length;
2007
+ return send(res, 200, { sent: sent.length, skipped });
2008
+ }
2009
+ }
2010
+
2011
+ if (parts[1] === 'announce' && method === 'POST') {
2012
+ const text = cleanText(body.text);
2013
+ if (!text) return fail(400, 'err.emptyAnnouncement');
2014
+ const sent = [];
2015
+ for (const a of db.agents) {
2016
+ if (!rt(a.id).pty) continue;
2017
+ sendToAgent(a, `[ANNOUNCEMENT from the boss to everyone in the office] ${text}`);
2018
+ sent.push(a.id);
2019
+ }
2020
+ broadcast({ t: 'bubble', ids: sent, text, kind: 'announce' });
2021
+ bump('announcements');
2022
+ return send(res, 200, { sent: sent.length, skipped: externals.size });
2023
+ }
2024
+
2025
+ // Break-game results: best score and runs feed the leaderboard and badges.
2026
+ if (parts[1] === 'arcade' && method === 'POST') {
2027
+ const score = Math.max(0, Math.min(1e7, Math.round(Number(body.score) || 0)));
2028
+ const c = db.game.counters;
2029
+ const newBest = score > (c.arcadeBest || 0);
2030
+ if (newBest) c.arcadeBest = score;
2031
+ bump('arcadeRuns');
2032
+ return send(res, 200, { best: c.arcadeBest || 0, newBest });
2033
+ }
2034
+
2035
+ if (parts[1] === 'buildings') {
2036
+ if (method === 'POST' && parts.length === 2) {
2037
+ const b = {
2038
+ id: newId(),
2039
+ name: cleanText(body.name, 40) || 'Office',
2040
+ company: cleanText(body.company, 40) || 'Getir',
2041
+ tool: TOOLS[body.tool] ? body.tool : 'claude',
2042
+ color: /^#[0-9a-f]{6}$/i.test(String(body.color || '')) ? body.color : BUILDING_COLORS[db.buildings.length % BUILDING_COLORS.length],
2043
+ createdAt: Date.now(),
2044
+ };
2045
+ db.buildings.push(b);
2046
+ save();
2047
+ broadcastState();
2048
+ return send(res, 200, b);
2049
+ }
2050
+ const b = findBuilding(parts[2]);
2051
+ if (!b) return fail(404, 'err.buildingNotFound');
2052
+ if (method === 'PATCH') {
2053
+ if (body.name) b.name = cleanText(body.name, 40);
2054
+ if (body.company !== undefined) b.company = cleanText(body.company, 40);
2055
+ if (TOOLS[body.tool]) b.tool = body.tool;
2056
+ if (/^#[0-9a-f]{6}$/i.test(String(body.color || ''))) b.color = body.color;
2057
+ save();
2058
+ broadcastState();
2059
+ return send(res, 200, b);
2060
+ }
2061
+ if (method === 'DELETE') {
2062
+ if (b.id === 'main') return fail(400, 'err.cannotDeleteHQ');
2063
+ // rooms of a removed building move to the HQ; nothing is fired
2064
+ for (const p of db.projects) if (p.building === b.id) p.building = 'main';
2065
+ db.buildings = db.buildings.filter((x) => x.id !== b.id);
2066
+ save();
2067
+ broadcastState();
2068
+ return send(res, 200, { ok: true });
2069
+ }
2070
+ }
2071
+
2072
+ if (parts[1] === 'rooms' && parts[2] === 'order' && method === 'POST') {
2073
+ db.roomOrder = (Array.isArray(body.ids) ? body.ids : []).map(String).slice(0, 500);
2074
+ save();
2075
+ broadcastState();
2076
+ return send(res, 200, { ok: true });
2077
+ }
2078
+
2079
+ if (parts[1] === 'conflicts' && parts[2] === 'notify' && method === 'POST') {
2080
+ // Tell everyone on the file who else is changing it, and how to reach them.
2081
+ const c = activeConflicts().find((x) => x.file === body.file);
2082
+ if (!c) return fail(404, 'err.conflictGone');
2083
+ let sent = 0;
2084
+ for (const id of c.agents) {
2085
+ const a = findAgent(id);
2086
+ if (!a || !rt(a.id).pty) continue;
2087
+ const others = c.agents.filter((x) => x !== id).map((x) => findAny(x).name);
2088
+ sendToAgent(a, `[CONFLICT] ${others.join(', ')} ${others.length > 1 ? 'are' : 'is'} also changing ${c.file} right now. Before you edit it again, coordinate with them using \`office send "<name>" "<message>"\` so you don't overwrite each other's work.`);
2089
+ sent++;
2090
+ }
2091
+ return send(res, 200, { sent, skipped: c.agents.length - sent });
2092
+ }
2093
+ if (parts[1] === 'meetings' && method === 'POST' && parts.length === 2) {
2094
+ const topic = cleanText(body.topic, 2000);
2095
+ if (!topic) return fail(400, 'err.emptyTopic');
2096
+ const ids = [...new Set(Array.isArray(body.agentIds) ? body.agentIds : [])];
2097
+ const team = ids.map(findAgent).filter((a) => a && isClaude(a) && rt(a.id).pty && rt(a.id).status === 'idle' && !rt(a.id).meeting);
2098
+ if (team.length < 2 || team.length !== ids.length || team.length > MEETING_MAX) return fail(400, 'err.meetingTeam', { max: MEETING_MAX });
2099
+ const m = { id: newId(), topic, lang, participants: team.map((a) => a.id), names: Object.fromEntries(team.map((a) => [a.id, a.name])), rounds: [], summary: '', status: 'running', round: 0, startedAt: Date.now() };
2100
+ db.meetings.unshift(m);
2101
+ db.meetings = db.meetings.slice(0, MEETINGS_KEEP);
2102
+ meetingRound(m, 0);
2103
+ bump('meetings');
2104
+ return send(res, 200, m);
2105
+ }
2106
+ if (parts[1] === 'meetings' && method === 'DELETE' && parts[2]) {
2107
+ const m = db.meetings.find((x) => x.id === parts[2]);
2108
+ if (m && m.status === 'running') endMeeting(m, 'cancelled');
2109
+ db.meetings = db.meetings.filter((x) => x.id !== parts[2]);
2110
+ save();
2111
+ broadcastState();
2112
+ return send(res, 200, { ok: true });
2113
+ }
2114
+ if (parts[1] === 'workday' && method === 'PATCH') {
2115
+ const w = db.workday;
2116
+ if (typeof body.autoHome === 'boolean') w.autoHome = body.autoHome;
2117
+ if (typeof body.autoWake === 'boolean') w.autoWake = body.autoWake;
2118
+ if (body.idleMin !== undefined) w.idleMin = Math.max(5, Math.min(480, Number(body.idleMin) | 0 || WORKDAY_DEFAULTS.idleMin));
2119
+ if (body.endHour !== undefined) w.endHour = body.endHour === null || body.endHour === '' ? null : Math.max(0, Math.min(23, Number(body.endHour) | 0));
2120
+ save();
2121
+ broadcastState();
2122
+ return send(res, 200, w);
2123
+ }
2124
+ if (parts[1] === 'start-all' && method === 'POST') {
2125
+ const errors = [];
2126
+ for (const a of db.agents) {
2127
+ if (rt(a.id).pty) continue;
2128
+ try {
2129
+ startAgent(a);
2130
+ } catch (e) {
2131
+ errors.push(`${a.name}: ${errText(lang, e)}`);
2132
+ }
2133
+ }
2134
+ return send(res, 200, { errors });
2135
+ }
2136
+
2137
+ if (parts[1] === 'agents') {
2138
+ if (method === 'POST' && parts.length === 2) {
2139
+ const project = findProject(body.projectId) || ensureProject(body.projectId);
2140
+ if (!project) return fail(400, 'err.pickRoom');
2141
+ const agent = {
2142
+ id: newId(),
2143
+ name: cleanText(body.name, 30) || 'Agent',
2144
+ role: ROLES.includes(body.role) ? body.role : 'mid',
2145
+ projectId: project.id,
2146
+ model: cleanText(body.model, 60),
2147
+ permissionMode: cleanText(body.permissionMode, 30) || 'default',
2148
+ tool: TOOLS[body.tool] ? body.tool : 'claude',
2149
+ command: cleanText(body.command, 200) || (TOOLS[body.tool] && TOOLS[body.tool].cmd) || 'claude',
2150
+ color: COLORS[Math.floor(Math.random() * COLORS.length)],
2151
+ createdAt: Date.now(),
2152
+ hasConversation: false,
2153
+ sessionId: null,
2154
+ look: ['f', 'm'].includes(body.look) ? body.look : 'auto',
2155
+ worktree: body.worktree === true,
2156
+ };
2157
+ db.agents.push(agent);
2158
+ save();
2159
+ bump('hires');
2160
+ try {
2161
+ if (body.start !== false) startAgent(agent, cleanText(body.initialPrompt) || undefined);
2162
+ } catch (e) {
2163
+ broadcastState();
2164
+ return send(res, 200, { agent, error: errText(lang, e) });
2165
+ }
2166
+ broadcastState();
2167
+ return send(res, 200, { agent });
2168
+ }
2169
+
2170
+ if (method === 'GET' && parts[3] === 'transcript') {
2171
+ const a = findAny(parts[2]);
2172
+ if (!a) return fail(404, 'err.agentNotFound');
2173
+ return send(res, 200, { messages: conversation(transcriptEntries(a.external ? a.transcript : rt(a.id).transcriptPath), 120) });
2174
+ }
2175
+
2176
+ const anyAgent = findAny(parts[2]);
2177
+ if (anyAgent && method === 'POST' && parts[3] === 'praise') {
2178
+ const l = gl(anyAgent.id);
2179
+ if (Date.now() - (l.lastPraise || 0) > 30000) {
2180
+ addMorale(anyAgent.id, 12);
2181
+ addXp(anyAgent.id, 2);
2182
+ bump('praises');
2183
+ }
2184
+ l.lastPraise = Date.now();
2185
+ if (g(anyAgent.id).sulking) {
2186
+ g(anyAgent.id).sulking = false;
2187
+ save();
2188
+ }
2189
+ broadcast({ t: 'bubble', ids: [anyAgent.id], key: 'bubble.thanks', kind: 'visit' });
2190
+ checkAchievements();
2191
+ broadcastState();
2192
+ return send(res, 200, { ok: true });
2193
+ }
2194
+ // The boss answered the request ("later", praise…): close it. The 12-hour
2195
+ // limit still holds because lastAskAt is kept.
2196
+ if (anyAgent && method === 'POST' && parts[3] === 'ask-answer') {
2197
+ resetAsks(anyAgent.id);
2198
+ broadcastState();
2199
+ return send(res, 200, { ok: true });
2200
+ }
2201
+ if (anyAgent && method === 'POST' && parts[3] === 'one-on-one') {
2202
+ const l = gl(anyAgent.id);
2203
+ if (body.on && !l.oneOnOne) {
2204
+ if (g(anyAgent.id).sulking || (g(anyAgent.id).asks || 0) >= MAX_ASKS) bump('rescues');
2205
+ l.oneOnOne = true;
2206
+ resetAsks(anyAgent.id);
2207
+ addMorale(anyAgent.id, 10);
2208
+ bump('oneOnOnes');
2209
+ } else if (!body.on && l.oneOnOne) {
2210
+ l.oneOnOne = false;
2211
+ l.idleSince = Date.now(); // a fresh start before getting bored again
2212
+ }
2213
+ broadcastState();
2214
+ return send(res, 200, { ok: true });
2215
+ }
2216
+
2217
+ const ext = externals.get(parts[2]);
2218
+ if (ext) {
2219
+ if (method === 'PATCH') {
2220
+ const meta = (db.external[ext.sessionId] = db.external[ext.sessionId] || {});
2221
+ if (body.role && ROLES.includes(body.role)) {
2222
+ if (ROLES.indexOf(body.role) < ROLES.indexOf(ext.role)) bump('promotions');
2223
+ meta.role = body.role;
2224
+ }
2225
+ if (body.name) meta.name = cleanText(body.name, 30);
2226
+ if (['f', 'm', 'auto'].includes(body.look)) meta.look = body.look;
2227
+ save();
2228
+ scanExternal();
2229
+ return send(res, 200, { ok: true });
2230
+ }
2231
+ if (method === 'POST' && parts[3] === 'takeover' && !ext.subagent) {
2232
+ // Continue the same conversation inside the office. If the outside
2233
+ // terminal is still open, continue from a copy (fork) of the session.
2234
+ try {
2235
+ fs.accessSync(ext.transcript || '', fs.constants.R_OK);
2236
+ } catch {
2237
+ return fail(400, 'err.transcriptUnreadable');
2238
+ }
2239
+ // Check before the session moves in, so a failed start leaves no copy behind.
2240
+ const bad = claudeConfigProblem();
2241
+ if (bad) return fail(400, 'err.claudeConfigUnreadable', bad);
2242
+ const project = ensureProject(ext.projectId);
2243
+ if (!project) return fail(400, 'err.projectNotFound');
2244
+ const alive = pidAlive(ext.pid);
2245
+ const agent = {
2246
+ id: newId(),
2247
+ name: ext.name,
2248
+ role: ext.role,
2249
+ projectId: project.id,
2250
+ model: '',
2251
+ permissionMode: 'default',
2252
+ command: 'claude',
2253
+ color: ext.color,
2254
+ createdAt: Date.now(),
2255
+ hasConversation: true,
2256
+ sessionId: ext.sessionId,
2257
+ forkOnce: alive,
2258
+ };
2259
+ db.agents.push(agent);
2260
+ delete db.external[ext.sessionId];
2261
+ if (db.game.agents[ext.id]) {
2262
+ db.game.agents[agent.id] = db.game.agents[ext.id];
2263
+ delete db.game.agents[ext.id];
2264
+ }
2265
+ gl(ext.id).oneOnOne = false;
2266
+ save();
2267
+ try {
2268
+ startAgent(agent, cleanText(body.prompt) || undefined);
2269
+ } catch (e) {
2270
+ return send(res, 200, { agent, error: errText(lang, e) });
2271
+ }
2272
+ externals.delete(ext.id);
2273
+ broadcastState();
2274
+ return send(res, 200, { agent, forked: alive });
2275
+ }
2276
+ if (method === 'DELETE' && !ext.subagent) {
2277
+ // Firing an outside session ends its Claude process; the conversation
2278
+ // stays on disk and can be resumed with `claude --resume`.
2279
+ try {
2280
+ process.kill(ext.pid, 'SIGTERM');
2281
+ } catch (e) {
2282
+ if (e.code === 'EPERM') return fail(403, 'err.fireNoPermission', { pid: ext.pid });
2283
+ if (e.code !== 'ESRCH') return send(res, 500, { error: e.message });
2284
+ }
2285
+ firedPids.add(ext.pid);
2286
+ delete db.external[ext.sessionId];
2287
+ externals.delete(ext.id);
2288
+ save();
2289
+ broadcastState();
2290
+ return send(res, 200, { ok: true });
2291
+ }
2292
+ return fail(400, 'err.externalReadOnly');
2293
+ }
2294
+
2295
+ const agent = findAgent(parts[2]);
2296
+ if (!agent) return fail(404, 'err.agentNotFound');
2297
+ const action = parts[3];
2298
+
2299
+ if (method === 'DELETE') {
2300
+ boardReturn(agent.id);
2301
+ stopAgent(agent);
2302
+ // give the process a moment to exit before looking at its worktree
2303
+ if (agent.worktreePath) {
2304
+ setTimeout(() => {
2305
+ const r = dropWorktree(agent);
2306
+ if (r && r.kept) broadcast({ t: 'toast', kind: 'info', key: 'srv.worktreeKept', params: { name: agent.name, path: r.kept, branch: agent.branch } });
2307
+ }, 1500);
2308
+ }
2309
+ db.agents = db.agents.filter((x) => x.id !== agent.id);
2310
+ runtime.delete(agent.id);
2311
+ fs.rmSync(path.join(SETTINGS_DIR, `${agent.id}.json`), { force: true });
2312
+ save();
2313
+ broadcastState();
2314
+ return send(res, 200, { ok: true });
2315
+ }
2316
+ if (method === 'PATCH') {
2317
+ if (body.role && ROLES.includes(body.role)) {
2318
+ if (ROLES.indexOf(body.role) < ROLES.indexOf(agent.role)) bump('promotions');
2319
+ agent.role = body.role;
2320
+ }
2321
+ if (body.name) agent.name = cleanText(body.name, 30);
2322
+ if (body.model !== undefined) agent.model = cleanText(body.model, 60);
2323
+ if (body.permissionMode) agent.permissionMode = cleanText(body.permissionMode, 30);
2324
+ if (typeof body.worktree === 'boolean' && !rt(agent.id).pty) agent.worktree = body.worktree;
2325
+ if (['f', 'm', 'auto'].includes(body.look)) agent.look = body.look;
2326
+ if (body.projectId && findProject(body.projectId) && !rt(agent.id).pty) agent.projectId = body.projectId;
2327
+ save();
2328
+ broadcastState();
2329
+ return send(res, 200, { agent });
2330
+ }
2331
+ try {
2332
+ if (action === 'start') {
2333
+ startAgent(agent, cleanText(body.prompt) || undefined);
2334
+ return send(res, 200, { ok: true });
2335
+ }
2336
+ if (action === 'stop') {
2337
+ stopAgent(agent);
2338
+ return send(res, 200, { ok: true });
2339
+ }
2340
+ if (action === 'message') {
2341
+ const text = cleanText(body.text);
2342
+ if (!text) return fail(400, 'err.emptyMessage');
2343
+ sendToAgent(agent, text);
2344
+ return send(res, 200, { ok: true });
2345
+ }
2346
+ if (action === 'visit') {
2347
+ const target = findAny(body.targetId);
2348
+ if (!target || target.id === agent.id) return fail(400, 'err.pickColleague');
2349
+ const tp = findProject(target.projectId) || (target.external ? { name: path.basename(target.cwd), path: target.cwd } : null);
2350
+ const topic = cleanText(body.text, 4000) || 'Catch up on what they are doing and see how your work relates.';
2351
+ const context = recentContext(target);
2352
+ const prompt = [
2353
+ `[VISIT] The boss sent you to talk with your colleague ${target.name} (${ROLE_LABELS[target.role]}, project "${tp ? tp.name : '?'}" at ${tp ? tp.path : '?'}).`,
2354
+ `Topic: ${topic}`,
2355
+ '',
2356
+ `Recent conversation from ${target.name}'s session:`,
2357
+ '"""',
2358
+ context || '(nothing yet)',
2359
+ '"""',
2360
+ tp ? `You may read files under ${tp.path} if needed. Summarize what you learned and what you will do next.` : '',
2361
+ ].join('\n');
2362
+ sendToAgent(agent, prompt);
2363
+ rt(agent.id).visit = { targetId: target.id, until: Date.now() + 10 * 60 * 1000 };
2364
+ if (body.notifyTarget && !target.external && rt(target.id).pty) {
2365
+ sendToAgent(target, `[VISIT] ${agent.name} (${ROLE_LABELS[agent.role]}) is coming over to talk to you about: ${topic}. Briefly say what you are working on and anything ${agent.name} should know.`);
2366
+ }
2367
+ broadcast({ t: 'bubble', ids: [agent.id, target.id], text: topic, kind: 'visit' });
2368
+ bump('visits');
2369
+ broadcastState();
2370
+ return send(res, 200, { ok: true });
2371
+ }
2372
+ if (action === 'answer') {
2373
+ // Answer the permission prompt from the approval queue: Enter picks
2374
+ // the highlighted "Yes", Escape declines and lets the boss redirect.
2375
+ const r = rt(agent.id);
2376
+ if (!r.pty) throw new OfficeError('err.offline', { name: agent.name });
2377
+ // Only a real permission request: other prompts (e.g. folder trust) default to "No".
2378
+ if (r.status !== 'waiting' || !r.ask) return fail(409, 'err.notWaiting', { name: agent.name });
2379
+ r.pty.write(body.allow ? '\r' : '\x1b');
2380
+ if (body.allow) setStatus(agent.id, 'working', { note: '' });
2381
+ else {
2382
+ gl(agent.id).declined = true;
2383
+ r.boardHold = true; // the boss wants to redirect: don't hand over the next card
2384
+ boardReturn(agent.id);
2385
+ setStatus(agent.id, 'idle', { note: { key: 'srv.declined' } });
2386
+ }
2387
+ return send(res, 200, { ok: true });
2388
+ }
2389
+ if (action === 'interrupt') {
2390
+ // Esc stops Claude's turn; it then waits for the boss. No credit for it.
2391
+ const r = rt(agent.id);
2392
+ if (!r.pty) throw new OfficeError('err.offline', { name: agent.name });
2393
+ r.pty.write('\x1b');
2394
+ gl(agent.id).declined = true;
2395
+ r.boardHold = true;
2396
+ boardReturn(agent.id);
2397
+ setStatus(agent.id, 'idle', { note: { key: 'srv.interrupted' } });
2398
+ return send(res, 200, { ok: true });
2399
+ }
2400
+ if (action === 'return') {
2401
+ rt(agent.id).visit = null;
2402
+ broadcastState();
2403
+ return send(res, 200, { ok: true });
2404
+ }
2405
+ } catch (e) {
2406
+ return send(res, 400, { error: errText(lang, e) });
2407
+ }
2408
+ }
2409
+
2410
+ return send(res, 404, { error: 'Not found' });
2411
+ }
2412
+
2413
+ const server = http.createServer(async (req, res) => {
2414
+ try {
2415
+ if (!allowedHosts.has(req.headers.host)) return send(res, 403, 'Forbidden host', 'text/plain');
2416
+ const url = new URL(req.url, `http://${req.headers.host}`);
2417
+ if (url.pathname.startsWith('/api/')) return await api(req, res, url);
2418
+ if (VENDOR[url.pathname]) {
2419
+ return send(res, 200, fs.readFileSync(VENDOR[url.pathname]), MIME[path.extname(url.pathname)]);
2420
+ }
2421
+ const rel = url.pathname === '/' ? 'index.html' : url.pathname.slice(1);
2422
+ const file = path.join(PUBLIC_DIR, path.normalize(rel));
2423
+ if (!file.startsWith(PUBLIC_DIR) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return send(res, 404, 'Not found', 'text/plain');
2424
+ send(res, 200, fs.readFileSync(file), MIME[path.extname(file)] || 'application/octet-stream');
2425
+ } catch (e) {
2426
+ send(res, 500, { error: e.message });
2427
+ }
2428
+ });
2429
+
2430
+ // ---------------------------------------------------------------- WebSocket
2431
+
2432
+ const wss = new WebSocketServer({ noServer: true });
2433
+ server.on('upgrade', (req, socket, head) => {
2434
+ if (!allowedHosts.has(req.headers.host) || !allowedOrigins.has(req.headers.origin) || !req.url.startsWith('/ws')) {
2435
+ socket.destroy();
2436
+ return;
2437
+ }
2438
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws));
2439
+ });
2440
+
2441
+ wss.on('connection', (ws) => {
2442
+ clients.add(ws);
2443
+ ws.attached = null;
2444
+ ws.send(JSON.stringify({ t: 'hello', bootId: BOOT_ID, dev: DEV }));
2445
+ if (Date.now() - usageAt > 60 * 1000) setTimeout(refreshUsage, 100);
2446
+ ws.send(JSON.stringify({ t: 'state', state: publicState() }));
2447
+ const bad = claudeConfigProblem();
2448
+ if (bad) ws.send(JSON.stringify({ t: 'toast', kind: 'warn', key: 'err.claudeConfigUnreadable', params: bad }));
2449
+ ws.on('message', (raw) => {
2450
+ let m;
2451
+ try {
2452
+ m = JSON.parse(raw);
2453
+ } catch {
2454
+ return;
2455
+ }
2456
+ const r = m.id ? runtime.get(m.id) : null;
2457
+ if (m.t === 'attach') {
2458
+ ws.attached = m.id;
2459
+ ws.send(JSON.stringify({ t: 'replay', id: m.id, data: r ? r.buffer : '' }));
2460
+ } else if (m.t === 'detach') {
2461
+ ws.attached = null;
2462
+ } else if (m.t === 'input' && r && r.pty) {
2463
+ r.pty.write(String(m.data));
2464
+ // The boss answered a permission prompt in the terminal.
2465
+ if (r.status === 'waiting') setStatus(m.id, 'working', { note: '' });
2466
+ } else if (m.t === 'resize' && r && r.pty) {
2467
+ const cols = Math.max(20, Math.min(400, m.cols | 0));
2468
+ const rows = Math.max(5, Math.min(200, m.rows | 0));
2469
+ try {
2470
+ r.pty.resize(cols, rows);
2471
+ } catch {
2472
+ /* exited */
2473
+ }
2474
+ }
2475
+ });
2476
+ ws.on('close', () => clients.delete(ws));
2477
+ });
2478
+
2479
+ // ---------------------------------------------------------------- lifecycle
2480
+
2481
+ function shutdown() {
2482
+ for (const r of runtime.values()) if (r.pty) try { r.pty.kill(); } catch { /* ignore */ }
2483
+ try {
2484
+ fs.writeFileSync(STATE_FILE, JSON.stringify(db, null, 2));
2485
+ } catch {
2486
+ /* ignore */
2487
+ }
2488
+ process.exit(0);
2489
+ }
2490
+ process.on('SIGINT', shutdown);
2491
+ process.on('SIGTERM', shutdown);
2492
+
2493
+ // ---------------------------------------------------------------- hot reload
2494
+
2495
+ // In a checkout (or with AGENT_OFFICE_DEV=1) the office reloads itself:
2496
+ // - files under public/ change → browsers reload, the server keeps running;
2497
+ // - server files change → once no office agent is mid-task, the server exits
2498
+ // with RESTART_CODE and the supervisor (bin/agent-office.js) starts it again.
2499
+ // Agents that were running are resumed with their sessions.
2500
+ const RESTART_CODE = 75;
2501
+ const BOOT_ID = crypto.randomBytes(4).toString('hex');
2502
+ const DEV = process.env.AGENT_OFFICE_DEV === '1' || (process.env.AGENT_OFFICE_DEV !== '0' && fs.existsSync(path.join(__dirname, '.git')));
2503
+ let restartPending = false;
2504
+
2505
+ function busyOfficeAgents() {
2506
+ return db.agents.filter((a) => {
2507
+ const r = rt(a.id);
2508
+ return r.pty && (r.status === 'working' || r.status === 'waiting' || r.status === 'starting');
2509
+ });
2510
+ }
2511
+
2512
+ function tryRestart() {
2513
+ if (!restartPending) return;
2514
+ if (!process.send) {
2515
+ // Not under the supervisor (e.g. `node server.js`): just tell the boss.
2516
+ broadcast({ t: 'toast', kind: 'warn', key: 'srv.restartManual' });
2517
+ restartPending = false;
2518
+ return;
2519
+ }
2520
+ try {
2521
+ execFileSync(process.execPath, ['--check', path.join(__dirname, 'server.js')], { stdio: 'pipe' });
2522
+ } catch (e) {
2523
+ broadcast({ t: 'toast', kind: 'err', key: 'srv.syntax', params: { error: String(e.stderr || e.message).split('\n').find((l) => /Error/.test(l)) || 'SyntaxError' } });
2524
+ restartPending = false;
2525
+ return;
2526
+ }
2527
+ const busy = busyOfficeAgents();
2528
+ if (busy.length) return; // wait until they finish their turn
2529
+ restartPending = false; // restart exactly once
2530
+ db.resumeOnBoot = db.agents.filter((a) => rt(a.id).pty).map((a) => a.id);
2531
+ broadcast({ t: 'restarting' });
2532
+ for (const r of runtime.values()) if (r.pty) try { r.pty.kill(); } catch { /* ignore */ }
2533
+ fs.writeFileSync(STATE_FILE, JSON.stringify(db, null, 2));
2534
+ setTimeout(() => process.exit(RESTART_CODE), 300);
2535
+ }
2536
+
2537
+ function watchForChanges() {
2538
+ if (!DEV) return;
2539
+ let publicTimer = null;
2540
+ let cssOnly = true;
2541
+ try {
2542
+ fs.watch(PUBLIC_DIR, { recursive: true }, (_, file) => {
2543
+ if (file && !/\.css$/.test(file)) cssOnly = false;
2544
+ clearTimeout(publicTimer);
2545
+ publicTimer = setTimeout(() => {
2546
+ broadcast({ t: 'reload', css: cssOnly });
2547
+ cssOnly = true;
2548
+ }, 150);
2549
+ });
2550
+ } catch {
2551
+ /* recursive watch unsupported */
2552
+ }
2553
+ let serverTimer = null;
2554
+ // Watch the folder rather than the files: editors often save by replacing the file.
2555
+ const serverFiles = new Set(['server.js', 'hook-relay.js']);
2556
+ {
2557
+ try {
2558
+ fs.watch(__dirname, (_, file) => {
2559
+ if (!serverFiles.has(String(file))) return;
2560
+ clearTimeout(serverTimer);
2561
+ serverTimer = setTimeout(() => {
2562
+ restartPending = true;
2563
+ const busy = busyOfficeAgents();
2564
+ if (busy.length && process.send) {
2565
+ broadcast({ t: 'toast', kind: 'info', key: 'srv.updateReady', params: { names: busy.map((a) => a.name).join(', ') } });
2566
+ }
2567
+ tryRestart();
2568
+ }, 300);
2569
+ });
2570
+ } catch {
2571
+ /* file missing */
2572
+ }
2573
+ }
2574
+ setInterval(tryRestart, 2000);
2575
+ }
2576
+
2577
+ // Bring back the agents that were at work before a hot restart.
2578
+ function resumeAfterRestart() {
2579
+ const ids = db.resumeOnBoot || [];
2580
+ delete db.resumeOnBoot;
2581
+ save();
2582
+ for (const id of ids) {
2583
+ const a = findAgent(id);
2584
+ if (!a) continue;
2585
+ try {
2586
+ startAgent(a);
2587
+ } catch (e) {
2588
+ console.error(`Could not resume ${a.name}: ${e.message}`);
2589
+ if (e.key) rt(a.id).note = { key: e.key, params: e.params };
2590
+ }
2591
+ }
2592
+ }
2593
+
2594
+ function listen(cb) {
2595
+ server.on('error', (e) => {
2596
+ if (e.code === 'EADDRINUSE') {
2597
+ console.error(`Port ${PORT} is in use. Start with another port: PORT=4322 npm start`);
2598
+ process.exit(1);
2599
+ }
2600
+ throw e;
2601
+ });
2602
+ server.listen(PORT, HOST, () => {
2603
+ const url = `http://127.0.0.1:${PORT}`;
2604
+ watchForChanges();
2605
+ resumeAfterRestart();
2606
+ if (process.send) process.send({ t: 'ready', url, dev: DEV });
2607
+ if (cb) cb(url);
2608
+ });
2609
+ }
2610
+
2611
+ module.exports = { listen };
2612
+
2613
+ if (require.main === module) listen((u) => !process.send && console.log(`Agent Hall running at ${u}`));