@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.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // Agent Standup from a terminal: the live call in your browser, and one-line status for status bars (Claude Code, tmux, Neovim…).
3
3
  // agent-standup [serve] [--port 4747] [--open] start the local server and (optionally) open the page
4
- // agent-standup status [--here] [--json] counts of working / needs you / your turn
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
6
  // 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
7
  const path = require('path'), { spawn } = require('child_process');
@@ -10,7 +10,7 @@ const argv = process.argv.slice(2), flags = {}, rest = [];
10
10
  for (let i = 0; i < argv.length; i++) {
11
11
  const a = argv[i], val = () => argv[++i];
12
12
  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
- 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;
13
+ 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();
14
14
  else if (a === '-h' || a === '--help') flags.help = true; else if (a === '-v' || a === '--version') flags.version = true; else rest.push(a);
15
15
  }
16
16
  const cmd = rest[0] || 'serve';
@@ -24,7 +24,9 @@ Usage
24
24
  Options
25
25
  --port N port of the local server (default 4747)
26
26
  --open open the page in your browser
27
- --projects DIR where the session files are (default ~/.claude/projects, or $CLAUDE_CONFIG_DIR/projects)
27
+ --projects DIR where the session files are (default ~/.claude/projects, or $CLAUDE_CONFIG_DIR/projects); when it is
28
+ named projects, the sessions folder beside it is read too (what waits for you)
29
+ --config DIR Claude Code's config folder, as CLAUDE_CONFIG_DIR (its projects and sessions folders are read)
28
30
  --codex DIR where Codex keeps its files (default ~/.codex, or $CODEX_HOME); "off" to leave Codex sessions out
29
31
  --vibe DIR where Mistral Vibe keeps its files (default ~/.vibe, or $VIBE_HOME); "off" to leave Vibe sessions out
30
32
  --cowork DIR where the Claude desktop app keeps its Cowork sessions (default: its local-agent-mode-sessions folder); "off" to leave them out
@@ -32,11 +34,13 @@ Options
32
34
  --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,
33
35
  which older versions ignore instead of refusing
34
36
  --here status: only sessions of the current folder (matched on its real path, as Claude Code names it)
