@double_geste/agent-standup 1.34.0 → 1.36.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
@@ -110,7 +110,7 @@ const toolLabel = (b, ts) => {
110
110
  case 'AskUserQuestion': out.d = { kind: 'text', what: 'question', text: clip((q0 ? q0.question + '\n' + (q0.options || []).map((o) => '• ' + (o.label || '')).join('\n') : ''), 500) }; break;
111
111
  case 'Skill': out.d = { kind: 'text', what: 'skill', v: i.skill, text: clip(i.skill + (i.args ? ' ' + i.args : ''), 200) }; break;
112
112
  case 'ToolSearch': out.d = { kind: 'text', what: 'toolsearch', text: clip(i.query, 200) }; break;
113
- case 'Artifact': if ((!i.action || i.action === 'publish') && !i.asset) { out.d = { kind: 'artifact', file: typeof i.file_path === 'string' ? i.file_path : '', title: clip(i.title, 120), note: clip(i.description, 240) }; break; } // a page published on claude.ai: the call shows it in a browser window (see artifactPage). Any other use of the tool (a read, a list, an upload) is a call like any other
113
+ case 'Artifact': if ((!i.action || i.action === 'publish') && !i.asset) { out.d = { kind: 'artifact', file: typeof i.file_path === 'string' ? i.file_path : '', title: clip(i.title, 120), note: clip(i.description, 240) }; const sent = i.files ? artSentOf(i) : [], pg = !/\.html?$/i.test(out.d.file) && sent.find((f) => /\.html?$/i.test(f)); if (sent.length > 1) out.d.sent = sent; if (pg) out.d.page = pg; break; } // a page published on claude.ai: the call shows it in a browser window (see artifactPage). Any other use of the tool (a read, a list, an upload) is a call like any other
114
114
  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)
115
115
  // falls through
116
116
  default: 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)
@@ -119,6 +119,12 @@ const toolLabel = (b, ts) => {
119
119
  return out;
120
120
  };
121
121
  // What a publish answered: the link of the page on claude.ai, its title and which version this is. typed: made from an Artifact type (a deck, a design, a document), whose page is the type's and not the file that was sent.
122
+ // What a publish sent along with its files (the artboards of a design, its canvas.json), as absolute paths, the way the Write calls that made them name them. page: the page of a publish whose main file is not one.
123
+ function artSentOf(i) {
124
+ const out = [], root = typeof i.root === 'string' && path.isAbsolute(i.root) ? i.root : '', add = (f) => { const p = typeof f !== 'string' || !f ? '' : path.isAbsolute(f) ? f : root ? path.join(root, f) : ''; if (p && !out.includes(p) && out.length < 60) out.push(p); };
125
+ add(i.file_path); for (const v of Array.isArray(i.files) ? i.files : i.files && typeof i.files === 'object' ? Object.values(i.files) : []) add(typeof v === 'string' ? v : v && (v.from || v.path));
126
+ return out;
127
+ }
122
128
  const ART_URL = /^https:\/\/claude\.ai\/(code\/)?artifact\/[\w-]{6,80}$/;
123
129
  const artifactOf = (u) => (u && typeof u === 'object' && typeof u.url === 'string' && ART_URL.test(u.url) ? { url: u.url, title: clip(u.title, 120), ...(u.seq > 0 ? { v: +u.seq } : {}), ...(u.type || u.created_from_type ? { typed: 1 } : {}) } : null);
124
130
  // What a call that put an artifact in front of the person answered, for the line of files: a publish (above); a doc the Claude Docs connector created, whose answer names the doc and its address;
@@ -179,52 +185,102 @@ function toolImage(file, toolId, n) { // looks for the tool's result line in t
179
185
  }
180
186
  // ---- 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
181
187
  // 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,
182
- // 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. A page made another way (by a command,
188
+ // 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
189
+ // that publish sent, an artboard, without the type's own page around it, which only claude.ai has: its scripts do not run, the rest of it reads as it is. A page made another way (by a command,
183
190
  // or written by another agent) has no preview: the call shows its title and its link. The page is served to a frame that can reach neither this server nor, unless the person asked, the network (see /api/artifact).
184
191
  const artMemo = new Map(), ART_MAX = 8 * 1024 * 1024;
185
192
  const editOnce = (text, e) => { const a = e && typeof e.old_string === 'string' ? e.old_string : '', b = e && typeof e.new_string === 'string' ? e.new_string : ''; if (!a) return text; if (e.replace_all) return text.split(a).join(b); const i = text.indexOf(a); return i < 0 ? text : text.slice(0, i) + b + text.slice(i + a.length); };
