@double_geste/agent-standup 1.45.0 → 1.46.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.
@@ -3,6 +3,7 @@
3
3
  // agent-standup [serve] [--port 4747] [--open] start the local server and (optionally) open the page
4
4
  // agent-standup status [--here] [--json] [--titles] counts of working / needs you / your turn
5
5
  // agent-standup statusline same, one short line; reads Claude Code's statusLine JSON on stdin
6
+ // agent-standup report [--day D] [--here] [--json] [--titles] what each session did that day: time worked, time it waited for you, calls, files (the plugin's whiteboard and timesheet skills read it)
6
7
  // Everything reads the local session files Claude Code already writes. Nothing is sent anywhere unless the call is in French, Spanish or Brazilian Portuguese or you turn on the jokes (they use your own Claude login or ANTHROPIC_API_KEY).
7
8
  const path = require('path'), { spawn } = require('child_process');
8
9
  const pkg = require('../package.json');
@@ -11,7 +12,7 @@ for (let i = 0; i < argv.length; i++) {
11
12
  const a = argv[i], val = () => argv[++i];
12
13
  if (a === '--port') flags.port = val(); else if (a === '--projects') flags.projects = val(); else if (a === '--codex') flags.codex = val(); else if (a === '--vibe') flags.vibe = val(); else if (a === '--cowork') flags.cowork = val(); else if (a === '--characters') flags.characters = val(); else if (a === '--config-dir') flags.config = val();
13
14
  else if (a === '--reply') flags.reply = /^(0|1|on|off|yes|no|true|false)$/i.test(argv[i + 1] || '') ? val() : 'on'; // alone or followed by on / off
14
- else if (a === '--from') flags.from = val(); else if (a === '--open') flags.open = true; else if (a === '--here') flags.here = true; else if (a === '--json') flags.json = true; else if (a === '--titles') flags.titles = true; else if (a === '--config') flags.config = val();
15
+ else if (a === '--from') flags.from = val(); else if (a === '--open') flags.open = true; else if (a === '--here') flags.here = true; else if (a === '--json') flags.json = true; else if (a === '--titles') flags.titles = true; else if (a === '--config') flags.config = val(); else if (a === '--day') flags.day = val();
15
16
  else if (a === '-h' || a === '--help') flags.help = true; else if (a === '-v' || a === '--version') flags.version = true; else rest.push(a);
16
17
  }
17
18
  const cmd = rest[0] || 'serve';