35
- --json status: machine-readable output (add --titles to include session titles)
37
+ --json status: machine-readable output
38
+ --titles include session titles, questions, commands and errors
36
39
  `;
37
40
  if (flags.help || cmd === 'help') { process.stdout.write(HELP); process.exit(0); }
38
41
  if (flags.version || cmd === 'version') { console.log(pkg.version); process.exit(0); }
39
42
  if (flags.projects) process.env.AGENT_STANDUP_PROJECTS = path.resolve(flags.projects);
43
+ if (flags.projects && path.basename(path.resolve(flags.projects)) === 'projects' && !process.env.AGENT_STANDUP_CC_SESSIONS) process.env.AGENT_STANDUP_CC_SESSIONS = path.join(path.dirname(path.resolve(flags.projects)), 'sessions'); // another Claude Code folder: its sessions' status (what needs you) is beside its projects
40
44
  if (flags.codex !== undefined) process.env.AGENT_STANDUP_CODEX = /^(0|off|no|false)?$/i.test(String(flags.codex)) ? 'off' : path.resolve(String(flags.codex));
41
45
  if (flags.vibe !== undefined) process.env.AGENT_STANDUP_VIBE = /^(0|off|no|false)?$/i.test(String(flags.vibe)) ? 'off' : path.resolve(String(flags.vibe));
42
46
  if (flags.cowork !== undefined) process.env.AGENT_STANDUP_COWORK = /^(0|off|no|false)?$/i.test(String(flags.cowork)) ? 'off' : path.resolve(String(flags.cowork));
@@ -48,18 +52,23 @@ if (flags.port !== undefined) { // a real port number or nothing: no silent fa
48
52
  }
49
53
  process.env.AGENT_STANDUP_HOST = (flags.from || process.env.AGENT_STANDUP_FROM) === 'plugin' ? 'claude code plugin' : 'command line'; // named in a problem report (⚙ › Report a problem), and what the usage count counts (--from plugin or AGENT_STANDUP_FROM=plugin: the Claude Code plugin's commands; the plugin uses the variable, since a version without --from refuses the flag)
50
54
  const server = require('../server.js');
51
- const projKey = (dir) => String(dir || '').replace(/[^a-zA-Z0-9]/g, '-'); // Claude Code's project folder naming
55
+ const projKey = (dir) => String(dir || '').replace(/[^a-zA-Z0-9]/g, '-'), fold = (k) => (process.platform === 'win32' ? String(k || '').toLowerCase() : k); // Claude Code's project folder naming · fold: on Windows a folder is the same whatever its case (c: or C:)
52
56
 
53
57
  function snapshot(dir) {
54
- const now = Date.now(), all = server.boardRows(), rows = dir ? all.filter((r) => r.proj === projKey(dir) || r.dir === projKey(dir)) : all; // dir: the folder a Codex session was started in, named the same way
58
+ const now = Date.now(), all = server.boardRows(), rows = dir ? all.filter((r) => fold(r.proj) === fold(projKey(dir)) || (!!r.dir && fold(r.dir) === fold(projKey(dir)))) : all; // dir: the folder a Codex session was started in, named the same way
55
59
  const act = rows.filter((r) => r.state !== 'idle' || now - r.mtime < 15 * 60e3), n = (st) => act.filter((r) => r.state === st).length;
56
- return { rows: act, needsYou: n('blocked'), working: n('working') + n('waiting'), yourTurn: n('turn'), idle: rows.length - act.length };
60
+ const turn = act.filter((r) => r.state === 'turn'), lim = turn.find((r) => r.limit); // a session stopped on your usage limit, or on a login that is gone: not a turn you can take
61
+ return { rows: act, needsYou: n('blocked'), working: n('working') + n('waiting'), yourTurn: turn.length, idle: rows.length - act.length, limit: lim ? (turn.every((r) => !r.limit || r.limit.resets === lim.limit.resets) ? lim.limit.resets || '' : '') : null, auth: turn.some((r) => r.auth), free: turn.some((r) => !r.limit && !r.auth) };
57
62
  }
58
- const line = (s, short) => { const p = []; if (s.needsYou) p.push(short ? `✋${s.needsYou}` : `✋ ${s.needsYou} needs you`); if (s.working) p.push(short ? `⚙${s.working}` : `⚙ ${s.working} working`); if (!s.needsYou && !s.working && s.yourTurn) p.push(short ? '✓' : '✓ your turn'); return p.join(short ? ' ' : ' · ') || (short ? '' : 'idle'); };
63
+ const line = (s, short) => {
64
+ const p = []; if (s.needsYou) p.push(short ? `✋${s.needsYou}` : `✋ ${s.needsYou} needs you`); if (s.working) p.push(short ? `⚙${s.working}` : `⚙ ${s.working} working`);
65
+ if (s.auth) p.push(short ? '⚠login' : '⚠ logged out: run /login'); if (s.limit != null) p.push(short ? '⏳' + s.limit.replace(/\s*\([^)]*\)\s*$/, '') : '⏳ usage limit' + (s.limit ? ' · resets ' + s.limit : '')); // short: the time without its zone
66
+ if (!s.needsYou && !s.working && s.free) p.push(short ? '✓' : '✓ your turn'); return p.join(short ? ' ' : ' · ') || (short ? '' : 'idle');
67
+ };
59
68
 
60
69
  if (cmd === 'status') {
61
70
  const s = snapshot(flags.here ? process.cwd() : '');
62
- 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, ...(flags.titles ? { title: r.title } : {}) })) }, null, 2));
71
+ 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
63
72
  else console.log(line(s, false));
64
73
  } else if (cmd === 'statusline') {
65
74
  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); };
package/codex.js CHANGED
@@ -1,9 +1,10 @@
1
1
  // Codex sessions (OpenAI's Codex: the desktop app and the command line) shown as the same call as Claude Code sessions.
2
- // Codex writes one "rollout" file per thread in <home>/sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl. Nothing is ever written there, and nothing else in the Codex folder is read
2
+ // Codex writes one "rollout" file per thread in <home>/sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl, and the desktop app later compresses a thread nobody uses (…jsonl.zst, read whole: see
3
+ // "compressed threads" below). Nothing is ever written there, and nothing else in the Codex folder is read
3
4
  // but session_index.jsonl (the names of the threads). server.js reads the files with its own incremental reader and hands each record to parser() below, which turns it into the
4
5
  // events a Claude Code record gives (say, user, tool, results, usage, compact), so everything after that is shared: the timeline, the live feed, the page.
5
6
  // All Codex sessions are listed under one made-up project, PROJ. No Claude Code project folder can have that name: theirs are paths with every other character turned into "-".
6
- const fs = require('fs'), os = require('os'), path = require('path');
7
+ const fs = require('fs'), os = require('os'), path = require('path'), zlib = require('zlib');
7
8
  const PROJ = '_codex', SOURCE = 'codex';
8
9
  // Where Codex keeps its files: AGENT_STANDUP_CODEX (a folder; "0" or "off" turns Codex sessions off), else $CODEX_HOME, else ~/.codex.
9
10
  // When AGENT_STANDUP_PROJECTS points the app at one folder of Claude Code sessions (--projects, the tests), Codex is only read if it is asked for too.
@@ -16,27 +17,29 @@ function home() {
16
17
  const dirKey = (cwd) => String(cwd || '').replace(/[^a-zA-Z0-9]/g, '-'); // the name Claude Code gives the same folder: how "this project" is asked for everywhere else
17
18
 
18
19
  // ---- finding the files
19
- const NAME = /^rollout-.*?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
20
+ const NAME = /^rollout-.*?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl(\.zst)?$/i;
21
+ const zstd = () => (typeof zlib.zstdDecompressSync === 'function' ? zlib.zstdDecompressSync : null); // Node 22.15 / 23.8 and later. With an older one (some VS Code and Electron versions) the compressed threads are left out, as before they were read
20
22
  let memo = { at: 0, home: undefined, rows: [], byId: new Map() };
21
23
  function scan() { // every rollout file with its date and size, newest first; shared by all the polls of two seconds
22
24
  const h = home(), now = Date.now(); if (memo.home === h && now - memo.at < 2000) return memo;
23
- const rows = [], byId = new Map();
25
+ const byId = new Map(), z = !!zstd();
24
26
  const walk = (dir, depth) => {
25
27
  let names; try { names = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
26
28
  for (const e of names) {
27
29
  const fp = path.join(dir, e.name);
28
30
  if (e.isDirectory()) { if (depth < 4) walk(fp, depth + 1); continue; }
29
- const m = NAME.exec(e.name); if (!m) continue;
31
+ const m = NAME.exec(e.name); if (!m || (m[2] && !z)) continue;
32
+ const id = m[1].toLowerCase(), was = byId.get(id); if (was && (!was.zst || m[2])) continue; // a thread in both forms for a moment (being compressed, or opened again): the plain file is the live one
30
33
  let st; try { st = fs.statSync(fp); } catch { continue; }
31
- const row = { id: m[1].toLowerCase(), file: fp, mtime: st.mtimeMs, size: st.size }; rows.push(row); byId.set(row.id, row);
34
+ byId.set(id, { id, file: fp, mtime: st.mtimeMs, size: st.size, ...(m[2] ? { zst: true } : {}) });
32
35
  }
33
36
  };
34
37
  if (h) walk(path.join(h, 'sessions'), 0);
35
- rows.sort((a, b) => b.mtime - a.mtime);
38
+ const rows = [...byId.values()]; rows.sort((a, b) => b.mtime - a.mtime);
36
39
  memo = { at: now, home: h, rows, byId }; return memo;
37
40
  }
38
41
  const row = (id) => scan().byId.get(String(id).toLowerCase()) || null;
39
- const fileOf = (id) => { const r = row(id); return r ? r.file : null; };
42
+ const fileOf = (id) => { let r = row(id); if (r && !fs.existsSync(r.file)) { memo.at = 0; r = row(id); } return r ? r.file : null; }; // a file that is gone (Codex compressed the thread while it was open): looked for again at once
40
43
 
41
44
  // ---- the first line of a file says what the thread is: its folder, and whether another thread started it
42
45
  const headCache = new Map(); // file → { ok, cwd, dir, child } (the first line never changes)
@@ -49,7 +52,13 @@ function firstLine(file, max = 1024 * 1024) {
49
52
  }
50
53
  function head(file) {
51
54
  const hit = headCache.get(file); if (hit) return hit;
52
- const { text, whole, capped } = firstLine(file); let out = { ok: false, cwd: '', dir: '', child: false };
55
+ if (/\.zst$/i.test(file)) { const z = zFacts(file); if (!z) return { ok: false, cwd: '', dir: '', child: false }; if (headCache.size > 5000) headCache.clear(); headCache.set(file, z.head); return z.head; } // the first line of a compressed thread never changes either
56
+ const { text, whole, capped } = firstLine(file), out = headOf(text, capped);
57
+ if (text && (whole || capped)) { if (headCache.size > 5000) headCache.clear(); headCache.set(file, out); } // a first line still being written is read again next time
58
+ return out;
59
+ }
60
+ function headOf(text, capped) {
61
+ let out = { ok: false, cwd: '', dir: '', child: false };
53
62
  if (!text) return out; // not written yet: looked at again next time
54
63
  let p = null; try { const r = JSON.parse(text); if (r && r.type === 'session_meta' && r.payload && typeof r.payload === 'object') p = r.payload; } catch {}
55
64
  if (p) out = { ok: true, cwd: typeof p.cwd === 'string' ? p.cwd : '', child: !!p.parent_thread_id || !!(p.source && typeof p.source === 'object' && p.source.subagent) };
@@ -58,7 +67,6 @@ function head(file) {
58
67
  out = { ok: true, cwd: c, child: /"parent_thread_id":"[^"]+"/.test(text) || /"source":\{"subagent"/.test(text) };
59
68
  }
60
69
  out.dir = dirKey(out.cwd);
61
- if (whole || capped) { if (headCache.size > 5000) headCache.clear(); headCache.set(file, out); } // a first line still being written is read again next time
62
70
  return out;
63
71
  }
64
72
  // The threads a person started, newest first. A thread started by another thread (Codex's review of a command before it runs, a sub-agent) is not a session of its own.
@@ -86,17 +94,38 @@ function typed(t) { // what the person typed, without what Codex wraps around
86
94
  return s.trim();
87
95
  }
88
96
  const partsText = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => (x && typeof x.text === 'string' ? x.text : '')).filter(Boolean).join('\n') : '');
97
+ // ---- pictures: those a call brought back, and those the person pasted, each { type, data (base64) }. The call counts them (img) and /api/media serves them (image, below), from the rollout itself.
98
+ // An MCP call's own (computer use: a screenshot, and the one its browser keeps of the page), a picture made (image_gen), and the parts of a raw output ("input_image", a data: address).
99
+ const DATA_IMG = /^data:(image\/(?:png|jpeg|gif|webp));base64,/;
100
+ const partImages = (c) => (Array.isArray(c) ? c : []).map((x) => { const m = x && x.type === 'input_image' && typeof x.image_url === 'string' ? DATA_IMG.exec(x.image_url.slice(0, 40)) : null; return m ? { type: m[1], data: x.image_url.slice(m[0].length) } : null; }).filter(Boolean);
101
+ function mcpImages(it) {
102
+ const res = it && it.result && typeof it.result === 'object' ? it.result : {}, out = (Array.isArray(res.content) ? res.content : []).filter((x) => x && x.type === 'image' && typeof x.data === 'string' && /^image\/(png|jpeg|gif|webp)$/.test(x.mimeType)).map((x) => ({ type: x.mimeType, data: x.data }));
103
+ const shot = res._meta && res._meta['codex/toolSurface'] && res._meta['codex/toolSurface'].screenshot, m = shot && typeof shot.url === 'string' ? DATA_IMG.exec(shot.url.slice(0, 40)) : null;
104
+ if (m) out.push({ type: m[1], data: shot.url.slice(m[0].length) });
105
+ return out;
106
+ }
107
+ const genImages = (it) => (it && typeof it.result === 'string' && it.result.length > 64 ? [{ type: 'image/png', data: it.result }] : []); // image_gen: the picture itself, base64
108
+ const localImages = (c) => (Array.isArray(c) ? c.filter((x) => x && x.type === 'local_image').length : 0); // what the person pasted, named by its path; the raw message of the same turn carries the pictures
109
+ const filePath = (p) => { if (typeof p !== 'string' || !/^file:\/\//i.test(p)) return p; try { return require('url').fileURLToPath(p); } catch { return p; } }; // an ImageView names its picture by a file: address
110
+ const hunksOf = (d) => { const out = []; let h = null; for (const l of String(d || '').split('\n')) { const m = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(l); if (m) out.push((h = { oldStart: +m[1], newStart: +m[2], lines: [] })); else if (h && /^[ +\-]/.test(l)) h.lines.push(l); } return out; }; // the parts of a unified diff, as Claude Code notes them (structuredPatch)
111
+ // A script of the model that looks at pictures (view_image) writes an ImageView item for each, then its output carries them, in the same order: they are matched when there are as many of each.
112
+ const viewMatch = (views, parts) => { const im = partImages(parts); return views.length && im.length === views.length ? im : null; };
89
113
  const promptCache = new Map(); // file → the first prompt ('' = looked for in the first megabyte and not there)
90
114
  function firstPrompt(r) {
115
+ if (r.zst) { const z = zFacts(r.file); return z ? z.prompt : ''; }
91
116
  const hit = promptCache.get(r.file); if (hit != null) return hit;
92
117
  let text = ''; try { const fd = fs.openSync(r.file, 'r'); try { const buf = Buffer.alloc(Math.min(1024 * 1024, r.size)); fs.readSync(fd, buf, 0, buf.length, 0); text = buf.toString('utf8'); } finally { fs.closeSync(fd); } } catch {}
118
+ const out = promptOf(text);
119
+ if (out || r.size > 64 * 1024) { if (promptCache.size > 2000) promptCache.clear(); promptCache.set(r.file, out); } // a file that has just been created is looked at again
120
+ return out;
121
+ }
122
+ function promptOf(text) { // the first thing the person typed in the first megabyte of a file
93
123
  let out = '';
94
124
  for (const l of text.split('\n')) {
95
125
  if (!l.includes('"UserMessage"') && !l.includes('"user_message"')) continue; let j; try { j = JSON.parse(l); } catch { continue; }
96
126
  const p = (j && j.payload) || {}, t = p.type === 'user_message' ? typed(p.message) : p.type === 'item_completed' && p.item && p.item.type === 'UserMessage' ? typed(partsText(p.item.content)) : '';
97
127
  if (t) { out = t.replace(/\s+/g, ' ').slice(0, 90); break; }
98
128
  }
99
- if (out || r.size > 64 * 1024) { if (promptCache.size > 2000) promptCache.clear(); promptCache.set(r.file, out); } // a file that has just been created is looked at again
100
129
  return out;
101
130
  }
102
131
  const title = (r) => threadNames().get(r.id) || firstPrompt(r) || r.id;
@@ -104,26 +133,79 @@ const title = (r) => threadNames().get(r.id) || firstPrompt(r) || r.id;
104
133
  // ---- the board: is the agent in the middle of a turn, or is it the person's turn? Read from the end of the file.
105
134
  const tailCache = new Map();
106
135
  function boardRow(r, now) {
107
- const sig = r.mtime + ':' + r.size; let t = tailCache.get(r.file);
108
- if (!t || t.sig !== sig) {
136
+ const sig = r.mtime + ':' + r.size; let t = r.zst ? zFacts(r.file) || { turn: 'closed', asked: 0 } : tailCache.get(r.file); // a compressed thread not read yet: Codex compresses only a thread nobody uses
137
+ if (!r.zst && (!t || t.sig !== sig)) {
109
138
  t = { sig, turn: '', asked: (t && t.asked) || 0 }; // asked: when the person last typed something there, which is what moves the live call (see currentSession in server.js)
110
139
  try {
111
140
  const fd = fs.openSync(r.file, 'r'); let text = ''; try { const n = Math.min(128 * 1024, r.size), buf = Buffer.alloc(n); fs.readSync(fd, buf, 0, n, r.size - n); text = buf.toString('utf8'); } finally { fs.closeSync(fd); }
112
- for (const l of text.split('\n')) { const m = /"type":"(task_started|task_complete|turn_started|turn_complete|turn_aborted)"/.exec(l.slice(0, 400)); if (m && l.includes('"event_msg"')) t.turn = /started/.test(m[1]) ? 'open' : 'closed';
113
- if (l.includes('"UserMessage"') || l.includes('"user_message"')) { try { const j = JSON.parse(l), p = (j && j.payload) || {}; if (p.type === 'user_message' ? typed(p.message) : p.type === 'item_completed' && p.item && p.item.type === 'UserMessage' && typed(partsText(p.item.content))) t.asked = Math.max(t.asked, Date.parse(j.timestamp) || 0); } catch {} } } // a first line cut in two does not parse
141
+ tailOf(text, t);
114
142
  } catch {}
115
143
  if (tailCache.size > 200) tailCache.delete(tailCache.keys().next().value); tailCache.set(r.file, t);
116
144
  }
117
145
  const age = now - r.mtime, state = age >= 30 * 60e3 ? 'idle' : t.turn === 'closed' ? 'turn' : age < 10 * 60e3 ? 'working' : 'idle';
118
146
  return { proj: PROJ, id: r.id, title: title(r), mtime: r.mtime, state, tool: '', ageMs: age, subActive: 0, subTotal: 0, asked: t.asked, dir: r.dir, source: 'codex' };
119
147
  }
148
+ function tailOf(text, t) { // the end of a file: whether the last turn is open or over (t.turn), and when the person last typed something (t.asked)
149
+ for (const l of text.split('\n')) { const m = /"type":"(task_started|task_complete|turn_started|turn_complete|turn_aborted)"/.exec(l.slice(0, 400)); if (m && l.includes('"event_msg"')) t.turn = /started/.test(m[1]) ? 'open' : 'closed';
150
+ if (l.includes('"UserMessage"') || l.includes('"user_message"')) { try { const j = JSON.parse(l), p = (j && j.payload) || {}; if (p.type === 'user_message' ? typed(p.message) : p.type === 'item_completed' && p.item && p.item.type === 'UserMessage' && typed(partsText(p.item.content))) t.asked = Math.max(t.asked, Date.parse(j.timestamp) || 0); } catch {} } } // a first line cut in two does not parse
151
+ return t;
152
+ }
153
+
154
+ // ---- compressed threads (…jsonl.zst). Codex no longer writes to them. What the list and the board need of one (zFacts) is read once in the background, from a stream that
155
+ // keeps only its first megabyte and its last 128 KB: a thread can be 78 MB uncompressed, and the first look at the list would otherwise hold every thread in memory and the server
156
+ // with it. Until then the thread is not listed (a second at most). The events of a thread opened in a call are read whole, at once (state(), which server.js asks before
157
+ // reading a file line by line), and kept for the last two only.
158
+ const ZMAX = 512 * 1024 * 1024, MB = 1024 * 1024, ZTAIL = 128 * 1024; // ZMAX: more than that uncompressed is not a thread: left out rather than filling the memory
159
+ const unzst = (file) => { const z = zstd(); return z ? z(fs.readFileSync(file), { maxOutputLength: ZMAX }) : null; };
160
+ const zCache = new Map(); // compressed file → { sig, head, prompt, turn, asked }, or { sig, bad } for one that could not be read (looked at again once it changes)
161
+ const zQueue = [], zQueued = new Set(); let zBusy = false;
162
+ function zFacts(file) { // null while it is being read
163
+ let sig; try { const s = fs.statSync(file); sig = s.mtimeMs + ':' + s.size; } catch { return null; }
164
+ const hit = zCache.get(file); if (hit && hit.sig === sig) return hit.bad ? null : hit;
165
+ if (!zQueued.has(file) && typeof zlib.createZstdDecompress === 'function') { zQueued.add(file); zQueue.push(file); zNext(); }
166
+ return null;
167
+ }
168
+ function zNext() { // one file at a time
169
+ if (zBusy || !zQueue.length) return; zBusy = true;
170
+ const file = zQueue.shift(), first = [], tail = []; let sig = '', n = 0, tn = 0, over = false, src, z;
171
+ const end = (ok) => {
172
+ if (over) return; over = true; zBusy = false; zQueued.delete(file); try { src.destroy(); z.destroy(); } catch {}
173
+ let out = { sig, bad: true };
174
+ if (ok) { const f = Buffer.concat(first), nl = f.indexOf(10); out = { sig, head: headOf(f.toString('utf8', 0, nl >= 0 ? nl : f.length), nl < 0 && n > MB), prompt: promptOf(f.toString('utf8')), ...tailOf(Buffer.concat(tail).subarray(-ZTAIL).toString('utf8'), tailOf(f.toString('utf8'), { turn: '', asked: 0 })) }; } // asked from both ends: a long command output can push the last thing typed out of the last 128 KB
175
+ if (sig) { if (zCache.size > 2000) zCache.clear(); zCache.set(file, out); }
176
+ setImmediate(zNext);
177
+ };
178
+ try { const s = fs.statSync(file); sig = s.mtimeMs + ':' + s.size; src = fs.createReadStream(file); z = zlib.createZstdDecompress(); } catch { return end(false); } // the stat before the read: a file changed meanwhile is read again
179
+ src.on('error', () => end(false)); z.on('error', () => end(false)); z.on('end', () => end(true));
180
+ z.on('data', (c) => {
181
+ if (n < MB) first.push(Buffer.from(c.subarray(0, MB - n)));
182
+ tail.push(c); tn += c.length; while (tail.length > 1 && tn - tail[0].length >= ZTAIL) tn -= tail.shift().length;
183
+ n += c.length; if (n > ZMAX) end(false);
184
+ });
185
+ src.pipe(z);
186
+ }
187
+ let made = null; // the record reader server.js made with parser(): a compressed thread goes through it here, whole
188
+ const zStates = new Map(); // compressed file → { sig, st }: the events of the last two threads read
189
+ function state(id) { // null: a plain file, which server.js reads line by line itself
190
+ const r = row(id); if (!r || !r.zst || !made) return null;
191
+ const sig = r.mtime + ':' + r.size, hit = zStates.get(r.file); if (hit && hit.sig === sig) { zStates.delete(r.file); zStates.set(r.file, hit); return hit.st; }
192
+ const st = { agent: 'main', file: r.file, journal: false, raw: [], toolName: {}, msgUsage: new Map() }; // what server.js's own reader would make of the plain file
193
+ let buf = null; try { buf = unzst(r.file); } catch {} if (!buf) return st; // unreadable for now: an empty session, never the compressed bytes taken for lines
194
+ for (let at = 0; at < buf.length;) {
195
+ let nl = buf.indexOf(10, at); if (nl < 0) nl = buf.length;
196
+ if (nl > at) { let j = null; try { j = JSON.parse(buf.toString('utf8', at, nl)); } catch {} if (j && typeof j === 'object') { try { made(st, j); } catch {} } } // one odd record must not take the whole timeline down
197
+ at = nl + 1;
198
+ }
199
+ zStates.set(r.file, { sig, st }); while (zStates.size > 2) zStates.delete(zStates.keys().next().value);
200
+ return st;
201
+ }
120
202
 
121
203
  // ---- one record of a rollout file → the events of the call
122
204
  // Two generations of the format are read. The current one (2026) writes an "item_completed" line for everything that happened: what was typed, what the agent said,
123
205
  // each command with its output, each file it changed, each search. The earlier one wrote the messages as "user_message" / "agent_message" events and the tool calls as
124
206
  // raw "function_call" records. A file of the current kind also carries those raw records (the script the model wrote around its commands), which would say everything twice:
125
207
  // once the first item is seen, the raw tool calls are left alone.
126
- function parser({ toolLabel, clip, resultMax = {} }) {
208
+ function parser({ toolLabel, clip, clipOut = clip, testsOf = () => null, diffOf = () => null, resultMax = {} }) { // clipOut: clip for an output (without the codes of a terminal) · testsOf: a test run's summary · diffOf: a change as a diff (server.js)
127
209
  const shellText = (c) => (Array.isArray(c) ? (c.length === 3 && /^-l?c$/.test(c[1]) ? c[2] : c.join(' ')) : String(c == null ? '' : c));
128
210
  const diffSides = (d) => { const add = [], del = []; for (const l of String(d || '').split('\n')) { if (/^(\+\+\+ |--- |@@|diff |index |\*\*\* )/.test(l)) continue; if (l[0] === '+') add.push(l.slice(1)); else if (l[0] === '-') del.push(l.slice(1)); } return { add: add.join('\n'), del: del.join('\n') }; };
129
211
  const patchFiles = (text) => { // the "*** Update File: x" blocks of an apply_patch call
@@ -132,16 +214,18 @@ function parser({ toolLabel, clip, resultMax = {} }) {
132
214
  return out.map((x) => ({ type: x.type, file: x.file, ...diffSides(x.body.join('\n')) }));
133
215
  };
134
216
  const NO_RESULT = new Set(['TodoWrite']);
135
- return function record(st, r) {
217
+ return (made = function record(st, r) {
136
218
  if (r.type !== 'event_msg' && r.type !== 'response_item' && r.type !== 'turn_context' && r.type !== 'compacted') return;
137
219
  const agent = st.agent, p = r.payload && typeof r.payload === 'object' ? r.payload : {}, cx = st.cx || (st.cx = { items: false, model: '', n: 0, tot: null, last: 0, userAt: -1 });
138
220
  const ts = Math.max(Date.parse(r.timestamp) || 0, st.lastTs || 0); st.lastTs = ts; // the lines of one file are in order; a line without a time takes the last one
139
221
  const push = (e) => { e.k = agent + ':' + st.raw.length; st.raw.push(e); if (e.ts > cx.last) cx.last = e.ts; return e; };
140
222
  const th = () => { const t = st.th; st.th = ''; return t ? { th: t } : {}; };
141
223
  const say = (text, final) => { const t = String(text == null ? '' : text).trim(); if (!t) return; const e = push({ ts, agent, kind: 'say', text: t, ...th() }); st.act = st.raw.length - 1; if (final && agent === 'main') e.end = 1; };
142
- const user = (text) => { const t = typed(text); if (!t) return; push({ ts, agent: 'user', kind: 'user', text: t }); cx.userAt = st.raw.length - 1; };
224
+ const user = (text, img, iid) => { const t = typed(text); if (!t) return; push({ ts, agent: 'user', kind: 'user', text: t, ...(img > 0 && typeof iid === 'string' && /^[\w.\-]{6,200}$/.test(iid) ? { img, iid } : {}) }); cx.userAt = st.raw.length - 1; };
143
225
  const call = (id, name, input, at) => { const when = Math.max(Math.min(at || ts, ts), cx.last); st.toolName[id] = name; push({ ts: when, agent, kind: 'tool', tool: toolLabel({ id, name, input: input || {} }, when), ...th() }); st.act = st.raw.length - 1; }; // a command is placed when it started, never before what the file already said
144
- const result = (id, out, err) => { const n = st.toolName[id]; if (!n || NO_RESULT.has(n)) return; push({ ts, agent, kind: 'results', items: [{ id, err: !!err, out: clip(String(out == null ? '' : out).trimEnd(), resultMax[n] || (/^mcp__/.test(n) ? 900 : 600)) }] }); };
226
+ const result = (id, out, err, more) => { const n = st.toolName[id]; if (!n || NO_RESULT.has(n)) return; push({ ts, agent, kind: 'results', items: [{ id, err: !!err, out: clipOut(String(out == null ? '' : out).trimEnd(), resultMax[n] || (/^mcp__/.test(n) ? 900 : 600)), ...more }] }); }; // more: what else the screen shows of it (img, tests, diff, search)
227
+ const views = () => { const v = cx.views || []; cx.views = []; return v; }; // the pictures looked at (ImageView) whose output has not come yet
228
+ const viewed = (parts) => { const v = views(), im = viewMatch(v, parts); v.forEach((id) => result(id, '', false, im ? { img: 1 } : {})); };
145
229
  const endTurn = () => { if (agent === 'main' && st.act > cx.userAt && st.raw[st.act]) st.raw[st.act].end = 1; }; // the turn is over (or was stopped): the last thing the lead said or did closes it
146
230
 
147
231
  if (r.type === 'turn_context') { if (typeof p.model === 'string') cx.model = p.model; return; }
@@ -149,21 +233,23 @@ function parser({ toolLabel, clip, resultMax = {} }) {
149
233
  if (r.type === 'event_msg') {
150
234
  if (p.type === 'item_completed' && p.item && typeof p.item === 'object') {
151
235
  const it = p.item, id = String(it.id || 'cx' + st.raw.length), at = +p.started_at_ms || 0; cx.items = true;
152
- if (it.type === 'UserMessage') user(partsText(it.content));
236
+ if (it.type === 'UserMessage') { viewed(null); user(partsText(it.content), localImages(it.content), it.id); }
153
237
  else if (it.type === 'AgentMessage') say(partsText(it.content), it.phase === 'final_answer');
154
- else if (it.type === 'CommandExecution') { call(id, 'Bash', { command: shellText(it.command) }, at); result(id, it.aggregated_output != null ? it.aggregated_output : [it.stdout, it.stderr].filter(Boolean).join('\n'), it.status === 'failed' || (typeof it.exit_code === 'number' && it.exit_code !== 0)); }
238
+ else if (it.type === 'CommandExecution') { call(id, 'Bash', { command: shellText(it.command) }, at); const o = it.aggregated_output != null ? String(it.aggregated_output) : [it.stdout, it.stderr].filter(Boolean).join('\n'), t = testsOf(o); result(id, o, it.status === 'failed' || (typeof it.exit_code === 'number' && it.exit_code !== 0), t ? { tests: t } : {}); }
155
239
  else if (it.type === 'FileChange') Object.entries(it.changes && typeof it.changes === 'object' ? it.changes : {}).forEach(([file, c], i) => {
156
240
  const cid = i ? id + ':' + i : id, kind = c && c.type, d = diffSides(c && c.unified_diff);
157
241
  if (kind === 'add') call(cid, 'Write', { file_path: file, content: c.content != null ? String(c.content) : d.add }, at);
158
242
  else call(cid, 'Edit', { file_path: file, old_string: kind === 'delete' && c.content != null ? String(c.content) : d.del, new_string: d.add }, at);
159
- result(cid, '', it.status === 'failed'); // the line is written once the change is made: without an answer the call would look like it is still waiting (for an approval, on a file change)
243
+ const df = kind !== 'add' && kind !== 'delete' ? diffOf([{ file, hunks: hunksOf(c && c.unified_diff) }], 0) : null; result(cid, '', it.status === 'failed', df ? { diff: df } : {}); // the line is written once the change is made: without an answer the call would look like it is still waiting (for an approval, on a file change)
160
244
  });
161
- else if (it.type === 'McpToolCall') { call(id, 'mcp__' + (it.server || 'mcp') + '__' + (it.tool || 'tool'), it.arguments && typeof it.arguments === 'object' ? it.arguments : {}, at); result(id, partsText(it.result && it.result.content), it.status === 'failed' || !!(it.result && it.result.isError)); }
162
- else if (it.type === 'ImageView') { call(id, 'Read', { file_path: it.path }, at); result(id, ''); }
245
+ else if (it.type === 'McpToolCall') { call(id, 'mcp__' + (it.server || 'mcp') + '__' + (it.tool || 'tool'), it.arguments && typeof it.arguments === 'object' ? it.arguments : {}, at); const n = mcpImages(it).length; result(id, partsText(it.result && it.result.content), it.status === 'failed' || !!(it.result && it.result.isError), n ? { img: n } : {}); }
246
+ else if (it.type === 'ImageView') { call(id, 'Read', { file_path: filePath(it.path) }, at); (cx.views = cx.views || []).push(id); } // answered with the output that carries its picture (viewed)
247
+ else if (it.type === 'Extension' && /^image_gen\./.test(it.kind || '')) { call(id, 'image_gen', { prompt: clip(it.revisedPrompt || it.prompt || '', 300) }, at); const n = genImages(it).length; result(id, typeof it.savedPath === 'string' ? it.savedPath : '', it.status === 'failed' || !!it.failure, n ? { img: n } : {}); }
163
248
  else if (it.type === 'Extension' && /^web\./.test(it.kind || '')) {
164
249
  const a = it.action && typeof it.action === 'object' ? it.action : {}, q = it.query || a.query || (Array.isArray(a.queries) && a.queries[0]) || '';
165
250
  if (a.url) call(id, 'WebFetch', { url: a.url }, at); else call(id, 'WebSearch', { query: q }, at);
166
- result(id, (Array.isArray(it.results) ? it.results : []).slice(0, 6).map((x) => (x.title || '') + (x.url ? ' · ' + x.url : '')).join('\n'));
251
+ const found = (Array.isArray(it.results) ? it.results : []).filter((x) => x && typeof x === 'object'), search = found.filter((x) => typeof x.url === 'string').slice(0, 8).map((x) => ({ t: clip(x.title, 120), u: clip(x.url, 300) }));
252
+ result(id, found.slice(0, 6).map((x) => (x.title || '') + (x.url ? ' · ' + x.url : '')).join('\n'), false, search.length ? { search } : {});
167
253
  }
168
254
  return;
169
255
  }
@@ -176,7 +262,7 @@ function parser({ toolLabel, clip, resultMax = {} }) {
176
262
  st.msgUsage.set('t' + cx.n++, { ts, u: { i: Math.max(0, (u.input_tokens || 0) - cached - w), o: u.output_tokens || 0, r: cached, w }, model: cx.model || 'codex', ...(info.model_context_window > 0 ? { cw: info.model_context_window } : {}) }); // cw: the size of the context window, which Codex states
177
263
  return;
178
264
  }
179
- if (p.type === 'task_complete' || p.type === 'turn_complete' || p.type === 'turn_aborted') endTurn();
265
+ if (p.type === 'task_complete' || p.type === 'turn_complete' || p.type === 'turn_aborted') { viewed(null); endTurn(); }
180
266
  return;
181
267
  }
182
268
  // response_item: what the model sent, raw
@@ -199,14 +285,57 @@ function parser({ toolLabel, clip, resultMax = {} }) {
199
285
  return;
200
286
  }
201
287
  if ((p.type === 'function_call_output' || p.type === 'custom_tool_call_output' || p.type === 'local_shell_call_output') && id) {
288
+ if (cx.items && (cx.views || []).length) viewed(p.output); // the output of a script that looked at pictures
202
289
  if (cx.items && st.toolName[id] !== 'AskUserQuestion') return; // in the current format the item already carried the output (an MCP call has the same id in both: it would be answered twice, the second time without its failure)
203
290
  let out = p.output, err = false;
204
291
  if (typeof out === 'string' && out[0] === '{') { try { const j = JSON.parse(out); if (j && typeof j === 'object' && ('output' in j || 'metadata' in j)) { err = !!(j.metadata && typeof j.metadata.exit_code === 'number' && j.metadata.exit_code !== 0); out = j.output != null ? j.output : ''; } } catch {} }
205
292
  else if (out && typeof out === 'object' && !Array.isArray(out)) { err = out.success === false; out = out.content != null ? out.content : ''; }
206
- result(id, partsText(out), err); for (let i = 1; i < ((cx.more || {})[id] || 0); i++) result(id + ':' + i, '', err);
293
+ const n = partImages(out).length; result(id, partsText(out), err, n ? { img: n } : {}); for (let i = 1; i < ((cx.more || {})[id] || 0); i++) result(id + ':' + i, '', err);
207
294
  return;
208
295
  }
209
296
  if (p.type === 'web_search_call' && !cx.items && id) call(id, 'WebSearch', { query: (p.action && p.action.query) || '' });
210
- };
297
+ });
298
+ }
299
+ // ---- /api/media for a Codex session: the n-th picture of a call (an MCP call, a picture looked at, one made, a raw output) or of a message the person sent (user: toolId is the message's item id),
300
+ // read from the rollout, plain or compressed, by the same rules as the count the call shows (img, above). The rollout read last is kept 20 s: a page asks for its pictures one after the other.
301
+ let imgBuf = { file: '', sig: '', buf: null, timer: null };
302
+ function rollout(r) {
303
+ const sig = r.mtime + ':' + r.size; if (imgBuf.file === r.file && imgBuf.sig === sig) return imgBuf.buf;
304
+ const buf = r.zst ? unzst(r.file) : fs.readFileSync(r.file); if (!buf) return null;
305
+ clearTimeout(imgBuf.timer); imgBuf = { file: r.file, sig, buf, timer: setTimeout(() => { imgBuf = { file: '', sig: '', buf: null, timer: null }; }, 20e3) }; if (imgBuf.timer.unref) imgBuf.timer.unref();
306
+ return buf;
307
+ }
308
+ function findImage(buf, toolId, n, user) { // { type, data } or null
309
+ const needle = Buffer.from('"' + toolId + '"'), VIEW = Buffer.from('"ImageView"'), OUT = Buffer.from('_call_output"'), PART = Buffer.from('"input_image"'), MSG = Buffer.from('"role":"user"'), pasted = new Map(); // pasted: turn → the raw message of the person that carries pictures
310
+ const parse = (line) => { try { const j = JSON.parse(line.toString('utf8')); return j && j.payload && typeof j.payload === 'object' ? j.payload : null; } catch { return null; } };
311
+ let views = [];
312
+ for (let a = 0; a < buf.length;) {
313
+ let b = buf.indexOf(10, a); if (b < 0) b = buf.length; const line = buf.subarray(a, b), hit = line.indexOf(needle) >= 0; a = b + 1;
314
+ if (user) {
315
+ if (line.indexOf(MSG) >= 0 && line.indexOf(PART) >= 0) { const p = parse(line); if (p && p.type === 'message' && p.role === 'user') { const m = p.internal_chat_message_metadata_passthrough; pasted.set(String((m && m.turn_id) || ''), p.content); if (pasted.size > 8) pasted.delete(pasted.keys().next().value); } }
316
+ else if (hit) { const p = parse(line), it = p && p.type === 'item_completed' && p.item; if (it && it.type === 'UserMessage' && it.id === toolId) return partImages(pasted.get(String(p.turn_id || '')))[n] || null; }
317
+ continue;
318
+ }
319
+ if (line.indexOf(VIEW) >= 0) { const p = parse(line), it = p && p.type === 'item_completed' && p.item; if (it && it.type === 'ImageView') { views.push(String(it.id)); continue; } }
320
+ if (line.indexOf(OUT) >= 0 && (views.length || hit)) {
321
+ const p = parse(line); if (!p || !/_call_output$/.test(String(p.type))) continue;
322
+ const v = views; views = []; const at = v.indexOf(toolId);
323
+ if (at >= 0) { const im = viewMatch(v, p.output); return im && n === 0 ? im[at] : null; }
324
+ if (hit && String(p.call_id) === toolId) { const im = partImages(p.output)[n]; if (im) return im; } // the earlier format: the call's own output
325
+ continue;
326
+ }
327
+ if (hit) { const p = parse(line), it = p && p.type === 'item_completed' && p.item; if (it && String(it.id) === toolId && (it.type === 'McpToolCall' || it.type === 'Extension')) return (it.type === 'McpToolCall' ? mcpImages(it) : genImages(it))[n] || null; }
328
+ }
329
+ return null;
330
+ }
331
+ const sniff = (b, type) => (b[0] === 0x89 && b[1] === 0x50 ? 'image/png' : b[0] === 0xff && b[1] === 0xd8 ? 'image/jpeg' : b.toString('latin1', 0, 4) === 'GIF8' ? 'image/gif' : b.toString('latin1', 8, 12) === 'WEBP' ? 'image/webp' : type); // the bytes say what they are: a computer-use screenshot written image/png is often a JPEG
332
+ const imgMemo = new Map();
333
+ function image(id, toolId, n, user) { // { type, buf } or null
334
+ const r = row(id); if (!r || typeof toolId !== 'string' || toolId.length < 4 || !(n >= 0)) return null;
335
+ const key = r.file + '|' + r.mtime + '|' + toolId + '|' + n + (user ? '|u' : ''); if (imgMemo.has(key)) return imgMemo.get(key);
336
+ let found = null; try { const buf = rollout(r); found = buf ? findImage(buf, toolId, n, !!user) : null; } catch {}
337
+ const b = found ? Buffer.from(found.data, 'base64') : null, out = b && b.length ? { type: sniff(b, found.type), buf: b } : null;
338
+ imgMemo.set(key, out); if (imgMemo.size > 12) imgMemo.delete(imgMemo.keys().next().value);
339
+ return out;
211
340
  }
212
- module.exports = { PROJ, SOURCE, home, dirKey, sessions, row, fileOf, cwd, inProject, projectLabel, title, boardRow, parser };
341
+ module.exports = { PROJ, SOURCE, home, dirKey, sessions, row, fileOf, cwd, inProject, projectLabel, title, boardRow, state, parser, image };