186
- function artifactPage(file, toolId, fp) { // the text of the page at fp as it was when the call toolId published it, or null
187
- const key = file + '|' + toolId, memo = artMemo.get(key); if (memo && memo.html != null) return memo;
188
- const pathMark = Buffer.from(JSON.stringify(fp).slice(1, -1)), errMark = Buffer.from('"is_error":true'), idMark = Buffer.from('"' + toolId + '"'), until = Date.now() + 2000;
189
- const ops = [], failed = new Set(); let fd, carry = Buffer.alloc(0), pos = 0, size = 0, seen = false;
193
+ function artifactFiles(file, wants) { // wants: [{ fp, until }] → for each, the text of the file at fp as it was when the publish until sent it, or null. One pass over the session file for them all
194
+ const key = file + '|' + wants.map((w) => w.fp + '@' + w.until).join('|'), memo = artMemo.get(key); if (memo && memo.found) return memo.found;
195
+ const W = wants.map((w) => ({ fp: w.fp, until: w.until, path: Buffer.from(JSON.stringify(w.fp).slice(1, -1)), id: Buffer.from('"' + w.until + '"'), ops: [], seen: false }));
196
+ const errMark = Buffer.from('"is_error":true'), until = Date.now() + 2000, failed = new Set(); let fd, carry = Buffer.alloc(0), pos = 0, size = 0;
190
197
  try {
191
- fd = fs.openSync(file, 'r'); size = fs.fstatSync(fd).size; if (memo && memo.miss === size) return null; // already looked for in vain, and nothing was written since
198
+ fd = fs.openSync(file, 'r'); size = fs.fstatSync(fd).size; if (memo && memo.miss === size) return W.map(() => null); // already looked for in vain, and nothing was written since
192
199
  while (pos < size && Date.now() < until) {
193
200
  const buf = Buffer.alloc(Math.min(8 * 1024 * 1024, size - pos)); fs.readSync(fd, buf, 0, buf.length, pos); pos += buf.length;
194
201
  const all = carry.length ? Buffer.concat([carry, buf]) : buf; let a = 0;
195
202
  for (let b; (b = all.indexOf(10, a)) >= 0; a = b + 1) {
196
- const line = all.subarray(a, b), mine = !seen && (line.indexOf(pathMark) >= 0 || line.indexOf(idMark) >= 0); if (!mine && line.indexOf(errMark) < 0) continue;
203
+ const line = all.subarray(a, b), mine = W.some((w) => !w.seen && (line.indexOf(w.path) >= 0 || line.indexOf(w.id) >= 0)); if (!mine && line.indexOf(errMark) < 0) continue;
197
204
  let r; try { r = JSON.parse(line.toString('utf8')); } catch { continue; }
198
205
  for (const blk of blocks(r)) {
199
206
  if (blk.type === 'tool_result' && blk.is_error) failed.add(blk.tool_use_id); // a write or an edit that was refused changed nothing (its answer may come after the publish, when both were asked at once)
200
- if (blk.type !== 'tool_use' || seen) continue; const i = blk.input || {};
201
- if (blk.id === toolId) seen = true; // what was written after that publish belongs to the next one
202
- else if (i.file_path === fp && (blk.name === 'Write' || blk.name === 'Edit' || blk.name === 'MultiEdit')) ops.push({ id: blk.id, name: blk.name, i });
207
+ if (blk.type !== 'tool_use') continue; const i = blk.input || {}, op = blk.name === 'Write' || blk.name === 'Edit' || blk.name === 'MultiEdit';
208
+ for (const w of W) { if (w.seen) continue; if (blk.id === w.until) w.seen = true; else if (op && i.file_path === w.fp) w.ops.push({ id: blk.id, name: blk.name, i }); } // what was written after that publish belongs to the next one
203
209
  }
204
210
  }
205
211
  carry = Buffer.from(all.subarray(a));
206
212
  }
207
213
  } catch {} finally { if (fd != null) fs.closeSync(fd); }
208
- let html = null;
209
- if (seen && pos >= size) for (const op of ops) {
210
- if (failed.has(op.id)) continue;
211
- if (op.name === 'Write') html = typeof op.i.content === 'string' ? op.i.content : null;
212
- else if (html != null) for (const e of op.name === 'MultiEdit' ? (Array.isArray(op.i.edits) ? op.i.edits : []) : [op.i]) html = editOnce(html, e);
213
- }
214
- if (html != null && html.length > ART_MAX) html = null;
215
- const found = html != null ? { html, net: /<script\b[^>]*\bsrc\s*=\s*["']?https?:/i.test(html) } : null; // net: it names a library kept on another server, which the frame does not load unless asked
216
- artMemo.delete(key); artMemo.set(key, found || { miss: size }); if (artMemo.size > 8) artMemo.delete(artMemo.keys().next().value);
214
+ const found = W.map((w) => {
215
+ let html = null; if (!w.seen || pos < size) return null;
216
+ for (const op of w.ops) {
217
+ if (failed.has(op.id)) continue;
218
+ if (op.name === 'Write') html = typeof op.i.content === 'string' ? op.i.content : null;
219
+ else if (html != null) for (const e of op.name === 'MultiEdit' ? (Array.isArray(op.i.edits) ? op.i.edits : []) : [op.i]) html = editOnce(html, e);
220
+ }
221
+ return html != null && html.length <= ART_MAX ? { html, net: /<script\b[^>]*\bsrc\s*=\s*["']?https?:/i.test(html) } : null; // net: it names a library kept on another server, which the frame does not load unless asked
222
+ });
223
+ artMemo.delete(key); artMemo.set(key, found.some(Boolean) ? { found } : { miss: size }); if (artMemo.size > 24) artMemo.delete(artMemo.keys().next().value);
217
224
  return found;
218
225
  }
219
- function artifactCall(proj, id, agent, toolId) { // the file a publish of that very session sent, when the call shows a page for it: a plain page, published without error
220
- let fp = '', ok = false;
226
+ const artifactPage = (file, toolId, fp) => artifactFiles(file, [{ fp, until: toolId }])[0]; // the text of the page at fp as it was when the call toolId published it, or null
227
+ // What the call shows for a publish of that very session, published without error: the page it sent. For an artifact made from a type that was sent several pages (the artboards of a design),
228
+ // also each page as its last publish up to this one sent it, and the canvas.json that places them, if one was sent: the whole document, once it is made, since claude.ai cannot be shown here.
229
+ const CANVAS = /(^|[\\/])canvas\.json$/i;
230
+ const ART_LS = new RegExp('[' + String.fromCharCode(0x2028, 0x2029) + ']', 'g'); // the two line ends JSON keeps and a script does not
231
+ function artifactPlan(proj, id, agent, toolId) {
232
+ const d = new Map(), ok = new Map(); let url = '', typed = false;
221
233
  for (const e of timeline(proj, id).events) {
222
234
  if (e.agent !== agent) continue;
223
- if (e.kind === 'tools') { for (const t of e.tools) if (t.id === toolId && t.d && t.d.kind === 'artifact') fp = t.d.file; }
224
- else if (e.kind === 'results') { for (const it of e.items) if (it.id === toolId && it.art && !it.art.typed) ok = true; }
235
+ if (e.kind === 'tools') { for (const t of e.tools) if (t.d && t.d.kind === 'artifact') d.set(t.id, t.d); }
236
+ else if (e.kind === 'results') { for (const it of e.items) if (it.art && d.has(it.id)) { ok.set(it.id, it.art.url); if (it.id === toolId) { url = it.art.url; typed = !!it.art.typed; } } }
225
237
  }
226
- return ok && /\.html?$/i.test(fp) ? fp : null;
238
+ const me = d.get(toolId), fp = me ? (typed && me.page) || me.file : ''; if (!url || !/\.html?$/i.test(fp)) return null; // the page sent beside a canvas.json counts for a template only: a plain artifact is its main file
239
+ const plan = { fp, pages: [], canvas: null }; if (!typed) return plan;
240
+ const last = new Map(); for (const [tid, u] of ok) { if (u === url) for (const f of d.get(tid).sent || [d.get(tid).file]) if (/\.html?$/i.test(f) || CANVAS.test(f)) last.set(f, tid); if (tid === toolId) break; } // in the order they were first sent
241
+ for (const [f, tid] of last) { if (CANVAS.test(f)) plan.canvas = { fp: f, until: tid }; else plan.pages.push({ fp: f, until: tid }); }
242
+ return plan;
243
+ }
244
+ function artifactBuild(file, toolId, plan, whole) { // the page to show, or null. pages, label: how many pages the document has so far, and the name the canvas gives this one
245
+ const one = artifactPage(file, toolId, plan.fp); if (!plan.pages.length) return one;
246
+ const got = artifactFiles(file, plan.canvas ? [...plan.pages, plan.canvas] : plan.pages), list = plan.pages.map((w, k) => ({ fp: w.fp, page: got[k] })).filter((x) => x.page);
247
+ let canvas = null; try { canvas = plan.canvas && got[plan.pages.length] ? JSON.parse(got[plan.pages.length].html) : null; } catch {}
248
+ const boards = canvas && canvas.boards && typeof canvas.boards === 'object' ? canvas.boards : {}, keyOf = (fp) => Object.keys(boards).find((k) => fp === k || fp.endsWith('/' + k)), board = (fp) => (keyOf(fp) ? boards[keyOf(fp)] : null);
249
+ const name = (fp) => clip((board(fp) || {}).title, 80) || path.basename(fp).replace(/(\.dc)?\.html?$/i, ''), label = name(plan.fp);
250
+ if (!whole || list.length < 2) return one && { ...one, pages: list.length, label };
251
+ const order = canvas && Array.isArray(canvas.order) ? canvas.order : [], rank = (x) => { const n = order.indexOf(keyOf(x.fp)); return n < 0 ? 1e6 : n; }; list.sort((a, b) => rank(a) - rank(b));
252
+ const num = (v, dflt) => (Number.isFinite(+v) && +v > 0 ? Math.min(+v, 20000) : dflt), pos = (v) => (Number.isFinite(+v) ? Math.max(-1e5, Math.min(1e5, +v)) : 0), PREV = /"\$preview"\s*:\s*\{\s*"width"\s*:\s*(\d+)\s*,\s*"height"\s*:\s*(\d+)/;
253
+ const items = list.map((x) => { const b = board(x.fp), pv = PREV.exec(x.page.html); return { html: x.page.html, title: name(x.fp), x: b ? pos(b.x) : null, y: b ? pos(b.y) : null, w: num(b && b.w, pv ? +pv[1] : 1100), h: num(b && b.h, pv ? +pv[2] : 800) }; });
254
+ const notes = canvas && canvas.notes && typeof canvas.notes === 'object' ? Object.values(canvas.notes).filter((n) => n && typeof n.text === 'string').slice(0, 40).map((n) => ({ text: clip(n.text, 120), x: pos(n.x), y: pos(n.y), big: /^title/.test(n.kind || '') })) : [];
255
+ const data = JSON.stringify({ items, notes }).replace(/</g, '\\u003c').replace(ART_LS, (ch) => '\\u' + ch.charCodeAt(0).toString(16));
256
+ return { html: ARTIFACT_WHOLE.replace('%DATA%', () => data), net: list.some((x) => x.page.net), pages: list.length, label };
227
257
  }
258
+ // The whole document: each page in a shadow root of its own (its styles stay its own; its script tags do not run, its inline handlers do, in the same sandbox as the frame of one page). Shared, every page at once in the grid that shows them
259
+ // largest; pinned (fit=w), where the canvas puts them (or three to a row), to the width of the window, to scroll through. No backslash in this script: the template literal would eat it.
260
+ const ARTIFACT_WHOLE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;background:#e8e8ec}#o{position:relative;margin:0 auto;overflow:hidden}#c{position:absolute;left:0;top:0;transform-origin:0 0}.b{position:absolute;overflow:hidden;background:#fff;box-shadow:0 2px 14px rgba(0,0,0,.18);font:initial;color:initial}.t,.n{position:absolute;white-space:nowrap;font:600 22px system-ui,sans-serif;color:#666}.n{font-size:30px;color:#333}.n.big{font-size:44px;font-weight:700}</style><div id="o"><div id="c"></div></div><script type="application/json" id="d">%DATA%</script><script>
261
+ (function () {
262
+ var D = JSON.parse(document.getElementById('d').textContent), c = document.getElementById('c'), o = document.getElementById('o'), M = 60, wide = /[?&]fit=w(&|$)/.test(location.search);
263
+ var placed = D.items.filter(function (it) { return it.x != null; }), gy = placed.length ? Math.max.apply(null, placed.map(function (it) { return it.y + it.h; })) + 160 : 0, gx = 0, col = 0, rowH = 0;
264
+ D.items.forEach(function (it) { if (it.x != null) return; if (col === 3) { col = 0; gx = 0; gy += rowH + 120; rowH = 0; } it.x = gx; it.y = gy; gx += it.w + 80; rowH = Math.max(rowH, it.h); col++; }); // pages the canvas does not place: three to a row, below it
265
+ var els = D.items.map(function (it) {
266
+ var b = document.createElement('div'), t = document.createElement('div'); b.className = 'b'; b.attachShadow({ mode: 'open' }).innerHTML = it.html; t.className = 't'; t.textContent = it.title; c.appendChild(t); c.appendChild(b); return { it: it, b: b, t: t };
267
+ });
268
+ var notes = D.notes.map(function (n) { var e = document.createElement('div'); e.className = 'n' + (n.big ? ' big' : ''); e.textContent = n.text; c.appendChild(e); return { n: n, e: e }; });
269
+ var fit = function () { // pinned (fit=w): where the canvas puts each page, to the width of the window, to scroll through; shared: every page at once, in the grid that shows them largest
270
+ var x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9, box = function (x, y, w, h) { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x + w); y1 = Math.max(y1, y + h); };
271
+ var put = function (e, x, y) { e.b.style.cssText = 'left:' + x + 'px;top:' + y + 'px;width:' + e.it.w + 'px;height:' + e.it.h + 'px'; e.t.style.cssText = 'left:' + x + 'px;top:' + (y - 38) + 'px'; box(x, y - 44, e.it.w, e.it.h + 44); };
272
+ if (wide) { els.forEach(function (e) { put(e, e.it.x, e.it.y); }); notes.forEach(function (n) { n.e.style.cssText = 'left:' + n.n.x + 'px;top:' + n.n.y + 'px'; box(n.n.x, n.n.y, 400, 60); }); }
273
+ else {
274
+ var n = els.length, cw = Math.max.apply(null, els.map(function (e) { return e.it.w; })) + 60, ch = Math.max.apply(null, els.map(function (e) { return e.it.h; })) + 84, k = 1, best = 0;
275
+ for (var j = 1; j <= n; j++) { var r = Math.ceil(n / j), s0 = Math.min(innerWidth / (j * cw + 2 * M), innerHeight / (r * ch + 2 * M)); if (s0 > best) { best = s0; k = j; } }
276
+ els.forEach(function (e, i) { put(e, (i % k) * cw, Math.floor(i / k) * ch + 44); }); notes.forEach(function (n) { n.e.style.cssText = 'display:none'; });
277
+ }
278
+ var bw = x1 - x0 + 2 * M, bh = y1 - y0 + 2 * M, s = wide ? innerWidth / bw : Math.min(innerWidth / bw, innerHeight / bh);
279
+ o.style.width = bw * s + 'px'; o.style.height = bh * s + 'px'; o.style.marginTop = wide ? '0' : Math.max(0, (innerHeight - bh * s) / 2) + 'px'; c.style.transform = 'scale(' + s + ') translate(' + (M - x0) + 'px,' + (M - y0) + 'px)';
280
+ };
281
+ fit(); addEventListener('resize', fit);
282
+ })();
283
+ </script>`;
228
284
  // What the frame of an artifact may do: run the page's own scripts, and nothing else. "sandbox" without allow-same-origin gives the page an origin of its own, also when its address is opened in a tab:
229
285
  // it cannot read this server (which refuses what does not come from its own page), keep anything, open a window or send a form. Without net, nothing is fetched from anywhere. With net (the person
230
286
  // asked for the libraries of the pages, ⚙ or the button in the window), scripts and fonts come from the servers claude.ai itself lets an artifact use, and from nowhere else; the page still cannot send anything out.
@@ -312,9 +368,31 @@ const readTail = (file, bytes) => { const fd = fs.openSync(file, 'r'); try { con
312
368
  const readHead = (file, bytes) => { const fd = fs.openSync(file, 'r'); try { const n = Math.min(bytes, fs.fstatSync(fd).size), buf = Buffer.alloc(n); fs.readSync(fd, buf, 0, n, 0); return buf.toString('utf8'); } finally { fs.closeSync(fd); } };
313
369
  const APPROVAL = /^(Edit|Write|MultiEdit|NotebookEdit)/, ASKS = /^(AskUserQuestion|ExitPlanMode)/, SUBTOOL = /^(Task|Agent)$/;
314
370
  const boardCache = new Map(); // file → { sig, parsed, title }
315
- let boardMemo = { at: 0, rows: [] };
371
+ let boardMemo = { at: 0, rows: [] }, boardForced = 0;
316
372
  const PR_URL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+$/; // nothing else is given to the page as a link to open
317
373
  const askOf = (b) => { const q = b.name === 'AskUserQuestion' && b.input && Array.isArray(b.input.questions) && b.input.questions[0] && b.input.questions[0].question; return typeof q === 'string' ? clip(q.trim(), 200) : ''; }; // the question a session stopped on, for its card
374
+ const callOf = (b) => { const i = b.input || {}, v = b.name === 'Bash' ? i.command : /^(Edit|Write|MultiEdit|NotebookEdit)$/.test(b.name) ? path.basename(String(i.file_path || i.notebook_path || '')) : b.name === 'WebFetch' ? i.url : ''; return typeof v === 'string' && v.trim() ? b.name + '(' + clip(v.replace(/\s+/g, ' ').trim(), 160) + ')' : ''; }; // what a call waiting for your go-ahead would do, written the way Claude Code shows it: Bash(npm test)
375
+ const PLAN_FILE = /[\\/]\.claude[\\/]plans[\\/][^\\/]+\.md$/, PLAN_DIR = process.env.CLAUDE_CONFIG_DIR ? path.join(process.env.CLAUDE_CONFIG_DIR, 'plans') + path.sep : '';
376
+ const planFile = (f) => PLAN_FILE.test(f) || (!!PLAN_DIR && f.startsWith(PLAN_DIR) && f.endsWith('.md')); // also where a CLAUDE_CONFIG_DIR set elsewhere keeps them
377
+ const planText = (f) => { try { const st = fs.statSync(f); if (!st.isFile() || st.size > 262144) return ''; return clip(fs.readFileSync(f, 'utf8').trim(), 1200); } catch { return ''; } };
378
+ const menuOf = (b) => { // what a menu waiting for you shows, from the call it waits on, word for word: the questions and their options in their order (the terminal numbers them the same way), the command, the file, the plan
379
+ const i = b.input || {}, t = (x, n) => (typeof x === 'string' ? clip(x.trim(), n) : '');
380
+ if (b.name === 'AskUserQuestion') return { kind: 'question', questions: (Array.isArray(i.questions) ? i.questions : []).slice(0, 4).map((q) => ({ q: t(q && q.question, 300), multi: !!(q && q.multiSelect), options: (q && Array.isArray(q.options) ? q.options : []).slice(0, 8).map((o) => ({ label: t(o && o.label, 80), about: t(o && o.description, 140) })).filter((o) => o.label) })).filter((q) => q.q) };
381
+ if (b.name === 'ExitPlanMode') return { kind: 'plan', text: t(i.plan, 1200) };
382
+ if (b.name === 'Bash') return { kind: 'command', cmd: t(i.command, 600), about: t(i.description, 160) };
383
+ if (/^(Edit|Write|MultiEdit|NotebookEdit)$/.test(b.name)) return { kind: 'edit', file: t(i.file_path || i.notebook_path, 300) };
384
+ if (b.name === 'WebFetch') return { kind: 'fetch', url: t(i.url, 300) };
385
+ return { kind: 'tool', tool: t(b.name, 80) };
386
+ };
387
+ // Claude Code also keeps <config>/sessions/<pid>.json for each open session: its status (busy, idle, or waiting while a menu waits for your answer: a permission, a question) and since when.
388
+ // 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.
389
+ const CC_SESSIONS = process.env.AGENT_STANDUP_CC_SESSIONS || path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'sessions');
390
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
391
+ function liveStatus() { // session id → { status, since }
392
+ const out = new Map(); let names = []; try { names = fs.readdirSync(CC_SESSIONS); } catch { return out; }
393
+ 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.waitingFor === 'dialog open' ? 'idle' : s.status, since: Number(s.statusUpdatedAt) || 0 }); } catch {} } /* a dialog you opened yourself (/model, /config, /mcp…) also says waiting: it is not a question for you */
394
+ return out;
395
+ }
318
396
  // 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).
319
397
  // 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.
320
398
  // 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.
@@ -334,8 +412,8 @@ function typedBefore(file) { // the first look at a session whose last order i
334
412
  function parseTail(file, st) {
335
413
  const sig = st.mtimeMs + ':' + st.size, hit = boardCache.get(file); if (hit && hit.sig === sig) return hit;
336
414
  const { text, cut } = readTail(file, 192 * 1024), lines = text.split('\n'); if (cut) lines.shift();
337
- const pend = new Map(); let 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;
338
- for (const l of lines) {
415
+ const pend = new Map(); let 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;
416
+ for (const l of lines) try { // one odd record costs that record, not the whole card
339
417
  if (!l) continue; let r; try { r = JSON.parse(l); } catch { continue; }
340
418
  const a = typedAt(r); if (a > asked) asked = a;
341
419
  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
@@ -343,8 +421,9 @@ function parseTail(file, st) {
343
421
  const t = Date.parse(r.timestamp) || 0, bl = blocks(r);
344
422
  if (r.type === 'assistant' || r.type === 'user') { 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;
345
423
  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
346
- for (const b of bl) { if (b.type === 'tool_use') pend.set(b.id, { name: b.name, ts: t, q: askOf(b) }); else if (b.type === 'tool_result') pend.delete(b.tool_use_id); }
347
- }
424
+ 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
425
+ 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); }
426
+ } catch {}
348
427
  if (!hit && !custom) { // first look at this file: a little further back than the lines read above, and without needing whole lines
349
428
  const big = readTail(file, 256 * 1024).text, un = (m) => { try { return m ? JSON.parse('"' + m[1] + '"') : null; } catch { return null; } };
350
429
  custom = un([...big.matchAll(/"type":"custom-title","customTitle":"((?:[^"\\]|\\.)*)"/g)].pop()); if (!ai) ai = un([...big.matchAll(/"type":"ai-title","aiTitle":"((?:[^"\\]|\\.)*)"/g)].pop());
@@ -352,7 +431,7 @@ function parseTail(file, st) {
352
431
  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
353
432
  if (!hit && !asked && cut) asked = typedBefore(file);
354
433
  const out = { sig, title: custom || ai || first || null, custom, ai, first, pr, lastType, lastTool, lastStop, stops, esc, lastTs, pending: [...pend.values()] }; // a title the person typed wins over the generated one, and both over the first prompt
355
- out.asked = asked; boardCache.set(file, out); if (boardCache.size > 200) boardCache.delete(boardCache.keys().next().value); return out;
434
+ out.asked = asked; out.plan = plan; 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
356
435
  }
357
436
  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
358
437
  const ONE = (t) => t.replace(/\s+/g, ' ').trim().slice(0, 90);
@@ -368,28 +447,42 @@ function boardRows() {
368
447
  if (Date.now() - boardMemo.at < 1200) return boardMemo.rows; // several windows polling at once share one scan
369
448
  const out = withDone(boardRows0()); boardMemo = { at: Date.now(), rows: out }; return out;
370
449
  }
450
+ // How many sessions the list keeps, newest first, of each kind (Claude Code, each other tool, Cowork): `most` of them, and whatever the count, the PER_FOLDER newest of each folder, so that
451
+ // sessions written elsewhere never push the ones of a folder out. That is what happened with only a count: the Claude Code session of the folder the call follows left the list, and with it its
452
+ // tab and the call, behind 40 sessions a desktop app had just written in temporary folders (issue #9). Sessions started in a temporary folder (see tmpKey) have places of their own, TMP_ROWS at most.
453
+ const PER_FOLDER = 3, TMP_ROWS = 10, ROWS_MAX = 200; // ROWS_MAX: a ceiling on what the folders add, for someone with hundreds of folders (one worktree per task)
454
+ function capRows(list, most, folderOf) { // list: newest first
455
+ const real = list.filter((r) => !tmpKey(folderOf(r))), keep = new Set(real.slice(0, most)), per = new Map();
456
+ 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); } }
457
+ return real.filter((r) => keep.has(r)).concat(list.filter((r) => tmpKey(folderOf(r))).slice(0, TMP_ROWS));
458
+ }
371
459
  function boardRows0() {
372
- const now = Date.now(), rows = [];
460
+ const now = Date.now(), rows = [], live = liveStatus();
373
461
  for (const m of SOURCES) for (const r of guard(() => m.sessions(), [])) if (now - r.mtime < 12 * 3600e3) rows.push({ proj: m.PROJ, id: r.id, st: { mtimeMs: r.mtime, size: r.size }, cx: r, src: m });
374
462
  for (const proj of projects()) {
375
463
  for (const { id, file } of transcripts(proj)) { try { const st = fs.statSync(file); if (now - st.mtimeMs < 12 * 3600e3) rows.push({ proj, id, st }); } catch {} }
376
464
  }
377
465
  rows.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs);
378
- return rows.filter((r) => !r.cx && r.proj !== COWORK).slice(0, 40).concat(...SOURCES.map((m) => rows.filter((r) => r.src === m).slice(0, 20)), rows.filter((r) => r.proj === COWORK).slice(0, 20)).sort((a, b) => b.st.mtimeMs - a.st.mtimeMs).map(({ proj, id, st, cx, src }) => {
466
+ const own = (r) => r.proj, folder = (r) => String(r.cx.key || r.cx.dir || ''); // a Claude Code session is listed under its folder; a Codex or Vibe one says which folder it was started in
467
+ return capRows(rows.filter((r) => !r.cx && r.proj !== COWORK), 40, own).concat(...SOURCES.map((m) => capRows(rows.filter((r) => r.src === m), 20, folder)), rows.filter((r) => r.proj === COWORK).slice(0, 20)).sort((a, b) => b.st.mtimeMs - a.st.mtimeMs).map(({ proj, id, st, cx, src }) => {
379
468
  if (cx) { const r = guard(() => src.boardRow(cx, now), null); if (r && tmpKey(r.dir)) r.tmp = 1; return r; } // tmp: started in the temporary folder (see tmpKey)
380
469
  const file = path.join(projDir(proj, id), id + '.jsonl'); let p; try { p = parseTail(file, st); } catch { p = { pending: [] }; }
381
- const age = now - st.mtimeMs, lp = (p.pending || [])[(p.pending || []).length - 1]; let state = 'idle', tool = '', ageMs = age;
382
- if (age < 30 * 60e3) {
470
+ const age = now - st.mtimeMs, pend = p.pending || [], w = live.get(id), lp = (w && w.status === 'waiting' && pend.find((c) => !SUBTOOL.test(c.name))) || pend[pend.length - 1]; let state = 'idle', tool = '', ageMs = age, since = 0, open = null; // lp: with a menu open and several calls waiting, Claude Code asks about the first of them
471
+ if (w && w.status === 'waiting' && lp) { state = 'blocked'; tool = lp.name; since = w.since || lp.ts || st.mtimeMs; ageMs = now - since; } // a menu is open in the session and a call waits on it: it needs you now, however long ago it was written
472
+ else if (w && w.status === 'waiting') { state = 'blocked'; since = w.since || st.mtimeMs; ageMs = now - since; const pt = p.plan && p.plan.ts > (p.asked || 0) ? planText(p.plan.file) : ''; open = { id: 'w' + since, tool: pt ? 'ExitPlanMode' : '', ...(pt ? { kind: 'plan', text: pt } : { kind: 'menu' }), sure: 1 }; } // a menu is open and the transcript has no call waiting on it: the plan to approve (Claude Code writes that call only once it is answered, the plan itself is in its file, written this turn), or a menu it does not record
473
+ else if (age < 30 * 60e3) {
383
474
  if (lp) { ageMs = now - (lp.ts || st.mtimeMs); tool = lp.name;
384
- state = SUBTOOL.test(lp.name) ? 'waiting' : (ASKS.test(lp.name) && ageMs > 4000) || (APPROVAL.test(lp.name) && ageMs > 15000) ? 'blocked' : 'working'; }
475
+ state = SUBTOOL.test(lp.name) ? 'waiting' : (ASKS.test(lp.name) && ageMs > 4000) || (APPROVAL.test(lp.name) && ageMs > 15000) ? 'blocked' : 'working'; if (state === 'blocked') since = lp.ts || st.mtimeMs; } // still a guess from how long a call has waited: a session in VS Code asks in its panel, which may not say "waiting"
385
476
  else if (p.esc) state = 'turn'; // you stopped it (Esc): it is your turn there, not "working" for the next ten minutes
386
477
  else if (p.lastType === 'assistant' && !p.lastTool && p.lastStop !== 'tool_use' && !(p.lastStop == null && p.stops && age < 45000)) state = '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.
387
478
  // 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)
388
479
  else state = age < 10 * 60e3 ? 'working' : 'idle';
480
+ if (state === 'turn') since = p.lastTs || st.mtimeMs;
389
481
  }
390
482
  let subActive = 0, subTotal = 0;
391
483
  for (const x of subFiles(proj, id)) { subTotal++; if (now - mtimeOf(x.file) < 90e3) subActive++; }
392
- return { proj, id, title: coworkTitle(proj, id) || p.title || id, mtime: st.mtimeMs, state, tool, ageMs, subActive, subTotal, asked: p.asked || 0, ...(p.pr ? { pr: p.pr } : {}), ...(state === 'blocked' && lp && lp.q ? { ask: lp.q } : {}), ...(p.esc ? { cut: 1 } : {}), ...(tmpKey(proj) ? { tmp: 1 } : {}) }; // cut: stopped by you, which is no news to tell you
484
+ const ran = since && p.asked && p.asked < since ? since - p.asked : 0, ask = state === 'blocked' && lp ? lp.q || lp.c : ''; // since: when it started to wait on you; ran: how long it worked, from your last order to then
485
+ return { proj, id, title: coworkTitle(proj, id) || p.title || id, mtime: st.mtimeMs, state, tool, ageMs, subActive, subTotal, asked: p.asked || 0, ...(since ? { since } : {}), ...(ran ? { ran } : {}), ...(p.pr ? { pr: p.pr } : {}), ...(ask ? { ask } : {}), ...(open ? { menu: open } : state === 'blocked' && lp && lp.m && !SUBTOOL.test(lp.name) ? { menu: { id: lp.id, tool: lp.name, ...lp.m, ...(w && w.status === 'waiting' ? { sure: 1 } : {}) } } : {}), ...(p.esc ? { cut: 1 } : {}), ...(tmpKey(proj) ? { tmp: 1 } : {}) }; // cut: stopped by you, which is no news to tell you
393
486
  }).filter(Boolean);
394
487
  }
395
488
  // 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).
@@ -459,6 +552,7 @@ process.on('uncaughtExceptionMonitor', (e, origin) => { try { if (OWN || String(
459
552
  // One exception, so that the call is not left on an empty room: when the session you last typed in has finished and been quiet for STICK_MS while another one is at work, the call
460
553
  // goes to that one. A session you went to by hand is not left that way.
461
554
  const STICK_MS = 90000;
555
+ const MENU_LIVE_MS = 30 * 60e3; // a menu left open longer still needs you (board, visitor), but no longer takes the call from where you work
462
556
  // Sessions started in the system's temporary folder: a program running Claude Code there for a moment (a test, a script, a tool that makes a folder per run), not a session someone works in.
463
557
  // When the call looks everywhere it leaves them out, unless there is nothing else; they have no tab then and send no visitor. They stay in the Sessions view, and a window open on such a folder follows it.
464
558
  // macOS: /var/folders/… (/private/… once resolved) and /tmp; Linux: /tmp; Windows: …\AppData\Local\Temp; and wherever TMPDIR points. A key is a folder as Claude Code names it, every other character a "-".
@@ -470,15 +564,26 @@ function sessionMtime(proj, id) {
470
564
  let m = sx ? r.mtime : mtimeOf(path.join(projDir(proj, id), id + '.jsonl')); if (!m) return 0; const subs = subFilesOf(proj, id);
471
565
  for (const x of subs) m = Math.max(m, mtimeOf(x.file)); for (const d of subs.dirs) m = Math.max(m, mtimeOf(d)); return m; // the folders too: a new file in them is activity, as when every file around the transcripts was looked at
472
566
  }
567
+ // 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).
568
+ // 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.
569
+ const projCwds = new Map(), dirKey = (d) => String(d || '').replace(/[^a-zA-Z0-9]/g, '-');
570
+ function projCwd(proj) {
571
+ if (projCwds.has(proj)) return projCwds.get(proj);
572
+ 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 {} }
573
+ 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
574
+ }
575
+ 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; };
473
576
  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)
474
577
  const safe = (x) => typeof x === 'string' && /^[\w.\-]+$/.test(x) && x !== '..', now = Date.now();
475
578
  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')));
476
- const inScope = (c) => (!projFilter ? anyTmp || !tmpSession(c.proj, c.id) : c.proj === projFilter || c.proj.startsWith(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
477
- const same = (a, b) => !!a && !!b && a.proj === b.proj && a.id === b.id, all = boardRows(), rows = all.filter(inScope), mine = there(pick) ? all.find((r) => same(r, pick)) : null;
579
+ 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
580
+ const same = (a, b) => !!a && !!b && a.proj === b.proj && a.id === b.id; let all = boardRows();
581
+ 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
582
+ const rows = all.filter(inScope), mine = there(pick) ? all.find((r) => same(r, pick)) : null;
478
583
  const asked = Math.max(0, (mine && mine.asked) || 0, ...rows.map((r) => r.asked || 0)); // the latest order, in the folder the call follows or in the session you went to
479
584
  const moved = pick && pick.pin ? Math.max(0, ...rows.filter((r) => !same(r, pick)).map((r) => r.asked || 0)) : asked; // pick.pin: a call pinned by a click on its tab (📌) is left for an order typed in another session only; what you type in it keeps it there
480
585
  if (there(pick) && !(moved > pick.since)) return { proj: pick.proj, id: pick.id, mtime: now, asked, pick: 1 }; // no "since" on the first question after a pick: the answer gives it (asked), and the page sends it back from then on
481
- const live = rows.filter((r) => /^(working|waiting|blocked)$/.test(r.state) || r.subActive > 0 || now - r.mtime < STICK_MS), last = Math.max(0, ...live.map((r) => r.asked || 0)), top = live.filter((r) => (r.asked || 0) === last);
586
+ const live = rows.filter((r) => /^(working|waiting)$/.test(r.state) || (r.state === 'blocked' && !(now - (r.since || now) > MENU_LIVE_MS)) || r.subActive > 0 || now - r.mtime < STICK_MS), last = Math.max(0, ...live.map((r) => r.asked || 0)), top = live.filter((r) => (r.asked || 0) === last);
482
587
  const to = top.find((r) => same(r, stick)) || top.sort((a, b) => b.mtime - a.mtime)[0]; // two sessions whose last order is not known (or of the same instant): the call stays where it is
483
588
  if (to) return { proj: to.proj, id: to.id, mtime: to.mtime, asked };
484
589
  if (there(stick) && inScope(stick)) return { proj: stick.proj, id: stick.id, mtime: sessionMtime(stick.proj, stick.id), asked }; // nobody is at work: the call stays where it is
@@ -486,7 +591,7 @@ function currentSession(projFilter, pick, stick, anyTmp) { // pick: { proj, id
486
591
  const consider = (proj, id, m) => { if (!best || m > best.mtime) best = { proj, id, mtime: m }; };
487
592
  for (const m of SOURCES) for (const r of guard(() => m.sessions(), [])) if (inScope({ proj: m.PROJ, id: r.id })) consider(m.PROJ, r.id, r.mtime);
488
593
  for (const proj of projects()) {
489
- if (projFilter ? proj !== projFilter && !proj.startsWith(projFilter + '-') : !anyTmp && tmpKey(proj)) continue; // the folder itself, or a folder inside it (a Cowork session is in no folder of yours: it counts when the call looks everywhere, or at Cowork)
594
+ if (projFilter ? !inFolder(proj, projFilter) : !anyTmp && tmpKey(proj)) continue; // the folder itself, or a folder inside it (a Cowork session is in no folder of yours: it counts when the call looks everywhere, or at Cowork)
490
595
  for (const { id } of transcripts(proj)) { const m = sessionMtime(proj, id); if (m) consider(proj, id, m); } // 0: a link to a transcript that is gone
491
596
  }
492
597
  if (!best && projFilter) return { ...currentSession('', null, stick), wide: 1 };
@@ -655,7 +760,8 @@ function buildTimeline(proj, id, files = []) {
655
760
 
656
761
  // Ask the local `claude` CLI (uses the user's existing login) to map a JSON array of strings to another array. Cached.
657
762
  const { spawn } = require('child_process');
658
- const cache = new Map();
763
+ const cache = new Map(), CACHE_MAX = 5000; // translations and little lines, by text: the oldest go first past CACHE_MAX (an editor open for days kept every line of every session)
764
+ const remember = (k, v) => { cache.delete(k); cache.set(k, v); if (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value); };
659
765
  // Find a usable `claude` binary: explicit setting → PATH → usual install spots → the one bundled with the VS Code Claude Code extension.
660
766
  let lastTrError = '', claudeCache = null;
661
767
  const exists = (f) => { try { return fs.statSync(f).isFile(); } catch { return false; } };
@@ -680,10 +786,14 @@ function findClaude() {
680
786
  const found = cands.find(exists) || bundledClaude() || null;
681
787
  return (claudeCache = found);
682
788
  }
789
+ // Through cmd.exe, Node joins the arguments with spaces and quotes none: the empty value of --tools vanished and the system prompt became one argument per word. Quoted, each stays whole
790
+ // (a line break or a double quote inside would end it: there are none in what is sent, and they are made harmless anyway).
791
+ const winArg = (a) => '"' + String(a).replace(/[\r\n]+/g, ' ').replace(/"/g, "'") + '"';
683
792
  function spawnClaude(args, opts) {
684
793
  const bin = findClaude(); if (!bin) { lastTrError = 'not-found'; return null; }
685
- if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(bin)) return spawn('"' + bin + '"', args, { ...opts, shell: true, windowsHide: true }); // npm's Windows shims need a shell
686
- return spawn(bin, args, { ...opts, windowsHide: true });
794
+ const p = process.platform === 'win32' && /\.(cmd|bat)$/i.test(bin) ? spawn('"' + bin + '"', args.map(winArg), { ...opts, shell: true, windowsHide: true }) : spawn(bin, args, { ...opts, windowsHide: true }); // npm's Windows shims need a shell, which takes the arguments as they are: each one is quoted
795
+ if (p.stdin) p.stdin.on('error', () => {}); // a claude that exits before reading its prompt (not signed in, an old version): EPIPE would otherwise end the whole server
796
+ return p;
687
797
  }
688
798
  let running = 0; const queue = [];
689
799
  const pump = () => { while (running < 3 && queue.length) { running++; queue.shift()(); } };
@@ -701,7 +811,7 @@ function claudeMap(kind, instruction, texts) {
701
811
  const done = (ok) => ({ texts: texts.map((t) => cache.get(kind + '|' + t) || t), ok });
702
812
  if (!need.length) return Promise.resolve(done(true));
703
813
  const prompt = instruction + ' Output ONLY a JSON array of strings, same length and order, no markdown.\n' + JSON.stringify(need);
704
- return apiMap(prompt, need).then((arr) => { need.forEach((t, i) => cache.set(kind + '|' + t, String(arr[i]))); return done(true); }).catch(() => schedule(() => new Promise((resolve) => {
814
+ return apiMap(prompt, need).then((arr) => { need.forEach((t, i) => remember(kind + '|' + t, String(arr[i]))); return done(true); }).catch(() => schedule(() => new Promise((resolve) => {
705
815
  const p = spawnClaude(['-p', '--model', 'haiku', '--no-session-persistence', '--tools', ''], { cwd: os.tmpdir() }); if (!p) return resolve(done(false));
706
816
  let out = ''; const timer = setTimeout(() => p.kill(), 60000);
707
817
  p.stdout.on('data', (d) => (out += d));
@@ -711,7 +821,7 @@ function claudeMap(kind, instruction, texts) {
711
821
  let ok = false;
712
822
  try {
713
823
  const arr = JSON.parse(out.slice(out.indexOf('['), out.lastIndexOf(']') + 1));
714
- if (arr.length === need.length) { need.forEach((t, i) => cache.set(kind + '|' + t, String(arr[i]))); ok = true; }
824
+ if (arr.length === need.length) { need.forEach((t, i) => remember(kind + '|' + t, String(arr[i]))); ok = true; }
715
825
  } catch {}
716
826
  resolve(done(ok));
717
827
  });
@@ -761,7 +871,7 @@ const pickWorker = () => trWorkers.reduce((a, b) => (a.q.length + a.busy <= b.q.
761
871
  async function translateFast(texts, lang = 'fr') {
762
872
  const need = [...new Set(texts.filter((t) => !cache.has(lang + '|' + t)))];
763
873
  if (need.length && need.length <= 3 && !process.env.ANTHROPIC_API_KEY) { // a few lines: warm workers in parallel; many lines: one batched call
764
- await Promise.all(need.map(async (t) => { const r = await pickWorker().ask(t, lang); if (r) cache.set(lang + '|' + t, r); }));
874
+ await Promise.all(need.map(async (t) => { const r = await pickWorker().ask(t, lang); if (r) remember(lang + '|' + t, r); }));
765
875
  return { texts: texts.map((t) => cache.get(lang + '|' + t) || t), ok: texts.every((t) => cache.has(lang + '|' + t)) };
766
876
  }
767
877
  return claudeMap(lang, trInstr(lang), texts);
@@ -790,10 +900,11 @@ function loadVoices() { // the same list for the page, asked without waiting:
790
900
  if (sayVoices) return Promise.resolve(sayVoices);
791
901
  return sayVoicesJob || (sayVoicesJob = new Promise((resolve) => { try { execFile(VOICES_CMD[0], VOICES_CMD[1], { encoding: 'utf8', timeout: VOICES_CMD[2], windowsHide: true }, (err, out) => resolve(sayVoices || (sayVoices = parseVoices(err ? '' : String(out))))); } catch { resolve(sayVoices || (sayVoices = parseVoices(''))); } }));
792
902
  }
793
- const ttsDir = path.join(os.tmpdir(), 'agent-standup-tts-' + (process.getuid ? process.getuid() : 'user'));
903
+ const ttsDir = process.platform === 'linux' ? path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'agent-standup', 'tts') : path.join(os.tmpdir(), 'agent-standup-tts-' + (process.getuid ? process.getuid() : 'user')); // Linux: /tmp is shared by every user, and a folder or file put there first by someone else would have been used (written through, or played); macOS and Windows give each user a temporary folder of their own
794
904
  try { fs.mkdirSync(ttsDir, { recursive: true, mode: 0o700 }); } catch {}
795
905
  const ttsJobs = new Map();
796
- try { for (const f of fs.readdirSync(ttsDir)) { const p = path.join(ttsDir, f); if (Date.now() - fs.statSync(p).mtimeMs > 864e5) fs.unlinkSync(p); } } catch {} // drop cached audio older than a day
906
+ const ttsClean = () => { try { for (const f of fs.readdirSync(ttsDir)) { const p = path.join(ttsDir, f); if (Date.now() - fs.statSync(p).mtimeMs > 864e5) fs.unlinkSync(p); } } catch {} }; // drop cached audio older than a day
907
+ ttsClean(); setInterval(ttsClean, 3600e3).unref(); // also while an editor stays open for days
797
908
  function synthesize(voice, wpm, text, out) {
798
909
  return new Promise((resolve, reject) => {
799
910
  let p; text = text.replace(/\[\[[^\]]*\]\]/g, ' ').replace(/\[(?=\[)/g, '[ ').replace(/\](?=\])/g, '] '); // macOS `say` obeys commands written between [[ and ]] (a 30-second silence, another voice, another speed) and this text comes from a transcript: they are taken out, and no two brackets are left side by side
@@ -946,14 +1057,18 @@ const reveal = { // run and stat: replaced in the tests, which must not open a
946
1057
  },
947
1058
  run(file) { const go = (list) => { const c = list[0]; if (!c) return; try { execFile(c[0], c[1], c[2] || {}, (err) => { if (err) go(list.slice(1)); }); } catch { go(list.slice(1)); } }; go(reveal.cmds(file)); },
948
1059
  };
949
- let audioOwner = { id: null, seen: 0 };
1060
+ // Which window plays sound, in a file next to the settings: each VS Code window has its own server, and two windows with the call open both spoke.
1061
+ const AUDIO = path.join(path.dirname(PREFS), 'audio.json');
1062
+ let audioMem = { id: null, seen: 0 }, audioFile = true; // audioFile false: the file cannot be written (a read-only folder), this server keeps the owner itself as it used to
1063
+ const audioOwner = () => { if (!audioFile) return audioMem; try { const a = JSON.parse(fs.readFileSync(AUDIO, 'utf8')); if (a && typeof a.id === 'string') return { id: a.id, seen: Math.min(+a.seen || 0, Date.now()) }; } catch {} return { id: null, seen: 0 }; }; // min: a clock set back left a time to come, and the owner never expired
1064
+ const audioSave = (a) => { audioMem = a; try { fs.mkdirSync(path.dirname(AUDIO), { recursive: true }); const t = AUDIO + '.' + process.pid; fs.writeFileSync(t, JSON.stringify(a)); fs.renameSync(t, AUDIO); } catch { audioFile = false; } }; // whole or not at all: another server may read it at that moment
950
1065
  function start(port = PORT) {
951
1066
  return http.createServer((req, res) => {
952
1067
  let url; try { url = new URL(req.url, 'http://x'); } catch { res.writeHead(400); return res.end('bad request'); } // "GET //" is not an address: answered, where it used to stop the whole server
953
1068
  req.on('error', () => {}); res.on('error', () => {}); // a browser that goes away mid-request is not our problem
954
1069
  // Only the local machine may talk to this server: blocks other websites (cross-site requests) and DNS-rebinding attempts.
955
1070
  const local = (h) => /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(h || '');
956
- let originOk = true; try { originOk = !req.headers.origin || local(new URL(req.headers.origin).host); } catch { originOk = false; }
1071
+ let originOk = true; try { originOk = !req.headers.origin || (local(new URL(req.headers.origin).host) && new URL(req.headers.origin).host === req.headers.host); } catch { originOk = false; } // the page's own address: another local page (a dev server on another port) is another site
957
1072
  if (!local(req.headers.host) || !originOk) { res.writeHead(403); return res.end('forbidden'); }
958
1073
  const json = (o, code = 200) => { try { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); } catch { res.destroy(); } }; // also called from callbacks that run later, where nothing would catch an exception
959
1074
  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
@@ -977,10 +1092,11 @@ function start(port = PORT) {
977
1092
  }
978
1093
  if (url.pathname === '/api/audio') { // only one window at a time plays sound: the last one that claimed it (expires if that window stops answering)
979
1094
  const cid = url.searchParams.get('cid') || '', ok = /^[\w-]{4,40}$/.test(cid);
980
- if (ok && url.searchParams.get('claim')) audioOwner = { id: cid, seen: Date.now() };
981
- else if (ok && audioOwner.id === cid) audioOwner.seen = Date.now();
982
- if (audioOwner.id && Date.now() - audioOwner.seen > 6000) audioOwner = { id: null, seen: 0 };
983
- return json({ owner: audioOwner.id });
1095
+ const now = Date.now(); let a = audioOwner();
1096
+ if (ok && url.searchParams.get('claim')) audioSave((a = { id: cid, seen: now }));
1097
+ else if (ok && a.id === cid && now - a.seen > 2000) audioSave((a = { id: cid, seen: now })); // the owner says it is still there, written every 2 s at most
1098
+ if (a.id && now - a.seen > 6000) a = { id: null, seen: 0 };
1099
+ return json({ owner: a.id });
984
1100
  }
985
1101
  if (url.pathname === '/api/health') return json({ claude: findClaude(), apiKey: !!process.env.ANTHROPIC_API_KEY, trError: lastTrError, platform: process.platform });
986
1102
  if (url.pathname === '/api/warm') { const lang = trLang(url.searchParams.get('lang')); trWorkers.forEach((w) => { if (!w.p) w.start(lang); }); return json({ ok: true }); }
@@ -1027,11 +1143,11 @@ function start(port = PORT) {
1027
1143
  if (!im) { res.writeHead(bad ? 400 : 404); return res.end(bad ? 'bad request' : 'not found'); }
1028
1144
  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);
1029
1145
  }
1030
- 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)
1146
+ 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
1031
1147
  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;
1032
1148
  if (bad) { res.writeHead(400); return res.end('bad request'); }
1033
- const file = sourceOf(q('proj')) ? null : mediaFile(q('proj'), q('id'), q('agent')), fp = file && fs.existsSync(file) && fs.existsSync(mediaFile(q('proj'), q('id'), 'main')) ? artifactCall(q('proj'), q('id'), q('agent'), q('tool')) : null, page = fp && artifactPage(file, q('tool'), fp);
1034
- if (q('check')) return json(page ? { ok: true, net: page.net } : { ok: false }, page ? 200 : 404);
1149
+ const file = sourceOf(q('proj')) ? null : mediaFile(q('proj'), q('id'), q('agent')), plan = file && fs.existsSync(file) && fs.existsSync(mediaFile(q('proj'), q('id'), 'main')) ? artifactPlan(q('proj'), q('id'), q('agent'), q('tool')) : null, page = plan && artifactBuild(file, q('tool'), plan, q('whole') === '1');
1150
+ if (q('check')) return json(page ? { ok: true, net: page.net, ...(page.pages > 1 ? { pages: page.pages, label: page.label } : {}) } : { ok: false }, page ? 200 : 404); // pages: a document of several pages, which can be shown whole (whole=1)
1035
1151
  if (!page) { res.writeHead(404); return res.end('not found'); }
1036
1152
  const body = Buffer.from((/^\s*<!doctype/i.test(page.html) ? '' : '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">') + page.html, 'utf8'); // an artifact is published as the inside of a page: claude.ai adds the rest, and so does this
1037
1153
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': body.length, 'content-security-policy': artifactCsp(q('net') === '1'), 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer', 'cache-control': 'private, no-store' }); return res.end(body);
@@ -1059,19 +1175,25 @@ function start(port = PORT) {
1059
1175
  let f = ''; try { f = decodeURIComponent(pk ? pk[2] : url.pathname.slice('/characters/'.length)); } catch {}
1060
1176
  const dir = pk ? packDir(pk[1]) : charactersDir(), fp = path.join(dir, f);
1061
1177
  try { const ls = fs.lstatSync(fp); if (!CHAR_NAME.test(f) || !fp.startsWith(dir + path.sep) || !ls.isFile() || ls.size > CHAR_MAX) throw 0; } catch { res.writeHead(404); return res.end('not found'); }
1062
- res.writeHead(200, { 'content-type': CHAR_TYPES[f.split('.').pop().toLowerCase()] || 'application/octet-stream', 'cache-control': 'no-cache' }); return sendFile(fp);
1178
+ res.writeHead(200, { 'content-type': CHAR_TYPES[f.split('.').pop().toLowerCase()] || 'application/octet-stream', 'cache-control': 'no-cache', 'x-content-type-options': 'nosniff' }); return sendFile(fp);
1063
1179
  }
1064
1180
  const file = path.join(PUBLIC, url.pathname === '/' ? 'index.html' : url.pathname);
1065
1181
  let fst = null; try { fst = fs.statSync(file); } catch {}
1066
1182
  if (!file.startsWith(PUBLIC + path.sep) || !fst || !fst.isFile()) { res.writeHead(404); return res.end('not found'); }
1067
1183
  // The only frame of the page is the window of an artifact, served from here. Without this line a page shown there could take its own frame to another site, and send out what it holds in the address.
1068
- res.writeHead(200, { 'content-type': MIME[path.extname(file)] || 'application/octet-stream', ...(path.extname(file) === '.html' ? { 'content-security-policy': "frame-src 'self'" } : {}) });
1184
+ res.writeHead(200, { 'content-type': MIME[path.extname(file)] || 'application/octet-stream', ...(path.extname(file) === '.html' ? { 'content-security-policy': "frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'" } : {}) });
1069
1185
  res.end(fs.readFileSync(file));
1070
1186
  } catch (e) { logError(req.method + ' ' + url.pathname, e); if (res.headersSent) return res.destroy(); json({ error: String(e.message || e) }, 500); }
1071
1187
  }).listen(port, '127.0.0.1', function () { console.log(`Agent Standup → http://localhost:${this.address().port}`); });
1072
1188
  }
1073
- module.exports = { start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, packsDir, installPack, logError, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
1074
- if (require.main === module) {
1189
+ module.exports = { _winArg: winArg, start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, packsDir, installPack, logError, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
1190
+ 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
1191
+ const srv = start(+process.env.PORT || 0), tell = (m) => { try { process.send(m); } catch {} };
1192
+ srv.on('listening', () => tell({ port: srv.address().port })).on('error', (e) => { tell({ error: e.code || String(e) }); process.exit(1); });
1193
+ process.on('message', (m) => { if (m && m.env && typeof m.env === 'object') for (const [k, v] of Object.entries(m.env)) { if (v == null) delete process.env[k]; else process.env[k] = String(v); } }); // a setting changed in the editor (claudePath, codex, vibe…)
1194
+ process.on('disconnect', () => { try { shutdown(); } catch {} process.exit(0); }); // the editor window closed, or its extension host ended: this server ends with it
1195
+ process.on('uncaughtException', (e) => logError('crash', e)); process.on('unhandledRejection', (e) => logError('promise', e)); // written down and gone on, as in the extension host it ran in before: one odd request does not end the call
1196
+ } else if (require.main === module) {
1075
1197
  start().on('error', (e) => {
1076
1198
  console.error(e.code === 'EADDRINUSE' ? `Port ${PORT} is already in use (maybe Agent Standup is already running, e.g. inside VS Code). Try: PORT=4790 node server.js` : String(e));
1077
1199
  process.exit(1);
package/vibe.js CHANGED
@@ -73,7 +73,8 @@ function meta(dir) {
73
73
  }
74
74
  // The sessions a person started, newest first, each with the folder it was started in.
75
75
  function sessions(limit = 80) { return scan().rows.slice(0, limit).map((r) => { const m = meta(r.dir); return { ...r, cwd: m.cwd, key: dirKey(m.cwd) }; }); } // meta.json is written in both formats
76
- const inProject = (id, key) => { const r = row(id); if (!r || !key) return false; if (key === PROJ) return true; const d = dirKey(meta(r.dir).cwd); return d === key || d.startsWith(key + '-'); };
76
+ const under = (cwd, key) => { for (let d = String(cwd || ''); d;) { if (dirKey(d) === key) return true; const up = path.dirname(d); if (up === d) return false; d = up; } return false; }; // key is the folder itself or one above it: a dashed name alone cannot tell app/old (inside app) from app-old (beside it)
77
+ const inProject = (id, key) => { const r = row(id); if (!r || !key) return false; if (key === PROJ) return true; const c = meta(r.dir).cwd, d = dirKey(c); return d === key || (d.startsWith(key + '-') && under(c, key)); };
77
78
  const cwd = (id) => { const r = row(id); return r ? meta(r.dir).cwd : ''; }; // the folder the session was started in: where a file it names by a relative path is
78
79
  const projectLabel = (cwd) => { const h = os.homedir(), rel = cwd && cwd.startsWith(h + path.sep) ? cwd.slice(h.length + 1) : cwd; return 'Mistral Vibe' + (rel ? ' · ' + rel.split(path.sep).join('/') : ''); };
79
80