@@ -21,6 +22,7 @@ Usage
21
22
  agent-standup [serve] [--port 4747] [--open] start the local server (http://localhost:4747)
22
23
  agent-standup status [--here] [--json] what is going on right now (--here: only the current folder)
23
24
  agent-standup statusline one short line for a status bar (reads Claude Code's JSON on stdin)
25
+ agent-standup report [--day D] [--json] what each session did that day: time worked, waits for you, calls, files
24
26
 
25
27
  Options
26
28
  --port N port of the local server (default 4747)
@@ -37,8 +39,9 @@ Options
37
39
  --characters DIR folder with your own pixel-art characters (default ~/.agent-standup/characters)
38
40
  --from plugin how the Claude Code plugin starts it (its usage, if you agree to share it, is counted apart); also AGENT_STANDUP_FROM=plugin,
39
41
  which older versions ignore instead of refusing
40
- --here status: only sessions of the current folder (matched on its real path, as Claude Code names it)
41
- --json status: machine-readable output
42
+ --here status, report: only sessions of the current folder (matched on its real path, as Claude Code names it)
43
+ --json status, report: machine-readable output
44
+ --day D report: the day to tell, YYYY-MM-DD, today (the default) or yesterday, in local time
42
45
  --titles include session titles, questions, commands and errors
43
46
  `;
44
47
  if (flags.help || cmd === 'help') { process.stdout.write(HELP); process.exit(0); }
@@ -71,10 +74,60 @@ const line = (s, short) => {
71
74
  if (!s.needsYou && !s.working && s.free) p.push(short ? '✓' : '✓ your turn'); return p.join(short ? ' ' : ' · ') || (short ? '' : 'idle');
72
75
  };
73
76
 
77
+ // What each session did in one day, from the timelines the call is drawn from: what the plugin's whiteboard (the standup, drawn) and timesheet (a row a session) skills fill their artifact with.
78
+ // Time is told from the gaps between a session's events, all its agents together (sub-agents working side by side are not counted twice): a gap of up to 10 minutes inside a turn is work; the gap
79
+ // before your next message, and a longer one inside a turn (most often a question or a permission menu, sometimes a long command), is time it waited for you, an hour at most each (a session left for the night did not wait all night).
80
+ const GAP_WORK = 10 * 60e3, GAP_WAIT = 60 * 60e3, pad = (n) => String(n).padStart(2, '0');
81
+ const ymd = (t) => { const d = new Date(t); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }, hm = (t) => { const d = new Date(t); return `${pad(d.getHours())}:${pad(d.getMinutes())}`; };
82
+ const dur = (min) => (min >= 60 ? `${Math.floor(min / 60)}h${pad(min % 60)}` : `${min}m`), clipT = (t, n) => { t = String(t || '').replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1) + '…' : t; };
83
+ function dayRange(d) { // [start, end) of a local day
84
+ const t = new Date(); t.setHours(0, 0, 0, 0);
85
+ if (d === 'yesterday') t.setDate(t.getDate() - 1);
86
+ else if (d && d !== 'today') { const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(d); if (!m || +m[2] < 1 || +m[2] > 12 || +m[3] < 1 || +m[3] > 31) { console.error(`Invalid --day "${d}": use YYYY-MM-DD, today or yesterday.`); process.exit(2); } t.setFullYear(+m[1], +m[2] - 1, +m[3]); if (t.getMonth() !== +m[2] - 1) { console.error(`Invalid --day "${d}": there is no such day.`); process.exit(2); } }
87
+ const end = new Date(t); end.setDate(end.getDate() + 1); return [+t, +end];
88
+ }
89
+ const TOOLS = { codex: 'Codex', vibe: 'Mistral Vibe', cowork: 'Cowork' }, projLabel = (p) => (path.isAbsolute(String(p)) ? String(p).split(/[\\/]+/).filter(Boolean).slice(-2).join('/') : p); // a folder written whole (Codex, Vibe): its last two names, as Claude Code's projects read
90
+ const CALLS = { cmd: 'commands', edit: 'edits', write: 'edits', read: 'reads', web: 'web', browser: 'browser', artifact: 'artifacts' };
91
+ async function report(day, dir, titles) {
92
+ const [from, to] = dayRange(day);
93
+ if (server.sessionsSince) { server.sessionsSince(from); for (let i = 0; i < 600 && server.codexPending && server.codexPending(); i++) await new Promise((r) => setTimeout(r, 100)); } // Codex's compressed threads are read in the background: wait for them (a minute at most) before listing
94
+ const live = new Map(server.boardRows().map((r) => [r.proj + '/' + r.id, r])), home = require('os').homedir(), short = (f) => (f.startsWith(home + path.sep) ? '~' + f.slice(home.length) : f), rows = [];
95
+ for (const r of (server.sessionsSince ? server.sessionsSince(from) : server.sessionRows())) { // every session written since that day began, not only the most recent ones
96
+ if (r.mtime < from) continue;
97
+ if (!r.source && r.proj !== '_demo') { try { const fs = require('fs'), fd = fs.openSync(server.transcriptFile(r.proj, r.id), 'r'), b = Buffer.alloc(32768), n = fs.readSync(fd, b, 0, b.length, 0); fs.closeSync(fd); const m = /"timestamp":"([^"]{10,40})"/.exec(b.toString('utf8', 0, n)), t0 = m ? Date.parse(m[1]) : NaN; if (t0 >= to) continue; } catch {} } // a Claude Code session whose first record is after that day has nothing of it (its first record says when it began; a copied file's dates do not)
98
+ const b = live.get(r.proj + '/' + r.id);
99
+ if (dir && !(fold(r.proj) === fold(projKey(dir)) || (b && b.dir && fold(b.dir) === fold(projKey(dir))))) continue;
100
+ let tl; try { tl = server.timeline(r.proj, r.id); } catch { continue; } // a session that cannot be read costs that session only
101
+ const ev = tl.events.filter((e) => e.ts >= from && e.ts < to).sort((x, y) => x.ts - y.ts); if (!ev.length) continue;
102
+ let work = 0, wait = 0, turns = 0, asked = '', said = ''; const calls = {}, files = new Set(), subs = new Set(), arts = new Map();
103
+ ev.forEach((e, i) => {
104
+ if (e.kind === 'user') { turns++; if (!asked) asked = e.text; }
105
+ if (e.kind === 'say' && e.agent === 'main') said = e.text;
106
+ if (e.agent !== 'main' && e.agent !== 'user') subs.add(e.agent);
107
+ if (e.kind === 'tools') for (const t of e.tools) { const k = CALLS[t.d && t.d.kind] || 'other'; calls[k] = (calls[k] || 0) + 1; if (t.d && (t.d.kind === 'edit' || t.d.kind === 'write') && typeof t.d.file === 'string' && t.d.file) files.add(short(t.d.file)); }
108
+ if (e.kind === 'results') for (const it of e.items) if (it.art && it.art.url) arts.set(it.art.url, it.art.title || (arts.get(it.art.url) || ''));
109
+ if (i) { const gap = ev[i].ts - ev[i - 1].ts; if (e.kind === 'user' || gap > GAP_WORK) wait += Math.min(gap, GAP_WAIT); else work += gap; }
110
+ });
111
+ const tool = TOOLS[r.source] || r.source || (r.project === 'Cowork' ? 'Cowork' : 'Claude Code');
112
+ rows.push({ project: projLabel(String(r.project || r.proj).replace(/^(Codex|Mistral Vibe|Vibe) · /, '')), tool, id: r.id, state: b ? b.state : 'idle', start: hm(ev[0].ts), end: hm(ev[ev.length - 1].ts), t0: ev[0].ts,
113
+ workMin: Math.round(work / 60e3), waitMin: Math.round(wait / 60e3), turns, subAgents: subs.size, calls, filesChanged: files.size,
114
+ ...(titles ? { title: clipT(r.title, 120), asked: clipT(asked, 240), said: clipT(said, 400), files: [...files].slice(0, 30), artifacts: [...arts].map(([url, title]) => ({ title: clipT(title, 120), url })) } : {}) });
115
+ }
116
+ rows.sort((a, b) => a.t0 - b.t0); rows.forEach((r) => delete r.t0);
117
+ return { day: ymd(from), sessions: rows.length, workMin: rows.reduce((n, r) => n + r.workMin, 0), waitMin: rows.reduce((n, r) => n + r.waitMin, 0), rows };
118
+ }
119
+
74
120
  if (cmd === 'status') {
75
121
  const s = snapshot(flags.here ? process.cwd() : '');
76
122
  if (flags.json) console.log(JSON.stringify({ needsYou: s.needsYou, working: s.working, yourTurn: s.yourTurn, idle: s.idle, sessions: s.rows.map((r) => ({ project: r.proj, id: r.id, state: r.state, tool: r.tool, ageMs: Math.round(r.ageMs), subAgentsActive: r.subActive, subAgents: r.subTotal, ...(r.since ? { since: r.since } : {}), ...(r.ran ? { ran: r.ran } : {}), ...(r.limit ? { limit: r.limit } : {}), ...(r.auth ? { auth: 1 } : {}), ...(flags.titles ? { title: r.title, ...(r.ask ? { ask: r.ask } : {}), ...(r.menu && r.menu.about ? { about: r.menu.about } : {}), ...(r.gave ? { gave: r.gave } : {}) } : {}) })) }, null, 2)); // since: when it started to wait, ran: how long it worked before · with --titles only, what the sessions say (it can hold a path, a command or a secret): ask, the question or command that waits for you, about, what that command is for, gave, the error it stopped on
77
123
  else console.log(line(s, false));
124
+ } else if (cmd === 'report') {
125
+ report(flags.day, flags.here ? process.cwd() : '', flags.titles).then((rep) => {
126
+ const callLine = (c) => Object.entries(c).sort((x, y) => y[1] - x[1]).map(([k, n]) => `${n} ${n === 1 ? k.replace(/s$/, '') : k}`).join(' · ');
127
+ const text = flags.json ? JSON.stringify(rep, null, 2) : [`${rep.day} · ${rep.sessions} session${rep.sessions === 1 ? '' : 's'} · ${dur(rep.workMin)} worked · ${dur(rep.waitMin)} waited for you`,
128
+ ...rep.rows.map((r) => ` ${r.start}–${r.end} ${(r.tool + ' · ' + r.project).padEnd(36).slice(0, 36)} ${dur(r.workMin).padStart(5)} worked ${dur(r.waitMin).padStart(5)} waited ${callLine(r.calls)}${r.title ? '\n ' + r.title : ''}`)].join('\n');
129
+ process.stdout.write(text + '\n', () => process.exit(0)); // the timelines leave timers behind: once written, it is done
130
+ });
78
131
  } else if (cmd === 'statusline') {
79
132
  let raw = ''; const go = () => { let dir = ''; try { const j = JSON.parse(raw); dir = (j.workspace && j.workspace.current_dir) || j.cwd || ''; } catch {} console.log(line(snapshot(dir), true)); process.exit(0); };
80
133
  if (process.stdin.isTTY) go(); else { process.stdin.setEncoding('utf8'); process.stdin.on('data', (d) => (raw += d)); process.stdin.on('end', go); setTimeout(go, 800); }
package/boards.js ADDED
@@ -0,0 +1,258 @@
1
+ // Claude Whiteboards and Claude Sheets on the shared screen. Neither sends a page when it is made: a board keeps its content in its own store (the ArtifactData tool's writes) and a Sheet
2
+ // keeps its cells on Anthropic's server (the Claude Docs connector's applyEdits). The call cannot fetch either, and does not try: like the pages of other artifacts, each is put together again
3
+ // from what the session file holds, the writes of that session up to the one asked for, in order, those that were refused left out. The result is a still picture (no script runs in it),
4
+ // close to what the person saw on claude.ai at that moment: what someone else drew on the same board, or typed in the same Sheet, is not in this session's file and so not in the picture.
5
+ 'use strict';
6
+ const fs = require('fs');
7
+
8
+ const LIVE_MAX = 32 * 1024 * 1024; // a session file read further than this for one picture is not read whole: the picture is drawn from what was read
9
+ const memo = new Map();
10
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
11
+ const blocksOf = (r) => { const c = r && r.message && r.message.content; return Array.isArray(c) ? c : []; };
12
+ const textOf = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => (x && typeof x.text === 'string' ? x.text : '')).join('\n') : '');
13
+ const BOARD_WRITES = new Set(['set', 'update', 'delete', 'str_replace', 'batch']);
14
+ const boardDoc = (w) => !!w && (String(w.collection || '') === 'elements' || (String(w.collection || '') === 'board' && /^(meta|claim-[a-z0-9]{1,40})$/.test(String(w.doc_id || ''))));
15
+ const onBoard = (i) => (i.action === 'batch' ? Array.isArray(i.writes) && i.writes.some(boardDoc) : boardDoc(i)); // a Whiteboard keeps its content in board/meta and elements/<id>: another page's own database (a tracker, a sign-up sheet) is not a board
16
+ const docsTool = (name) => { const m = /^mcp__(.+?)__(update|read)$/.exec(name || ''); return m && /(^|_)Claude_Docs$/.test(m[1]) ? m[2] : ''; };
17
+
18
+ // What a call does to a board or a Sheet, or null: { key, kind: 'board' | 'sheet', op: 'write' | 'read' }. key: the board's address, or the Sheet's project in Claude Docs.
19
+ function liveCall(name, i) {
20
+ if (!i || typeof i !== 'object') return null;
21
+ if (name === 'ArtifactData' && BOARD_WRITES.has(i.action) && typeof i.url === 'string' && onBoard(i)) return { key: i.url, kind: 'board', op: 'write' };
22
+ const d = docsTool(name), proj = i.container && typeof i.container.id === 'string' ? i.container.id : '', p = i.payload && typeof i.payload === 'object' ? i.payload : null;
23
+ if (!d || !proj || i.engine !== 'workbook' || !p) return null;
24
+ if (d === 'update' && p.kind === 'applyEdits' && Array.isArray(p.edits)) return { key: proj, kind: 'sheet', op: 'write' };
25
+ if (d === 'read' && p.kind === 'readCells') return { key: proj, kind: 'sheet', op: 'read' };
26
+ return null;
27
+ }
28
+
29
+ // One pass over the session file: the calls on the same board or Sheet as toolId, up to toolId's answer, each with whether it went through (and, for a read of cells, what they came to).
30
+ function collect(file, toolId) {
31
+ const ops = [], byId = new Map(); let target = null, done = false, tail = false, fd, pos = 0, size = 0, carry = Buffer.alloc(0);
32
+ const marks = [Buffer.from('"ArtifactData"'), Buffer.from('Claude_Docs__'), Buffer.from('"tool_result"')];
33
+ try {
34
+ fd = fs.openSync(file, 'r'); size = fs.fstatSync(fd).size;
35
+ while (pos < size && pos < LIVE_MAX && !done) {
36
+ const buf = Buffer.alloc(Math.min(8 * 1024 * 1024, size - pos)); fs.readSync(fd, buf, 0, buf.length, pos); pos += buf.length;
37
+ const all = carry.length ? Buffer.concat([carry, buf]) : buf; let a = 0;
38
+ for (let b; !done && (b = all.indexOf(10, a)) >= 0; a = b + 1) {
39
+ const line = all.subarray(a, b);
40
+ if (line.indexOf(marks[0]) < 0 && line.indexOf(marks[1]) < 0 && !(byId.size && line.indexOf(marks[2]) >= 0)) continue;
41
+ let r; try { r = JSON.parse(line.toString('utf8')); } catch { continue; }
42
+ for (const blk of blocksOf(r)) {
43
+ if (blk.type === 'tool_use') { const c = liveCall(blk.name, blk.input); if (!c) continue;
44
+ if (tail && (c.key !== target.key || c.op !== 'read')) { if (c.key === target.key) done = true; continue; } /* after the write: only the reads of the same Sheet, up to its next write */
45
+ const op = { id: blk.id, ...c, i: blk.input, ok: null }; ops.push(op); byId.set(blk.id, op); if (blk.id === toolId) target = op; }
46
+ else if (blk.type === 'tool_result' && byId.has(blk.tool_use_id)) {
47
+ const op = byId.get(blk.tool_use_id), text = textOf(blk.content);
48
+ if (blk.is_error) op.ok = false;
49
+ else if (op.kind === 'board') op.ok = !/\bnothing (was )?written\b|\brefused\b/i.test(text.slice(0, 400));
50
+ else { const j = docsJson(text); op.ok = !!(j && j.verdict !== 'deny' && (op.op === 'read' ? j.value && j.value.rows : j.data && Number.isFinite(+j.data.revision))); if (op.ok && op.op === 'read') op.value = j.value; }
51
+ byId.delete(blk.tool_use_id); if (blk.tool_use_id === toolId) { if (op.kind === 'sheet' && op.ok) tail = true; else done = true; } /* a Sheet: what the formulas came to is told by a read that follows */
52
+ }
53
+ }
54
+ }
55
+ carry = Buffer.from(all.subarray(a));
56
+ }
57
+ } catch {} finally { if (fd != null) fs.closeSync(fd); }
58
+ if (!target || target.op !== 'write' || !(done || tail) || !target.ok) return null; // a write that was refused, or whose answer is not written yet, has no picture of its own
59
+ return { kind: target.kind, ops: ops.filter((o) => o.key === target.key && o.kind === target.kind && o.ok), size };
60
+ }
61
+ function docsJson(text) { // the connector's answer: a line that says it comes from others, then the JSON
62
+ const s = text.indexOf('{"verdict"'); if (s < 0) return null;
63
+ try { return JSON.parse(text.slice(s)); } catch {}
64
+ try { return JSON.parse(text.slice(s, text.lastIndexOf('}') + 1)); } catch { return null; }
65
+ }
66
+
67
+ // ---- The board: its store, as the writes left it, then drawn as one SVG.
68
+ const DEL = (v) => v && typeof v === 'object' && v.__delete__ === true, BAD_KEY = new Set(['__proto__', 'constructor', 'prototype']);
69
+ const clean = (v) => JSON.parse(JSON.stringify(v), (k, x) => (BAD_KEY.has(k) ? undefined : x)); // a copy with no key that could reach a prototype: a session's records must not change the server's objects
70
+ function merge(into, data, depth = 0) {
71
+ for (const [k, v] of Object.entries(data || {})) {
72
+ if (BAD_KEY.has(k)) continue;
73
+ if (DEL(v)) delete into[k];
74
+ else if (depth < 40 && v && typeof v === 'object' && !Array.isArray(v) && into[k] && typeof into[k] === 'object' && !Array.isArray(into[k])) merge(into[k], v, depth + 1);
75
+ else into[k] = v;
76
+ }
77
+ return into;
78
+ }
79
+ function boardStore(ops) {
80
+ let room = 4e6; // what str_replace may add to the board's texts in all: a board holds 2 MB
81
+ const docs = new Map(), one = (w) => {
82
+ if (!boardDoc(w)) return; // only the board's own documents
83
+ const key = String(w.collection || '') + '/' + String(w.doc_id || ''), data = w.data && typeof w.data === 'object' ? w.data : null;
84
+ if (w.op === 'delete' || w.action === 'delete') docs.delete(key);
85
+ else if ((w.op || w.action) === 'set' && data) docs.set(key, clean(data));
86
+ else if ((w.op || w.action) === 'update' && data) docs.set(key, merge(docs.get(key) || {}, clean(data)));
87
+ else if (w.action === 'str_replace' && docs.has(key) && !BAD_KEY.has(w.field)) { const d = docs.get(key), f = w.field; if (typeof d[f] === 'string' && typeof w.old_str === 'string' && w.old_str) { const n = w.replace_all ? d[f].split(w.old_str).length - 1 : 1, grows = String(w.new_str || '').length - w.old_str.length; if (d[f].length + n * grows <= 100000 && (grows <= 0 || (room -= n * grows) >= 0)) d[f] = w.replace_all ? d[f].split(w.old_str).join(w.new_str || '') : d[f].replace(w.old_str, () => w.new_str || ''); } } /* a text that would grow past what a board holds is not grown (doubling it could end the process) */
88
+ };
89
+ for (const o of ops) { if (o.i.action === 'batch') for (const w of Array.isArray(o.i.writes) ? o.i.writes : []) one(w); else one(o.i); }
90
+ return docs;
91
+ }
92
+ const FILL = { yellow: '#fff1b3', peach: '#ffd9bf', pink: '#ffd3e4', green: '#d3f2da', blue: '#d4e6ff', purple: '#e6dbff', white: '#ffffff' };
93
+ const INK = { ink: '#1f1f22', terracotta: '#c2613d', blue: '#2f6fdb', green: '#2e8b57', purple: '#7b4fd6' };
94
+ const HEX = /^#[0-9a-f]{6}$/i, fillOf = (c, dflt) => (HEX.test(c || '') ? c : FILL[c] || dflt), inkOf = (c) => (HEX.test(c || '') ? c : INK[c] || INK.ink);
95
+ const SIZE = { small: 14, body: 16, large: 28, title: 48, huge: 96 };
96
+ const num = (v, d = 0) => (Number.isFinite(+v) ? Math.max(-1e6, Math.min(1e6, +v)) : d);
97
+ function inline(t) { // the few marks a board's text has: **bold**, *italic*, `code`, [label](link), and lists, on escaped text
98
+ return String(t || '').slice(0, 4000).split('\n').map((ln) => {
99
+ const li = /^(- |\d+\. )/.exec(ln), body = esc(li ? ln.slice(li[0].length) : ln)
100
+ .replace(/`([^`]+)`/g, '<code>$1</code>').replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>').replace(/\*([^*]+)\*/g, '<i>$1</i>').replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<u>$1</u>');
101
+ return li ? `<div class="li">${li[0].trim() === '-' ? '•' : esc(li[0].trim())} ${body}</div>` : `<div>${body || '&nbsp;'}</div>`;
102
+ }).join('');
103
+ }
104
+ const fo = (x, y, w, h, cls, style, html) => `<foreignObject x="${x}" y="${y}" width="${Math.max(1, w)}" height="${Math.max(1, h)}"><div xmlns="http://www.w3.org/1999/xhtml" class="${cls}" style="${style}">${html}</div></foreignObject>`;
105
+ function tableSize(el) {
106
+ const cols = Object.entries(el.cols || {}).sort((a, b) => num(a[1] && a[1].at) - num(b[1] && b[1].at)).slice(0, 30).map(([k]) => k), rows = Object.values(el.rows || {}).filter((r) => r && typeof r === 'object').sort((a, b) => num(a.at) - num(b.at)).slice(0, 200);
107
+ const widths = cols.map((c) => Math.min(320, Math.max(60, ...rows.map((r) => String(r[c] == null ? '' : r[c]).length * 8 + 24))));
108
+ return { cols, rows, widths, w: widths.reduce((a, b) => a + b, 0), h: rows.length * 34 };
109
+ }
110
+ function drawBoard(docs) {
111
+ const meta = docs.get('board/meta') || {}, els = new Map(); for (const [k, v] of docs) if (k.startsWith('elements/') && v && typeof v === 'object') els.set(k.slice(9), v);
112
+ const order = (Array.isArray(meta.order) ? meta.order.filter((id) => els.has(id)) : []), ids = [...new Set([...order, ...els.keys()])].slice(0, 800);
113
+ const box = new Map(); let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; const grow = (x, y, w, h) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x + w); y1 = Math.max(y1, y + h); };
114
+ for (const id of ids) { // where each thing stands, for the arrows and the frame
115
+ const e = els.get(id), x = num(e.x), y = num(e.y);
116
+ if (e.type === 'text') { const s = SIZE[e.size] || 16, lines = String(e.text || '').split('\n'), w = e.wrap ? num(e.wrap, 300) : lines.reduce((m, l) => Math.max(m, l.length), 0) * s * 0.56 + 8, h = (e.wrap ? Math.ceil(String(e.text || '').length * s * 0.55 / w) + lines.length - 1 : lines.length) * s * 1.4; box.set(id, { x, y, w, h }); grow(x, y, w, h); }
117
+ else if (e.type === 'table') { const t = tableSize(e); box.set(id, { x, y, w: t.w, h: t.h, t }); grow(x, y, t.w, t.h); }
118
+ else if (e.type === 'link') { box.set(id, { x, y, w: 320, h: 56 }); grow(x, y, 320, 56); }
119
+ else if (e.type === 'stroke') { const p = Array.isArray(e.points) ? e.points.slice(0, 8000).map((v) => num(v)) : []; for (let k = 0; k + 1 < p.length; k += 2) grow(x + p[k], y + p[k + 1], 1, 1); }
120
+ else if (e.type !== 'arrow' && e.type !== 'sticker') { const w = num(e.w, 160), h = num(e.h, 80); box.set(id, { x, y, w, h }); grow(x, y - (e.type === 'container' ? 34 : 0), w, h + (e.type === 'container' ? 34 : 0)); }
121
+ }
122
+ if (!docs.has('board/meta') && !els.size) return null; // nothing of a board: no picture (the call shows the artifact's card)
123
+ if (x0 > x1) return page('board', esc(meta.title || ''), '<div class="empty">The board is empty so far.</div>');
124
+ const out = [], P = 40;
125
+ for (const id of ids) {
126
+ const e = els.get(id), b = box.get(id), x = num(e.x), y = num(e.y);
127
+ if (e.type === 'container') { out.push(`<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="18" fill="${fillOf(e.color, '#f4f4f1')}" fill-opacity="${e.color ? 0.45 : 1}" stroke="#d9d9d3"/>`); if (e.text) out.push(fo(x, y - 34, b.w, 30, 'ct', '', inline(String(e.text).split('\n')[0]))); }
128
+ else if (e.type === 'shape') {
129
+ const w = b.w, h = b.h, fill = e.hollow ? 'none' : fillOf(e.color, FILL.green), st = e.stroke ? ` stroke="${inkOf(e.stroke)}" stroke-width="2"` : ' stroke="rgba(0,0,0,.08)"', k = e.kind;
130
+ out.push(k === 'ellipse' ? `<ellipse cx="${x + w / 2}" cy="${y + h / 2}" rx="${w / 2}" ry="${h / 2}" fill="${fill}"${st}/>` : k === 'diamond' ? `<polygon points="${x + w / 2},${y} ${x + w},${y + h / 2} ${x + w / 2},${y + h} ${x},${y + h / 2}" fill="${fill}"${st}/>`
131
+ : k === 'hexagon' ? `<polygon points="${x + w * 0.2},${y} ${x + w * 0.8},${y} ${x + w},${y + h / 2} ${x + w * 0.8},${y + h} ${x + w * 0.2},${y + h} ${x},${y + h / 2}" fill="${fill}"${st}/>`
132
+ : k === 'parallelogram' ? `<polygon points="${x + w * 0.15},${y} ${x + w},${y} ${x + w * 0.85},${y + h} ${x},${y + h}" fill="${fill}"${st}/>`
133
+ : `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${k === 'pill' ? h / 2 : k === 'rect' ? 4 : 14}" fill="${fill}"${st}/>`);
134
+ const inset = k === 'diamond' || k === 'ellipse' ? 0.18 : 0.04;
135
+ if (e.text) out.push(fo(x + w * inset + 6, y + 4, w * (1 - 2 * inset) - 12, h - 8, 'sh', `font-size:${SIZE[e.size] || 15}px;text-align:${['left', 'right'].includes(e.textAlign) ? e.textAlign : 'center'};justify-content:${e.textAlign === 'left' ? 'flex-start' : e.textAlign === 'right' ? 'flex-end' : 'center'}`, inline(e.text)));
136
+ }
137
+ else if (e.type === 'note') { out.push(`<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="6" fill="${FILL.yellow}" stroke="rgba(0,0,0,.08)"/>`); if (e.text) out.push(fo(x + 8, y + 6, b.w - 16, b.h - 12, 'sh', 'font-size:15px;text-align:left;justify-content:flex-start', inline(e.text))); }
138
+ else if (e.type === 'text') out.push(fo(x, y, b.w + 40, b.h + 20, 'tx', `font-size:${SIZE[e.size] || 16}px;color:${inkOf(e.color)};${e.wrap ? '' : 'white-space:pre;'}text-align:${['center', 'right'].includes(e.textAlign) ? e.textAlign : 'left'};${e.size === 'title' || e.size === 'huge' ? 'font-weight:700;' : ''}`, inline(e.text)));
139
+ else if (e.type === 'stroke') { const p = Array.isArray(e.points) ? e.points.slice(0, 8000).map((v) => num(v)) : [], pts = []; for (let k = 0; k + 1 < p.length; k += 2) pts.push(`${x + p[k]},${y + p[k + 1]}`); if (pts.length > 1) out.push(`<polyline points="${pts.join(' ')}" fill="none" stroke="${inkOf(e.color)}" stroke-width="${Math.min(20, num(e.width, 3))}" stroke-linecap="round" stroke-linejoin="round"/>`); }
140
+ else if (e.type === 'image') { const src = typeof e.src === 'string' && /^data:image\/(png|jpeg|webp|gif|svg\+xml)[;,]/.test(e.src) && e.src.length < 400000 ? e.src : ''; out.push(src ? `<image x="${x}" y="${y}" width="${b.w}" height="${b.h}" href="${esc(src)}" preserveAspectRatio="xMidYMid meet"/>` : `<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="10" fill="#ececea"/>` + fo(x, y, b.w, b.h, 'sh muted', 'font-size:14px', 'picture')); }
141
+ else if (e.type === 'html') { out.push(`<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="10" fill="#fff" stroke="#cfcfca"/>`); const t = /<title>([^<]{1,80})<\/title>/i.exec(String(e.html || '')); out.push(fo(x, y, b.w, b.h, 'sh muted', 'font-size:14px', '▶ ' + esc(t ? t[1] : 'embed'))); }
142
+ else if (e.type === 'link') { out.push(`<rect x="${x}" y="${y}" width="320" height="56" rx="12" fill="#fff" stroke="#cfcfca"/>`); out.push(fo(x + 14, y + 4, 292, 48, 'sh', 'font-size:15px;text-align:left;justify-content:flex-start', '↗ ' + esc(String(e.title || e.href || '').slice(0, 80)))); }
143
+ else if (e.type === 'table') { const t = b.t; out.push(fo(x, y, t.w + 2, t.h + 2, 'tb', '', `<table>${t.rows.map((r, n) => `<tr>${t.cols.map((c, k) => `<${n ? 'td' : 'th'} style="width:${t.widths[k]}px">${inline(r[c] == null ? '' : String(r[c]).split('\n')[0])}</${n ? 'td' : 'th'}>`).join('')}</tr>`).join('')}</table>`)); }
144
+ }
145
+ const side = (bx, s) => (s === 'top' ? [bx.x + bx.w / 2, bx.y] : s === 'bottom' ? [bx.x + bx.w / 2, bx.y + bx.h] : s === 'left' ? [bx.x, bx.y + bx.h / 2] : [bx.x + bx.w, bx.y + bx.h / 2]);
146
+ const end = (v, s, other) => { // an end of an arrow: a point, or the middle of a side of what it joins (the side facing the other end when none is named)
147
+ if (Array.isArray(v)) return { p: [num(v[0]), num(v[1])], s: '' };
148
+ const bx = box.get(v); if (!bx) return null; if (s) return { p: side(bx, s), s };
149
+ const o = other || [bx.x + bx.w + 100, bx.y], cx = bx.x + bx.w / 2, cy = bx.y + bx.h / 2, dx = o[0] - cx, dy = o[1] - cy;
150
+ const f = Math.abs(dx) * bx.h > Math.abs(dy) * bx.w ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'bottom' : 'top'; return { p: side(bx, f), s: f };
151
+ };
152
+ const centre = (v) => (Array.isArray(v) ? [num(v[0]), num(v[1])] : box.has(v) ? [box.get(v).x + box.get(v).w / 2, box.get(v).y + box.get(v).h / 2] : null);
153
+ for (const id of ids) {
154
+ const e = els.get(id); if (e.type !== 'arrow') continue;
155
+ const ca = centre(e.from), cb = centre(e.to); if (!ca || !cb) continue;
156
+ const a = end(e.from, e.fromSide, cb), z = end(e.to, e.toSide, ca); if (!a || !z) continue;
157
+ const [ax, ay] = a.p, [zx, zy] = z.p, flat = (s) => s === 'left' || s === 'right', pts = [[ax, ay]];
158
+ if (Math.abs(ax - zx) > 2 && Math.abs(ay - zy) > 2) { if (flat(a.s || 'right')) { const mx = (ax + zx) / 2; pts.push([mx, ay], [mx, zy]); } else { const my = (ay + zy) / 2; pts.push([ax, my], [zx, my]); } }
159
+ pts.push([zx, zy]);
160
+ const heads = Array.isArray(e.heads) ? e.heads : e.head === 'both' ? ['arrow', 'arrow'] : e.head === 'none' ? ['none', 'none'] : ['none', 'arrow'], col = inkOf(e.color);
161
+ out.push(`<polyline points="${pts.map((p) => p.join(',')).join(' ')}" fill="none" stroke="${col}" stroke-width="2.2"${e.dash ? ' stroke-dasharray="7 6"' : ''}${heads[1] === 'arrow' ? ' marker-end="url(#ah)"' : ''}${heads[0] === 'arrow' ? ' marker-start="url(#ahs)"' : ''}/>`);
162
+ if (e.label) { const m = pts[Math.floor((pts.length - 1) / 2)], n = pts[Math.floor((pts.length - 1) / 2) + 1] || m, lx = (m[0] + n[0]) / 2, ly = (m[1] + n[1]) / 2; out.push(fo(lx - 80, ly - 14, 160, 28, 'al', '', inline(String(e.label).split('\n')[0]))); }
163
+ }
164
+ const vb = [x0 - P, y0 - P, x1 - x0 + 2 * P, y1 - y0 + 2 * P].map((v) => Math.round(v));
165
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vb.join(' ')}" preserveAspectRatio="xMidYMin meet"><defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M0,0L10,5L0,10z" fill="${INK.ink}"/></marker><marker id="ahs" viewBox="0 0 10 10" refX="1" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M10,0L0,5L10,10z" fill="${INK.ink}"/></marker></defs>${out.join('')}</svg>`;
166
+ return page('board', esc(meta.title || ''), svg);
167
+ }
168
+
169
+ // ---- The Sheet: its sheets and cells as the edits left them, the values the reads gave the formulas, then the sheet edited last drawn as a grid.
170
+ const colNum = (s) => { let n = 0; for (const ch of String(s).toUpperCase()) n = n * 26 + ch.charCodeAt(0) - 64; return n; };
171
+ const colName = (n) => { let s = ''; for (; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + ((n - 1) % 26)) + s; return s; };
172
+ const addr = (a) => { const m = /^([A-Z]{1,3})(\d{1,7})$/i.exec(String(a || '').trim()); return m ? [+m[2], colNum(m[1])] : null; };
173
+ function rangeOf(rg, sh) { // "A1:C4", "B2", "3:4", "B:C" → [r0, c0, r1, c1], bounded by what the sheet holds
174
+ const s = String(rg || '').trim(), [p, q = p] = s.split(':'), MAXR = Math.max(sh.maxR, 1), MAXC = Math.max(sh.maxC, 1);
175
+ if (/^\d+$/.test(p) && /^\d+$/.test(q)) return [+p, 1, Math.min(+q, +p + 2000, R_MAX), Math.min(Math.max(MAXC + 5, 40), C_MAX)]; /* whole rows, whole columns: as far as the sheet holds anything, not the million rows of the Sheet */
176
+ if (/^[A-Z]+$/i.test(p) && /^[A-Z]+$/i.test(q)) return [1, colNum(p), Math.min(Math.max(MAXR + 50, 400), R_MAX), Math.min(colNum(q), colNum(p) + 60, C_MAX)];
177
+ const a = addr(p), b = addr(q) || a; if (!a) return null;
178
+ return [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.min(Math.max(a[0], b[0]), a[0] + 2000), Math.min(Math.max(a[1], b[1]), a[1] + 60)];
179
+ }
180
+ const R_MAX = 2400, C_MAX = 240, inGrid = (r, c) => r >= 1 && c >= 1 && r <= R_MAX && c <= C_MAX; // the picture shows 400 rows and 40 columns: what lies far past them is not kept
181
+ function sheetState(ops) {
182
+ let budget = 400000; const spend = (n) => (budget -= n) > 0; // one budget for the whole replay (cells written, formatted, moved, fitted, read): records made to be slow cost their own picture only
183
+ const book = [], find = (n) => book.find((s) => s.name === n), mk = (name) => { const s = { name: String(name).slice(0, 100), cells: new Map(), fmt: new Map(), widths: new Map(), head: 0, maxR: 0, maxC: 0 }; book.push(s); return s; };
184
+ let last = null; mk('Sheet1').phantom = true; // a new Sheet starts with Sheet1; a Sheet made in another session is known only by the sheets its edits and reads name
185
+ const named = (n, make) => { if (typeof n !== 'string' || !n) return null; let s = find(n); if (!s && make && book.length < 200) s = mk(n); /* a workbook has 200 sheets at most */ if (s) s.phantom = false; return s; };
186
+ const shift = (s, at, n, rows) => { if (!spend(s.cells.size + s.fmt.size)) return; for (const m of [s.cells, s.fmt]) { const moved = new Map(); for (const [k, v] of m) { const [r, c] = k.split(',').map(Number), key = rows ? (r >= at ? `${r + n},${c}` : n < 0 && r >= at + n ? null : k) : c >= at ? `${r},${c + n}` : n < 0 && c >= at + n ? null : k; /* a delete: what lay in the deleted rows goes, what lay after moves up */ if (key) moved.set(key, v); } m.clear(); for (const [k, v] of moved) m.set(k, v); } };
187
+ for (const o of ops) {
188
+ if (o.op === 'read') { const v = o.value, rg = v && typeof v.range === 'string' ? addr(v.range.split(':')[0]) : null, s = rg && v.rows && typeof v.rows === 'object' ? named(v.sheet, true) : null; if (!s) continue;
189
+ for (const [rn, row] of Object.entries(v.rows).slice(0, 5000)) if (Array.isArray(row) && +rn > 0 && spend(row.length)) row.slice(0, 200).forEach((cell, k) => { const key = `${+rn},${rg[1] + k}`, mine = s.cells.get(key); if (cell == null || !inGrid(+rn, rg[1] + k)) return;
190
+ if (!s.cells.has(key)) { s.cells.set(key, cell); s.maxR = Math.max(s.maxR, +rn); s.maxC = Math.max(s.maxC, rg[1] + k); } /* what a read shows of cells this session did not write */
191
+ else if (typeof cell === 'object' && 'formula' in cell && typeof mine === 'string' && mine.trim().toUpperCase() === String(cell.formula).trim().toUpperCase()) s.cells.set(key, { formula: mine, value: cell.value }); });
192
+ continue; }
193
+ for (const e of o.i.payload.edits.slice(0, 64)) {
194
+ if (budget <= 0) break; if (!e || typeof e !== 'object') continue; const s = named(e.sheet, e.kind !== 'deleteSheet' && e.kind !== 'restoreSheet');
195
+ if (e.kind === 'renameSheet' && s && typeof e.name === 'string') { s.name = e.name.slice(0, 100); last = s; }
196
+ else if (e.kind === 'addSheet' && typeof e.name === 'string' && !find(e.name)) last = named(e.name, true) || last;
197
+ else if (e.kind === 'deleteSheet' && s) { book.splice(book.indexOf(s), 1); if (last === s) last = null; }
198
+ else if (e.kind === 'restoreSheet' && typeof e.sheet === 'string' && !find(e.name || e.sheet)) last = named(e.name || e.sheet, true) || last;
199
+ else if (e.kind === 'writeCells' && s && Array.isArray(e.rows)) { const a = addr(e.topLeft); if (!a) continue; last = s;
200
+ e.rows.slice(0, 5000).forEach((row, i) => Array.isArray(row) && spend(row.length) && row.slice(0, 200).forEach((v, k) => { const key = `${a[0] + i},${a[1] + k}`; if (!inGrid(a[0] + i, a[1] + k)) return; if (v == null) s.cells.delete(key); else { s.cells.set(key, v); s.maxR = Math.max(s.maxR, a[0] + i); s.maxC = Math.max(s.maxC, a[1] + k); } })); }
201
+ else if (e.kind === 'formatCells' && s && Array.isArray(e.ranges) && e.format) { last = s; const f = e.format, look = {}; if (f.font && typeof f.font.bold === 'boolean') look.b = f.font.bold; if (f.font && typeof f.font.italic === 'boolean') look.i = f.font.italic; if (f.fillColor && HEX.test(f.fillColor.hex || '')) look.fill = f.fillColor.hex; if (f.fillColor && f.fillColor.kind === 'none') look.fill = '';
202
+ if (Object.keys(look).length) for (const rg of e.ranges.slice(0, 40)) { const R = rangeOf(rg, s); if (R) for (let r = R[0]; r <= Math.min(R[2], R_MAX) && budget > 0; r++) for (let c = R[1]; c <= Math.min(R[3], C_MAX) && budget-- > 0; c++) s.fmt.set(`${r},${c}`, { ...(s.fmt.get(`${r},${c}`) || {}), ...look }); } }
203
+ else if (e.kind === 'setColumnWidths' && s && typeof e.columns === 'string') { const [p, q = p] = e.columns.split(':'); for (let c = colNum(p); c <= colNum(q) && c < colNum(p) + 200; c++) s.widths.set(c, Math.max(20, Math.min(800, num(e.widthInPixels, 104)))); }
204
+ else if (e.kind === 'fitColumns' && s && typeof e.columns === 'string') { const [p, q = p] = e.columns.split(':'); for (let c = colNum(p); c <= colNum(q) && c < colNum(p) + 200 && spend(s.maxR); c++) { let w = 40; for (let r = 1; r <= Math.min(s.maxR, 2000); r++) { const v = s.cells.get(`${r},${c}`); if (v != null && !(typeof v === 'string' && v.length > 60 && !s.cells.has(`${r},${c + 1}`))) w = Math.max(w, (typeof v === 'string' && v[0] === '=' ? 8 : cellText(v).t.length) * 7.4 + 18); /* a formula: what it comes to, most often a short number */ } s.widths.set(c, Math.min(360, Math.round(w))); } }
205
+ else if (e.kind === 'setCellTable' && s) s.head = e.cellTable && e.cellTable.headerRows ? +String(e.cellTable.headerRows).split(':').pop() || 0 : 0;
206
+ else if ((e.kind === 'insertRows' || e.kind === 'insertColumns') && s) { const n = Math.min(1000, num(e.count, 1)), at = e.kind === 'insertRows' ? num(e.besideRow) + (e.side === 'below' ? 1 : 0) : colNum(e.besideColumn) + (e.side === 'right' ? 1 : 0); shift(s, at, n, e.kind === 'insertRows'); if (e.kind === 'insertRows') s.maxR += n; else s.maxC += n; last = s; }
207
+ else if ((e.kind === 'deleteRows' || e.kind === 'deleteColumns') && s) { const [p, q = p] = String(e.rows || e.columns || '').split(':'), rows = e.kind === 'deleteRows', a = rows ? +p : colNum(p), b = rows ? +q : colNum(q); if (a > 0 && b >= a) { shift(s, b + 1, -(b - a + 1), rows); last = s; } }
208
+ }
209
+ }
210
+ const shown = book.filter((x) => !x.phantom);
211
+ return { book: shown, last: last && shown.includes(last) ? last : shown[0] || null };
212
+ }
213
+ function cellText(v) { // what a cell shows, as far as the session knows it: a formula it never read shows as written
214
+ if (v == null) return { t: '' };
215
+ if (typeof v === 'number') return { t: v.toLocaleString('en-US', { maximumFractionDigits: 6 }), n: 1 };
216
+ if (typeof v === 'boolean') return { t: v ? '☑' : '☐', c: 1 };
217
+ if (typeof v === 'string') { if (/^=/.test(v)) return { t: v, f: 1 }; if (/^'/.test(v)) return { t: v.slice(1) }; return /^[-+]?[\d,]*\.?\d+%?$|^[$€£]\s?[\d,.]+$/.test(v.trim()) ? { t: v, n: 1 } : /^\d{1,2}:\d{2}(:\d{2})?(\s?[AP]M)?$/i.test(v.trim()) ? { t: v, n: 1 } : { t: v }; }
218
+ if (Array.isArray(v)) return { t: v.map((x) => (x && x.name) || '').join(', ') };
219
+ if (typeof v === 'object') {
220
+ if ('formula' in v) { const r = cellText(v.value); return r.t === '' && v.value == null ? { t: String(v.formula), f: 1 } : r; }
221
+ if ('error' in v) return { t: String(v.error), c: 1 };
222
+ if ('shown' in v) return { t: String(v.shown), n: 1 }; if ('date' in v) return { t: String(v.date), n: 1 }; if ('time' in v) return { t: String(v.time).replace(/:00$/, ''), n: 1 }; if ('dateTime' in v) return { t: String(v.dateTime).replace('T', ' ').replace(/:00$/, ''), n: 1 };
223
+ if ('markdown' in v) return { t: String(v.markdown).replace(/\*\*|~~|<\/?u>|\\/g, '').replace(/(^|[^*])\*([^*]+)\*/g, '$1$2').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') };
224
+ if ('name' in v) return { t: String(v.name) };
225
+ }
226
+ return { t: '' };
227
+ }
228
+ function drawSheet(st) {
229
+ const s = st.last; if (!s) return null; // no sheet any edit named: no picture (the call shows the artifact's card)
230
+ const R = Math.min(Math.max(s.maxR, 12), 400), C = Math.min(Math.max(s.maxC, 6), 40), head = [`<tr><th class="corner"></th>${Array.from({ length: C }, (_, k) => `<th style="width:${s.widths.get(k + 1) || 104}px">${colName(k + 1)}</th>`).join('')}</tr>`];
231
+ for (let r = 1; r <= R; r++) {
232
+ const tds = []; for (let c = 1; c <= C; c++) { const v = cellText(s.cells.get(`${r},${c}`)); let span = 1; if (v.t && !v.n && !v.c) while (c + span <= C && span < 16 && !s.cells.has(`${r},${c + span}`) && v.t.length * 7.2 > Array.from({ length: span }, (_, k) => s.widths.get(c + k) || 104).reduce((x, y) => x + y, 0)) span++; /* text runs on over the empty cells beside it, as in the Sheet */
233
+ const f = s.fmt.get(`${r},${c}`) || {}, cls = [v.n ? 'n' : '', v.c ? 'c' : '', v.f ? 'f' : '', r === s.head ? 'h' : ''].filter(Boolean).join(' '), sty = (f.fill ? `background:${f.fill};` : '') + (f.b ? 'font-weight:700;' : '') + (f.i ? 'font-style:italic;' : '');
234
+ tds.push(`<td${span > 1 ? ` colspan="${span}"` : ''}${cls ? ` class="${cls}"` : ''}${sty ? ` style="${sty}"` : ''}>${esc(v.t.slice(0, 400))}</td>`); c += span - 1; }
235
+ head.push(`<tr><th>${r}</th>${tds.join('')}</tr>`);
236
+ }
237
+ const tabs = st.book.slice(0, 30).map((x) => `<span class="${x === s ? 'on' : ''}">${esc(x.name)}</span>`).join('');
238
+ const tw = 38 + Array.from({ length: C }, (_, k) => s.widths.get(k + 1) || 104).reduce((x, y) => x + y, 0);
239
+ return page('sheet', '', `<div class="grid"><table style="width:${tw}px">${head.join('')}</table></div><div class="tabs">${tabs}</div>`);
240
+ }
241
+
242
+ const STYLE = {
243
+ board: 'html,body{margin:0;background:#fbfbf8;font:15px/1.35 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1f1f22}svg{display:block;width:100%;height:auto;max-height:100vh}.sh{height:100%;display:flex;flex-direction:column;justify-content:center;overflow:hidden;line-height:1.3}.sh>div{width:100%}.tx{line-height:1.4}.ct{font-weight:600;font-size:16px;color:#55554f;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.al{font-size:13px;text-align:center;background:#fbfbf8;border-radius:6px}.muted{color:#8a8a84}.li{padding-left:2px}code{font:13px ui-monospace,Menlo,monospace;background:rgba(0,0,0,.06);padding:0 3px;border-radius:3px}.tb table{border-collapse:collapse;background:#fff;font-size:14px}.tb th,.tb td{border:1px solid #deded8;padding:6px 10px;text-align:left;height:21px;overflow:hidden;white-space:nowrap}.tb th{background:#f1f1ed}.empty{padding:80px;text-align:center;color:#8a8a84}',
244
+ sheet: 'html,body{margin:0;height:100%;background:#fff;font:13px/1.2 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1f1f22}body{display:flex;flex-direction:column}.grid{flex:1;overflow:auto}table{border-collapse:collapse;table-layout:fixed}th,td{border:1px solid #e3e3e0;height:27px;padding:0 6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:800px}th{background:#f6f6f4;color:#77776f;font-weight:500;position:sticky;top:0;z-index:1}th.corner{width:38px}tr th:first-child{position:sticky;left:0;text-align:center;z-index:2}th.corner{z-index:3}td.n{text-align:right;font-variant-numeric:tabular-nums}td.c{text-align:center}td.f{color:#8a8a84;font-style:italic}td.h{font-weight:600}.tabs{display:flex;gap:2px;padding:6px 8px 8px;background:#f6f6f4;border-top:1px solid #e3e3e0}.tabs span{padding:5px 12px;border-radius:6px;color:#66665f}.tabs span.on{background:#fff;color:#1f1f22;font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.12)}.empty{padding:80px;text-align:center;color:#8a8a84}',
245
+ };
246
+ const page = (kind, title, body) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${title ? `<title>${title}</title>` : ''}<style>${STYLE[kind]}</style>${body}`;
247
+
248
+ // The picture of the board or the Sheet as the write toolId left it, or null (not such a write, refused, or not answered yet).
249
+ function livePage(file, toolId) {
250
+ let size = 0; try { size = fs.statSync(file).size; } catch { return null; }
251
+ const key = file + '|' + toolId, hit = memo.get(key); if (hit && hit.size === size) return hit.page;
252
+ let html = null; const got = collect(file, toolId);
253
+ try { html = got ? (got.kind === 'board' ? drawBoard(boardStore(got.ops.filter((o) => o.op === 'write'))) : drawSheet(sheetState(got.ops))) : null; } catch { html = null; } // records too odd to draw cost that picture only
254
+ const out = html ? { html, net: false } : null;
255
+ memo.delete(key); memo.set(key, { size, page: out }); if (memo.size > 24) memo.delete(memo.keys().next().value);
256
+ return out;
257
+ }
258
+ module.exports = { liveCall, livePage, _draw: { board: (ops) => drawBoard(boardStore(ops)), sheet: (ops) => drawSheet(sheetState(ops)) } };
package/codex.js CHANGED
@@ -388,4 +388,5 @@ function image(id, toolId, n, user, agent = 'main') { // { type, buf } or null
388
388
  imgMemo.set(key, out); if (imgMemo.size > 12) imgMemo.delete(imgMemo.keys().next().value);
389
389
  return out;
390
390
  }
391
- module.exports = { PROJ, SOURCE, home, dirKey, sessions, row, fileOf, cwd, inProject, projectLabel, title, boardRow, subFiles, subCount, state, parser, image };
391
+ const zPending = () => zBusy || zQueue.length > 0; // compressed threads still being read in the background (the day report waits for them)
392
+ module.exports = { zPending, PROJ, SOURCE, home, dirKey, sessions, row, fileOf, cwd, inProject, projectLabel, title, boardRow, subFiles, subCount, state, parser, image };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@double_geste/agent-standup",
3
- "version": "1.45.0",
3
+ "version": "1.46.0",
4
4
  "description": "Your Claude Code, Codex and Mistral Vibe agents as a live video call, from the terminal: a local page in your browser, plus one-line status for status bars. Free, open source, zero token cost.",
5
5
  "bin": {
6
6
  "agent-standup": "bin/agent-standup.js"
@@ -9,6 +9,7 @@
9
9
  "files": [
10
10
  "bin",
11
11
  "server.js",
12
+ "boards.js",
12
13
  "codex.js",
13
14
  "vibe.js",
14
15
  "reply.js",
package/public/index.html CHANGED
@@ -1771,7 +1771,8 @@ function activityLabel(t) { // the short "what is on their screen" tag
1771
1771
  case 'glob': return L('Liste ', 'Listing ') + String(d.pattern || '').slice(0, 24);
1772
1772
  case 'todo': case 'task': return L('Met à jour sa todo', 'Updating todo list');
1773
1773
  case 'plan': return L('Présente le plan', 'Presenting the plan');
1774
- case 'artifact': return (d.open ? L('Montre ', 'Showing ') : d.doc ? L('Crée ', 'Writing ') : L('Publie ', 'Publishing ')) + (d.title || (d.open ? 'Artifact' : f)).slice(0, 30);
1774
+ case 'artifact': if (d.live) return (d.live === 'board' ? L('Dessine sur ', 'Drawing on ') : L('Remplit ', 'Filling ')) + (d.title || (d.live === 'board' ? 'Whiteboard' : 'Sheet')).slice(0, 30); /* a write to a Claude Whiteboard or Sheet */
1775
+ return (d.open ? L('Montre ', 'Showing ') : d.doc ? L('Crée ', 'Writing ') : L('Publie ', 'Publishing ')) + (d.title || (d.open ? 'Artifact' : f)).slice(0, 30);
1775
1776
  case 'browser': { const s = (d.steps || []).slice(-1)[0] || {}, n = (s.n || '').trim(), h = hostOf(s.u); if (n) return n.length > 36 ? n.slice(0, 36).replace(/\s+\S*$/, '') + '…' : n; if (!h && PREVIEW.test(t.name)) return 'Preview · ' + String(s.a || '').replace(/_/g, ' '); return h ? L('Navigue sur ', 'Browsing ') + h : L('Navigue sur le web', 'Browsing the web'); }
1776
1777
  case 'web': return d.url ? L('Consulte ', 'Fetching ') + d.url.replace(/^https?:\/\//, '').slice(0, 26) : L('Recherche sur le web', 'Web search');
1777
1778
  case 'text': { const w = d.what; if (w === 'question') return L('Pose une question', 'Asking a question'); if (w === 'skill') return L('Utilise ', 'Using skill ') + (d.v || ''); if (w === 'mcp') return d.v || t.name; if (w === 'toolsearch') return L('Cherche un outil', 'Looking for a tool'); return t.name; }
@@ -194,6 +194,8 @@
194
194
  "Web search": "Websøgning",
195
195
  "working": "arbejder",
196
196
  "Writing ": "Skriver ",
197
+ "Drawing on ": "Tegner på ",
198
+ "Filling ": "Udfylder ",
197
199
  "You": "Dig",
198
200
  "You can also switch between Call, Tree and Sessions at the top of the window.": "Du kan også skifte mellem Opkald, Træ og Sessioner øverst i vinduet.",
199
201
  "Your agents are done 🎉": "Dine agenter er færdige 🎉",
@@ -168,6 +168,8 @@
168
168
  "Web search": "Websuche",
169
169
  "working": "arbeitet",
170
170
  "Writing ": "Schreibe ",
171
+ "Drawing on ": "Zeichnet auf ",
172
+ "Filling ": "Füllt ",
171
173
  "You": "Du",
172
174
  "Your agents are done 🎉": "Deine Agenten sind fertig 🎉",
173
175
  "Your Claude Code agents as a live team call": "Deine Claude Code-Agenten live im Team-Videoanruf",
@@ -109,6 +109,7 @@
109
109
  "Download the new app from GitHub.": "Download the new app from GitHub.",
110
110
  "Downloading the real voices… you can carry on.": "Downloading the real voices… you can carry on.",
111
111
  "Downloading, you can carry on: the agents babble meanwhile.": "Downloading, you can carry on: the agents babble meanwhile.",
112
+ "Drawing on ": "Drawing on ",
112
113
  "Drawn by": "Drawn by",
113
114
  "Drawn characters": "Drawn characters",
114
115
  "duration": "duration",
@@ -134,6 +135,7 @@
134
135
  "Files created in this session": "Files created in this session",
135
136
  "Files made for you, when a turn ends": "Files made for you, when a turn ends",
136
137
  "Files touched": "Files touched",
138
+ "Filling ": "Filling ",
137
139
  "Final report": "Final report",
138
140
  "Find a session": "Find a session",
139
141
  "Find a session…": "Find a session…",
@@ -168,6 +168,8 @@
168
168
  "Web search": "Búsqueda web",
169
169
  "working": "trabajando",
170
170
  "Writing ": "Escribiendo ",
171
+ "Drawing on ": "Dibujando en ",
172
+ "Filling ": "Rellenando ",
171
173
  "You": "Tú",
172
174
  "Your agents are done 🎉": "Tus agentes han terminado 🎉",
173
175
  "Your Claude Code agents as a live team call": "Tus agentes de Claude Code, en videollamada de equipo en directo",
@@ -168,6 +168,8 @@
168
168
  "Web search": "Web検索",
169
169
  "working": "作業中",
170
170
  "Writing ": "書き込み中: ",
171
+ "Drawing on ": "描画中: ",
172
+ "Filling ": "記入中: ",
171
173
  "You": "あなた",
172
174
  "Your agents are done 🎉": "エージェントが完了しました 🎉",
173
175
  "Your Claude Code agents as a live team call": "Claude Code のエージェントを、ライブのチーム通話で",
@@ -168,6 +168,8 @@
168
168
  "Web search": "웹 검색",
169
169
  "working": "작업 중",
170
170
  "Writing ": "작성 중: ",
171
+ "Drawing on ": "그리는 중: ",
172
+ "Filling ": "채우는 중: ",
171
173
  "You": "나",
172
174
  "Your agents are done 🎉": "에이전트 작업이 끝났습니다 🎉",
173
175
  "Your Claude Code agents as a live team call": "Claude Code 에이전트를 실시간 팀 통화로",
@@ -175,6 +175,8 @@
175
175
  "Web search": "Pesquisa na web",
176
176
  "working": "trabalhando",
177
177
  "Writing ": "Escrevendo ",
178
+ "Drawing on ": "Desenhando em ",
179
+ "Filling ": "Preenchendo ",
178
180
  "You": "Você",
179
181
  "Your agents are done 🎉": "Seus agentes terminaram 🎉",
180
182
  "Your Claude Code agents as a live team call": "Seus agentes do Claude Code em uma chamada de equipe ao vivo",
@@ -168,6 +168,8 @@
168
168
  "Web search": "网页搜索",
169
169
  "working": "工作中",
170
170
  "Writing ": "正在写入 ",
171
+ "Drawing on ": "正在绘制 ",
172
+ "Filling ": "正在填写 ",
171
173
  "You": "你",
172
174
  "Your agents are done 🎉": "你的代理都完成啦 🎉",
173
175
  "Your Claude Code agents as a live team call": "把你的 Claude Code 代理变成实时团队通话",
@@ -175,6 +175,8 @@
175
175
  "Web search": "網頁搜尋",
176
176
  "working": "工作中",
177
177
  "Writing ": "撰寫 ",
178
+ "Drawing on ": "繪製 ",
179
+ "Filling ": "填寫 ",
178
180
  "You": "你",
179
181
  "Your agents are done 🎉": "你的代理都完成了 🎉",
180
182
  "Your Claude Code agents as a live team call": "把你的 Claude Code 代理變成即時團隊通話",
package/server.js CHANGED
@@ -8,6 +8,7 @@ const os = require('os');
8
8
  const crypto = require('crypto');
9
9
  const codex = require('./codex.js'); // Codex sessions, read as the same call (see codex.js)
10
10
  const vibe = require('./vibe.js'); // Mistral Vibe sessions, the same way (see vibe.js)
11
+ const boards = require('./boards.js'); // Claude Whiteboards and Sheets, drawn again from the session's writes for the shared screen (see boards.js)
11
12
  const reply = require('./reply.js'); // the human's line, typed into the session's tmux pane (see reply.js); off unless AGENT_STANDUP_REPLY=on
12
13
  const SOURCES = [codex, vibe], sourceOf = (proj) => SOURCES.find((m) => m.PROJ === proj) || null, guard = (fn, or) => { try { return fn(); } catch (e) { logError('reader', e); return or; } }; // guard: a session of another tool that cannot be read costs that session, never the list // the tools other than Claude Code: each lists its sessions under one made-up project
13
14
  const kokoro = require('./kokoro.js'); // natural voices, installed on demand (see kokoro.js)
@@ -39,10 +40,11 @@ function claudeHomes() { // [CLAUDE_HOME, the other folders that hold sessions
39
40
  const home = os.homedir(), real = (d) => { try { return fs.statSync(d).isDirectory() ? fs.realpathSync(d) : ''; } catch { return ''; } };
40
41
  let names = []; try { names = fs.readdirSync(home).filter((n) => /^\.claude[-_.][^\\/]+$/.test(n) && !/([-_.~ ](bak|bkp|backup|old|orig|copy|save|saved|prev|archive|snapshot)[\dT_.-]*| \(copy( \d+)?\)| \d+|[-_.]\d{6,}[\dT_.-]*|~)$/i.test(n) && ['.claude.json', '.config.json', '.claude-custom-oauth.json'].some((j) => isFile(path.join(home, n, j)))).sort(); } catch {}
41
42
  const extra = EXTRA_HOMES.split(path.delimiter).map((d) => d.trim()).filter(Boolean).map((d) => path.resolve(d.replace(/^~(?=$|[\\/])/, home)));
42
- const list = [CLAUDE_HOME], seen = new Set([real(path.join(CLAUDE_HOME, 'projects')) || path.join(CLAUDE_HOME, 'projects')]);
43
- for (const d of [path.join(home, '.claude'), ...names.map((n) => path.join(home, n)), ...extra]) { const r = real(path.join(d, 'projects')); if (r && !seen.has(r)) { seen.add(r); list.push(d); } }
44
- homesMemo = { at: now, list }; return list;
43
+ const list = [CLAUDE_HOME], seen = new Set([real(path.join(CLAUDE_HOME, 'projects')) || path.join(CLAUDE_HOME, 'projects')]), twins = [], seenS = new Set([real(path.join(CLAUDE_HOME, 'sessions')) || path.join(CLAUDE_HOME, 'sessions')]);
44
+ for (const d of [path.join(home, '.claude'), ...names.map((n) => path.join(home, n)), ...extra]) { const r = real(path.join(d, 'projects')), s = real(path.join(d, 'sessions')); if (r && !seen.has(r)) { seen.add(r); list.push(d); if (s) seenS.add(s); } else if (r && s && !seenS.has(s)) { seenS.add(s); twins.push(d); } } // a twin: its projects folder is a link to one already read (claude --resume works from both logins), its sessions folder its own
45
+ homesMemo = { at: now, list, twins }; return list;
45
46
  }
47
+ function twinHomes() { claudeHomes(); return homesMemo.twins || []; } // the twins of the last look: their sessions folders are read for status, their projects never twice
46
48
  const projRoots = () => { const h = claudeHomes(); return h.length < 2 ? [ROOT] : h.map((d) => path.join(d, 'projects')); }; // one folder, as most people have: exactly the one read before
47
49
  const PUBLIC = path.join(__dirname, 'public');
48
50
  // Cowork, a tab of the Claude desktop app, keeps each of its sessions in the app's own folder, in the format of Claude Code: <folder>/<account>/<organisation>/<session>/.claude/projects/<project>/<id>.jsonl.
@@ -213,6 +215,7 @@ const toolLabel = (b, ts) => {
213
215
  const outs = i.files.map((f) => (typeof f === 'string' ? f : f && f.file_path)).filter((f) => typeof f === 'string' && path.isAbsolute(f) && f.length <= 400).slice(0, 16);
214
216
  out.d = { kind: 'text', what: 'mcp', v: 'cowork · present_files', text: clip(outs.map((f) => path.basename(f)).join('\n'), 400), ...(outs.length ? { outs } : {}) }; break;
215
217
  }
218
+ { const lv = boards.liveCall(b.name, i); if (lv && lv.op === 'write') { out.d = { kind: 'artifact', file: '', title: '', note: '', live: lv.kind, key: clip(lv.key, 200) }; break; } } // a write to a Claude Whiteboard (its store) or a Claude Sheet (its cells): the call shows the board or the Sheet as that write left it (see liveNote)
216
219
  if (mcp && /(^|_)Claude_Docs$/.test(mcp[1] || '') && mcp[2] === 'batch' && i.container && i.container.create && typeof i.container.create.name === 'string') { out.d = { kind: 'artifact', file: '', title: clip(i.container.create.name, 120), note: '', doc: 1 }; break; } // a doc of the Claude Docs connector being born (its later edits are calls like any other)
217
220
  out.d = mcp ? { kind: 'text', what: 'mcp', v: (mcp[1] || '') + ' · ' + (mcp.slice(2).join('__') || ''), text: clip(JSON.stringify(i), 400) } : { kind: 'text', text: clip(JSON.stringify(i), 300) };
218
221
  }
@@ -230,12 +233,19 @@ const artifactOf = (u) => (u && typeof u === 'object' && typeof u.url === 'strin
230
233
  // What a call that put an artifact in front of the person answered, for the line of files: a publish (above); a doc the Claude Docs connector created, whose answer names the doc and its address;
231
234
  // an artifact opened on the person's screen, only when this session did not publish or create it already (the same artifact under its other address would show twice, and an open would take the place of the publish that has the preview).
232
235
  const DOC_ID = /"created":\{[^{}]*"minted":"([\w-]{6,80})"/, DOC_URL = /"frame":\{[^{}]*"url":"(https:\/\/claude\.ai\/(?:code\/)?artifact\/[\w-]{6,80})"/;
233
- function artOf(st, how, u, text) {
236
+ function artOf(st, how, u, text, tid) {
234
237
  const seen = (st.artIds = st.artIds || new Set()), note = (id, url) => { if (id) seen.add('id ' + id); seen.add('url ' + url); }; // known by its id and by its address: a publish may answer without an id
238
+ if (how === 'peek') { const m = SHEET_FRAME.exec(text); if (m && ART_URL.test(m[2])) (st.sheetUrl = st.sheetUrl || new Map()).set(m[1], m[2]); return null; } // a read of a Sheet names its address: a Sheet made in another session can be shown too
239
+ if (how === 'live') { const d = st.lives && st.lives.get(tid); if (!d) return null; const url = d.live === 'board' ? d.key : (st.sheetUrl && st.sheetUrl.get(d.key)) || ''; if (!ART_URL.test(url) || (st.plainArt && st.plainArt.has(url)) || (d.live === 'sheet' && !/"data":\{"revision":\d+/.test(text))) return null; return { url, title: (st.artT && st.artT.get(url)) || '', typed: 1, live: d.live }; } // a write that went through: a new version of that board or Sheet
235
240
  if (how === 'doc') { const id = DOC_ID.exec(text), m = DOC_URL.exec(text); if (!id || !m || !ART_URL.test(m[1])) return null; note(id[1], m[1]); return { url: m[1], title: '', typed: 1 }; }
236
241
  const a = artifactOf(u), id = a && typeof u.artifact_id === 'string' ? u.artifact_id : ''; if (!a) return null;
237
242
  if (how === 'open') { if ((id && seen.has('id ' + id)) || seen.has('url ' + a.url)) return null; note(id, a.url); return { ...a, typed: 1 }; } // opened, not made here: the window gives its title and its link
238
- note(id, a.url); return a;
243
+ note(id, a.url); (st.artT = st.artT || new Map()).set(a.url, a.title); if (!a.typed) (st.plainArt = st.plainArt || new Set()).add(a.url); /* a page this session published from its own file: its database writes are its own, not a board's */ const sp = SHEET_MADE.exec(text); if (sp) (st.sheetUrl = st.sheetUrl || new Map()).set(sp[1], a.url); return a; // its title, for the writes that fill it; a Sheet: the Claude Docs project that holds its cells
244
+ }
245
+ const SHEET_MADE = /Claude Docs document \(project "([\w-]{6,80})"\)/, SHEET_FRAME = /"frame":\{"slug":"([\w-]{6,80})","url":"(https:\/\/claude\.ai\/(?:code\/)?artifact\/[\w-]{6,80})"/;
246
+ function liveNote(st, b, tool) { // a write to a board or a Sheet is looked up when its answer comes (artOf, 'live'); a read of a Sheet tells its address ('peek')
247
+ const d = tool.d; if (d && d.live) { (st.lives = st.lives || new Map()).set(b.id, d); const url = d.live === 'board' ? d.key : (st.sheetUrl && st.sheetUrl.get(d.key)) || ''; d.title = (st.artT && st.artT.get(url)) || ''; return; }
248
+ if (/^mcp__.+Claude_Docs__read$/.test(b.name || '')) (st.pubs = st.pubs || new Map()).set(b.id, 'peek');
239
249
  }
240
250
  const resultText = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => x.text || '').join('\n') : '');
241
251
  // The colours and cursor moves of a terminal (ANSI escape codes) are taken out of what a tool printed: the page shows text. clipOut: clip for an output, taking them out of the part it keeps.
@@ -478,9 +488,9 @@ function listSessions() {
478
488
  if (Date.now() - sessionsMemo.at < 2000) return sessionsMemo.rows;
479
489
  const out = listSessions0(); sessionsMemo = { at: Date.now(), rows: out }; return out;
480
490
  }
481
- function listSessions0() {
491
+ function listSessions0(since) { // since: every session written since then, however many (the day report), instead of the most recent ones
482
492
  const rows = [];
483
- for (const m of SOURCES) for (const r of guard(() => m.sessions(30), [])) rows.push({ proj: m.PROJ, id: r.id, mtime: r.mtime, size: r.size, agents: guard(() => (m.subCount ? m.subCount(r.id) : m.subFiles ? m.subFiles(r.id).length : 0), 0), cx: r, src: m });
493
+ for (const m of SOURCES) for (const r of guard(() => m.sessions(since != null ? 2000 : 30), [])) rows.push({ proj: m.PROJ, id: r.id, mtime: r.mtime, size: r.size, agents: guard(() => (m.subCount ? m.subCount(r.id) : m.subFiles ? m.subFiles(r.id).length : 0), 0), cx: r, src: m });
484
494
  for (const proj of projects()) {
485
495
  for (const { id, file } of transcripts(proj)) {
486
496
  let st; try { st = fs.statSync(file); } catch { continue; } // a link to a transcript that is gone
@@ -488,7 +498,7 @@ function listSessions0() {
488
498
  }
489
499
  }
490
500
  rows.sort((a, b) => b.mtime - a.mtime);
491
- const own = (r) => !r.cx && r.proj !== COWORK, top = rows.filter(own).slice(0, 60).concat(rows.filter((r) => r.cx), rows.filter((r) => r.proj === COWORK).slice(0, 30)).sort((a, b) => b.mtime - a.mtime); // the 60 most recent Claude Code sessions as always, and up to 30 of each other tool beside them, Cowork included: none pushes another out
501
+ const own = (r) => !r.cx && r.proj !== COWORK, top = since != null ? rows.filter((r) => r.mtime >= since) : rows.filter(own).slice(0, 60).concat(rows.filter((r) => r.cx), rows.filter((r) => r.proj === COWORK).slice(0, 30)).sort((a, b) => b.mtime - a.mtime); // the 60 most recent Claude Code sessions as always, and up to 30 of each other tool beside them, Cowork included: none pushes another out
492
502
  for (const r of top) {
493
503
  if (r.cx) { const c = r.cx, m = r.src; delete r.cx; delete r.src; r.title = guard(() => m.title(c), '') || r.id; r.project = guard(() => m.projectLabel(c.cwd), '') || m.SOURCE; r.source = m.SOURCE; continue; }
494
504
  // titles come from the cached tail read (custom title, then AI title, then first prompt): no whole-file reads
@@ -578,7 +588,7 @@ const PR_URL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+$/; // noth
578
588
  const askOf = (b) => { const q = b.name === 'AskUserQuestion' && b.input && Array.isArray(b.input.questions) && b.input.questions[0] && b.input.questions[0].question; return typeof q === 'string' ? clip(q.trim(), 200) : ''; }; // the question a session stopped on, for its card
579
589
  const callOf = (b) => { const i = b.input || {}, v = b.name === 'Bash' ? i.command : /^(Edit|Write|MultiEdit|NotebookEdit)$/.test(b.name) ? path.basename(String(i.file_path || i.notebook_path || '')) : b.name === 'WebFetch' ? i.url : ''; return typeof v === 'string' && v.trim() ? b.name + '(' + clip(v.replace(/\s+/g, ' ').trim(), 160) + ')' : ''; }; // what a call waiting for your go-ahead would do, written the way Claude Code shows it: Bash(npm test)
580
590
  const PLAN_FILE = /[\\/]\.claude[\\/]plans[\\/][^\\/]+\.md$/, PLAN_DIR = process.env.CLAUDE_CONFIG_DIR ? path.join(process.env.CLAUDE_CONFIG_DIR, 'plans') + path.sep : '';
581
- const planFile = (f) => PLAN_FILE.test(f) || (!!PLAN_DIR && f.startsWith(PLAN_DIR) && f.endsWith('.md')) || (f.endsWith('.md') && claudeHomes().slice(1).some((h) => f.startsWith(path.join(h, 'plans') + path.sep))); // also where a CLAUDE_CONFIG_DIR set elsewhere keeps them, and the other folders read (claudeHomes)
591
+ const planFile = (f) => PLAN_FILE.test(f) || (!!PLAN_DIR && f.startsWith(PLAN_DIR) && f.endsWith('.md')) || (f.endsWith('.md') && claudeHomes().slice(1).concat(twinHomes()).some((h) => f.startsWith(path.join(h, 'plans') + path.sep))); // also where a CLAUDE_CONFIG_DIR set elsewhere keeps them, and the other folders read (claudeHomes, and their twins)
582
592
  const planDoc = (f) => { try { const st = fs.statSync(f); if (!st.isFile() || st.size > 262144) return ''; return clip(fs.readFileSync(f, 'utf8').trim(), 4000); } catch { return ''; } }; // the whole plan, for the shared screen
583
593
  const planText = (f) => { try { const st = fs.statSync(f); if (!st.isFile() || st.size > 262144) return ''; return clip(fs.readFileSync(f, 'utf8').trim(), 1200); } catch { return ''; } };
584
594
  const menuOf = (b) => { // what a menu waiting for you shows, from the call it waits on, word for word: the questions and their options in their order (the terminal numbers them the same way), the command, the file, the plan
@@ -593,7 +603,7 @@ const menuOf = (b) => { // what a menu waiting for you shows, from the call it
593
603
  // Claude Code also keeps <config>/sessions/<pid>.json for each open session: its status (busy, idle, or waiting while a menu waits for your answer: a permission, a question) and since when.
594
604
  // It is the only sign of a Bash approval: in the transcript, a command waiting for your go-ahead looks just like one that runs. A file whose process has ended is left out.
595
605
  const CC_SESSIONS = process.env.AGENT_STANDUP_CC_SESSIONS || path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'sessions'), CC_SESSIONS_SET = !!process.env.AGENT_STANDUP_CC_SESSIONS;
596
- const statusDirs = () => { const h = CC_SESSIONS_SET ? [] : claudeHomes(); return h.length < 2 ? [CC_SESSIONS] : h.map((d) => path.join(d, 'sessions')); }; // each folder read keeps the status of its own sessions
606
+ const statusDirs = () => { const h = CC_SESSIONS_SET ? [] : claudeHomes().concat(twinHomes()); return h.length < 2 ? [CC_SESSIONS] : h.map((d) => path.join(d, 'sessions')); }; // each folder read keeps the status of its own sessions
597
607
  const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
598
608
  function liveStatus() { // session id → { status, since, pid, ep (where it runs: claude-vscode, cli, claude-desktop, sdk-cli…), and for missingTranscripts: raw (the status as written), cwd, kind, startedAt, version, updatedAt (when the file was last written: a /clear moves it, and the id, but not statusUpdatedAt) }
599
609
  const out = new Map(), later = (a, b) => Math.max(a.updatedAt, a.since) > Math.max(b.updatedAt, b.since);
@@ -1049,7 +1059,7 @@ function parseRecord(st, r) {
1049
1059
  const one = blocks(r).filter((b) => b.type === 'tool_result').length === 1; // what Claude Code noted about the call (toolUseResult) is that call's when the record answers one call
1050
1060
  if (one && st.plans && r.toolUseResult && typeof r.toolUseResult.plan === 'string' && r.toolUseResult.plan.trim()) for (const b of blocks(r)) if (b.type === 'tool_result' && st.plans.has(b.tool_use_id)) st.plans.get(b.tool_use_id).d.text = clip(r.toolUseResult.plan.trim(), 4000); // the answer names the plan exactly: the plan file holds only the latest one
1051
1061
  for (const b of blocks(r)) if (b.type === 'tool_result' && st.toolName[b.tool_use_id] && !NO_RESULT.has(st.toolName[b.tool_use_id])) {
1052
- const n = st.toolName[b.tool_use_id], text = resultText(b.content), img = resultImages(b.content).length, files = n === 'Bash' && !b.is_error ? docPaths(text, false).map((f) => absPath(f, r.cwd)) : [], art = !b.is_error && st.pubs && st.pubs.has(b.tool_use_id) ? artOf(st, st.pubs.get(b.tool_use_id), r.toolUseResult, text) : null;
1062
+ const n = st.toolName[b.tool_use_id], text = resultText(b.content), img = resultImages(b.content).length, files = n === 'Bash' && !b.is_error ? docPaths(text, false).map((f) => absPath(f, r.cwd)) : [], art = !b.is_error && st.pubs && st.pubs.has(b.tool_use_id) ? artOf(st, st.pubs.get(b.tool_use_id), r.toolUseResult, text, b.tool_use_id) : null;
1053
1063
  items.push({ id: b.tool_use_id, err: !!b.is_error, out: clipOut(text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trimEnd(), RESULT_MAX[n] || (/^mcp__/.test(n) ? 900 : 600)), ...(img ? { img } : {}), ...(files.length ? { files } : {}), ...(art ? { art } : {}), ...(BROWSER_MCP.test(n) && !b.is_error ? browserSeen(text, n) : {}), ...resultMore(n, text, one ? r.toolUseResult : null) }); // img: how many pictures came back; the page fetches them from /api/media · files: the documents a command says it made
1054
1064
  }
1055
1065
  if (items.length) push({ ts, agent, kind: 'results', items });
@@ -1074,7 +1084,7 @@ function parseRecord(st, r) {
1074
1084
  else if (b.type === 'tool_use') {
1075
1085
  st.toolName[b.id] = b.name; if (b.name === 'TaskCreate') st.tasks = 1; (st.out = st.out || new Set()).add(b.id); if (b.input && b.input.run_in_background) (st.bg = st.bg || {})[b.id] = true; // out: the calls that have no answer yet
1076
1086
  if (b.name === 'Agent' || b.name === 'Task') push({ ts, agent, kind: 'agentcall', toolId: b.id, bg: !!(b.input && b.input.run_in_background), text: (b.input && b.input.prompt) || '', title: (b.input && b.input.description) || '', ...(b.input && typeof b.input.name === 'string' && b.input.name.trim() ? { nm: b.input.name.trim() } : {}) });
1077
- else { const tool = toolLabel(b, ts); if (tool.d && tool.d.outs) tool.d.outs = tool.d.outs.map((f) => absPath(f, r.cwd)); if (/^(Write|Edit|MultiEdit)$/.test(b.name) && b.input && planFile(String(b.input.file_path || ''))) { st.planF = String(b.input.file_path); st.planW = b.name === 'Write' && typeof b.input.content === 'string' ? { mid: m.id, text: clip(b.input.content.trim(), 4000) } : null; } if (tool.d && tool.d.kind === 'plan') { (st.plans = st.plans || new Map()).set(b.id, tool); if (st.planW && st.planW.mid && st.planW.mid === m.id) tool.d.text = st.planW.text; else if (!tool.d.text && st.planF) tool.d.text = (st.planW && st.planW.text) || planDoc(st.planF); } /* a plan written in the same message as its call: the call carries the one before, or none */ /* Claude Code 2.1.30x sends ExitPlanMode with no plan: the plan is the file the session just wrote in ~/.claude/plans */ if (tool.d && tool.d.kind === 'artifact') (st.pubs = st.pubs || new Map()).set(b.id, tool.d.open ? 'open' : tool.d.doc ? 'doc' : 'pub'); push({ ts, agent, kind: 'tool', tool, ...th() }); st.act = st.raw.length - 1; }
1087
+ else { const tool = toolLabel(b, ts); if (tool.d && tool.d.outs) tool.d.outs = tool.d.outs.map((f) => absPath(f, r.cwd)); if (/^(Write|Edit|MultiEdit)$/.test(b.name) && b.input && planFile(String(b.input.file_path || ''))) { st.planF = String(b.input.file_path); st.planW = b.name === 'Write' && typeof b.input.content === 'string' ? { mid: m.id, text: clip(b.input.content.trim(), 4000) } : null; } if (tool.d && tool.d.kind === 'plan') { (st.plans = st.plans || new Map()).set(b.id, tool); if (st.planW && st.planW.mid && st.planW.mid === m.id) tool.d.text = st.planW.text; else if (!tool.d.text && st.planF) tool.d.text = (st.planW && st.planW.text) || planDoc(st.planF); } /* a plan written in the same message as its call: the call carries the one before, or none */ /* Claude Code 2.1.30x sends ExitPlanMode with no plan: the plan is the file the session just wrote in ~/.claude/plans */ liveNote(st, b, tool); if (tool.d && tool.d.kind === 'artifact') (st.pubs = st.pubs || new Map()).set(b.id, tool.d.open ? 'open' : tool.d.doc ? 'doc' : tool.d.live ? 'live' : 'pub'); push({ ts, agent, kind: 'tool', tool, ...th() }); st.act = st.raw.length - 1; }
1078
1088
  }
1079
1089
  }
1080
1090
  if (agent === 'main' && (m.stop_reason === 'end_turn' || ((r.isApiErrorMessage || (m.model === '<synthetic>' && m.stop_reason === 'stop_sequence')) && !(st.out && st.out.size)))) { // also a turn that ends on a message Claude Code writes itself, in the place of the model's: the API is down, the limit is reached, the request was refused, or there was nothing to answer. Nothing follows it, unless a call of the lead is still out: the connection dropped while its agents worked, and it goes on when they answer. (A message of the model that a safety check cuts is not the end either: Claude Code tells the model, which goes on.) The lead's turn is over: Claude Code writes one record per content block, each with the message's stop reason, so the mark goes on the line this record carries (a thinking block carries none)
@@ -1585,7 +1595,7 @@ function start(port = PORT) {
1585
1595
  if (url.pathname === '/api/artifact') { // the page a publish of this session sent, for the frame of the shared screen · check=1: is there one, and does it name libraries (asked before the frame is drawn) · whole=1: the whole document
1586
1596
  const q = (k) => url.searchParams.get(k) || '', SAFE = /^[\w.\-]+$/, bad = [q('proj'), q('id'), q('agent'), q('tool')].some((v) => !SAFE.test(v) || v === '..' || v.length > 200) || q('tool').length < 6;
1587
1597
  if (bad) { res.writeHead(400); return res.end('bad request'); }
1588
- const file = sourceOf(q('proj')) ? null : mediaFile(q('proj'), q('id'), q('agent')), plan = file && fs.existsSync(file) && fs.existsSync(mediaFile(q('proj'), q('id'), 'main')) ? artifactPlan(q('proj'), q('id'), q('agent'), q('tool')) : null, page = plan && artifactBuild(file, q('tool'), plan, q('whole') === '1');
1598
+ const file = sourceOf(q('proj')) ? null : mediaFile(q('proj'), q('id'), q('agent')), plan = file && fs.existsSync(file) && fs.existsSync(mediaFile(q('proj'), q('id'), 'main')) ? artifactPlan(q('proj'), q('id'), q('agent'), q('tool')) : null, page = plan ? artifactBuild(file, q('tool'), plan, q('whole') === '1') : file && fs.existsSync(file) ? guard(() => boards.livePage(file, q('tool')), null) : null; // no page sent: a write to a board or a Sheet, drawn again from the session's writes
1589
1599
  if (q('check')) return json(page ? { ok: true, net: page.net, ...(page.pages > 1 ? { pages: page.pages, label: page.label } : {}) } : { ok: false }, page ? 200 : 404); // pages: a document of several pages, which can be shown whole (whole=1)
1590
1600
  if (!page) { res.writeHead(404); return res.end('not found'); }
1591
1601
  const body = Buffer.from((/^\s*<!doctype/i.test(page.html) ? '' : '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">') + page.html, 'utf8'); // an artifact is published as the inside of a page: claude.ai adds the rest, and so does this
@@ -1632,7 +1642,7 @@ function start(port = PORT) {
1632
1642
  } catch (e) { logError(req.method + ' ' + url.pathname, e); if (res.headersSent) return res.destroy(); json({ error: String(e.message || e) }, 500); }
1633
1643
  }).listen(port, '127.0.0.1', function () { console.log(`Agent Standup → http://localhost:${this.address().port}`); });
1634
1644
  }
1635
- module.exports = { answerIn, missingTranscripts, noteEditor, forgetEditor, _winArg: winArg, start, currentSession, shutdown, findClaude, bundledClaude, boardRows, transcriptFile: (proj, id) => path.join(projDir(proj, id), id + '.jsonl'), sessionRows: listSessions, charactersDir, listCharacters, packsDir, installPack, logError, updateInfo, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
1645
+ module.exports = { answerIn, missingTranscripts, noteEditor, forgetEditor, _winArg: winArg, start, currentSession, shutdown, findClaude, bundledClaude, boardRows, timeline: (proj, id) => timelineEntry(proj, id).tl, transcriptFile: (proj, id) => path.join(projDir(proj, id), id + '.jsonl'), sessionRows: listSessions, sessionsSince: (t) => listSessions0(+t || 0), codexPending: () => guard(() => !!(codex.zPending && codex.zPending()), false), charactersDir, listCharacters, packsDir, installPack, logError, updateInfo, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
1636
1646
  if (require.main === module && process.env.AGENT_STANDUP_CHILD === '1' && typeof process.send === 'function') { // started by the VS Code extension in a process of its own (see extension.js): reading a large session no longer stops the editor's extensions. Asked for by name: pm2 and others give any app a channel too
1637
1647
  const srv = start(+process.env.PORT || 0), tell = (m) => { try { process.send(m); } catch {} };
1638
1648
  srv.on('listening', () => tell({ port: srv.address().port })).on('error', (e) => { tell({ error: e.code || String(e) }); process.exit(1); });