pixel-agent-office 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 donasman
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # Agent Office
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Watch your Claude Code agents work in a pixel-art office. The main agent is the boss. Every subagent is a staff member who wakes up when given a task, works at their desk, sends a report flying to the boss when done, and goes back to sleep.
4
+
5
+ ## Quick start
6
+
7
+ 1. In Claude Code, install the plugin:
8
+
9
+ ```
10
+ /plugin marketplace add donasman/pixel-agent-office
11
+ /plugin install agent-office@agent-office
12
+ ```
13
+
14
+ 2. Open the office (Node.js 18 or later):
15
+
16
+ ```
17
+ npx pixel-agent-office
18
+ ```
19
+
20
+ Then use Claude Code as usual, in any terminal or IDE. The office opens in an app window (Edge or Chrome) or in your default browser. Close the window and the viewer stops.
21
+
22
+ ## What happens in the office
23
+
24
+ | In Claude Code | In the office |
25
+ |---|---|
26
+ | A subagent starts | A sleeping staff member wakes up with a "!" and gets the task's name |
27
+ | Edit / Write, Read / Grep, Bash | Typing, reading papers, a terminal on the monitor |
28
+ | A subagent finishes | Its report flies to the boss's desk; the boss reads the first line |
29
+ | Permission prompt | A "?" bubble, a chime, and a blinking taskbar (desktop app) |
30
+ | A tool fails | Sweat and "OOPS"; three failures in a row make the monitor smoke |
31
+ | `git commit` / tests pass | Confetti / the whole office claps |
32
+ | Context compaction | A robot vacuum cleans up and the report pile is filed away |
33
+ | Rate limit or overload | The lights go out |
34
+
35
+ Click anyone to see their task, recent tools, work time and last report. Three office themes: day, late night and wood.
36
+
37
+ The art lives in `public/art/`. It is cut out of the pixel-art design by `node tools/import-design.js` (inputs in `tools/design/`).
38
+
39
+ ## How it works
40
+
41
+ ```
42
+ Claude Code hooks ──curl──▶ local server (127.0.0.1) ──SSE──▶ office page
43
+ │
44
+ └─ reads ~/.agent-office/port, which exists only while the office is open
45
+ ```
46
+
47
+ - The hooks run in the background (`async`), so they never slow Claude down.
48
+ - When the office isn't open there is no port file, and the hooks exit at once: nothing is sent and nothing is printed.
49
+ - Everything stays on your machine. The server keeps only what the office draws (tool names, task names, a report's first line) and drops file contents and command output. To show the boss's model, it reads the end of the session transcript.
50
+
51
+ Requirements: `bash` and `curl`. macOS and Linux have both. On Windows, Claude Code runs hooks in Git Bash, which includes curl.
52
+
53
+ ## Desktop app with a built-in terminal (optional, Windows)
54
+
55
+ Claude on the left, the office on the right, in one window:
56
+
57
+ ```
58
+ git clone https://github.com/donasman/pixel-agent-office.git
59
+ cd pixel-agent-office
60
+ npm install
61
+ npm start
62
+ ```
63
+
64
+ It runs your own `claude` login, so it uses your subscription as usual.
65
+
66
+ ## Uninstall
67
+
68
+ ```
69
+ /plugin uninstall agent-office@agent-office
70
+ ```
71
+
72
+ and delete the `~/.agent-office` folder.
73
+
74
+ ## Development
75
+
76
+ ```
77
+ npm test # office logic, server, npx entry
78
+ npm run viewer # the viewer from source
79
+ npm start # the desktop app
80
+ ```
81
+
82
+ `core/server.js` receives hook events and streams them; `public/` is the office page; `plugin/` is the Claude Code plugin; `electron/` is the desktop app.
83
+
84
+ ## License
85
+
86
+ [MIT](LICENSE) © donasman
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ // npx pixel-agent-office: start the office server (or find the one already running) and open it in an app window.
3
+ // Stops by itself once every office window has been closed, which removes the port file and quiets the hooks.
4
+ const { spawn } = require('child_process');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { start } = require('../core/server');
8
+
9
+ const IDLE_MS = Number(process.env.AGENT_OFFICE_IDLE_MS || 15000); // grace period: a page reload reconnects well within it
10
+
11
+ // A Chromium browser can open the page as an app window (no tabs, no address bar); otherwise use the default browser.
12
+ function appBrowser() {
13
+ const env = process.env;
14
+ const candidates = {
15
+ win32: [env['ProgramFiles(x86)'], env.ProgramFiles, env.LOCALAPPDATA].filter(Boolean).flatMap(dir => [
16
+ path.join(dir, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
17
+ path.join(dir, 'Google', 'Chrome', 'Application', 'chrome.exe'),
18
+ ]),
19
+ darwin: ['/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'],
20
+ linux: ['microsoft-edge', 'google-chrome', 'chromium', 'chromium-browser'].flatMap(b => (env.PATH || '').split(':').filter(Boolean).map(d => path.join(d, b))),
21
+ }[process.platform] || [];
22
+ return candidates.find(f => fs.existsSync(f));
23
+ }
24
+
25
+ function openWindow(url) {
26
+ const browser = appBrowser();
27
+ const [cmd, args] = browser ? [browser, [`--app=${url}`, '--window-size=960,720']]
28
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] // '' = start's window title, quoted to "" by node
29
+ : [process.platform === 'darwin' ? 'open' : 'xdg-open', [url]];
30
+ spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true }).on('error', () => console.log(`Open ${url} in your browser.`)).unref();
31
+ }
32
+
33
+ (async () => {
34
+ const office = await start();
35
+ const url = `http://127.0.0.1:${office.port}/`;
36
+ if (!process.argv.includes('--no-open')) openWindow(url);
37
+ if (office.attached) return console.log(`Agent Office is already running: ${url}`);
38
+
39
+ console.log(`Agent Office: ${url}\nCtrl+C stops it. Closing the office window stops it too.`);
40
+ process.on('SIGINT', () => process.exit(0)); // process.exit runs the handler that removes the port file
41
+ let seen = false, idleSince = 0;
42
+ setInterval(() => {
43
+ if (office.pages() > 0) { seen = true; idleSince = 0; return; }
44
+ if (!seen) return; // --no-open, or the window hasn't connected yet
45
+ idleSince ||= Date.now();
46
+ if (Date.now() - idleSince >= IDLE_MS) { console.log('The office window was closed: stopping.'); process.exit(0); }
47
+ }, 500);
48
+ })();
package/core/server.js ADDED
@@ -0,0 +1,172 @@
1
+ // Agent Office core: receives Claude Code hook events (POST /events), streams them to office pages (GET /stream, SSE)
2
+ // and serves the office page (public/). While running it writes its port to ~/.agent-office/port: that file is how the
3
+ // hooks find it, and no file means the hooks stay silent. One server per machine: a second start attaches to the first.
4
+ const crypto = require('crypto');
5
+ const http = require('http');
6
+ const fs = require('fs');
7
+ const os = require('os');
8
+ const path = require('path');
9
+
10
+ const PUBLIC = path.join(__dirname, '..', 'public');
11
+ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.png': 'image/png' };
12
+ const MAX_BODY = 8 * 1024 * 1024; // hook payloads can carry whole files (Write/Edit), so accept big bodies, then slim them
13
+ const LOG_MAX = 1000; // events replayed to a page that opens late
14
+ const CLAUDE_DIR = path.resolve(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'));
15
+
16
+ // Keep only what the office uses: payloads also hold file contents, command output and prompts.
17
+ function slim(e) {
18
+ const cut = (v, n) => (typeof v === 'string' ? v.slice(0, n) : undefined);
19
+ const ti = e.tool_input || {}, tr = e.tool_response;
20
+ return {
21
+ hook_event_name: e.hook_event_name, session_id: e.session_id, agent_id: e.agent_id, agent_type: e.agent_type,
22
+ source: e.source, tool_name: e.tool_name, tool_use_id: e.tool_use_id,
23
+ tool_input: { description: cut(ti.description, 200), command: cut(ti.command, 300), message: cut(ti.message, 400) }, // message: a subagent's report
24
+ tool_response: tr && typeof tr === 'object' && typeof tr.agentId === 'string' ? { agentId: tr.agentId } : undefined,
25
+ is_interrupt: e.is_interrupt, error: cut(e.error, 200), notification_type: e.notification_type, message: cut(e.message, 200),
26
+ last_assistant_message: cut(e.last_assistant_message, 400), to_model: e.to_model, trigger: e.trigger,
27
+ };
28
+ }
29
+
30
+ // Hook events don't say which model the main agent runs; its transcript does. Only the main thread's assistant lines
31
+ // count: other lines (api-request-shape, side requests) can name a different model.
32
+ function lastAssistantModel(text) {
33
+ const lines = text.split('\n');
34
+ for (let i = lines.length - 1; i >= 0; i--) {
35
+ if (!lines[i].includes('"type":"assistant"')) continue;
36
+ let j;
37
+ try { j = JSON.parse(lines[i]); } catch { continue; } // the tail's first line is usually cut
38
+ const m = j.message?.model;
39
+ if (j.type === 'assistant' && !j.isSidechain && typeof m === 'string' && m.startsWith('claude-')) return m;
40
+ }
41
+ }
42
+ const models = new Map(); // session_id -> model id
43
+ const inside = (file, dir) => {
44
+ const f = path.resolve(file), d = dir + path.sep;
45
+ return process.platform === 'win32' ? f.toLowerCase().startsWith(d.toLowerCase()) : f.startsWith(d);
46
+ };
47
+ function modelOf(e) {
48
+ if (e.agent_id || typeof e.session_id !== 'string') return undefined;
49
+ if (e.hook_event_name === 'PostModelSwitch' && typeof e.to_model === 'string') models.set(e.session_id, e.to_model);
50
+ const t = e.transcript_path;
51
+ if (!models.has(e.session_id) && typeof t === 'string' && t.endsWith('.jsonl') && inside(t, CLAUDE_DIR)) {
52
+ // shortcut: reads only the transcript's last 256 KB; if no assistant line is in there, the model shows up a turn later
53
+ try {
54
+ const fd = fs.openSync(t, 'r');
55
+ try {
56
+ const size = fs.fstatSync(fd).size, len = Math.min(size, 256 * 1024), buf = Buffer.alloc(len);
57
+ fs.readSync(fd, buf, 0, len, size - len);
58
+ const m = lastAssistantModel(buf.toString('utf8'));
59
+ if (m) models.set(e.session_id, m);
60
+ } finally { fs.closeSync(fd); }
61
+ } catch {} // transcript not written yet
62
+ }
63
+ return models.get(e.session_id);
64
+ }
65
+
66
+ function isOffice(port) {
67
+ return new Promise(ok => {
68
+ const r = http.get({ host: '127.0.0.1', port, path: '/health', timeout: 500 }, res => {
69
+ let b = '';
70
+ res.on('data', d => (b += d));
71
+ res.on('end', () => { try { ok(JSON.parse(b).app === 'agent-office'); } catch { ok(false); } });
72
+ });
73
+ r.on('error', () => ok(false));
74
+ r.on('timeout', () => { r.destroy(); ok(false); });
75
+ });
76
+ }
77
+
78
+ async function start({
79
+ port = Number(process.env.AGENT_OFFICE_PORT || 47100), // a stable port keeps the page's origin (and its saved settings) the same
80
+ home = process.env.AGENT_OFFICE_HOME || path.join(os.homedir(), '.agent-office'),
81
+ } = {}) {
82
+ const portFile = path.join(home, 'port');
83
+ const clients = new Set(), log = [];
84
+ // The same hook can be registered twice (the plugin + the app's --settings) and claude runs both: drop exact repeats.
85
+ const recent = new Map(); // body hash -> receive time, oldest first
86
+ let actual;
87
+
88
+ const send = (res, status, type, body) => { res.writeHead(status, type ? { 'Content-Type': type } : {}); res.end(body); };
89
+
90
+ function receive(req, res) {
91
+ // only the hooks' curl sends JSON; a web page can't without a CORS preflight we never answer
92
+ if (!String(req.headers['content-type']).startsWith('application/json')) return send(res, 415);
93
+ let size = 0;
94
+ const chunks = [];
95
+ req.on('data', d => {
96
+ size += d.length;
97
+ if (size > MAX_BODY) { send(res, 413); req.destroy(); } else chunks.push(d);
98
+ });
99
+ req.on('end', () => {
100
+ if (res.writableEnded) return;
101
+ const raw = Buffer.concat(chunks);
102
+ let e;
103
+ try { e = JSON.parse(raw.toString('utf8')); } catch { return send(res, 400); }
104
+ if (!e || typeof e.hook_event_name !== 'string') return send(res, 400);
105
+ send(res, 204);
106
+ const now = Date.now(), key = crypto.createHash('sha1').update(raw).digest('hex');
107
+ for (const [k, t] of recent) { if (now - t <= 5000) break; recent.delete(k); }
108
+ if (recent.has(key)) return; // distinct events always differ (tool_use_id, prompt_id, agent_id...)
109
+ recent.set(key, now);
110
+ const out = { ...slim(e), model: modelOf(e), _t: now };
111
+ log.push(out);
112
+ if (log.length > LOG_MAX) log.shift();
113
+ const msg = `data: ${JSON.stringify(out)}\n\n`;
114
+ for (const c of clients) c.write(msg);
115
+ });
116
+ }
117
+
118
+ function stream(req, res) {
119
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
120
+ res.write(': connected\n\n'); // sends the headers now; without it the page only "opens" at the first event
121
+ for (const m of log) res.write(`data: ${JSON.stringify(m)}\n\n`);
122
+ clients.add(res);
123
+ req.on('close', () => clients.delete(res));
124
+ }
125
+
126
+ function serveFile(pathname, res) {
127
+ let file;
128
+ try { file = path.join(PUBLIC, pathname === '/' ? 'index.html' : decodeURIComponent(pathname)); } catch { return send(res, 400); }
129
+ if (!file.startsWith(PUBLIC + path.sep)) return send(res, 404);
130
+ fs.readFile(file, (err, data) => (err ? send(res, 404) : send(res, 200, TYPES[path.extname(file)] || 'application/octet-stream', data)));
131
+ }
132
+
133
+ const server = http.createServer((req, res) => {
134
+ // DNS rebinding guard: only answer requests addressed to this machine's loopback
135
+ if (req.headers.host !== `127.0.0.1:${actual}` && req.headers.host !== `localhost:${actual}`) return send(res, 403);
136
+ const { pathname } = new URL(req.url, 'http://127.0.0.1');
137
+ if (req.method === 'POST' && pathname === '/events') return receive(req, res);
138
+ if (req.method !== 'GET') return send(res, 405);
139
+ if (pathname === '/health') return send(res, 200, 'application/json', JSON.stringify({ app: 'agent-office', port: actual, pages: clients.size }));
140
+ if (pathname === '/stream') return stream(req, res);
141
+ serveFile(pathname, res);
142
+ });
143
+
144
+ const listen = p => new Promise((ok, fail) => {
145
+ server.once('error', fail);
146
+ server.listen(p, '127.0.0.1', () => { server.off('error', fail); ok(server.address().port); });
147
+ });
148
+ try {
149
+ actual = await listen(port);
150
+ } catch (err) {
151
+ if (err.code !== 'EADDRINUSE') throw err;
152
+ if (await isOffice(port)) return { port, attached: true, pages: () => 0, close: () => Promise.resolve() };
153
+ actual = await listen(0); // something else owns the preferred port
154
+ }
155
+
156
+ fs.mkdirSync(home, { recursive: true });
157
+ fs.writeFileSync(portFile, String(actual));
158
+ const removePortFile = () => { try { if (fs.readFileSync(portFile, 'utf8') === String(actual)) fs.rmSync(portFile); } catch {} };
159
+ process.on('exit', removePortFile);
160
+ return {
161
+ port: actual,
162
+ attached: false,
163
+ pages: () => clients.size, // office pages connected right now
164
+ close: () => new Promise(ok => {
165
+ removePortFile(); // first, so hooks go quiet even if closing the sockets takes a while
166
+ for (const c of clients) c.end();
167
+ server.close(() => ok());
168
+ }),
169
+ };
170
+ }
171
+
172
+ module.exports = { start };
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "pixel-agent-office",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Watch your Claude Code subagents work in a pixel-art office. The local viewer for the agent-office Claude Code plugin.",
5
+ "author": "donasman",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/donasman/pixel-agent-office#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/donasman/pixel-agent-office.git"
11
+ },
12
+ "bugs": "https://github.com/donasman/pixel-agent-office/issues",
13
+ "keywords": [
14
+ "claude-code",
15
+ "subagents",
16
+ "hooks",
17
+ "pixel-art",
18
+ "visualizer"
19
+ ],
20
+ "bin": {
21
+ "pixel-agent-office": "bin/pixel-agent-office.js"
22
+ },
23
+ "files": [
24
+ "bin/",
25
+ "core/",
26
+ "public/"
27
+ ],
28
+ "engines": {
29
+ "node": ">=18"
30
+ },
31
+ "scripts": {
32
+ "start": "electron electron/main.js",
33
+ "viewer": "node bin/pixel-agent-office.js",
34
+ "test": "node test/office.test.js && node test/server.test.js && node test/cli.test.js"
35
+ },
36
+ "devDependencies": {
37
+ "@xterm/addon-fit": "^0.11.0",
38
+ "@xterm/xterm": "^6.0.0",
39
+ "electron": "^45.3.3",
40
+ "node-pty": "^1.1.0"
41
+ }
42
+ }
package/public/app.js ADDED
@@ -0,0 +1,142 @@
1
+ // Office page: hook events streamed by the core server -> office state -> drawing, roster, info card, sounds.
2
+ // Runs alone in a browser, or inside the Electron app's iframe; there it talks to the app with postMessage.
3
+ const embedded = window.parent !== window;
4
+ const toShell = kind => { if (embedded) window.parent.postMessage({ agentOffice: kind }, '*'); }; // carries no data
5
+
6
+ let state = Office.createState();
7
+ let selected = null; // id of the character whose info card is open
8
+ let resetAt = 0; // events from before the app restarted claude are ignored
9
+ let appFocused = embedded || document.hasFocus();
10
+
11
+ // Text nodes only below: task and report text come from the model.
12
+ const el = (tag, cls, ...kids) => { const n = document.createElement(tag); if (cls) n.className = cls; n.append(...kids); return n; };
13
+
14
+ const roster = document.getElementById('roster');
15
+ function renderRoster() {
16
+ roster.replaceChildren(...Object.values(state.chars).filter(c => c.kind === 'boss' || c.busy).map(c => {
17
+ const dot = el('span', 'dot');
18
+ dot.style.background = c.color;
19
+ return el('li', '', dot, c.label + (c.task ? `: ${c.task}` : ''),
20
+ el('span', 'st', ` — ${Office.STATUS_KO[c.status]}${c.tool ? ` (${c.tool})` : ''}`));
21
+ }));
22
+ }
23
+
24
+ const card = document.getElementById('card');
25
+ const cardBody = document.getElementById('card-body');
26
+ const mmss = ms => `${Math.floor(ms / 60000)}분 ${Math.floor(ms / 1000) % 60}초`;
27
+ function renderCard() {
28
+ const c = selected && state.chars[selected];
29
+ card.hidden = !c;
30
+ if (!c) return;
31
+ const rows = [
32
+ ['상태', Office.STATUS_KO[c.status] + (c.tool ? ` (${c.tool})` : '')],
33
+ ['맡은 일', c.task || '-'],
34
+ ['최근 도구', c.history.join(' → ') || '-'],
35
+ ['이번 근무', c.status !== 'sleeping' && c.since ? mmss(Date.now() - c.since) : '-'],
36
+ ];
37
+ if (c.kind === 'boss') rows.push(['모델', c.model || '?'], ['받은 보고서', `${state.reports}장`]);
38
+ else rows.push(['받은 업무', `${c.jobs}건`], ['마지막 보고', c.lastReport || '-']);
39
+ cardBody.replaceChildren(
40
+ el('strong', '', c.kind === 'boss' ? 'Claude (보스)' : c.label || `직원 ${c.desk}`),
41
+ ...rows.map(([k, v]) => el('div', '', el('span', 'k', k), v)));
42
+ }
43
+ setInterval(renderCard, 1000); // keeps the work timer ticking
44
+
45
+ // Attention sounds, synthesized (no audio files). Muting is a per-viewer preference.
46
+ const muteBtn = document.getElementById('mute');
47
+ let muted = false, audio;
48
+ try { muted = localStorage.getItem('muted') === '1'; } catch {}
49
+ const showMute = () => { muteBtn.textContent = muted ? '🔕' : '🔔'; muteBtn.setAttribute('aria-pressed', String(muted)); };
50
+ showMute();
51
+ muteBtn.addEventListener('click', () => {
52
+ muted = !muted;
53
+ try { localStorage.setItem('muted', muted ? '1' : '0'); } catch {}
54
+ showMute();
55
+ });
56
+ function beep(freqs) {
57
+ audio ??= new AudioContext();
58
+ freqs.forEach((hz, i) => {
59
+ const o = audio.createOscillator(), g = audio.createGain(), t0 = audio.currentTime + i * 0.12;
60
+ o.frequency.value = hz;
61
+ g.gain.setValueAtTime(0.0001, t0);
62
+ g.gain.exponentialRampToValueAtTime(0.08, t0 + 0.01);
63
+ g.gain.exponentialRampToValueAtTime(0.0001, t0 + 0.25);
64
+ o.connect(g).connect(audio.destination);
65
+ o.start(t0);
66
+ o.stop(t0 + 0.3);
67
+ });
68
+ }
69
+ function notify(freqs) { toShell('flash'); if (!muted) beep(freqs); }
70
+
71
+ // The office's art comes from the pixel-art design (tools/import-design.js). Until it loads the canvas stays plain.
72
+ const THEME_KO = { day: '주간', night: '야근', wood: '우드' };
73
+ const themeBtn = document.getElementById('theme');
74
+ let themeName = 'day';
75
+ try { themeName = localStorage.getItem('theme') || 'day'; } catch {}
76
+ const showTheme = () => { themeName = Office.setTheme(themeName); themeBtn.textContent = THEME_KO[themeName] || themeName; };
77
+ themeBtn.addEventListener('click', () => {
78
+ const list = Office.themes();
79
+ themeName = list[(list.indexOf(themeName) + 1) % list.length] || 'day';
80
+ showTheme();
81
+ try { localStorage.setItem('theme', themeName); } catch {}
82
+ });
83
+ const loadImg = src => new Promise((ok, fail) => { const i = new Image(); i.onload = () => ok(i); i.onerror = () => fail(new Error('art/' + src)); i.src = 'art/' + src; });
84
+ fetch('art/art.json').then(r => r.json()).then(async art => {
85
+ const [people, standing, bubbles, screens] = await Promise.all([art.people.file, art.standing.file, art.bubbles.file, art.screens.file].map(loadImg));
86
+ const themes = {};
87
+ for (const [name, t] of Object.entries(art.themes)) {
88
+ themes[name] = { room: await loadImg(t.room), people: t.people ? await loadImg(t.people) : people, standing: t.standing ? await loadImg(t.standing) : standing };
89
+ }
90
+ Office.useArt(art, { themes, bubbles, screens });
91
+ showTheme();
92
+ }).catch(err => console.error('office art failed to load:', err.message));
93
+
94
+ function apply(e) {
95
+ if (e._t < resetAt) return;
96
+ Office.reduce(state, e, e._t); // the server's receive time, so replayed history doesn't replay its effects
97
+ renderRoster();
98
+ renderCard();
99
+ if (Date.now() - e._t > 3000) return; // history replayed on (re)connect: no sounds
100
+ if (e.hook_event_name === 'PermissionRequest') notify([880, 1320]); // claude needs an answer
101
+ else if (e.hook_event_name === 'Stop' && !appFocused) notify([660]); // done while you were elsewhere
102
+ }
103
+
104
+ const events = new EventSource('/stream');
105
+ events.onopen = () => { state = Office.createState(); renderRoster(); renderCard(); }; // the server replays its history on every (re)connect
106
+ events.onmessage = m => { try { apply(JSON.parse(m.data)); } catch {} };
107
+
108
+ if (embedded) {
109
+ window.addEventListener('message', m => {
110
+ if (m.source !== window.parent || !m.data) return;
111
+ if (m.data.agentOffice === 'focus') appFocused = Boolean(m.data.value);
112
+ else if (m.data.agentOffice === 'reset') { // the app restarted claude: start from an empty office
113
+ resetAt = Date.now();
114
+ state = Office.createState();
115
+ selected = null;
116
+ renderRoster();
117
+ renderCard();
118
+ }
119
+ });
120
+ } else {
121
+ window.addEventListener('focus', () => (appFocused = true));
122
+ window.addEventListener('blur', () => (appFocused = false));
123
+ }
124
+
125
+ const canvas = document.getElementById('office');
126
+ canvas.addEventListener('mousemove', ev => { canvas.style.cursor = Office.hit(state, ev.offsetX, ev.offsetY) ? 'pointer' : ''; });
127
+ canvas.addEventListener('click', ev => {
128
+ const c = Office.hit(state, ev.offsetX, ev.offsetY);
129
+ selected = c && c.id;
130
+ renderCard();
131
+ if (!c) return;
132
+ c.petAt = Date.now(); // hop + heart
133
+ card.style.left = Math.max(8, Math.min(ev.offsetX + 12, document.body.clientWidth - card.offsetWidth - 8)) + 'px';
134
+ card.style.top = Math.max(8, Math.min(ev.offsetY + 12, document.body.clientHeight - card.offsetHeight - 8)) + 'px';
135
+ if (c.kind === 'boss') toShell('focus-terminal');
136
+ });
137
+ document.getElementById('card-close').addEventListener('click', () => { selected = null; renderCard(); });
138
+
139
+ requestAnimationFrame(function frame(t) {
140
+ Office.step(canvas, state, t);
141
+ requestAnimationFrame(frame);
142
+ });
@@ -0,0 +1,239 @@
1
+ {
2
+ "size": [
3
+ 192,
4
+ 144
5
+ ],
6
+ "cell": [
7
+ 16,
8
+ 28
9
+ ],
10
+ "poses": [
11
+ "idle",
12
+ "typeA",
13
+ "typeB",
14
+ "read",
15
+ "raise",
16
+ "sleep"
17
+ ],
18
+ "people": {
19
+ "file": "people.png",
20
+ "rows": {
21
+ "boss": 0,
22
+ "staff": [
23
+ 1,
24
+ 2,
25
+ 3,
26
+ 4,
27
+ 5,
28
+ 6,
29
+ 7,
30
+ 8
31
+ ],
32
+ "temp": 9,
33
+ "opus": 10,
34
+ "haiku": 11,
35
+ "fable": 12
36
+ },
37
+ "clothes": [
38
+ "#d97757",
39
+ "#e8ecf4",
40
+ "#f0c9c4",
41
+ "#5b6078",
42
+ "#8aad6a",
43
+ "#2f3e5c",
44
+ "#d9a441",
45
+ "#7a5c46",
46
+ "#a3382f",
47
+ "#34548a",
48
+ "#3a3d52",
49
+ "#7cc47a",
50
+ "#7c4dcf"
51
+ ]
52
+ },
53
+ "standing": {
54
+ "file": "standing.png",
55
+ "w": 24,
56
+ "h": 38,
57
+ "at": [
58
+ 134,
59
+ 28
60
+ ]
61
+ },
62
+ "themes": {
63
+ "day": {
64
+ "room": "room-day.png",
65
+ "plateInk": "#5a5063"
66
+ },
67
+ "night": {
68
+ "room": "room-night.png",
69
+ "plateInk": "#adb1c3",
70
+ "people": "people-night.png",
71
+ "standing": "standing-night.png"
72
+ },
73
+ "wood": {
74
+ "room": "room-wood.png",
75
+ "plateInk": "#fff1dc"
76
+ }
77
+ },
78
+ "bubbles": {
79
+ "file": "bubbles.png",
80
+ "items": {
81
+ "delegate": {
82
+ "x": 0,
83
+ "y": 0,
84
+ "w": 9,
85
+ "h": 10
86
+ },
87
+ "wake": {
88
+ "x": 10,
89
+ "y": 0,
90
+ "w": 7,
91
+ "h": 10
92
+ },
93
+ "edit": {
94
+ "x": 18,
95
+ "y": 0,
96
+ "w": 9,
97
+ "h": 10
98
+ },
99
+ "read": {
100
+ "x": 28,
101
+ "y": 0,
102
+ "w": 9,
103
+ "h": 10
104
+ },
105
+ "ask": {
106
+ "x": 38,
107
+ "y": 0,
108
+ "w": 7,
109
+ "h": 10
110
+ },
111
+ "run": {
112
+ "x": 46,
113
+ "y": 0,
114
+ "w": 9,
115
+ "h": 10
116
+ },
117
+ "think": {
118
+ "x": 56,
119
+ "y": 0,
120
+ "w": 15,
121
+ "h": 10
122
+ }
123
+ }
124
+ },
125
+ "screens": {
126
+ "file": "screens.png",
127
+ "w": 10,
128
+ "h": 6,
129
+ "items": [
130
+ "edit",
131
+ "read",
132
+ "off",
133
+ "ask",
134
+ "run",
135
+ "think",
136
+ "delegate"
137
+ ]
138
+ },
139
+ "glyphs": {
140
+ "E": [
141
+ "111",
142
+ "100",
143
+ "110",
144
+ "100",
145
+ "111"
146
+ ],
147
+ "X": [
148
+ "101",
149
+ "101",
150
+ "010",
151
+ "101",
152
+ "101"
153
+ ],
154
+ "P": [
155
+ "110",
156
+ "101",
157
+ "110",
158
+ "100",
159
+ "100"
160
+ ],
161
+ "L": [
162
+ "100",
163
+ "100",
164
+ "100",
165
+ "100",
166
+ "111"
167
+ ],
168
+ "O": [
169
+ "010",
170
+ "101",
171
+ "101",
172
+ "101",
173
+ "010"
174
+ ],
175
+ "R": [
176
+ "110",
177
+ "101",
178
+ "110",
179
+ "101",
180
+ "101"
181
+ ],
182
+ "A": [
183
+ "010",
184
+ "101",
185
+ "111",
186
+ "101",
187
+ "101"
188
+ ],
189
+ "N": [
190
+ "110",
191
+ "101",
192
+ "101",
193
+ "101",
194
+ "101"
195
+ ],
196
+ "V": [
197
+ "101",
198
+ "101",
199
+ "101",
200
+ "101",
201
+ "010"
202
+ ],
203
+ "I": [
204
+ "111",
205
+ "010",
206
+ "010",
207
+ "010",
208
+ "111"
209
+ ],
210
+ "W": [
211
+ "101",
212
+ "101",
213
+ "111",
214
+ "111",
215
+ "101"
216
+ ],
217
+ "T": [
218
+ "111",
219
+ "010",
220
+ "010",
221
+ "010",
222
+ "010"
223
+ ],
224
+ "S": [
225
+ "011",
226
+ "100",
227
+ "010",
228
+ "001",
229
+ "110"
230
+ ],
231
+ "G": [
232
+ "011",
233
+ "100",
234
+ "101",
235
+ "101",
236
+ "011"
237
+ ]
238
+ }
239
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,39 @@
1
+ <!doctype html>
2
+ <html lang="ko">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'unsafe-inline'">
7
+ <title>Agent Office</title>
8
+ <style>
9
+ html, body { margin: 0; height: 100%; overflow: hidden; background: #181825; color: #cdd6f4; font: 13px "Malgun Gothic", sans-serif; }
10
+ body { display: flex; flex-direction: column; position: relative; }
11
+ #office { flex: 1; min-height: 0; display: block; width: 100%; }
12
+ #roster { margin: 0; padding: 8px 12px; list-style: none; flex: 0 0 22%; box-sizing: border-box; overflow-y: auto; border-top: 1px solid #313244; } /* fixed height so the office doesn't jump as people come and go */
13
+ #roster li { padding: 2px 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
14
+ #roster .dot { display: inline-block; width: 8px; height: 8px; margin-right: 6px; outline: 1px solid #6c7086; }
15
+ #roster .st { color: #a6adc8; }
16
+ #card { position: absolute; min-width: 180px; max-width: 280px; padding: 10px 12px; background: #11111b; border: 1px solid #45475a; border-radius: 6px; box-shadow: 0 4px 16px #0008; font-size: 12px; line-height: 1.6; }
17
+ #card[hidden] { display: none; }
18
+ #card strong { display: block; margin-bottom: 4px; font-size: 13px; color: #f9e2af; }
19
+ #card .k { display: inline-block; width: 64px; color: #a6adc8; }
20
+ #card-close { position: absolute; top: 4px; right: 6px; border: 0; background: none; color: #a6adc8; font-size: 16px; cursor: pointer; }
21
+ #card-close:hover, #card-close:focus-visible { color: #cdd6f4; }
22
+ #mute, #theme { position: absolute; top: 8px; right: 8px; padding: 2px 6px; border: 1px solid #45475a; border-radius: 4px; background: #11111b; color: #cdd6f4; font: 13px "Malgun Gothic", sans-serif; cursor: pointer; }
23
+ #theme { right: 52px; }
24
+ #mute:hover, #mute:focus-visible, #theme:hover, #theme:focus-visible { border-color: #a6adc8; }
25
+ </style>
26
+ </head>
27
+ <body>
28
+ <canvas id="office" aria-label="에이전트 사무실"></canvas>
29
+ <ul id="roster" aria-live="polite"></ul>
30
+ <button id="mute" aria-label="알림 소리 끄기" aria-pressed="false" title="알림 소리 켜기/끄기">🔔</button>
31
+ <button id="theme" title="사무실 테마 바꾸기">주간</button>
32
+ <div id="card" role="dialog" aria-label="캐릭터 정보" hidden>
33
+ <button id="card-close" aria-label="닫기">×</button>
34
+ <div id="card-body"></div>
35
+ </div>
36
+ <script src="office.js"></script>
37
+ <script src="app.js"></script>
38
+ </body>
39
+ </html>
@@ -0,0 +1,401 @@
1
+ // Office state from Claude Code hook events, plus the pixel drawing.
2
+ // Everyone sits at a fixed desk asleep; a subagent starting wakes a staff member, finishing puts them back to sleep
3
+ // and sends a report flying to the boss. reduce() and hit() are plain logic checked by office.test.js; step() draws.
4
+ // The art (rooms, people, bubbles, screens) comes from the pixel-art design via tools/import-design.js.
5
+ (function () {
6
+ const W = 192, H = 144; // logical pixels, scaled up by an integer factor so pixels stay crisp
7
+ // The design's layout: a desk is its partition's top-left; desk 0 is the boss's, 1..8 are staff desks.
8
+ const DESKS = [{ x: 73, y: 37, w: 46 }, ...[77, 117].flatMap(y => [7, 53, 99, 145].map(x => ({ x, y, w: 34 })))];
9
+ const SPOTS = [[134, 28], [40, 28]]; // where temps stand when every desk is taken
10
+ const PILE = { x: 108, y: 42 }; // the boss's in-tray
11
+
12
+ const TOOL_STATUS = {
13
+ Edit: 'typing', Write: 'typing', MultiEdit: 'typing', NotebookEdit: 'typing',
14
+ Read: 'reading', Grep: 'reading', Glob: 'reading', WebFetch: 'reading', WebSearch: 'reading',
15
+ Bash: 'running', PowerShell: 'running', Agent: 'delegating', Task: 'delegating',
16
+ SubagentHandback: 'typing', // a subagent writing up its report for the main agent
17
+ };
18
+ const STATUS_KO = {
19
+ sleeping: '꿀잠 중', thinking: '생각 중', typing: '코드 작성', reading: '자료 조사', running: '명령 실행',
20
+ working: '작업 중', delegating: '업무 지시', waiting: '승인 대기',
21
+ };
22
+ const TEST_CMD = /\b(npm|pnpm|yarn|bun)\b[^|&;]*\btest\b|\b(pytest|jest|vitest|mocha)\b|\b(cargo|go|dotnet|mvn|gradle|deno)\s+test\b/;
23
+ const COMMIT_CMD = /\bgit\s+commit\b/;
24
+ // clothing colours from the design (the roster's dots): the boss per model, then staff desks 1..8, then temps
25
+ const OUTFITS = { sonnet: '#d97757', opus: '#3a3d52', haiku: '#7cc47a', fable: '#7c4dcf' };
26
+ const SHIRTS = ['#e8ecf4', '#f0c9c4', '#5b6078', '#8aad6a', '#2f3e5c', '#d9a441', '#7a5c46', '#a3382f'];
27
+ const TEMP_SHIRT = '#34548a';
28
+ const PAPER_MS = 1200;
29
+ const EFFECT_MS = { paper: PAPER_MS, confetti: 2500, clap: 1500, sparkle: 1000 };
30
+ const CONFETTI = ['#f38ba8', '#f9e2af', '#a6e3a1', '#89b4fa', '#cba6f7', '#fab387'];
31
+ const INK = '#22222c', PAPER = '#fbfbf8', HOT = '#f9e2af', RED = '#e64553'; // the design's bubble colours
32
+
33
+ function newChar(id, kind, desk, n) {
34
+ return {
35
+ id, kind, desk, n, label: kind === 'boss' ? 'Claude' : '', task: '', status: 'sleeping', tool: null,
36
+ busy: false, jobs: 0, history: [], since: 0, wokeAt: 0, petAt: 0,
37
+ say: null, oopsAt: 0, failStreak: 0, lastReport: '', handback: '', model: null,
38
+ color: kind === 'boss' ? OUTFITS.sonnet : kind === 'temp' ? TEMP_SHIRT : SHIRTS[(desk - 1) % SHIRTS.length],
39
+ };
40
+ }
41
+
42
+ function createState() {
43
+ const chars = { boss: newChar('boss', 'boss', 0, 0) };
44
+ for (let i = 1; i < DESKS.length; i++) chars['desk' + i] = newChar('desk' + i, 'staff', i, i);
45
+ return {
46
+ chars, who: {}, bossSession: null, pendingTasks: [], knownTasks: {}, doneTools: new Set(), gone: new Map(),
47
+ seq: DESKS.length, temps: 0, lights: null, cleaning: 0, effects: [], reports: 0,
48
+ };
49
+ }
50
+
51
+ // A report (SubagentHandback) can arrive after its SubagentStop: file it with whoever wrote it.
52
+ function lateReport(s, charId, msg) {
53
+ const c = s.chars[charId];
54
+ if (msg && c && c.lastReport === '완료') c.lastReport = firstLine(msg);
55
+ return s;
56
+ }
57
+
58
+ // Hooks run async, so a fast tool's PostToolUse can arrive before its PreToolUse: remember finished tools.
59
+ function markDone(s, id) {
60
+ if (!id) return;
61
+ s.doneTools.add(id);
62
+ if (s.doneTools.size > 200) s.doneTools.delete(s.doneTools.values().next().value);
63
+ }
64
+
65
+ // A background Agent call's result names the subagent it launched, so its task is exact whatever order hooks arrive in.
66
+ function assignTask(s, agentId, desc) {
67
+ const sub = s.who[agentId] && s.chars[s.who[agentId]], i = s.pendingTasks.indexOf(desc);
68
+ if (!sub) { s.knownTasks[agentId] = desc; return; }
69
+ sub.task = desc;
70
+ if (i >= 0) s.pendingTasks.splice(i, 1);
71
+ }
72
+
73
+ function takeTask(s, agentId) {
74
+ if (!(agentId in s.knownTasks)) return s.pendingTasks.shift() || ''; // best guess: Agent calls in order
75
+ const desc = s.knownTasks[agentId], i = s.pendingTasks.indexOf(desc);
76
+ delete s.knownTasks[agentId];
77
+ if (i >= 0) s.pendingTasks.splice(i, 1);
78
+ return desc;
79
+ }
80
+
81
+ function setModel(s, name) {
82
+ const m = Object.keys(OUTFITS).find(k => String(name || '').toLowerCase().includes(k));
83
+ if (m) Object.assign(s.chars.boss, { model: m, color: OUTFITS[m] });
84
+ }
85
+
86
+ // First meaningful line of a subagent's final message (headings skipped, markdown stripped), for the card.
87
+ function firstLine(msg) {
88
+ const lines = String(msg || '').split('\n').map(l => l.trim()).filter(Boolean);
89
+ const pick = lines.find(l => !l.startsWith('#')) || lines[0] || '';
90
+ // strip emphasis and line markers only: a lone * is content (*.md)
91
+ const line = pick.replace(/\*\*|__|`/g, '').replace(/^(#+|>|[-*])\s+/, '').replace(/\s+/g, ' ').trim() || '완료';
92
+ return line.length > 40 ? line.slice(0, 39) + '…' : line;
93
+ }
94
+
95
+ // The character an event belongs to. A new subagent or teammate wakes up a sleeping staff member.
96
+ function charFor(s, e, now) {
97
+ const id = e.agent_id || e.session_id;
98
+ if (!id) return null;
99
+ if (s.who[id]) return s.chars[s.who[id]];
100
+ if (e.hook_event_name === 'SubagentStop') return null;
101
+ if (e.agent_id && s.gone.has(e.agent_id)) return null; // late event from a finished subagent: don't wake anyone
102
+ // the first session is the boss; /clear, resume and compact give the boss a new session id
103
+ if (!e.agent_id && (!s.bossSession || ['clear', 'resume', 'compact'].includes(e.source))) {
104
+ s.bossSession = id;
105
+ return s.chars[(s.who[id] = 'boss')];
106
+ }
107
+ const label = e.agent_type || 'teammate';
108
+ const free = Object.values(s.chars).filter(c => c.kind === 'staff' && !c.busy);
109
+ let c = free.find(f => f.label === label) || free[0]; // the same kind of agent gets its old desk back
110
+ if (!c) { const n = ++s.seq; c = s.chars['temp' + n] = newChar('temp' + n, 'temp', -1, s.temps++); } // office full: a temp stands in
111
+ Object.assign(c, { busy: true, label, task: '', tool: null, history: [], handback: '', since: now });
112
+ c.jobs++;
113
+ s.who[id] = c.id;
114
+ return c;
115
+ }
116
+
117
+ function wake(c, status, now) {
118
+ if (c.status === 'sleeping') { c.wokeAt = now; if (c.kind === 'boss') c.since = now; }
119
+ c.status = status;
120
+ }
121
+
122
+ // A speech bubble: pixel-font text (ASCII only: the font has no Hangul) or an icon.
123
+ function say(c, text, now, { ms = 2000, delay = 0, icon = null, ink = INK } = {}) {
124
+ c.say = { text, icon, ink, from: now + delay, until: now + delay + ms };
125
+ }
126
+
127
+ function reduce(s, e, now = Date.now()) {
128
+ const handback = e.tool_name === 'SubagentHandback' ? e.tool_input?.message : undefined;
129
+ if (handback && s.gone.has(e.agent_id)) return lateReport(s, s.gone.get(e.agent_id), handback);
130
+ const c = charFor(s, e, now);
131
+ if (!c) return s;
132
+ if (handback) c.handback = handback; // interactive claude: subagents report through this tool, not their last message
133
+ const ev = e.hook_event_name, cmd = e.tool_name === 'Bash' ? String(e.tool_input?.command || '') : '';
134
+ if (c.kind === 'boss' && e.model) setModel(s, e.model); // the server reads it from the transcript
135
+ if (ev === 'SessionStart' || ev === 'UserPromptSubmit' || ev === 'PreToolUse') s.lights = null; // power is back
136
+ switch (ev) {
137
+ case 'SessionStart': if (c.kind !== 'boss') wake(c, 'thinking', now); break;
138
+ case 'SubagentStart': c.task = takeTask(s, e.agent_id); wake(c, 'thinking', now); break;
139
+ case 'UserPromptSubmit': wake(c, 'thinking', now); break;
140
+ case 'PreToolUse':
141
+ c.history = [...c.history, e.tool_name].slice(-5);
142
+ if (s.doneTools.has(e.tool_use_id)) break; // arrived after its PostToolUse: the tool is already done
143
+ if (TOOL_STATUS[e.tool_name] === 'delegating') s.pendingTasks.push(e.tool_input?.description || '');
144
+ wake(c, TOOL_STATUS[e.tool_name] || 'working', now);
145
+ c.tool = e.tool_name === 'SubagentHandback' ? '보고서' : e.tool_name;
146
+ break;
147
+ case 'PermissionRequest': wake(c, 'waiting', now); break;
148
+ case 'PostToolUse':
149
+ markDone(s, e.tool_use_id);
150
+ if (TOOL_STATUS[e.tool_name] === 'delegating' && e.tool_response?.agentId) assignTask(s, e.tool_response.agentId, e.tool_input?.description || '');
151
+ if (c.status !== 'sleeping') c.status = 'thinking';
152
+ c.tool = null;
153
+ c.failStreak = 0;
154
+ if (TEST_CMD.test(cmd)) s.effects.push({ type: 'clap', at: now });
155
+ if (COMMIT_CMD.test(cmd)) { s.effects.push({ type: 'confetti', at: now }); say(c, 'COMMIT!', now); }
156
+ break;
157
+ case 'PostToolUseFailure':
158
+ markDone(s, e.tool_use_id);
159
+ if (c.status !== 'sleeping') c.status = 'thinking';
160
+ c.tool = null;
161
+ if (e.is_interrupt) break; // the user pressed Esc: not the agent's mistake
162
+ c.oopsAt = now;
163
+ c.failStreak++;
164
+ if (TEST_CMD.test(cmd)) say(c, 'FAIL', now, { ink: RED }); else say(c, 'OOPS', now);
165
+ break;
166
+ case 'Notification':
167
+ if (e.notification_type === 'permission_prompt' || /permission/i.test(e.message || '')) wake(c, 'waiting', now);
168
+ else c.status = 'sleeping';
169
+ break;
170
+ case 'Stop': c.status = 'sleeping'; c.tool = null; break;
171
+ case 'StopFailure': s.lights = { reason: e.error || 'unknown' }; c.status = 'sleeping'; c.tool = null; break;
172
+ case 'PreCompact': s.cleaning = now; say(s.chars.boss, 'TIDY', now, { ms: 120000 }); break;
173
+ case 'PostCompact':
174
+ s.cleaning = 0;
175
+ s.reports = 0; // the report pile gets filed away
176
+ s.chars.boss.say = null;
177
+ s.effects.push({ type: 'sparkle', at: now });
178
+ break;
179
+ case 'PostModelSwitch': setModel(s, e.to_model); break;
180
+ case 'SubagentStop': {
181
+ const from = seat(c), report = firstLine(e.last_assistant_message || c.handback);
182
+ Object.assign(c, { status: 'sleeping', tool: null, busy: false, lastReport: report });
183
+ delete s.who[e.agent_id];
184
+ s.gone.set(e.agent_id, c.id);
185
+ if (s.gone.size > 200) s.gone.delete(s.gone.keys().next().value);
186
+ if (c.kind === 'temp') delete s.chars[c.id];
187
+ s.effects.push({ type: 'paper', at: now, x: from.x + 6, y: from.y + 8 });
188
+ s.reports++;
189
+ say(s.chars.boss, '', now, { ms: 3000, delay: PAPER_MS, icon: 'doc' }); // boss reads it once the paper lands
190
+ break;
191
+ }
192
+ }
193
+ return s;
194
+ }
195
+
196
+ // Top-left of a person's sprite: 16x28 seated cells sit at (desk.x+17, desk.y-15); temps stand.
197
+ function seat(c) {
198
+ if (c.desk < 0) { const [x, y] = SPOTS[c.n % SPOTS.length]; return { x: x - 6 * Math.floor(c.n / SPOTS.length), y, standing: true }; }
199
+ const d = DESKS[c.desk];
200
+ return { x: d.x + 17, y: d.y - 15 };
201
+ }
202
+
203
+ let view = { S: 1, ox: 0, oy: 0, dpr: 1 }; // last frame's scale/offset, to map clicks back to office pixels
204
+
205
+ // Character under a point given in CSS pixels on the canvas, or null. Clicking a desk counts as its owner.
206
+ function hit(s, cx, cy) {
207
+ const x = (cx * view.dpr - view.ox) / view.S, y = (cy * view.dpr - view.oy) / view.S;
208
+ return Object.values(s.chars).find(c => {
209
+ const p = seat(c), d = DESKS[c.desk];
210
+ const r = d ? { x: d.x, y: d.y - 9, w: d.w, h: 28 } : { x: p.x + 4, y: p.y, w: 16, h: 38 };
211
+ return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;
212
+ }) || null;
213
+ }
214
+
215
+ // ---- art ----
216
+
217
+ let art = null, imgs = null, theme = 'day';
218
+ function useArt(a, images) { art = a; imgs = images; }
219
+ function setTheme(name) { if (art?.themes[name]) theme = name; return theme; }
220
+ const themes = () => (art ? Object.keys(art.themes) : []);
221
+
222
+ // 3x5 pixel font. Letters the design spelled on its nameplates come from art.json; the rest are drawn to match.
223
+ const FONT = {
224
+ A: '010101111101101', B: '110101110101110', C: '011100100100011', D: '110101101101110', E: '111100110100111',
225
+ F: '111100110100100', G: '011100101101011', H: '101101111101101', I: '111010010010111', J: '001001001101010',
226
+ K: '101101110101101', L: '100100100100111', M: '101111111101101', N: '110101101101101', O: '010101101101010',
227
+ P: '110101110100100', Q: '010101101110011', R: '110101110101101', S: '011100010001110', T: '111010010010010',
228
+ U: '101101101101111', V: '101101101101010', W: '101101111111101', X: '101101010101101', Y: '101101010010010',
229
+ Z: '111001010100111', 0: '111101101101111', 1: '010110010010111', 2: '110001010100111', 3: '110001010001110',
230
+ 4: '101101111001001', 5: '111100110001110', 6: '011100110101010', 7: '111001010010010', 8: '010101010101010',
231
+ 9: '010101011001110', '!': '010010010000010', '?': '110001010000010', '.': '000000000000010', '-': '000000111000000',
232
+ ':': '000010000010000', '/': '001001010100100', ' ': '000000000000000',
233
+ };
234
+ const glyph = ch => (art?.glyphs[ch] ? art.glyphs[ch].join('') : FONT[ch] || FONT['?']);
235
+ const textWidth = text => Math.max(0, text.length * 4 - 1);
236
+ function text(R, str, x, y, color) {
237
+ [...str].forEach((ch, i) => { const g = glyph(ch); for (let k = 0; k < 15; k++) if (g[k] === '1') R(x + i * 4 + (k % 3), y + ((k / 3) | 0), 1, 1, color); });
238
+ }
239
+ // what fits a 30px nameplate: the agent type's first word, letters and digits, 7 at most
240
+ const plateText = label => (label === 'teammate' ? 'TEAM' : String(label).split(/[-_\s]/)[0].toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 7));
241
+
242
+ // ---- drawing ----
243
+
244
+ const POSE = { idle: 0, typeA: 1, typeB: 2, read: 3, raise: 4, sleep: 5 };
245
+ const SCREEN_FOR = { typing: 'edit', reading: 'read', running: 'run', delegating: 'delegate', waiting: 'ask', thinking: 'think', working: 'think' };
246
+ const ICON_FOR = { typing: 'edit', reading: 'read', running: 'run', delegating: 'delegate', waiting: 'ask', thinking: 'think', working: 'think' };
247
+ const plus = (R, x, y, color) => { R(x + 1, y, 1, 3, color); R(x, y + 1, 3, 1, color); };
248
+
249
+ function poseOf(c, t) {
250
+ switch (c.status) {
251
+ case 'sleeping': return POSE.sleep;
252
+ case 'typing': case 'running': return Math.floor(t / 220) % 2 ? POSE.typeB : POSE.typeA;
253
+ case 'reading': return POSE.read;
254
+ case 'waiting': return POSE.raise;
255
+ default: return POSE.idle;
256
+ }
257
+ }
258
+
259
+ function rowOf(c) {
260
+ const rows = art.people.rows;
261
+ if (c.kind === 'boss') return rows[c.model] ?? rows.boss;
262
+ return rows.staff[(c.desk - 1) % rows.staff.length];
263
+ }
264
+
265
+ // A bubble the design's way: rounded 1px outline, white (yellow when it needs you), a 2px tail under the middle.
266
+ function textBubble(R, str, cx, bottom, { ink = INK, hot = false } = {}) {
267
+ const w = textWidth(str) + 4, h = 10, x = Math.round(cx - Math.floor(w / 2)), y = bottom - h + 1;
268
+ R(x + 1, y, w - 2, 1, INK); R(x + 1, y + 8, w - 2, 1, INK); R(x, y + 1, 1, 7, INK); R(x + w - 1, y + 1, 1, 7, INK);
269
+ R(x + 1, y + 1, w - 2, 7, hot ? HOT : PAPER);
270
+ R(x + Math.floor(w / 2) - 1, y + 9, 2, 1, INK);
271
+ text(R, str, x + 2, y + 2, ink);
272
+ }
273
+
274
+ function iconBubble(ctx, R, name, cx, bottom) {
275
+ if (name === 'doc') { // a report: a little page with lines
276
+ textBubble(R, ' ', cx, bottom);
277
+ const x = Math.round(cx) - 2, y = bottom - 7;
278
+ R(x, y, 5, 5, '#4c4f69'); R(x + 1, y + 1, 3, 3, PAPER); R(x + 1, y + 2, 3, 1, '#9ca0b0');
279
+ return;
280
+ }
281
+ const b = art.bubbles.items[name];
282
+ if (b) ctx.drawImage(imgs.bubbles, b.x, b.y, b.w, b.h, Math.round(cx - Math.floor(b.w / 2)), bottom - b.h + 1, b.w, b.h);
283
+ }
284
+
285
+ function zzz(ctx, R, p, t, n) {
286
+ const Z = ['1111', '0010', '0100', '1111'], z = ['111', '010', '111'];
287
+ for (const [k, g, dx, dy] of [[0, Z, 17, 4], [1, z, 13, 9]]) {
288
+ const ph = (t / 2400 + k * 0.5 + n * 0.13) % 1; // each drifts up and fades
289
+ ctx.globalAlpha = 1 - ph;
290
+ const x = p.x + dx + Math.round(ph * 3), y = p.y + dy - Math.round(ph * 8);
291
+ g.forEach((row, j) => [...row].forEach((v, i) => { if (v === '1') R(x + i, y + j, 1, 1, i === row.length - 1 && j === 0 ? '#f9f8f3' : '#f3ede1'); }));
292
+ }
293
+ ctx.globalAlpha = 1;
294
+ }
295
+
296
+ function heart(R, x, y) {
297
+ R(x, y, 2, 1, RED); R(x + 3, y, 2, 1, RED); R(x, y + 1, 5, 1, RED); R(x + 1, y + 2, 3, 1, RED); R(x + 2, y + 3, 1, 1, RED);
298
+ }
299
+
300
+ function drawOverlay(ctx, R, c, t, now, clap) {
301
+ const p = seat(c), cx = p.x + (p.standing ? 12 : 8), bottom = p.y + (p.standing ? 2 : 4);
302
+ if (now - c.petAt < 1000) heart(R, cx + 5, bottom - 2 - Math.floor((now - c.petAt) / 150));
303
+ if (now - c.oopsAt < 1500) { // sweat drops
304
+ const off = Math.floor((now - c.oopsAt) / 120) % 4;
305
+ R(cx - 7, bottom + 5 + off, 1, 2, '#89dceb');
306
+ R(cx + 6, bottom + 4 + off, 1, 2, '#89dceb');
307
+ }
308
+ if (clap) return textBubble(R, 'YAY!', cx, bottom);
309
+ if (c.say && now >= c.say.from && now < c.say.until) {
310
+ return c.say.icon ? iconBubble(ctx, R, c.say.icon, cx, bottom) : textBubble(R, c.say.text, cx, bottom, { ink: c.say.ink });
311
+ }
312
+ if (c.status === 'sleeping') return p.standing ? null : zzz(ctx, R, p, t, c.n);
313
+ iconBubble(ctx, R, now - c.wokeAt < 900 ? 'wake' : ICON_FOR[c.status], cx, bottom);
314
+ }
315
+
316
+ function drawEffect(R, f, age, t) {
317
+ if (f.type === 'paper') { // a report flying in an arc to the boss's in-tray
318
+ const p = Math.min(1, age / PAPER_MS);
319
+ const x = Math.round(f.x + (PILE.x - f.x) * p), y = Math.round(f.y + (PILE.y - 6 - f.y) * p - Math.sin(Math.PI * p) * 18);
320
+ R(x, y, 7, 8, '#4c4f69'); R(x + 1, y + 1, 5, 6, PAPER); R(x + 2, y + 2, 3, 1, '#9ca0b0'); R(x + 2, y + 4, 3, 1, '#9ca0b0');
321
+ } else if (f.type === 'confetti') {
322
+ for (let i = 0; i < 48; i++) {
323
+ const x = (i * 37 + Math.sin(age / 300 + i) * 4 + W) % W, y = -4 + (age / 1000) * (50 + ((i * 13) % 50)) - (i % 7) * 6;
324
+ if (y > -2 && y < H) R(Math.round(x), Math.round(y), 1, 2, CONFETTI[i % CONFETTI.length]);
325
+ }
326
+ } else if (f.type === 'sparkle') {
327
+ const d = DESKS[0];
328
+ for (let k = 0; k < 5; k++) if ((Math.floor(t / 120) + k) % 2) plus(R, d.x + 4 + k * 9, d.y - 4 + (k % 2) * 8, HOT);
329
+ }
330
+ }
331
+
332
+ function step(canvas, s, t) {
333
+ const now = Date.now(), dpr = window.devicePixelRatio || 1;
334
+ const cw = Math.round(canvas.clientWidth * dpr), ch = Math.round(canvas.clientHeight * dpr);
335
+ if (canvas.width !== cw || canvas.height !== ch) { canvas.width = cw; canvas.height = ch; }
336
+ const S = Math.max(1, Math.floor(Math.min(cw / W, ch / H)));
337
+ view = { S, ox: Math.floor((cw - W * S) / 2), oy: Math.floor((ch - H * S) / 2), dpr };
338
+ const ctx = canvas.getContext('2d');
339
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
340
+ ctx.fillStyle = '#181825';
341
+ ctx.fillRect(0, 0, cw, ch);
342
+ if (!art || !imgs) return; // art still loading
343
+ ctx.setTransform(S, 0, 0, S, view.ox, view.oy);
344
+ ctx.imageSmoothingEnabled = false;
345
+ const R = (x, y, w, h, color) => { ctx.fillStyle = color; ctx.fillRect(x, y, w, h); };
346
+ s.effects = s.effects.filter(f => now - f.at < EFFECT_MS[f.type]);
347
+ const chars = Object.values(s.chars), clap = s.effects.some(f => f.type === 'clap');
348
+ const look = imgs.themes[theme], [cellW, cellH] = art.cell;
349
+
350
+ ctx.drawImage(look.room, 0, 0);
351
+
352
+ // people at their desks (in front of the partition, above the desk), temps standing in the open
353
+ for (const c of chars) {
354
+ const p = seat(c);
355
+ const hop = now - c.wokeAt < 300 || now - c.petAt < 300 ? -2 : clap && Math.floor(t / 150) % 2 ? -1 : 0;
356
+ if (p.standing) ctx.drawImage(look.standing, p.x, p.y + hop);
357
+ else ctx.drawImage(look.people, poseOf(c, t) * cellW, rowOf(c) * cellH, cellW, cellH, p.x, p.y + hop, cellW, cellH);
358
+ }
359
+
360
+ // screens and nameplates
361
+ const blink = Math.floor(t / 400) % 2;
362
+ for (const c of chars) {
363
+ const d = DESKS[c.desk];
364
+ if (!d) continue;
365
+ const scr = c.status === 'sleeping' ? -1 : art.screens.items.indexOf(SCREEN_FOR[c.status]); // asleep: the room's screen is off
366
+ if (scr >= 0 && !(c.status === 'waiting' && blink)) ctx.drawImage(imgs.screens, scr * art.screens.w, 0, art.screens.w, art.screens.h, d.x + 3, d.y - 1, art.screens.w, art.screens.h);
367
+ if (c.kind === 'staff' && c.label) { const str = plateText(c.label); text(R, str, d.x + 2 + Math.floor((30 - textWidth(str)) / 2), d.y + 13, art.themes[theme].plateInk); }
368
+ }
369
+
370
+ // report pile in the boss's in-tray (papers still in the air don't count yet)
371
+ const pile = Math.min(6, s.reports - s.effects.filter(f => f.type === 'paper').length);
372
+ for (let k = 0; k < pile; k++) R(PILE.x, PILE.y - k, 7, 1, k % 2 ? PAPER : '#bcc0cc');
373
+ for (const c of chars) { // a monitor smoking after three failures in a row
374
+ const d = DESKS[c.desk];
375
+ if (!d || c.failStreak < 3) continue;
376
+ for (let k = 0; k < 3; k++) { const ph = (t / 1500 + k / 3) % 1; ctx.globalAlpha = 1 - ph; R(Math.round(d.x + 6 + Math.sin(ph * 6 + k) * 2), Math.round(d.y - 4 - ph * 12), 3, 3, '#9399b2'); }
377
+ ctx.globalAlpha = 1;
378
+ }
379
+ if (s.cleaning && now - s.cleaning < 120000) { // a robot vacuum doing laps down the aisle + sparkles over desks
380
+ const rx = Math.floor(((now - s.cleaning) / 25) % (W + 16)) - 8;
381
+ R(rx, 99, 9, 4, '#585b70'); R(rx + 1, 98, 7, 1, '#9399b2'); R(rx + 4, 99, 1, 1, blink ? '#f38ba8' : '#a6e3a1');
382
+ DESKS.forEach((d, i) => { if ((Math.floor(t / 250) + i) % 3 === 0) plus(R, d.x + 20 + ((i * 7) % 10), d.y + 8, HOT); });
383
+ }
384
+ for (const f of s.effects) drawEffect(R, f, now - f.at, t);
385
+ for (const c of chars) drawOverlay(ctx, R, c, t, now, clap);
386
+
387
+ if (s.lights) { // blackout: lights off + a sign hanging from the ceiling
388
+ ctx.fillStyle = 'rgba(17,17,27,0.7)';
389
+ ctx.fillRect(0, 0, W, H);
390
+ const str = { rate_limit: 'LIMIT', overloaded: 'OVERLOAD' }[s.lights.reason] || 'ERROR';
391
+ const w = textWidth(str) + 8, x = Math.round(W / 2 - w / 2);
392
+ R(x + 2, 0, 1, 9, '#6c6f85'); R(x + w - 3, 0, 1, 9, '#6c6f85');
393
+ R(x - 1, 8, w + 2, 11, INK); R(x, 9, w, 9, HOT);
394
+ text(R, str, x + 4, 11, INK);
395
+ }
396
+ }
397
+
398
+ const Office = { createState, reduce, step, hit, setModel, useArt, setTheme, themes, plateText, STATUS_KO };
399
+ if (typeof module === 'object') module.exports = Office;
400
+ else window.Office = Office;
401
+ })();