@double_geste/agent-standup 1.40.0 → 1.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.js CHANGED
@@ -42,10 +42,17 @@ function coworkMap() { // session id → the folder its transcript is in; look
42
42
  }
43
43
  coworkMemo = { at: now, key, map }; return map;
44
44
  }
45
- const coworkNotes = new Map(); // note file → { sig, title }
45
+ const coworkNotes = new Map(), coworkNoteOf = new Map(); // note file → { sig, title }; session folder → { f: its note in the newer layout, at: when looked for }
46
+ function coworkNote(s, id) { // the note of the session folder s: <s>.json, or in the newer layout (a folder named after the start of the session's own id) local_<s>-….json beside it, the one that names this transcript when there are several
47
+ if (mtimeOf(s + '.json')) return s + '.json';
48
+ const c = coworkNoteOf.get(s); if (c && (c.f ? mtimeOf(c.f) : Date.now() - c.at < 10e3)) return c.f; // a folder without a note is looked at again after 10 s, not at every scan
49
+ const parent = path.dirname(s), pre = 'local_' + path.basename(s) + '-'; let names = []; try { names = fs.readdirSync(parent).filter((n) => n.startsWith(pre) && n.endsWith('.json')).map((n) => path.join(parent, n)); } catch {}
50
+ const f = names.length === 1 ? names[0] : names.find((p) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')).cliSessionId === id; } catch { return false; } }) || '';
51
+ coworkNoteOf.set(s, { f, at: Date.now() }); return f;
52
+ }
46
53
  function coworkTitle(proj, id) { // the name the desktop app gave the session, the one its own list shows: kept in a note beside the session's folder, of which the title alone is taken
47
54
  const dir = proj === COWORK && coworkMap().get(id); if (!dir) return '';
48
- const f = path.resolve(dir, '..', '..', '..') + '.json'; let st; try { st = fs.statSync(f); } catch { return ''; }
55
+ const f = coworkNote(path.resolve(dir, '..', '..', '..'), id); let st; try { st = fs.statSync(f); } catch { return ''; }
49
56
  const sig = st.mtimeMs + ':' + st.size, c = coworkNotes.get(f); if (c && c.sig === sig) return c.title;
50
57
  let title = ''; try { const j = JSON.parse(fs.readFileSync(f, 'utf8')); if (typeof j.title === 'string') title = j.title.trim().slice(0, 200); } catch {}
51
58
  coworkNotes.set(f, { sig, title }); return title;
@@ -93,9 +100,17 @@ function docPaths(text, cd) {
93
100
  const absPath = (f, cwd) => (/^~([\\/]|$)/.test(f) ? path.join(os.homedir(), f.slice(1)) : path.isAbsolute(f) ? path.normalize(f) : cwd ? path.resolve(cwd, f) : f); // cwd: the folder the session was in when it wrote that record
94
101
  // A call that drives a browser (Claude in Chrome, written claude-in-chrome by Claude Code and Claude_in_Chrome by the desktop app; the desktop app's own browser): its steps (one, or those of a browser_batch, in order), for the browser window of the shared screen.
95
102
  // a: what it did · x, y: where it clicked, in the frame of the page's screenshots · t: what it typed or the key it pressed · u: the address it went to · q: what it looked for · n: its own one-line account of the step
96
- const BROWSER_MCP = /^mcp__(?:[^_]+__)?(claude-in-chrome|Claude_in_Chrome|Claude_Browser)__/;
103
+ // Claude Preview (the desktop app's preview of a local server, mcp__Claude_Preview__preview_*, also offered by its browser) is one too: its steps are named after the tool, without "preview_" (start, eval, resize, screenshot, logs, stop…).
104
+ const BROWSER_MCP = /^mcp__(?:[^_]+__)?(claude-in-chrome|Claude_in_Chrome|Claude_Browser|Claude_Preview)__/;
105
+ const previewStep = (name, i) => {
106
+ const a = name.slice(8) === 'console_logs' ? 'logs' : name.slice(8, 38), s = { a };
107
+ if (a === 'eval' && typeof i.expression === 'string') s.q = clip(i.expression, 120); if (typeof i.url === 'string') s.u = clip(i.url, 300); // the page a start names, as 1.40 showed it
108
+ if (a === 'resize') { if (Number.isFinite(+i.width) && Number.isFinite(+i.height) && i.width != null && i.height != null) { s.w = +i.width; s.h = +i.height; } else if (typeof i.preset === 'string') s.preset = clip(i.preset, 30); } // a size, or one of its presets (desktop, mobile…)
109
+ return s;
110
+ };
97
111
  const browserStep = (name, i) => {
98
- i = i && typeof i === 'object' ? i : {}; const s = { a: String(i.action || name || '').slice(0, 30) }, c = Array.isArray(i.coordinate) ? i.coordinate : null;
112
+ i = i && typeof i === 'object' ? i : {}; if (!i.action && /^preview_/.test(name || '')) return previewStep(name, i);
113
+ const s = { a: String(i.action || name || '').slice(0, 30) }, c = Array.isArray(i.coordinate) ? i.coordinate : null;
99
114
  if (c && Number.isFinite(+c[0]) && Number.isFinite(+c[1])) { s.x = +c[0]; s.y = +c[1]; }
100
115
  if (typeof i.url === 'string') s.u = clip(i.url, 300); if (typeof i.text === 'string' && /type|key/.test(s.a)) s.t = clip(i.text, 80); if (typeof i.query === 'string') s.q = clip(i.query, 120); if (typeof i.action_summary === 'string') s.n = clip(i.action_summary, 140);
101
116
  return s;
@@ -103,12 +118,19 @@ const browserStep = (name, i) => {
103
118
  const browserLabel = (name, i) => ({ kind: 'browser', steps: (Array.isArray(i.actions) ? i.actions.slice(-12).map((x) => browserStep(x && x.name, x && x.input)) : [browserStep(name, i)]) });
104
119
  // What a browser call answered about the page: its address and title, the frame its clicks are counted in (a screenshot at half scale is still clicked in full-size coordinates),
105
120
  // and p: where its last click landed, which the desktop app's browser says when the agent named an element instead of a point ("left_click at (628, 441) [ref_112]"). Its tabs have names ("seed"), not numbers; the desktop app's Chrome writes a tab's address without quotes
106
- function browserSeen(text) {
121
+ // A preview's answers say other things: the port of the server it started (u), the size it gave the page (f), and the last lines of the page's console or of the server's log (log, [] when there are none), shown under the page.
122
+ function previewSeen(tool, text, web) {
123
+ if (tool === 'preview_start') { const m = /"port":\s*(\d{2,5})\b/.exec(text); if (m) web.u = 'http://localhost:' + m[1]; }
124
+ else if (tool === 'preview_resize') { const m = /\b(\d{2,5}) ?x ?(\d{2,5})\b/.exec(text); if (m && +m[1] > 0 && +m[2] > 0) web.f = [+m[1], +m[2]]; }
125
+ else if (tool === 'preview_console_logs' || tool === 'preview_logs') { const lines = noAnsi(text.slice(-64000)).split('\n').map((l) => l.trimEnd()).filter((l) => l.trim()); web.log = lines.length === 1 && /^No\b.*\.$/.test(lines[0]) ? [] : lines.slice(-12).map((l) => clip(l, 200)); } // "No console logs."
126
+ }
127
+ function browserSeen(text, name) {
107
128
  const all = (re) => [...text.matchAll(re)].pop(), web = {}, tab = (text.match(/Executed on tabId: ([\w-]+)/) || [])[1], row = tab && all(new RegExp(`tabId ${tab}: "(.*)" \\("?([^"\\s]*?)"?\\)\\s*$`, 'gm'));
108
129
  const u = all(/(?:[Nn]avigated to|URL:) *(\S+)/g), t = all(/^Title: *(.+)$/gm), f = all(/coordinate frame: *(\d+)x(\d+)/g) || all(/captured screenshot \((\d+)x(\d+)/g) || all(/Screenshot size: *(\d+)x(\d+)/g), p = all(/\b(?:left_click|right_click|double_click|triple_click|hover) at \((\d+), *(\d+)\)/g);
109
130
  const url = (u && u[1]) || (row && row[2]) || ''; if (/^(https?|file|chrome|about):/i.test(url)) web.u = clip(url, 300);
110
131
  const title = (t && t[1]) || (row && row[1] !== row[2] && row[1]) || ''; if (title) web.t = clip(title.trim(), 120);
111
132
  if (f && +f[1] > 0 && +f[2] > 0) web.f = [+f[1], +f[2]]; if (p) web.p = [+p[1], +p[2]];
133
+ const tool = String(name || '').split('__').pop(); if (/^preview_/.test(tool)) previewSeen(tool, text, web);
112
134
  return Object.keys(web).length ? { web } : {};
113
135
  }
114
136
  // What each tool call looks like on a screen ("d"), plus its id/timestamp so the result can be matched later.
@@ -125,6 +147,9 @@ const toolLabel = (b, ts) => {
125
147
  case 'Grep': out.d = { kind: 'grep', pattern: clip(i.pattern, 100), path: i.path, glob: i.glob }; break;
126
148
  case 'Glob': out.d = { kind: 'glob', pattern: clip(i.pattern, 100), path: i.path }; break;
127
149
  case 'TodoWrite': out.d = { kind: 'todo', items: (i.todos || []).slice(0, 20).map((x) => ({ c: clip(x.content, 120), s: x.status })) }; break;
150
+ case 'TaskCreate': out.d = { kind: 'task', op: 'create', subject: clip(i.subject, 120), active: clip(i.activeForm, 120) }; if (typeof i.subject === 'string') out.arg = i.subject.slice(0, 90); break; // the task list of Claude Code 2.1.200 on, one call per task (TaskStop and TaskOutput are about background commands: calls like any other)
151
+ case 'TaskUpdate': out.d = { kind: 'task', op: 'update', taskId: clip(i.taskId, 40), ...(typeof i.status === 'string' ? { status: i.status.slice(0, 20) } : {}), ...(typeof i.subject === 'string' ? { subject: clip(i.subject, 120) } : {}) }; break;
152
+ case 'ExitPlanMode': out.d = { kind: 'plan', text: clip(i.plan, 4000) }; break;
128
153
  case 'WebFetch': out.d = { kind: 'web', url: i.url }; break;
129
154
  case 'WebSearch': out.d = { kind: 'web', query: i.query }; break;
130
155
  case 'NotebookEdit': out.d = { kind: 'edit', file: i.notebook_path, old: '', new: clip(i.new_source, 500) }; break;
@@ -135,6 +160,12 @@ const toolLabel = (b, ts) => {
135
160
  if (i.action === 'open') { out.d = { kind: 'artifact', file: '', title: '', note: '', open: 1 }; break; } // a page put on the person's screen: in the line of files when this session did not make it (see artOf)
136
161
  // falls through
137
162
  default: if (BROWSER_MCP.test(b.name)) { out.d = browserLabel(mcp[mcp.length - 1], i); const s = out.d.steps[out.d.steps.length - 1]; if (s) out.arg = String(s.n || s.u || s.q || s.a).slice(0, 90); break; }
163
+ if ((b.name === 'mcp__workspace__bash' || b.name === 'mcp__terminal__run_in_terminal') && typeof i.command === 'string') { out.d = { kind: 'cmd', text: clip(i.command, 1200), note: clip(i.title || i.description, 140) }; break; } // Cowork's commands (its sandbox, the person's own terminal): commands like Bash
164
+ if (b.name === 'mcp__workspace__web_fetch' && typeof i.url === 'string') { out.d = { kind: 'web', url: i.url }; break; }
165
+ if (b.name === 'mcp__cowork__present_files' && Array.isArray(i.files)) { // Cowork hands files to the person: the line of files shows them (outs), as the documents a command makes
166
+ 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);
167
+ 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;
168
+ }
138
169
  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)
139
170
  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) };
140
171
  }
@@ -160,6 +191,61 @@ function artOf(st, how, u, text) {
160
191
  note(id, a.url); return a;
161
192
  }
162
193
  const resultText = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => x.text || '').join('\n') : '');
194
+ // 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.
195
+ const ANSI = /\x1b\[[0-?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]|\x1b/g; // and an escape left alone (a sequence cut short, bytes that are not text)
196
+ const noAnsi = (s) => (s.includes('\x1b') ? s.replace(ANSI, '') : s);
197
+ const clipOut = (x, n = 700) => { const s = String(x == null ? '' : x); return noAnsi(s.length > n + 400 ? s.slice(0, n + 400) : s).slice(0, n); };
198
+ // A test run, summed up for the shared screen: its runner, how many passed, failed and were skipped, and the names of the first that failed. Only when the output has the summary line of one of
199
+ // these runners: node:test (its spec and TAP reporters), vitest, jest, pytest, mocha, go test, cargo test. Any other output, numbers and all, is not a test run.
200
+ const TESTS_SEEN = /^[ \t]*(?:ℹ (?:tests|pass|fail) \d|# (?:tests|pass|fail) \d|Tests:? +\d|=+ [^\n]{0,300}?\b(?:passed|failed|errors?|skipped|no tests ran)\b[^\n]{0,300}? in [\d.]+s\b|\d+ (?:passing|failing)\b|test result: |(?:ok|FAIL)[ \t]+\S+[ \t]+(?:[\d.]+s|\(cached\))|--- FAIL: )/m;
201
+ function testsOf(text0) { // the patterns are bounded per line (300 characters): a long line of output must not hold the server
202
+ let text = String(text0 || ''); if (text.length > 400000) text = text.slice(-400000); // a summary is at the end
203
+ text = noAnsi(text); if (!TESTS_SEEN.test(text)) return null;
204
+ const all = (re, s = text) => [...s.matchAll(re)], counts = (s) => { const o = {}; for (const x of s.matchAll(/(\d+) ([a-z]+)/g)) o[x[2]] = (o[x[2]] || 0) + +x[1]; return o; }, failed = [];
205
+ const name = (s) => { s = String(s || '').trim().slice(0, 120); if (s && failed.length < 6 && !failed.includes(s)) failed.push(s); };
206
+ const out = (runner, pass, fail, skip, total) => ({ runner, pass, fail, skip, total: total || pass + fail + skip, failed });
207
+ let m = all(/^test result: \w+\. (\d+) passed; (\d+) failed; (\d+) ignored/gm); // cargo: one line per test binary
208
+ if (m.length) { for (const x of all(/^test (\S+) \.\.\. FAILED[ \t]*$/gm)) name(x[1]); const sum = (i) => m.reduce((s, x) => s + +x[i], 0); return out('cargo', sum(1), sum(2), sum(3)); }
209
+ m = all(/^=+ ([^\n=]{0,300}?\b(?:passed|failed|errors?|skipped|no tests ran)\b[^\n=]{0,300}?) in [\d.]+s\b[^\n]{0,300}?=+[ \t]*$/gm).pop(); // pytest: "=== 3 failed, 40 passed, 2 skipped in 1.2s ==="
210
+ if (m) { const c = counts(m[1]); for (const x of all(/^(?:FAILED|ERROR) (\S+)/gm)) name(x[1]); return out('pytest', (c.passed || 0) + (c.xpassed || 0), (c.failed || 0) + (c.error || 0) + (c.errors || 0), (c.skipped || 0) + (c.xfailed || 0)); }
211
+ const gp = all(/^(ok|FAIL)[ \t]+\S+[ \t]+(?:[\d.]+s|\(cached\))/gm), gt = all(/^[ \t]*--- (PASS|FAIL|SKIP): (\S+)/gm), k = (w) => gt.filter((x) => x[1] === w).length; // go test: a line per package, and one per test with -v (failures always)
212
+ if (gp.length || k('FAIL')) { for (const x of gt) if (x[1] === 'FAIL') name(x[2]); return k('PASS') ? out('go', k('PASS'), k('FAIL'), k('SKIP')) : out('go', gp.filter((x) => x[1] === 'ok').length, k('FAIL') || gp.filter((x) => x[1] === 'FAIL').length, k('SKIP')); }
213
+ m = all(/^[ \t]*Tests[ \t]{2,}(.+?)[ \t]*\((\d+)\)[ \t]*$/gm).pop(); // vitest: "Tests 3 failed | 40 passed (43)"
214
+ if (m) { const c = counts(m[1]); for (const x of all(/^[ \t]*FAIL[ \t]+(.+?)[ \t]*$/gm)) name(x[1]); for (const x of all(/^[ \t]*[×✗][ \t]+(.+?)(?:[ \t]+\d+m?s)?[ \t]*$/gm)) name(x[1]); return out('vitest', c.passed || 0, c.failed || 0, (c.skipped || 0) + (c.todo || 0), +m[2]); }
215
+ m = all(/^[ \t]*Tests:[ \t]+(.+?)[ \t]*$/gm).pop(); // jest: "Tests: 2 failed, 40 passed, 42 total"
216
+ if (m) { const c = counts(m[1]); for (const x of all(/^[ \t]*● (.+?)[ \t]*$/gm)) if (!/^(Console|Test suite failed to run)$/.test(x[1])) name(x[1]); for (const x of all(/^[ \t]*[✕×][ \t]+(.+?)(?:[ \t]+\(\d+ m?s\))?[ \t]*$/gm)) name(x[1]); return out('jest', c.passed || 0, c.failed || 0, (c.skipped || 0) + (c.todo || 0), c.total); }
217
+ const mp = /^[ \t]*(\d+) passing\b/m.exec(text), mf = /^[ \t]*(\d+) failing\b/m.exec(text), mn = /^[ \t]*(\d+) pending\b/m.exec(text); // mocha: "40 passing (2s)", "3 failing", then the failures, numbered
218
+ if (mp) { // mocha always says how many passed: a count of failures alone is some other script's
219
+ const ls = mf ? text.slice(mf.index).split('\n') : [], seen = new Set(); // a failure's title runs over several lines, its suites then the test, which ends with ":"
220
+ for (let i = 0; i < ls.length && failed.length < 6; i++) { const x = /^[ \t]*(\d+)\) (.+?)[ \t]*$/.exec(ls[i]); if (!x || seen.has(x[1])) continue; seen.add(x[1]); let t = x[2]; for (let j = i + 1; !/:$/.test(t) && j < Math.min(ls.length, i + 6) && ls[j].trim(); j++) t += ' › ' + ls[j].trim(); name(t.replace(/:$/, '')); }
221
+ return out('mocha', mp ? +mp[1] : 0, mf ? +mf[1] : 0, mn ? +mn[1] : 0);
222
+ }
223
+ m = all(/^(?:ℹ|#) (tests|pass|fail|cancelled|skipped|skip|todo) (\d+)[ \t]*$/gm); // node:test, spec reporter (ℹ) or TAP (#); a command that runs it twice prints two summaries
224
+ if (m.some((x) => x[1] === 'tests')) { const c = {}; for (const x of m) c[x[1]] = (c[x[1]] || 0) + +x[2]; for (const x of all(/^[ \t]*not ok \d+ - (.+?)(?:[ \t]+#.*)?[ \t]*$/gm)) name(x[1]); for (const x of all(/^[ \t]*✖ (.+?)(?: \([\d.]+m?s\))?[ \t]*$/gm)) if (x[1] !== 'failing tests:') name(x[1]); return out('node', c.pass || 0, (c.fail || 0) + (c.cancelled || 0), (c.skipped || 0) + (c.skip || 0), c.tests); }
225
+ return null;
226
+ }
227
+ // A change shown as a diff, from what Claude Code noted of an Edit or a Write (structuredPatch), or of a command that changed files (bashEditDiff, 2.1.283 on). At most 3 files, 4 parts of each, 40 lines a part. more: the files left out.
228
+ function diffOf(files, moreFiles) {
229
+ const fl = files.filter((f) => f && typeof f.file === 'string' && Array.isArray(f.hunks) && f.hunks.length); if (!fl.length) return null;
230
+ const out = { files: fl.slice(0, 3).map((f) => ({ file: clip(f.file, 400), hunks: f.hunks.slice(0, 4).map((h) => ({ o: +(h && h.oldStart) || 0, n: +(h && h.newStart) || 0, lines: (h && Array.isArray(h.lines) ? h.lines : []).slice(0, 40).map((l) => clip(l, 200)) })) })) };
231
+ const more = (+moreFiles > 0 ? +moreFiles : 0) + fl.length - out.files.length; if (more) out.more = more;
232
+ return out;
233
+ }
234
+ // What else a result says, for the shared screen, from its text and from what Claude Code noted about the call (u: the record's toolUseResult): tests, diff, search (the links a search found), fetch (a page read),
235
+ // task (a task created), bg (the id of a command left running in the background, whose output /api/taskout reads). The original of an edited file, which Claude Code also notes, is never kept.
236
+ const CMD_TOOL = new Set(['Bash', 'mcp__workspace__bash', 'mcp__terminal__run_in_terminal']), taskId = (v) => (typeof v === 'string' && /^[\w-]{1,40}$/.test(v) ? v : '');
237
+ function resultMore(n, text, u) {
238
+ const o = {}; if (CMD_TOOL.has(n)) { const t = testsOf(text); if (t) o.tests = t; }
239
+ if (!u || typeof u !== 'object' || Array.isArray(u)) return o;
240
+ if (n === 'Bash') { const d = u.bashEditDiff, x = d && Array.isArray(d.files) && diffOf(d.files.map((f) => ({ file: f && f.filePath, hunks: f && f.hunks })), d.moreFiles); if (x) o.diff = x; if (taskId(u.backgroundTaskId)) o.bg = u.backgroundTaskId; }
241
+ else if (n === 'Edit' || n === 'MultiEdit' || n === 'Write') { const x = Array.isArray(u.structuredPatch) && diffOf([{ file: u.filePath, hunks: u.structuredPatch }], 0); if (x) o.diff = x; }
242
+ else if (n === 'WebSearch' && Array.isArray(u.results)) { const s = []; for (const r of u.results) for (const c of r && Array.isArray(r.content) ? r.content : []) if (c && typeof c.url === 'string' && s.length < 8) s.push({ t: clip(c.title, 120), u: clip(c.url, 300) }); if (s.length) o.search = s; }
243
+ else if (n === 'WebFetch' && typeof u.url === 'string') o.fetch = { u: clip(u.url, 300), ...(Number.isFinite(u.code) ? { code: u.code } : {}), ...(Number.isFinite(u.bytes) ? { bytes: u.bytes } : {}), ...(Number.isFinite(u.durationMs) ? { ms: u.durationMs } : {}) };
244
+ else if (n === 'TaskCreate' && u.task && u.task.id != null) o.task = { id: clip(u.task.id, 40), subject: clip(u.task.subject, 120) };
245
+ else if (n === 'Monitor' && taskId(u.taskId)) o.bg = u.taskId;
246
+ else if (n === 'TaskOutput' && u.task && taskId(u.task.task_id) && !/agent/.test(String(u.task.task_type || ''))) o.bg = u.task.task_id; // a command's output asked for; a sub-agent's is its transcript
247
+ return o;
248
+ }
163
249
  // Pictures a tool returned (a screenshot, an image file that was read). They are served from the transcript itself, so nothing outside the session files is ever read, and only bitmap types are sent.
164
250
  const IMG_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']), mediaMemo = new Map();
165
251
  const isImg = (x) => !!x && x.type === 'image' && !!x.source && x.source.type === 'base64' && typeof x.source.data === 'string' && IMG_TYPES.has(x.source.media_type);
@@ -181,12 +267,12 @@ function subFiles(proj, id) {
181
267
  }
182
268
  const subFilesOf = (proj, id) => { const sx = sourceOf(proj); return sx && sx.subFiles ? guard(() => sx.subFiles(id), Object.assign([], { dirs: [], journals: [] })) : subFiles(proj, id); }; // Mistral Vibe keeps its sub-agents its own way
183
269
  function mediaFile(proj, sid, agent) {
184
- if (agent === 'main') return path.join(projDir(proj, sid), sid + '.jsonl');
270
+ if (agent === 'main' || agent === 'user') return path.join(projDir(proj, sid), sid + '.jsonl'); // user: the pictures pasted with a message, in the lead's file
185
271
  const hit = subFiles(proj, sid).find((x) => x.aid === agent);
186
272
  return hit ? hit.file : null;
187
273
  }
188
- function toolImage(file, toolId, n) { // looks for the tool's result line in the transcript, 8 MB at a time; the few pictures asked last are kept in memory
189
- const key = file + '|' + toolId + '|' + n, memo = mediaMemo.get(key); if (memo && memo.buf) return memo;
274
+ function toolImage(file, toolId, n, user) { // looks for the tool's result line in the transcript, 8 MB at a time; the few pictures asked last are kept in memory. user: toolId is the id of a message the person sent (its uuid), and the pictures are the ones pasted with it
275
+ const key = file + '|' + toolId + '|' + n + (user ? '|u' : ''), memo = mediaMemo.get(key); if (memo && memo.buf) return memo;
190
276
  const needle = Buffer.from('"' + toolId + '"'), mark = Buffer.from('"image"'), until = Date.now() + 2000; let fd, found = null, carry = Buffer.alloc(0), pos = 0, size = 0; // the id between its quotes, so a made-up one-letter id does not match on every line; and never more than 2 s of searching
191
277
  try {
192
278
  fd = fs.openSync(file, 'r'); size = fs.fstatSync(fd).size; if (memo && memo.miss === size) return null; // already searched in vain, and nothing was written since
@@ -197,6 +283,7 @@ function toolImage(file, toolId, n) { // looks for the tool's result line in t
197
283
  const a = all.lastIndexOf(10, hit) + 1, b = all.indexOf(10, hit); if (b < 0) break; // the line goes on in the next chunk
198
284
  from = b + 1; if (all.subarray(a, b).indexOf(mark) < 0) continue;
199
285
  let r; try { r = JSON.parse(all.subarray(a, b).toString('utf8')); } catch { continue; }
286
+ if (user) { const im = r.type === 'user' && r.uuid === toolId ? blocks(r).filter(isImg)[n] : null; if (im) found = { type: im.source.media_type, buf: Buffer.from(im.source.data, 'base64') }; continue; }
200
287
  for (const blk of blocks(r)) if (blk.type === 'tool_result' && blk.tool_use_id === toolId) { const im = resultImages(blk.content)[n]; if (im) found = { type: im.source.media_type, buf: Buffer.from(im.source.data, 'base64') }; }
201
288
  }
202
289
  carry = all.subarray(all.lastIndexOf(10) + 1);
@@ -205,6 +292,32 @@ function toolImage(file, toolId, n) { // looks for the tool's result line in t
205
292
  mediaMemo.delete(key); mediaMemo.set(key, found || { miss: size }); if (mediaMemo.size > 12) mediaMemo.delete(mediaMemo.keys().next().value);
206
293
  return found;
207
294
  }
295
+ // ---- A command left running in the background (Bash sent to the background, Monitor): Claude Code writes what it prints, as it comes, to <its temporary folder>/<project>/<session id>/tasks/<task id>.output,
296
+ // and ends the file with "[exited with code N]" once it stops. The shared screen shows the end of it while it runs. Only that file is read, of a session the call knows; nothing is sent anywhere.
297
+ // The temporary folder is claude-<uid> in /tmp (macOS and Linux), in the system's own (os.tmpdir) or in CLAUDE_CODE_TMPDIR. The project is found by the session's folder: a session that moved to a worktree writes under another name.
298
+ const TASKOUT_MAX = 12 * 1024;
299
+ function claudeTemps() {
300
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null, out = []; if (uid == null) return out;
301
+ for (const d of ['/tmp', os.tmpdir(), process.env.CLAUDE_CODE_TMPDIR]) { if (!d) continue; let real; try { real = fs.realpathSync(path.join(d, 'claude-' + uid)); const st = fs.statSync(real); if (st.uid !== uid || (st.mode & 0o022)) continue; } catch { continue; } if (!out.includes(real)) out.push(real); } // yours, and nobody else can write in it (a shared /tmp)
302
+ return out;
303
+ }
304
+ function taskOutput(proj, id, task) { // { text: its last whole lines (12 KB at most), done, code: its exit code once it said it, size, mtime }, or null
305
+ for (const root of claudeTemps()) {
306
+ let keys = []; try { keys = fs.readdirSync(root); } catch { continue; }
307
+ for (const key of keys.includes(proj) ? [proj, ...keys.filter((k) => k !== proj)] : keys) {
308
+ const fp = path.join(root, key, id, 'tasks', task + '.output'); let st; try { st = fs.lstatSync(fp); } catch { continue; }
309
+ if (!st.isFile()) continue; // a link (a sub-agent's output is one, to its transcript) is not followed
310
+ let buf = Buffer.alloc(0), size = st.size; const fd = fs.openSync(fp, 'r');
311
+ try { size = fs.fstatSync(fd).size; const n = Math.min(size, TASKOUT_MAX + 4096); buf = Buffer.alloc(n); fs.readSync(fd, buf, 0, n, size - n); } finally { fs.closeSync(fd); }
312
+ let text = buf.toString('utf8'); if (buf.length < size) { const nl = text.indexOf('\n'); text = nl >= 0 ? text.slice(nl + 1) : text.slice(text.lastIndexOf('\r') + 1); } // whole lines only; with no line at all, a progress bar redrawn with \r: from its last state
313
+ text = noAnsi(text).split('\n').map((l) => { l = l.replace(/\r$/, ''); const r = l.lastIndexOf('\r'); return r >= 0 ? l.slice(r + 1) : l; }).join('\n'); // a progress bar redrawn in place: its last state
314
+ const over = Buffer.byteLength(text) - TASKOUT_MAX; if (over > 0) { const b = Buffer.from(text), nl = b.indexOf(10, over); text = nl >= 0 && nl < b.length - 1 ? b.subarray(nl + 1).toString('utf8') : b.subarray(b.length - TASKOUT_MAX / 4).toString('utf8'); } // cut once, at the first whole line that fits
315
+ const m = /\[exited with code (-?\d+)\]\s*$/.exec(text);
316
+ return { text, done: !!m || Date.now() - st.mtimeMs > 10 * 60e3, code: m ? +m[1] : null, size, mtime: st.mtimeMs }; // done: it said so, or it has been silent for 10 minutes
317
+ }
318
+ }
319
+ return null;
320
+ }
208
321
  // ---- Artifacts: a page a session published on claude.ai is shown in the call, in a browser window on the shared screen. claude.ai lets no other page frame it, and the file that was published
209
322
  // is most often in a temporary folder that is emptied later: the page is put together again from the session file, which keeps in full the Write call that created it and the Edit calls that followed,
210
323
  // up to the publish that is asked for (so an old session shows each version as it was). Nothing outside the session files is read, as for the pictures. An artifact made from a type (a design) shows the page
@@ -370,7 +483,7 @@ function feedStep(prev, tl, files) {
370
483
  let f = prev && files.every((x) => { const was = prev.gens.get(x); return was === undefined || was === (fileStates.get(x) || {}).gen; }) ? prev : null; // a transcript read again from its start numbers its events again: the keys no longer mean the same thing
371
484
  for (let pass = 0; ; pass++) {
372
485
  if (!f) f = { ep: crypto.randomBytes(6).toString('hex'), seq: 0, known: new Map(), gens: new Map() };
373
- const n = tl.events.length, sq = new Uint32Array(n), seq = f.seq + 1, before = f.known.size, z = tl.events.find((e) => e.kind !== 'usage' && e.kind !== 'finish' && e.kind !== 'compact'), t0 = z ? z.ts : 0, moved = f.t0 !== t0; let hits = 0, changed = false; f.t0 = t0; // time zero moved (something now comes before the first line): every `t` is different
486
+ const n = tl.events.length, sq = new Uint32Array(n), seq = f.seq + 1, before = f.known.size, z = tl.events.find((e) => e.kind !== 'usage' && e.kind !== 'finish' && e.kind !== 'compact' && e.kind !== 'tasks'), t0 = z ? z.ts : 0, moved = f.t0 !== t0; let hits = 0, changed = false; f.t0 = t0; // time zero moved (something now comes before the first line): every `t` is different
374
487
  for (let i = 0; i < n; i++) {
375
488
  const e = tl.events[i], s = sigOf(e), was = f.known.get(e.k);
376
489
  if (was) { hits++; if (was.s !== s || moved) { was.s = s; was.q = seq; changed = true; } sq[i] = was.q; } else { f.known.set(e.k, { s, q: seq }); sq[i] = seq; changed = true; }
@@ -433,11 +546,33 @@ const menuOf = (b) => { // what a menu waiting for you shows, from the call it
433
546
  // 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.
434
547
  const CC_SESSIONS = process.env.AGENT_STANDUP_CC_SESSIONS || path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'sessions');
435
548
  const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
436
- function liveStatus() { // session id → { status, since, pid, ep (where it runs: claude-vscode, cli, claude-desktop, sdk-cli…) }
549
+ 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) }
437
550
  const out = new Map(); let names = []; try { names = fs.readdirSync(CC_SESSIONS); } catch { return out; }
438
- for (const n of names) { if (!/^\d+\.json$/.test(n)) continue; try { const s = JSON.parse(fs.readFileSync(path.join(CC_SESSIONS, n), 'utf8')); if (s && typeof s.sessionId === 'string' && /^(busy|idle|waiting)$/.test(s.status) && Number.isInteger(s.pid) && s.pid > 0 && alive(s.pid)) out.set(s.sessionId, { status: s.status !== 'waiting' ? s.status : s.waitingFor === 'dialog open' ? 'idle' : s.entrypoint === 'sdk-cli' ? 'busy' : s.status, since: Number(s.statusUpdatedAt) || 0, pid: s.pid, ep: String(s.entrypoint || '') }); } catch {} } /* a dialog you opened yourself (/model, /config, /mcp…) also says waiting: it is not a question for you. Nor is a menu of a session started with claude -p (entrypoint sdk-cli): its question goes to the program that started it. An Agent SDK host (sdk-ts, sdk-py: Zed, a home-made app) may show its menus to a person, so those are kept */
551
+ for (const n of names) { if (!/^\d+\.json$/.test(n)) continue; try { const s = JSON.parse(fs.readFileSync(path.join(CC_SESSIONS, n), 'utf8')); if (s && typeof s.sessionId === 'string' && /^(busy|idle|waiting)$/.test(s.status) && Number.isInteger(s.pid) && s.pid > 0 && alive(s.pid)) out.set(s.sessionId, { status: s.status !== 'waiting' ? s.status : s.waitingFor === 'dialog open' ? 'idle' : s.entrypoint === 'sdk-cli' ? 'busy' : s.status, since: Number(s.statusUpdatedAt) || 0, pid: s.pid, ep: String(s.entrypoint || ''), raw: s.status, cwd: typeof s.cwd === 'string' ? s.cwd : '', kind: typeof s.kind === 'string' ? s.kind : '', startedAt: Number(s.startedAt) || 0, version: typeof s.version === 'string' ? s.version : '', updatedAt: Number(s.updatedAt) || 0 }); } catch {} } /* a dialog you opened yourself (/model, /config, /mcp…) also says waiting: it is not a question for you. Nor is a menu of a session started with claude -p (entrypoint sdk-cli): its question goes to the program that started it. An Agent SDK host (sdk-ts, sdk-py: Zed, a home-made app) may show its menus to a person, so those are kept */
439
552
  return out;
440
553
  }
554
+ // A Claude Code session that is open and has worked, yet whose transcript is nowhere in the projects folder read here. The call cannot show it; the page says so, and why it may be (issue #9). Read from the status files alone, nothing sent.
555
+ // Only one cause is visible this way (Claude Code 2.1.304, tried): CLAUDE_CODE_SKIP_PROMPT_HISTORY=1 writes the status file (interactive, idle/busy) and shows "Transcript saving is off", but no transcript.
556
+ // An inherited CLAUDE_CODE_CHILD_SESSION=1 writes neither, and another CLAUDE_CONFIG_DIR puts the status file in that other folder: neither leaves anything here. What is listed may also be a cause not known yet.
557
+ // Listed only once this server has seen the session busy, under its current id, for 5 s: a session just opened, one where you opened /model or /config, and one right after /clear
558
+ // (a new id and updatedAt, while status and statusUpdatedAt are still those of the id before) have written no transcript yet, and need none.
559
+ let missingMemo = { at: 0, list: [] }; const transcriptSeen = new Set(), busySeen = new Map(); // transcriptSeen: ids found once are not looked for again, a transcript stays where it was written · busySeen: id → when it was first seen busy (at most 500)
560
+ function missingTranscripts() { // [{ id, cwd, name, version, ep, since }]: one look every 10 s at most
561
+ if (process.env.AGENT_STANDUP_PROJECTS && !process.env.AGENT_STANDUP_CC_SESSIONS) return []; // sessions read from another folder than the one these status files belong to: every live session would look as if it wrote nothing
562
+ const now = Date.now(); if (now - missingMemo.at < 10e3) return missingMemo.list;
563
+ const list = []; let dirs = null;
564
+ for (const [id, w] of liveStatus()) {
565
+ if ((w.kind && w.kind !== 'interactive') || /^sdk-(cli|ts|py)$/.test(w.ep) || transcriptSeen.has(id) || !/^[\w-]+$/.test(id)) continue; // a session a program runs keeps no transcript a person would look for
566
+ if (w.raw === 'busy' && w.since >= w.updatedAt && !busySeen.has(id)) { if (busySeen.size >= 500) busySeen.delete(busySeen.keys().next().value); busySeen.set(id, Math.min(now, w.since || now)); } // a status written for this id (an older Claude Code writes no updatedAt: 0)
567
+ if (!(now - (busySeen.get(id) || now) >= 5e3)) continue; // Claude Code writes the transcript with the first message: never busy yet, or only just
568
+ const name = id + '.jsonl', key = w.cwd.replace(/[^a-zA-Z0-9]/g, '-'); // Claude Code's project folder naming: the folder of its cwd, looked at first
569
+ if ((key && mtimeOf(path.join(ROOT, key, name))) || coworkMap().has(id)) { transcriptSeen.add(id); continue; }
570
+ if (!dirs) { dirs = []; try { dirs = fs.readdirSync(ROOT); } catch {} } // a long path is shortened in its folder name: every folder, then
571
+ if (dirs.some((d) => mtimeOf(path.join(ROOT, d, name)))) { transcriptSeen.add(id); continue; }
572
+ list.push({ id, cwd: w.cwd, name: w.cwd ? path.basename(w.cwd) : '', version: w.version, ep: w.ep, since: w.startedAt || w.since });
573
+ }
574
+ missingMemo = { at: now, list }; return list;
575
+ }
441
576
  // When the person last did something in a session: an order, a slash command, a "!" command, an order typed while the lead was working. It is what moves the live call (see currentSession).
442
577
  // Not what the harness writes as a user record: the result of a tool, a reminder, the news that a background task ended, the summary of a compaction, an Esc.
443
578
  // Nor the prompt of a task Cowork runs on a schedule (it opens with <scheduled-task …>): nobody typed it, so it does not take the call from the session you are in.
@@ -501,26 +636,38 @@ function answerIn(id, opts = {}) { // { how: 'editor' | 'app' | '', app, link
501
636
  // Where it does, no status means its process has ended: a question left open there was given up, not asked.
502
637
  const verAtLeast = (v, min) => { const x = String(v || '').split('.').map((n) => parseInt(n, 10) || 0); for (let i = 0; i < 3; i++) if ((x[i] || 0) !== min[i]) return (x[i] || 0) > min[i]; return true; };
503
638
  const statusWritten = (proj, p) => proj !== COWORK && !!p.ver && p.ep !== 'local-agent' && verAtLeast(p.ver, p.ep === 'cli' ? [2, 1, 221] : [2, 1, 269]);
639
+ // The error Claude Code writes as the last message when it cannot go on: your plan's usage limit ("You've hit your limit · resets 7:20pm (Europe/Paris)"; before, "Claude AI usage limit reached|<epoch>",
640
+ // "5-hour limit reached ∙ resets 3pm"…) or a login that is gone ("Not logged in · Please run /login", "Failed to authenticate: OAuth session expired…", "Invalid API key"). Said as what it is, not as "gave up".
641
+ const LIMIT_ERR = /hit your (?:[\w-]+ )?limit|\b(?:usage|5-hour|weekly|daily|monthly|session|spend(?:ing)?) (?:[\w-]+ )?limit (?:reached|exceeded)|limit will reset/i, NOT_LIMIT = /context|not your usage limit|temporarily limiting/i;
642
+ const AUTH_ERR = /not logged in|please run \/login|oauth (?:token|session) (?:has )?expired|failed to authenticate|invalid api key|authentication_error/i;
643
+ function errKind(text, code) { // { limit: { resets } } | { auth: 1 } | null; code: the error field of the record (authentication_failed…), which older versions do not write
644
+ if (code === 'authentication_failed') return { auth: 1 };
645
+ if (!LIMIT_ERR.test(text) || NOT_LIMIT.test(text)) return AUTH_ERR.test(text) ? { auth: 1 } : null; // a limit first: its text may offer /login to switch accounts
646
+ const at = /limit reached\|(\d{9,11})\b/i.exec(text), m = /\breset(?:s)?(?: at)?\s+([^\n·∙|]+)/i.exec(text);
647
+ let resets = m ? m[1].trim().replace(/\.$/, '').slice(0, 80) : ''; if (!resets && at) { const d = new Date(+at[1] * 1000); resets = String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0'); } // the oldest form gives the time as a number: said in this computer's hours
648
+ return { limit: { resets } };
649
+ }
504
650
  function parseTail(file, st) {
505
651
  const sig = st.mtimeMs + ':' + st.size, hit = boardCache.get(file); if (hit && hit.sig === sig) return hit;
506
652
  const { lines, cut } = boardTail(file);
507
- const pend = new Map(), bg = new Map(); let ver = '', ep = '', idle = false, lastType = null, lastTool = false, lastStop = null, stops = false, esc = false, lastTs = 0, custom = (hit && hit.custom) || null, ai = (hit && hit.ai) || null, first = hit ? hit.first : undefined, pr = (hit && hit.pr) || null, asked = (hit && hit.asked) || 0, plan = (hit && hit.plan) || null, say = '', err = ''; // say: the first text since the last call or message of yours, the start of what closes the turn; err: an error that closed it
653
+ const pend = new Map(), bg = new Map(), runs = new Map(); let ver = '', ep = '', idle = false, lastType = null, lastTool = false, lastStop = null, stops = false, esc = false, lastTs = 0, stamp = 0, bare = false, custom = (hit && hit.custom) || null, ai = (hit && hit.ai) || null, first = hit ? hit.first : undefined, pr = (hit && hit.pr) || null, asked = (hit && hit.asked) || 0, plan = (hit && hit.plan) || null, say = '', err = '', errK = null; // say: the first text since the last call or message of yours, the start of what closes the turn; err: an error that closed it, errK: what kind (errKind)
508
654
  for (const l of lines) try { // one odd record costs that record, not the whole card
509
655
  if (!l) continue; let r; try { r = JSON.parse(l); } catch { continue; }
510
656
  const a = typedAt(r); if (a > asked) asked = a; if (a && r.type === 'user') pend.clear(); if (typeof r.version === 'string') ver = r.version; if (typeof r.entrypoint === 'string') ep = r.entrypoint; /* which Claude Code, and where: does it write a status that says a menu is open (statusWritten) */ /* an order of yours: a call still without its answer was given up (a menu you passed over by typing, a session closed mid-call), it waits on nothing any more */
511
657
  if (r.type === 'custom-title' && typeof r.customTitle === 'string') custom = r.customTitle; else if (r.type === 'ai-title' && typeof r.aiTitle === 'string') ai = r.aiTitle; // a session is renamed, or named, long after its row was first shown: the latest one read wins
512
658
  if (r.type === 'pr-link' && PR_URL.test(r.prUrl)) pr = { n: +r.prUrl.slice(r.prUrl.lastIndexOf('/') + 1), url: r.prUrl }; // the pull request Claude Code noted for the session: the latest one, shown on its card
513
- const t = Date.parse(r.timestamp) || 0, bl = blocks(r);
659
+ const t = Date.parse(r.timestamp) || 0, bl = blocks(r); if (t) { stamp = t; bare = false; } else bare = true; // bare: only records without a time since the last one that has one (last-prompt, ai-title, mode, cost-state…), which Claude Code also writes when its tab is closed: no one moved there
514
660
  if (r.type === 'system' && r.subtype === 'compact_boundary') idle = /^idle/.test(String((r.compactMetadata && r.compactMetadata.trigger) || '')); // Claude Code 2.1.299 compacts a large session left idle for about 54 minutes: nobody moved there
515
661
  if (r.isCompactSummary) continue; // the summary of a compaction is not a message: the turn stands as it was
516
662
  if (r.type === 'assistant' || r.type === 'user') { idle = false; lastType = r.type; lastTool = bl.some((b) => b.type === 'tool_use'); lastStop = (r.type === 'assistant' && r.message && r.message.stop_reason) || null; if (lastStop) stops = true; if (t) lastTs = t;
517
663
  esc = r.type === 'user' && bl.some((b) => b.type === 'text' && /^\s*\[Request interrupted/i.test(b.text || '')); if (esc) pend.clear(); } // Esc: the turn stops there, and no call is waited for any more
518
- if (r.type === 'user' || (r.type === 'assistant' && lastTool)) { say = ''; err = ''; }
519
- else if (r.type === 'assistant' && !r.isSidechain) { const tx = bl.filter((b) => b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim(), m = r.message || {}; err = (r.isApiErrorMessage || m.model === '<synthetic>') && tx && !/^No response requested/i.test(tx) ? tx : ''; if (tx && !say) say = tx; }
664
+ if (r.type === 'user' || (r.type === 'assistant' && lastTool)) { say = ''; err = ''; errK = null; }
665
+ else if (r.type === 'assistant' && !r.isSidechain) { const tx = bl.filter((b) => b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').trim(), m = r.message || {}; err = (r.isApiErrorMessage || m.model === '<synthetic>') && tx && !/^No response requested/i.test(tx) ? tx : ''; errK = err ? errKind(err, r.error) : null; if (tx && !say) say = tx; }
520
666
  for (const b of bl) if (b.type === 'tool_use' && /^(Write|Edit|MultiEdit)$/.test(b.name) && b.input && planFile(String(b.input.file_path || ''))) plan = { file: String(b.input.file_path), ts: t }; // the plan, written in its own file before it is shown for approval
521
667
  for (const b of bl) { if (b.type === 'tool_use') pend.set(b.id, { id: String(b.id || ''), name: b.name, ts: t, q: askOf(b), c: callOf(b), m: menuOf(b) }); else if (b.type === 'tool_result') pend.delete(b.tool_use_id); }
522
668
  if (r.type === 'user' && !r.isSidechain) for (const b of bl) { // the sub-agents the lead launched in the background, until the news that each one ended (Claude Code 2.1.302 runs them all in the background in VS Code and the desktop app)
523
- if (b.type === 'tool_result') { const m = /^\s*Async agent launched[\s\S]*?agentId: ?([\w-]+)/i.exec(resultText(b.content)); if (m) bg.set(m[1], t); }
669
+ if (b.type === 'tool_result') { const rt = resultText(b.content), m = /^\s*Async agent launched[\s\S]*?agentId: ?([\w-]+)/i.exec(rt), wf = !m && /^\s*Workflow launched in background\.\s*Task ID: ?([\w-]+)/i.exec(rt); if (m) bg.set(m[1], t);
670
+ else if (wf) { bg.set(wf[1], t); const run = /\bRun ID: ?([\w-]+)/.exec(rt) || /[\\/]subagents[\\/]workflows[\\/]([\w-]+)/.exec(rt); if (run) runs.set(wf[1], run[1]); } } // a workflow too, until the news of its task id; its agents write in subagents/workflows/<run id>
524
671
  else if (b.type === 'text') for (const m of String(b.text || '').matchAll(/<task-notification>[\s\S]*?<task-id>([\w-]+)<\/task-id>/g)) bg.delete(m[1]);
525
672
  }
526
673
  const queued = r.isSidechain ? '' : r.type === 'attachment' && r.attachment && r.attachment.type === 'queued_command' && typeof r.attachment.prompt === 'string' ? r.attachment.prompt : r.type === 'queue-operation' && r.operation === 'enqueue' && typeof r.content === 'string' ? r.content : '';
@@ -532,8 +679,8 @@ function parseTail(file, st) {
532
679
  }
533
680
  if (!custom && !ai && first == null) first = firstPrompt(file) || (st.size > 64 * 1024 ? '' : null); // '' = looked for and not there; a file that has just been created is looked at again
534
681
  if (!hit && !asked && cut) asked = typedBefore(file);
535
- const out = { sig, title: custom || ai || first || null, custom, ai, first, pr, lastType, lastTool, lastStop, stops, esc, lastTs, pending: [...pend.values()], ...(lastType === 'assistant' && (err || gaveUp(say)) ? { gave: (err || gaveUp(say)).replace(/\s+/g, ' ').slice(0, 240) } : {}) }; // a title the person typed wins over the generated one, and both over the first prompt
536
- out.ver = ver || (hit && hit.ver) || ''; out.ep = ep || (hit && hit.ep) || ''; out.asked = asked; out.plan = plan; out.bg = [...bg].filter(([, ts]) => ts >= asked); if (idle && lastTs) out.quiet = lastTs; boardCache.set(file, out); if (boardCache.size > 3 * ROWS_MAX) boardCache.delete(boardCache.keys().next().value); return out; // more than the list can hold: a full list never pushes its own rows out, which read every row again at each scan
682
+ const out = { sig, title: custom || ai || first || null, custom, ai, first, pr, lastType, lastTool, lastStop, stops, esc, lastTs, pending: [...pend.values()], ...(lastType === 'assistant' && errK ? errK : lastType === 'assistant' && (err || gaveUp(say)) ? { gave: (err || gaveUp(say)).replace(/\s+/g, ' ').slice(0, 240) } : {}) }; // limit, auth: it stopped on your usage limit, or a login that is gone, not of its own accord // a title the person typed wins over the generated one, and both over the first prompt
683
+ out.ver = ver || (hit && hit.ver) || ''; out.ep = ep || (hit && hit.ep) || ''; out.asked = asked; out.plan = plan; out.bg = [...bg].filter(([, ts]) => ts >= asked).map(([k, ts]) => (runs.has(k) ? [k, ts, runs.get(k)] : [k, ts])); if (idle && lastTs) out.quiet = lastTs; else if (bare && stamp) out.quiet = stamp; boardCache.set(file, out); if (boardCache.size > 3 * ROWS_MAX) boardCache.delete(boardCache.keys().next().value); return out; // more than the list can hold: a full list never pushes its own rows out, which read every row again at each scan
537
684
  }
538
685
  function firstPrompt(file) { // the first thing the person typed, read record by record: a pattern over the raw text ran from a user record into the assistant's first answer and took that as the title
539
686
  const ONE = (t) => t.replace(/\s+/g, ' ').trim().slice(0, 90);
@@ -558,10 +705,15 @@ function capRows(list, most, folderOf) { // list: newest first
558
705
  for (const r of real) { if (keep.size >= ROWS_MAX) break; const k = folderOf(r), n = per.get(k) || 0; if (n < PER_FOLDER) { keep.add(r); per.set(k, n + 1); } }
559
706
  return real.filter((r) => keep.has(r)).concat(list.filter((r) => tmpKey(folderOf(r))).slice(0, TMP_ROWS));
560
707
  }
561
- function bgAtWork(proj, id, bg, now) { // bg: [agent id, launched at]. Still at work: not marked finished in its meta file (Claude Code 2.1.302 on) and written to, or launched, in the last 30 minutes
562
- for (const [aid, ts] of bg || []) {
563
- if (!/^[\w-]+$/.test(aid)) continue; const f = path.join(projDir(proj, id), id, 'subagents', 'agent-' + aid);
564
- let done = false; try { done = JSON.parse(fs.readFileSync(f + '.meta.json', 'utf8')).finished === true; } catch {}
708
+ function bgAtWork(proj, id, bg, now) { // bg: [agent id, launched at] or [workflow task id, launched at, run id]. Still at work: not marked finished in its meta file (Claude Code 2.1.302 on) and written to, or launched, in the last 30 minutes
709
+ for (const [aid, ts, run] of bg || []) {
710
+ if (!/^[\w-]+$/.test(aid)) continue;
711
+ if (run) { // a workflow: done once Claude Code writes its record in <session>/workflows/<run>.json (it does at the end); at work while one of its agents wrote in the last 30 minutes
712
+ if (!/^[\w-]+$/.test(run)) continue; const d = path.join(projDir(proj, id), id), wd = path.join(d, 'subagents', 'workflows', run); let last = 0; const w = readMeta(path.join(d, 'workflows', run + '.json')), done = !!w && typeof w === 'object' && Object.keys(w).length > 0 && !/^(running|pending)$/.test(String(w.status)); // readMeta: read again only when the file changes
713
+ if (!done) { try { for (const f of fs.readdirSync(wd)) if (f.endsWith('.jsonl')) last = Math.max(last, mtimeOf(path.join(wd, f))); } catch {} if (now - Math.max(last, ts || 0) < 30 * 60e3) return true; }
714
+ continue;
715
+ } const f = path.join(projDir(proj, id), id, 'subagents', 'agent-' + aid);
716
+ const done = (readMeta(f + '.meta.json') || {}).finished === true;
565
717
  if (!done && now - Math.max(mtimeOf(f + '.jsonl'), ts || 0) < 30 * 60e3) return true;
566
718
  }
567
719
  return false;
@@ -584,16 +736,17 @@ function boardRows0() {
584
736
  if (lp) { ageMs = now - (lp.ts || st.mtimeMs); tool = lp.name;
585
737
  state = SUBTOOL.test(lp.name) ? 'waiting' : 'working'; if (!w && ASKS.test(lp.name) && ageMs > 4000 && !statusWritten(proj, p)) { state = 'blocked'; asks = 1; since = lp.ts || st.mtimeMs; } else if (!w && ((APPROVAL.test(lp.name) && ageMs > 15000) || (ASKS.test(lp.name) && ageMs > 4000))) { maybe = 1; since = lp.ts || st.mtimeMs; } } // asks: no status (Cowork, Claude Code before 2.1.269), but a question or a plan open in the transcript is one: it needs you // maybe: only a guess from how long a call has waited, for a session whose status Claude Code does not write (Cowork, before 2.1.2xx): shown on its tile, never as "needs you" (no visitor, no red, no notification). A status that says busy or idle is believed: the panel in VS Code also says "waiting" while it asks
586
738
  else if (p.esc) state = 'turn'; // you stopped it (Esc): it is your turn there, not "working" for the next ten minutes
587
- else if (p.lastType === 'assistant' && !p.lastTool && p.lastStop !== 'tool_use' && !(p.lastStop == null && p.stops && age < 45000)) state = !p.gave && bgAtWork(proj, id, p.bg, now) ? 'waiting' : 'turn'; // a line whose message goes on with a tool call is not the end of the turn: the call is written after it, a long one many seconds after.
739
+ else if (p.lastType === 'assistant' && !p.lastTool && p.lastStop !== 'tool_use' && !(p.lastStop == null && p.stops && age < 45000)) state = !p.gave && !p.limit && !p.auth && bgAtWork(proj, id, p.bg, now) ? 'waiting' : 'turn'; // a line whose message goes on with a tool call is not the end of the turn: the call is written after it, a long one many seconds after.
588
740
  // A lead that ends its turn on "the agents are running, I'll wait" is not waiting for you: it goes on when they report (a sub-agent launched in the background, and not since an order of yours)
589
741
  // Claude Code up to 2.1.87 writes that line without saying why it stopped: in a transcript that does say it elsewhere, such a line is given 45 s for its call to come (1 in 100 takes longer than 25 s)
590
742
  else state = age < 10 * 60e3 ? 'working' : 'idle';
591
743
  if (state === 'turn') since = p.lastTs || st.mtimeMs;
592
744
  }
745
+ else if (p.bg && p.bg.length && p.lastType === 'assistant' && !p.lastTool && !p.gave && !p.limit && !p.auth && bgAtWork(proj, id, p.bg, now)) state = 'waiting'; // a lead quiet for more than 30 minutes while what it launched in the background still works (a long workflow): waiting on it, not idle
593
746
  let subActive = 0, subTotal = 0;
594
747
  for (const x of subFiles(proj, id)) { subTotal++; if (now - mtimeOf(x.file) < 90e3) subActive++; }
595
748
  const ran = since && p.asked && p.asked < since ? since - p.asked : 0, ask = (state === 'blocked' || maybe) && lp ? lp.q || lp.c : ''; // since: when it started to wait on you; ran: how long it worked, from your last order to then
596
- return { proj, id, title: coworkTitle(proj, id) || p.title || id, mtime: moved, state, tool, ageMs, subActive, subTotal, asked: p.asked || 0, ...(since ? { since } : {}), ...(ran ? { ran } : {}), ...(p.pr ? { pr: p.pr } : {}), ...(ask ? { ask } : {}), ...(state === 'blocked' && ((w && w.status === 'waiting') || asks) ? { sure: 1 } : {}), ...(maybe ? { maybe } : {}), ...(w ? { known: 1 } : {}), ...(open ? { menu: open } : (state === 'blocked' || maybe) && lp && lp.m && !SUBTOOL.test(lp.name) ? { menu: { id: lp.id, tool: lp.name, ...lp.m, ...((w && w.status === 'waiting') || asks ? { sure: 1 } : {}) } } : {}), ...(state === 'turn' && p.gave ? { gave: p.gave } : {}), ...(p.esc ? { cut: 1 } : {}), ...(tmpKey(proj) ? { tmp: 1 } : {}) }; // cut: stopped by you, which is no news to tell you
749
+ return { proj, id, title: coworkTitle(proj, id) || p.title || id, mtime: moved, state, tool, ageMs, subActive, subTotal, asked: p.asked || 0, ...(since ? { since } : {}), ...(ran ? { ran } : {}), ...(p.pr ? { pr: p.pr } : {}), ...(ask ? { ask } : {}), ...(state === 'blocked' && ((w && w.status === 'waiting') || asks) ? { sure: 1 } : {}), ...(maybe ? { maybe } : {}), ...(w ? { known: 1 } : {}), ...(open ? { menu: open } : (state === 'blocked' || maybe) && lp && lp.m && !SUBTOOL.test(lp.name) ? { menu: { id: lp.id, tool: lp.name, ...lp.m, ...((w && w.status === 'waiting') || asks ? { sure: 1 } : {}) } } : {}), ...(state === 'turn' && p.gave ? { gave: p.gave } : {}), ...(state === 'turn' && p.limit ? { limit: p.limit } : {}), ...(state === 'turn' && p.auth ? { auth: 1 } : {}), ...(p.esc ? { cut: 1 } : {}), ...(tmpKey(proj) ? { tmp: 1 } : {}) }; // cut: stopped by you, which is no news to tell you
597
750
  }).filter(Boolean);
598
751
  }
599
752
  // Settings live in a file, not only in the page's localStorage: the port changes between VS Code windows and reloads, and localStorage is per origin (port included).
@@ -748,16 +901,18 @@ function sessionMtime(proj, id) {
748
901
  // A project of Claude Code is named after its folder with every character other than a letter or digit made a dash: -Users-a-app-old may be app/old (inside app) or app-old (beside it).
749
902
  // Which one is told by the folder its sessions were started in (the cwd of its first records), read once per project. Not found (an empty project): counted as before, by its name.
750
903
  const projCwds = new Map(), dirKey = (d) => String(d || '').replace(/[^a-zA-Z0-9]/g, '-');
904
+ const foldKey = (k) => (process.platform === 'win32' ? String(k).toLowerCase() : k); // Windows: a folder is the same whatever its case (the editor sends C:, Claude Code may have written c:)
751
905
  function projCwd(proj) {
752
906
  if (projCwds.has(proj)) return projCwds.get(proj);
753
907
  let cwd = ''; for (const { id } of transcripts(proj).slice(0, 3)) { try { const m = /"cwd":"((?:[^"\\]|\\.)*)"/.exec(readHead(path.join(projDir(proj, id), id + '.jsonl'), 64 * 1024)); if (m) { cwd = JSON.parse('"' + m[1] + '"'); break; } } catch {} }
754
- if (cwd && dirKey(cwd) === proj) projCwds.set(proj, cwd); return cwd && dirKey(cwd) === proj ? cwd : ''; // kept once it is sure: the folder whose name is the project's
908
+ const sure = !!cwd && foldKey(dirKey(cwd)) === foldKey(proj); if (sure) projCwds.set(proj, cwd); return sure ? cwd : ''; // kept once it is sure: the folder whose name is the project's
755
909
  }
756
- const inFolder = (proj, key) => { if (proj === key) return true; if (!proj.startsWith(key + '-')) return false; const cwd = projCwd(proj); if (!cwd) return true; for (let d = cwd; d;) { if (dirKey(d) === key) return true; const up = path.dirname(d); if (up === d) return false; d = up; } return false; };
910
+ const inFolder = (proj, key) => { const p = foldKey(proj), k = foldKey(key); if (p === k) return true; if (!p.startsWith(k + '-')) return false; const cwd = projCwd(proj); if (!cwd) return true; for (let d = cwd; d;) { if (foldKey(dirKey(d)) === k) return true; const up = path.dirname(d); if (up === d) return false; d = up; } return false; };
757
911
  function currentSession(projFilter, pick, stick, anyTmp) { // pick: { proj, id, since } the session you went to by hand, and the latest order there was then · stick: the session the call is in · anyTmp: sessions in the temporary folder count too (see tmpKey)
758
912
  const safe = (x) => typeof x === 'string' && /^[\w.\-]+$/.test(x) && x !== '..', now = Date.now();
913
+ const keys = process.platform === 'win32' && /^[a-zA-Z]-/.test(projFilter || '') ? [projFilter, (projFilter[0] === projFilter[0].toLowerCase() ? projFilter[0].toUpperCase() : projFilter[0].toLowerCase()) + projFilter.slice(1)] : [projFilter]; // Windows: a Codex or Vibe session's folder, with its drive letter in either case
759
914
  const there = (c) => !!c && safe(c.id) && safe(c.proj) && (sourceOf(c.proj) ? !!guard(() => sourceOf(c.proj).fileOf(c.id), null) : fs.existsSync(path.join(projDir(c.proj, c.id), c.id + '.jsonl')));
760
- const inScope = (c) => (!projFilter ? anyTmp || !tmpSession(c.proj, c.id) : inFolder(c.proj, projFilter) || !!(sourceOf(c.proj) && guard(() => sourceOf(c.proj).inProject(c.id, projFilter), false))); // a Codex or Vibe session counts for a project when it was started in that folder
915
+ const inScope = (c) => (!projFilter ? anyTmp || !tmpSession(c.proj, c.id) : inFolder(c.proj, projFilter) || !!(sourceOf(c.proj) && guard(() => keys.some((k) => sourceOf(c.proj).inProject(c.id, k)), false))); // a Codex or Vibe session counts for a project when it was started in that folder
761
916
  const same = (a, b) => !!a && !!b && a.proj === b.proj && a.id === b.id; let all = boardRows();
762
917
  if (there(pick) && !all.some((r) => same(r, pick)) && now - boardForced > 5000 && sessionMtime(pick.proj, pick.id) > boardMemo.at - 1500) { boardForced = now; boardMemo.at = 0; all = boardRows(); } // boardForced: at most every 5 s, for a session written to that the list never holds (older than 12 h, past the places of its kind) // the session you went to was written after the list shared for 1.2 s was made: without it, its order read as none, and the next answer dropped your pick
763
918
  const rows = all.filter(inScope), mine = there(pick) ? all.find((r) => same(r, pick)) : null;
@@ -821,6 +976,11 @@ function parseRecord(st, r) {
821
976
  if (id && status && status !== 'running') push({ ts, agent, kind: 'agentdone', toolId: id });
822
977
  return;
823
978
  }
979
+ if (r.type === 'attachment' && r.attachment && r.attachment.type === 'task_reminder' && Array.isArray(r.attachment.content)) { // Claude Code reminds the agent of its task list now and then: the whole list as it stands, which the shared screen takes over from the calls that changed it
980
+ const c = r.attachment.content; if (!c.length && !st.tasks) return; st.tasks = 1; // an empty list before any task is no news
981
+ push({ ts, agent, kind: 'tasks', items: c.slice(0, 50).map((x) => ({ id: clip(x && x.id, 40), c: clip(x && x.subject, 120), s: clip((x && x.status) || 'pending', 20), a: clip(x && x.activeForm, 120) })) });
982
+ return;
983
+ }
824
984
  if (r.type === 'attachment' && r.attachment && r.attachment.type === 'queued_command') { // an order typed while the lead was working: Claude Code hands it over in the middle of the turn, as an attachment and not as a user message
825
985
  const q = r.attachment, human = q.origin ? q.origin.kind === 'human' : q.commandMode === 'prompt'; if (agent !== 'main' || !human) return; // the same record also carries task notifications
826
986
  const txt = (Array.isArray(q.prompt) ? q.prompt.filter((b) => b && b.type === 'text').map((b) => b.text).join('\n') : typeof q.prompt === 'string' ? q.prompt : '').replace(HARNESS, '').trim();
@@ -832,16 +992,17 @@ function parseRecord(st, r) {
832
992
  if (st.out) for (const b of blocks(r)) if (b.type === 'tool_result') st.out.delete(b.tool_use_id);
833
993
  for (const b of blocks(r)) if (b.type === 'tool_result' && wf) push({ ts, agent, kind: 'wfrun', toolId: b.tool_use_id, run: wf }); // the answer to a Workflow call names the run it started: its agents are in subagents/workflows/<run>/
834
994
  for (const b of blocks(r)) if (b.type === 'tool_result' && (st.toolName[b.tool_use_id] === 'Agent' || st.toolName[b.tool_use_id] === 'Task') && !(st.bg && st.bg[b.tool_use_id]) && !/^\s*Async agent launched/i.test(resultText(b.content))) push({ ts, agent, kind: 'agentdone', toolId: b.tool_use_id }); // a synchronous call: the lead got the sub-agent's answer back, so it has finished (async launches answer immediately and are not a completion)
995
+ 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
835
996
  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])) {
836
- const n = st.toolName[b.tool_use_id], img = resultImages(b.content).length, files = n === 'Bash' && !b.is_error ? docPaths(resultText(b.content), 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, resultText(b.content)) : null;
837
- items.push({ id: b.tool_use_id, err: !!b.is_error, out: clip(resultText(b.content).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(resultText(b.content)) : {}) }); // img: how many pictures came back; the page fetches them from /api/media · files: the documents a command says it made
997
+ 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;
998
+ 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
838
999
  }
839
1000
  if (items.length) push({ ts, agent, kind: 'results', items });
840
1001
  const typed = blocks(r).filter((b) => b.type === 'text').map((b) => b.text).join('\n').replace(HARNESS, ''), cut = /^\s*\[Request interrupted[^\]]*\]/i.test(typed); // what the human typed, without the blocks the harness wraps around it
841
1002
  if (agent !== 'main') { if (!st.prompt && typed.trim() && !st.raw.length) st.prompt = { ts, text: typed.trim() }; return; } // a sub-agent's first user message is the order, emitted from the parent's side (kept here for the agents of a workflow, whose order is in no other file)
842
1003
  if (cut && st.out) st.out.clear(); if (cut && st.act >= 0) st.raw[st.act].end = 1; // Esc: the turn stops there, without the end_turn mark. The last thing the lead said or did closes it
843
1004
  const txt = typed.replace(/^\s*\[Request interrupted[^\]]*\]\s*/i, '').trim();
844
- if (txt && !/^<(system-reminder|command-|local-command|task-notification)/.test(txt) && !r.isMeta && !r.isCompactSummary) { if (st.out) st.out.clear(); push({ ts, agent: 'user', kind: 'user', text: txt }); } // a call that never got its answer is not waited for across your next message · not the summary Claude Code writes when it compacts: thousands of characters the human never typed
1005
+ if (txt && !/^<(system-reminder|command-|local-command|task-notification)/.test(txt) && !r.isMeta && !r.isCompactSummary) { if (st.out) st.out.clear(); const pics = blocks(r).filter(isImg).length; push({ ts, agent: 'user', kind: 'user', text: txt, ...(pics && typeof r.uuid === 'string' && /^[\w.\-]{6,200}$/.test(r.uuid) ? { img: pics, iid: r.uuid } : {}) }); } // img: the pictures pasted with it, served by /api/media (agent=user, tool=iid) // a call that never got its answer is not waited for across your next message · not the summary Claude Code writes when it compacts: thousands of characters the human never typed
845
1006
  } else if (r.type === 'assistant') {
846
1007
  const m = r.message || {}; let said = null;
847
1008
  if (agent === 'main') { st.lead = 1; if (m.stop_reason) st.stops = 1; } // this transcript says why each message stopped: its turns end with a mark, and until one comes the lead is at work (see marks, below)
@@ -856,7 +1017,7 @@ function parseRecord(st, r) {
856
1017
  else if (b.type === 'text' && typeof b.text === 'string' && b.text.trim()) { said = push({ ts, agent, kind: 'say', text: b.text.trim(), ...th() }); st.act = st.raw.length - 1; st.sayOf = m.id; st.sayAt = st.act; }
857
1018
  else if (b.type === 'tool_use' && b.name === 'SubagentHandback' && agent !== 'main' && b.input && typeof b.input.message === 'string' && b.input.message.trim()) { said = push({ ts, agent, kind: 'say', text: b.input.message.trim(), ...th() }); st.act = st.raw.length - 1; st.sayOf = m.id; st.sayAt = st.act; } // since Claude Code 2.1.293 a sub-agent hands its report back through this call, and most write no sentence beside it: the message of the call is what it says last
858
1019
  else if (b.type === 'tool_use') {
859
- st.toolName[b.id] = b.name; (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
1020
+ 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
860
1021
  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() } : {}) });
861
1022
  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 (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; }
862
1023
  }
@@ -867,7 +1028,7 @@ function parseRecord(st, r) {
867
1028
  }
868
1029
  }
869
1030
  }
870
- const codexRecord = codex.parser({ toolLabel, clip, resultMax: RESULT_MAX }), vibeRecord = vibe.parser({ toolLabel, clip, resultMax: RESULT_MAX });
1031
+ const codexRecord = codex.parser({ toolLabel, clip, clipOut, testsOf, diffOf, resultMax: RESULT_MAX }), vibeRecord = vibe.parser({ toolLabel, clip: clipOut, resultMax: RESULT_MAX }); // Vibe clips only thoughts and outputs: without the codes of a terminal
871
1032
  const recordOf = (sx) => (sx === codex ? codexRecord : sx === vibe ? vibeRecord : parseRecord);
872
1033
  // A sub-agent the person named keeps that name on screen: the name given when it was launched, or else its type when that type is the person's own (.claude/agents/code-reviewer.md → "Code Reviewer").
873
1034
  // The types Claude Code ships are not names: those agents get a first name from the page, as before.
@@ -934,11 +1095,11 @@ function buildTimeline(proj, id, files = []) {
934
1095
  const merged = []; let lastReal = -1; // consecutive tool calls of one agent become one activity beat; usage events are transparent to that rule
935
1096
  for (const e of events) {
936
1097
  const p = lastReal >= 0 ? merged[lastReal] : null;
937
- if (e.kind === 'usage' || e.kind === 'finish' || e.kind === 'compact') { merged.push(e); continue; }
1098
+ if (e.kind === 'usage' || e.kind === 'finish' || e.kind === 'compact' || e.kind === 'tasks') { merged.push(e); continue; } // tasks: the list Claude Code reminds the agent of, which comes between two calls of one beat
938
1099
  if (e.kind === 'tool' && p && p.kind === 'tools' && p.agent === e.agent && !p.end) { p.tools.push(e.tool); if (e.end) p.end = 1; } // a beat keeps the key of its first call; one that closed a turn takes no more calls
939
1100
  else { merged.push(e.kind === 'tool' ? { ts: e.ts, agent: e.agent, kind: 'tools', tools: [e.tool], ...(e.end ? { end: 1 } : {}), ...(e.th ? { th: e.th } : {}), k: e.k } : e); lastReal = merged.length - 1; }
940
1101
  }
941
- const real = merged.find((e) => e.kind !== 'usage' && e.kind !== 'finish' && e.kind !== 'compact'), first = real ? real.ts : 0, last = merged.length ? merged[merged.length - 1].ts : 0; // time zero = the first thing said or done
1102
+ const real = merged.find((e) => e.kind !== 'usage' && e.kind !== 'finish' && e.kind !== 'compact' && e.kind !== 'tasks'), first = real ? real.ts : 0, last = merged.length ? merged[merged.length - 1].ts : 0; // time zero = the first thing said or done
942
1103
  const marks = !sx && states[0] && (states[0].stops || !states[0].lead) ? { marks: 1 } : {}; // a Claude Code session whose turns end with a mark, also before the lead has written anything: a session that has not closed a turn yet is not one without marks, and its lead is not "done" each time it thinks for a while
943
1104
  const ms = states.find((x) => x && x.agent === 'main'), cost = ms && ms.cost ? { usd: Math.round(ms.cost.usd * 1e4) / 1e4, final: !merged.some((e) => e.kind === 'usage' && e.ts > ms.cost.at) } : null; // final: nothing was spent after Claude Code counted it (else it is a floor)
944
1105
  return { id, proj, agents: Object.values(agents), events: merged.map((e) => ({ ...e, t: Math.max(0, e.ts - first) })), durationMs: last - first, recentUntil, ...marks, ...(cost ? { cost } : {}) };
@@ -987,10 +1148,12 @@ const schedule = (fn) => new Promise((res, rej) => { queue.push(() => fn().then(
987
1148
  // Fast path (~1-2 s instead of ~6 s): if the user has an Anthropic API key in the environment, call the API directly.
988
1149
  async function apiMap(prompt, need) {
989
1150
  const key = process.env.ANTHROPIC_API_KEY; if (!key) throw new Error('no key');
990
- const r = await fetch('https://api.anthropic.com/v1/messages', { method: 'POST', headers: { 'content-type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01' },
991
- body: JSON.stringify({ model: 'claude-haiku-5-5', max_tokens: 2000, messages: [{ role: 'user', content: prompt }] }) });
992
- const j = await r.json(); const out = j.content[0].text, arr = JSON.parse(out.slice(out.indexOf('['), out.lastIndexOf(']') + 1));
993
- if (arr.length !== need.length) throw new Error('bad length'); return arr;
1151
+ const r = await fetch('https://api.anthropic.com/v1/messages', { method: 'POST', headers: { 'content-type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01' }, signal: AbortSignal.timeout(30000),
1152
+ body: JSON.stringify({ model: 'claude-haiku-5-5', max_tokens: 4000, messages: [{ role: 'user', content: prompt }] }) }); // a request that hangs gives way to claude -p after 30 s
1153
+ if (!r.ok) throw new Error('api ' + r.status);
1154
+ const j = await r.json(), tb = j && Array.isArray(j.content) ? j.content.find((b) => b && b.type === 'text' && typeof b.text === 'string') : null; if (!tb) throw new Error('no text'); // the text block, wherever it is: a model that thinks first puts its thinking before it
1155
+ const out = tb.text, arr = JSON.parse(out.slice(out.indexOf('['), out.lastIndexOf(']') + 1));
1156
+ if (!Array.isArray(arr) || arr.length !== need.length) throw new Error('bad length'); return arr;
994
1157
  }
995
1158
  function claudeMap(kind, instruction, texts) {
996
1159
  const need = [...new Set(texts.filter((t) => !cache.has(kind + '|' + t)))];
@@ -1224,7 +1387,7 @@ async function claimPack(name, typed) { // typed: a code the person pastes (an
1224
1387
  // The same goes for a document one of its commands names (an export, a report made by a script), from the moment that command started: an older file by that name is not one of its files.
1225
1388
  function sessionFile(proj, id, file) { // { fp: where it is, since: 0 for a file it wrote, else when the first command that names it started }
1226
1389
  const sx = sourceOf(proj); if (!(sx ? guard(() => sx.fileOf(id), null) : fs.existsSync(path.join(projDir(proj, id), id + '.jsonl')))) return null;
1227
- const ev = timeline(proj, id).events, said = new Set(); let since = ev.some((e) => e.kind === 'tools' && e.tools.some((t) => t.d && t.d.kind === 'write' && t.d.file === file)) ? 0 : null;
1390
+ const ev = timeline(proj, id).events, said = new Set(); let since = ev.some((e) => e.kind === 'tools' && e.tools.some((t) => t.d && ((t.d.kind === 'write' && t.d.file === file) || (t.name === 'mcp__cowork__present_files' && t.d.outs && t.d.outs.includes(file))))) ? 0 : null; // written by the session, or handed to the person by Cowork
1228
1391
  if (since == null) {
1229
1392
  for (const e of ev) if (e.kind === 'results') for (const it of e.items) if (it.files && it.files.includes(file)) said.add(it.id); // named in what a command printed: counted from when that command started
1230
1393
  for (const e of ev) if (e.kind === 'tools' && e.tools.some((t) => said.has(t.id) || (t.d && t.d.kind === 'cmd' && t.d.outs && t.d.outs.includes(file)))) since = since == null ? e.ts || 1 : Math.min(since, e.ts || 1);
@@ -1260,7 +1423,7 @@ function start(port = PORT) {
1260
1423
  const sendFile = (fp) => { const s = fs.createReadStream(fp); s.on('error', () => res.destroy()); s.pipe(res); }; // a file that vanished between the check and the read ends this answer, not the server
1261
1424
  // Endpoints with side effects (they spawn programs or claim the sound), and the one that serves pictures from a session, refuse requests that a browser marks as coming from another site, e.g. an <img> on a web page.
1262
1425
  const sfs = req.headers['sec-fetch-site'];
1263
- if (sfs && sfs !== 'same-origin' && sfs !== 'none' && (req.method !== 'GET' || ['/api/translate', '/api/quips', '/api/warm', '/api/audio', '/api/tts', '/api/prefs', '/api/prefs.js', '/api/voices', '/api/kokoro', '/api/kokoro/install', '/api/media', '/api/artifact', '/api/errors', '/api/packs', '/api/update'].includes(url.pathname))) { res.writeHead(403); return res.end('forbidden'); }
1426
+ if (sfs && sfs !== 'same-origin' && sfs !== 'none' && (req.method !== 'GET' || ['/api/translate', '/api/quips', '/api/warm', '/api/audio', '/api/tts', '/api/prefs', '/api/prefs.js', '/api/voices', '/api/kokoro', '/api/kokoro/install', '/api/media', '/api/taskout', '/api/artifact', '/api/errors', '/api/packs', '/api/update'].includes(url.pathname))) { res.writeHead(403); return res.end('forbidden'); }
1264
1427
  const readBody = (cb, max = 262144) => { // request bodies are small JSON: stop reading beyond 256 KB (or max) and give up after 10 s
1265
1428
  const chunks = []; let size = 0, over = false; req.setTimeout(10000, () => req.destroy());
1266
1429
  if (+req.headers['content-length'] > max) { res.writeHead(413); res.end('too large'); return req.destroy(); }
@@ -1307,6 +1470,7 @@ function start(port = PORT) {
1307
1470
  if (url.pathname === '/api/errors') return json(errorReport());
1308
1471
  if (url.pathname === '/api/current') { const q = (k) => url.searchParams.get(k) || ''; return json(currentSession(q('proj'), q('pid') ? { proj: q('pproj'), id: q('pid'), since: q('since') ? +q('since') : NaN, pin: q('pin') === '1' } : null, { proj: q('sproj'), id: q('sid') })); }
1309
1472
  if (url.pathname === '/api/board') return json(boardRows());
1473
+ if (url.pathname === '/api/missing') return json(missingTranscripts()); // live Claude Code sessions whose transcript is not where the call reads (missingTranscripts)
1310
1474
  if (url.pathname === '/api/characters') return json(listCharacters(url.searchParams.get('pack') || ''));
1311
1475
  if (url.pathname === '/api/characters/add' && req.method === 'POST') return readBody((body) => { try { const b = JSON.parse(body || '{}') || {}; json(addCharacter(String(b.role || ''), b.name, b.data)); } catch (e) { if (!e.word) logError('add character', e); json({ error: e.word || 'write' }, e.word ? 400 : 500); } }, 512 * 1024); // a picture of 300 KB is 400 KB once written as text
1312
1476
  if (url.pathname === '/api/characters/remove' && req.method === 'POST') return readBody((body) => { let b = {}; try { b = JSON.parse(body || '{}') || {}; } catch {} try { json(removeCharacter(b.file) ? { ok: true } : { error: 'file' }, 200); } catch (e) { logError('remove character', e); json({ error: 'write' }, 500); } });
@@ -1315,22 +1479,30 @@ function start(port = PORT) {
1315
1479
  let b = {}; try { b = JSON.parse(body || '{}') || {}; } catch {} const name = String(b.pack || ''); if (!hasOwn(SHOP_PACKS, name)) return json({ error: 'pack' }, 404);
1316
1480
  (url.pathname.endsWith('/buy') ? buyPack(name) : claimPack(name, typeof b.code === 'string' ? b.code.trim().slice(0, 260) : '')).then((r) => json(r, r.status), (e) => { logError('shop', e); json({ error: 'shop' }, 500); });
1317
1481
  });
1318
- if (url.pathname === '/api/reveal' && req.method === 'POST') return readBody((body) => { // 404: not a file this session created · 410: created, and no longer there
1482
+ if (url.pathname === '/api/reveal' && req.method === 'POST') return readBody((body) => { // 404: not a file this session created · 410: created, and no longer there. A check (check: true) is answered 200 { exists: false, reason: 'unknown' | 'gone' } instead: the page asks it of every document it may show, and an error status there is a console error each time
1319
1483
  try {
1320
1484
  let b = null; try { b = JSON.parse(body); } catch {} const SAFE = /^[\w.\-]+$/, ok = (v) => typeof v === 'string' && SAFE.test(v) && v !== '..' && v.length <= 200;
1321
1485
  if (!b || !ok(b.proj) || !ok(b.id) || typeof b.file !== 'string' || !b.file || b.file.length > 4096) return json({ error: 'bad request' }, 400);
1322
- const f = sessionFile(b.proj, b.id, b.file); if (!f) return json({ error: 'not a file of this session' }, 404);
1323
- let st = null; try { st = reveal.stat(f.fp); } catch {} if (!st || !st.isFile()) return json({ error: 'gone' }, 410);
1324
- if (f.since && st.mtimeMs < f.since - 2000) return json({ error: 'not a file of this session' }, 404); // a command names it, and it was there before: read, listed or removed, not made
1325
- if (b.check !== true) reveal.run(f.fp); json({ ok: true }); // check: the page asks whether a document a command names is there, before it shows it
1486
+ const no = (reason, error, code) => (b.check === true ? json({ exists: false, reason }) : json({ error }, code));
1487
+ const f = sessionFile(b.proj, b.id, b.file); if (!f) return no('unknown', 'not a file of this session', 404);
1488
+ let st = null; try { st = reveal.stat(f.fp); } catch {} if (!st || !st.isFile()) return no('gone', 'gone', 410);
1489
+ if (f.since && st.mtimeMs < f.since - 2000) return no('unknown', 'not a file of this session', 404); // a command names it, and it was there before: read, listed or removed, not made
1490
+ if (b.check !== true) reveal.run(f.fp); json(b.check === true ? { ok: true, exists: true } : { ok: true }); // check: the page asks whether a document a command names is there, before it shows it
1326
1491
  } catch (e) { json({ error: String(e.message || e) }, 500); }
1327
1492
  });
1328
1493
  if (url.pathname === '/api/media') {
1329
1494
  const q = (k) => url.searchParams.get(k) || '', SAFE = /^[\w.\-]+$/, n = +q('n') || 0, bad = [q('proj'), q('id'), q('agent'), q('tool')].some((v) => !SAFE.test(v) || v === '..' || v.length > 200) || q('tool').length < 6; // no tool call has an id that short, and looking for one meant reading the whole transcript
1330
- const file = bad || !Number.isInteger(n) || n < 0 || n > 9 ? null : mediaFile(q('proj'), q('id'), q('agent')), im = file && toolImage(file, q('tool'), n);
1495
+ const sx = sourceOf(q('proj')), user = q('agent') === 'user', ok = !bad && Number.isInteger(n) && n >= 0 && n <= 9, file = ok && !sx ? mediaFile(q('proj'), q('id'), q('agent')) : null;
1496
+ const im = !ok ? null : q('proj') === '_demo' ? require('./demo.js').picture(q('tool'), n) : sx ? (sx.image ? guard(() => sx.image(q('id'), q('tool'), n, user), null) : null) : file && toolImage(file, q('tool'), n, user); // a Codex session: from its rollout, plain or compressed (codex.js)
1331
1497
  if (!im) { res.writeHead(bad ? 400 : 404); return res.end(bad ? 'bad request' : 'not found'); }
1332
1498
  res.writeHead(200, { 'content-type': im.type, 'content-length': im.buf.length, 'cache-control': 'private, max-age=3600', 'x-content-type-options': 'nosniff' }); return res.end(im.buf);
1333
1499
  }
1500
+ if (url.pathname === '/api/taskout') { // the end of what a command left running in the background has printed so far (taskOutput)
1501
+ const q = (k) => url.searchParams.get(k) || '', SAFE = /^[\w.\-]+$/, bad = [q('proj'), q('id')].some((v) => !SAFE.test(v) || /^\.+$/.test(v) || v.length > 200) || !/^[\w-]{1,40}$/.test(q('task'));
1502
+ if (bad) return json({ error: 'bad request' }, 400);
1503
+ const out = !sourceOf(q('proj')) && fs.existsSync(path.join(projDir(q('proj'), q('id')), q('id') + '.jsonl')) ? taskOutput(q('proj'), q('id'), q('task')) : null; // a session the call knows, of Claude Code: the other tools keep no such file
1504
+ return out ? json(out) : json({ error: 'not found' }, 404);
1505
+ }
1334
1506
  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
1335
1507
  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;
1336
1508
  if (bad) { res.writeHead(400); return res.end('bad request'); }
@@ -1374,7 +1546,7 @@ function start(port = PORT) {
1374
1546
  } catch (e) { logError(req.method + ' ' + url.pathname, e); if (res.headersSent) return res.destroy(); json({ error: String(e.message || e) }, 500); }
1375
1547
  }).listen(port, '127.0.0.1', function () { console.log(`Agent Standup → http://localhost:${this.address().port}`); });
1376
1548
  }
1377
- module.exports = { answerIn, noteEditor, forgetEditor, _winArg: winArg, start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, packsDir, installPack, logError, updateInfo, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
1549
+ module.exports = { answerIn, missingTranscripts, noteEditor, forgetEditor, _winArg: winArg, start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, packsDir, installPack, logError, updateInfo, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
1378
1550
  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
1379
1551
  const srv = start(+process.env.PORT || 0), tell = (m) => { try { process.send(m); } catch {} };
1380
1552
  srv.on('listening', () => tell({ port: srv.address().port })).on('error', (e) => { tell({ error: e.code || String(e) }); process.exit(1); });