@double_geste/agent-standup 1.31.0 → 1.32.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/bin/agent-standup.js +4 -1
- package/codex.js +4 -3
- package/kokoro-worker.js +35 -4
- package/kokoro.js +26 -10
- package/package.json +1 -1
- package/public/index.html +396 -168
- package/public/locales/README.md +2 -2
- package/public/locales/da.json +34 -12
- package/public/locales/de.json +34 -12
- package/public/locales/en.json +32 -10
- package/public/locales/es.json +34 -12
- package/public/locales/ja.json +34 -12
- package/public/locales/ko.json +34 -12
- package/public/locales/pt-BR.json +34 -12
- package/public/locales/zh-CN.json +34 -12
- package/public/locales/zh-TW.json +34 -12
- package/server.js +267 -73
- package/vibe.js +10 -6
package/server.js
CHANGED
|
@@ -8,7 +8,7 @@ const os = require('os');
|
|
|
8
8
|
const crypto = require('crypto');
|
|
9
9
|
const codex = require('./codex.js'); // Codex sessions, read as the same call (see codex.js)
|
|
10
10
|
const vibe = require('./vibe.js'); // Mistral Vibe sessions, the same way (see vibe.js)
|
|
11
|
-
const SOURCES = [codex, vibe], sourceOf = (proj) => SOURCES.find((m) => m.PROJ === proj) || null, guard = (fn, or) => { try { return fn(); } catch { return or; } }; // guard: a session of another tool that cannot be read costs that session, never the list // the tools other than Claude Code: each lists its sessions under one made-up project
|
|
11
|
+
const SOURCES = [codex, vibe], sourceOf = (proj) => SOURCES.find((m) => m.PROJ === proj) || null, guard = (fn, or) => { try { return fn(); } catch (e) { logError('reader', e); return or; } }; // guard: a session of another tool that cannot be read costs that session, never the list // the tools other than Claude Code: each lists its sessions under one made-up project
|
|
12
12
|
const kokoro = require('./kokoro.js'); // natural voices, installed on demand (see kokoro.js)
|
|
13
13
|
const zlib = require('zlib');
|
|
14
14
|
const { execFileSync, execFile } = require('child_process');
|
|
@@ -17,6 +17,46 @@ const PORT = process.env.PORT || 4747;
|
|
|
17
17
|
// Same place Claude Code writes to: honours CLAUDE_CONFIG_DIR (custom config dirs are common on Linux); AGENT_STANDUP_PROJECTS overrides it.
|
|
18
18
|
const ROOT = process.env.AGENT_STANDUP_PROJECTS || path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'projects');
|
|
19
19
|
const PUBLIC = path.join(__dirname, 'public');
|
|
20
|
+
// Cowork, a tab of the Claude desktop app, keeps each of its sessions in the app's own folder, in the format of Claude Code: <folder>/<account>/<organisation>/<session>/.claude/projects/<project>/<id>.jsonl.
|
|
21
|
+
// They are listed under one made-up project, as the sessions of the other tools are, and read like any Claude Code session from there on.
|
|
22
|
+
// Where: AGENT_STANDUP_COWORK (a folder; "0" or "off" turns them off), else where the desktop app keeps its files on this system. When AGENT_STANDUP_PROJECTS points the app at one folder (--projects, the tests), only if asked for.
|
|
23
|
+
const COWORK = '_cowork';
|
|
24
|
+
function coworkHomes() {
|
|
25
|
+
const v = process.env.AGENT_STANDUP_COWORK, home = os.homedir(), sub = 'local-agent-mode-sessions';
|
|
26
|
+
if (v != null) return /^(0|off|no|false)?$/i.test(v.trim()) ? [] : [v];
|
|
27
|
+
if (process.env.AGENT_STANDUP_PROJECTS) return [];
|
|
28
|
+
if (process.platform === 'darwin') return [path.join(home, 'Library', 'Application Support', 'Claude', sub)];
|
|
29
|
+
if (process.platform !== 'win32') return [path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), 'Claude', sub)];
|
|
30
|
+
const local = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), out = [path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Claude', sub)];
|
|
31
|
+
try { for (const p of fs.readdirSync(path.join(local, 'Packages'))) if (/claude/i.test(p)) out.push(path.join(local, 'Packages', p, 'LocalCache', 'Roaming', 'Claude', sub)); } catch {} // installed as a Windows package, the app has its folder there
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
let coworkMemo = { at: 0, key: null, map: new Map() };
|
|
35
|
+
function coworkMap() { // session id → the folder its transcript is in; looked up again every 3 s, and at once when the place to look changes
|
|
36
|
+
const homes = coworkHomes(), key = homes.join('\n'), now = Date.now(); if (coworkMemo.key === key && now - coworkMemo.at < 3000) return coworkMemo.map;
|
|
37
|
+
const map = new Map(), ls = (d) => { try { return fs.readdirSync(d); } catch { return []; } };
|
|
38
|
+
for (const h of homes) for (const a of ls(h)) for (const o of ls(path.join(h, a))) for (const s of ls(path.join(h, a, o))) {
|
|
39
|
+
if (s.endsWith('.json')) continue; // what the app notes about a session, next to its folder
|
|
40
|
+
const pd = path.join(h, a, o, s, '.claude', 'projects');
|
|
41
|
+
for (const p of ls(pd)) for (const f of ls(path.join(pd, p))) if (/^[\w.\-]+\.jsonl$/.test(f) && !map.has(f.slice(0, -6))) map.set(f.slice(0, -6), path.join(pd, p));
|
|
42
|
+
}
|
|
43
|
+
coworkMemo = { at: now, key, map }; return map;
|
|
44
|
+
}
|
|
45
|
+
const coworkNotes = new Map(); // note file → { sig, title }
|
|
46
|
+
function coworkTitle(proj, id) { // the name the desktop app gave the session, the one its own list shows: kept in a note beside the session's folder, of which the title alone is taken
|
|
47
|
+
const dir = proj === COWORK && coworkMap().get(id); if (!dir) return '';
|
|
48
|
+
const f = path.resolve(dir, '..', '..', '..') + '.json'; let st; try { st = fs.statSync(f); } catch { return ''; }
|
|
49
|
+
const sig = st.mtimeMs + ':' + st.size, c = coworkNotes.get(f); if (c && c.sig === sig) return c.title;
|
|
50
|
+
let title = ''; try { const j = JSON.parse(fs.readFileSync(f, 'utf8')); if (typeof j.title === 'string') title = j.title.trim().slice(0, 200); } catch {}
|
|
51
|
+
coworkNotes.set(f, { sig, title }); return title;
|
|
52
|
+
}
|
|
53
|
+
const projDir = (proj, id) => (proj === COWORK && coworkMap().get(id)) || path.join(ROOT, proj); // the folder that holds <id>.jsonl and the sub-agents of that session
|
|
54
|
+
const projects = () => { let names = []; try { names = fs.readdirSync(ROOT); } catch {} return coworkMap().size ? names.concat(COWORK) : names; };
|
|
55
|
+
function transcripts(proj) { // the sessions of a project: { id, file }
|
|
56
|
+
const cw = proj === COWORK ? coworkMap() : null; if (cw && cw.size) return [...cw].map(([id, dir]) => ({ id, file: path.join(dir, id + '.jsonl') }));
|
|
57
|
+
const dir = path.join(ROOT, proj); let files; try { files = fs.readdirSync(dir); } catch { return []; }
|
|
58
|
+
return files.filter((f) => f.endsWith('.jsonl')).map((f) => ({ id: f.slice(0, -6), file: path.join(dir, f) }));
|
|
59
|
+
}
|
|
20
60
|
|
|
21
61
|
const blocks = (rec) => {
|
|
22
62
|
const c = rec.message && rec.message.content;
|
|
@@ -70,10 +110,15 @@ const toolLabel = (b, ts) => {
|
|
|
70
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;
|
|
71
111
|
case 'Skill': out.d = { kind: 'text', what: 'skill', v: i.skill, text: clip(i.skill + (i.args ? ' ' + i.args : ''), 200) }; break;
|
|
72
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
|
|
114
|
+
// falls through
|
|
73
115
|
default: out.d = mcp ? { kind: 'text', what: 'mcp', v: (mcp[1] || '') + ' · ' + (mcp.slice(2).join('__') || ''), text: clip(JSON.stringify(i), 400) } : { kind: 'text', text: clip(JSON.stringify(i), 300) };
|
|
74
116
|
}
|
|
75
117
|
return out;
|
|
76
118
|
};
|
|
119
|
+
// 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.
|
|
120
|
+
const ART_URL = /^https:\/\/claude\.ai\/(code\/)?artifact\/[\w-]{6,80}$/;
|
|
121
|
+
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);
|
|
77
122
|
const resultText = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => x.text || '').join('\n') : '');
|
|
78
123
|
// Pictures a tool returned (a screenshot, an image file that was read). They are served from the transcript itself, so nothing outside the session files is ever read, and only bitmap types are sent.
|
|
79
124
|
const IMG_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']), mediaMemo = new Map();
|
|
@@ -82,7 +127,7 @@ const resultImages = (c) => (Array.isArray(c) ? c.filter(isImg) : []);
|
|
|
82
127
|
const mtimeOf = (f) => { try { return fs.statSync(f).mtimeMs; } catch { return 0; } }; // 0 for a file that is gone, or a symlink that points nowhere: never an exception
|
|
83
128
|
// Every sub-agent transcript of a session: <id>/subagents/*.jsonl, plus the ones a workflow launched, one folder deeper in <id>/subagents/workflows/<run>/agent-*.jsonl (each run also keeps a journal.jsonl, which is not an agent).
|
|
84
129
|
function subFiles(proj, id) {
|
|
85
|
-
const sd = path.join(
|
|
130
|
+
const sd = path.join(projDir(proj, id), id, 'subagents'), out = [], seen = new Set(['main', 'user']); out.dirs = [sd]; out.journals = [];
|
|
86
131
|
const add = (dir, f, run) => { let aid = f.replace(/^agent-/, '').replace(/\.jsonl$/, '').replace(/[^\w.-]/g, '_'); const id0 = aid; if (seen.has(aid)) aid = (run || 'agent').replace(/[^\w.-]/g, '_') + '.' + aid; seen.add(aid); out.push({ file: path.join(dir, f), aid, id0, run }); }; // an id is the file name; the same name in two folders gets its run in front
|
|
87
132
|
let names; try { names = fs.readdirSync(sd); } catch { return out; }
|
|
88
133
|
for (const f of names) if (f.endsWith('.jsonl')) add(sd, f, '');
|
|
@@ -96,7 +141,7 @@ function subFiles(proj, id) {
|
|
|
96
141
|
}
|
|
97
142
|
const subFilesOf = (proj, id) => { const sx = sourceOf(proj); return sx && sx.subFiles ? guard(() => sx.subFiles(id), Object.assign([], { dirs: [], journals: [] })) : subFiles(proj, id); }; // Mistral Vibe keeps its sub-agents its own way
|
|
98
143
|
function mediaFile(proj, sid, agent) {
|
|
99
|
-
if (agent === 'main') return path.join(
|
|
144
|
+
if (agent === 'main') return path.join(projDir(proj, sid), sid + '.jsonl');
|
|
100
145
|
const hit = subFiles(proj, sid).find((x) => x.aid === agent);
|
|
101
146
|
return hit ? hit.file : null;
|
|
102
147
|
}
|
|
@@ -120,6 +165,59 @@ function toolImage(file, toolId, n) { // looks for the tool's result line in t
|
|
|
120
165
|
mediaMemo.delete(key); mediaMemo.set(key, found || { miss: size }); if (mediaMemo.size > 12) mediaMemo.delete(mediaMemo.keys().next().value);
|
|
121
166
|
return found;
|
|
122
167
|
}
|
|
168
|
+
// ---- 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
|
|
169
|
+
// 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,
|
|
170
|
+
// 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,
|
|
171
|
+
// 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).
|
|
172
|
+
const artMemo = new Map(), ART_MAX = 8 * 1024 * 1024;
|
|
173
|
+
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); };
|
|
174
|
+
function artifactPage(file, toolId, fp) { // the text of the page at fp as it was when the call toolId published it, or null
|
|
175
|
+
const key = file + '|' + toolId, memo = artMemo.get(key); if (memo && memo.html != null) return memo;
|
|
176
|
+
const pathMark = Buffer.from(JSON.stringify(fp).slice(1, -1)), errMark = Buffer.from('"is_error":true'), idMark = Buffer.from('"' + toolId + '"'), until = Date.now() + 2000;
|
|
177
|
+
const ops = [], failed = new Set(); let fd, carry = Buffer.alloc(0), pos = 0, size = 0, seen = false;
|
|
178
|
+
try {
|
|
179
|
+
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
|
|
180
|
+
while (pos < size && Date.now() < until) {
|
|
181
|
+
const buf = Buffer.alloc(Math.min(8 * 1024 * 1024, size - pos)); fs.readSync(fd, buf, 0, buf.length, pos); pos += buf.length;
|
|
182
|
+
const all = carry.length ? Buffer.concat([carry, buf]) : buf; let a = 0;
|
|
183
|
+
for (let b; (b = all.indexOf(10, a)) >= 0; a = b + 1) {
|
|
184
|
+
const line = all.subarray(a, b), mine = !seen && (line.indexOf(pathMark) >= 0 || line.indexOf(idMark) >= 0); if (!mine && line.indexOf(errMark) < 0) continue;
|
|
185
|
+
let r; try { r = JSON.parse(line.toString('utf8')); } catch { continue; }
|
|
186
|
+
for (const blk of blocks(r)) {
|
|
187
|
+
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)
|
|
188
|
+
if (blk.type !== 'tool_use' || seen) continue; const i = blk.input || {};
|
|
189
|
+
if (blk.id === toolId) seen = true; // what was written after that publish belongs to the next one
|
|
190
|
+
else if (i.file_path === fp && (blk.name === 'Write' || blk.name === 'Edit' || blk.name === 'MultiEdit')) ops.push({ id: blk.id, name: blk.name, i });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
carry = Buffer.from(all.subarray(a));
|
|
194
|
+
}
|
|
195
|
+
} catch {} finally { if (fd != null) fs.closeSync(fd); }
|
|
196
|
+
let html = null;
|
|
197
|
+
if (seen && pos >= size) for (const op of ops) {
|
|
198
|
+
if (failed.has(op.id)) continue;
|
|
199
|
+
if (op.name === 'Write') html = typeof op.i.content === 'string' ? op.i.content : null;
|
|
200
|
+
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);
|
|
201
|
+
}
|
|
202
|
+
if (html != null && html.length > ART_MAX) html = null;
|
|
203
|
+
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
|
|
204
|
+
artMemo.delete(key); artMemo.set(key, found || { miss: size }); if (artMemo.size > 8) artMemo.delete(artMemo.keys().next().value);
|
|
205
|
+
return found;
|
|
206
|
+
}
|
|
207
|
+
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
|
|
208
|
+
let fp = '', ok = false;
|
|
209
|
+
for (const e of timeline(proj, id).events) {
|
|
210
|
+
if (e.agent !== agent) continue;
|
|
211
|
+
if (e.kind === 'tools') { for (const t of e.tools) if (t.id === toolId && t.d && t.d.kind === 'artifact') fp = t.d.file; }
|
|
212
|
+
else if (e.kind === 'results') { for (const it of e.items) if (it.id === toolId && it.art && !it.art.typed) ok = true; }
|
|
213
|
+
}
|
|
214
|
+
return ok && /\.html?$/i.test(fp) ? fp : null;
|
|
215
|
+
}
|
|
216
|
+
// 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:
|
|
217
|
+
// 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
|
|
218
|
+
// 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.
|
|
219
|
+
const ART_LIBS = 'https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://unpkg.com https://cdn.tailwindcss.com https://code.jquery.com';
|
|
220
|
+
const artifactCsp = (net) => "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'" + (net ? ' ' + ART_LIBS : '') + "; style-src 'unsafe-inline'" + (net ? ' https://fonts.googleapis.com' : '') + '; font-src data:' + (net ? ' https://fonts.gstatic.com' : '') + "; img-src data: blob:; media-src data: blob:; connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'";
|
|
123
221
|
const RESULT_MAX = { AskUserQuestion: 900, Skill: 300, ToolSearch: 500, Read: 1900, Bash: 1300, Grep: 900, Glob: 800, WebFetch: 800, WebSearch: 800, Edit: 200, MultiEdit: 200, Write: 200 };
|
|
124
222
|
const NO_RESULT = new Set(['Agent', 'Task', 'SendMessage', 'TodoWrite']); // internal bookkeeping, nothing to show
|
|
125
223
|
const HARNESS = /<(system-reminder|browser_instruction|ide_selection|ide_opened_file|task-notification|command-name|command-message|command-args|local-command-stdout|local-command-caveat)>[\s\S]*?<\/\1>\s*/g; // blocks the harness wraps around what the human typed
|
|
@@ -133,29 +231,25 @@ function listSessions() {
|
|
|
133
231
|
function listSessions0() {
|
|
134
232
|
const rows = [];
|
|
135
233
|
for (const m of SOURCES) for (const r of guard(() => m.sessions(30), [])) rows.push({ proj: m.PROJ, id: r.id, mtime: r.mtime, size: r.size, agents: guard(() => (m.subCount ? m.subCount(r.id) : m.subFiles ? m.subFiles(r.id).length : 0), 0), cx: r, src: m });
|
|
136
|
-
for (const proj of
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { continue; }
|
|
140
|
-
for (const f of files) {
|
|
141
|
-
const id = f.replace(/\.jsonl$/, '');
|
|
142
|
-
let st; try { st = fs.statSync(path.join(dir, f)); } catch { continue; } // a link to a transcript that is gone
|
|
234
|
+
for (const proj of projects()) {
|
|
235
|
+
for (const { id, file } of transcripts(proj)) {
|
|
236
|
+
let st; try { st = fs.statSync(file); } catch { continue; } // a link to a transcript that is gone
|
|
143
237
|
rows.push({ proj, id, mtime: st.mtimeMs, size: st.size, agents: subFiles(proj, id).length });
|
|
144
238
|
}
|
|
145
239
|
}
|
|
146
240
|
rows.sort((a, b) => b.mtime - a.mtime);
|
|
147
|
-
const
|
|
241
|
+
const own = (r) => !r.cx && r.proj !== COWORK, top = rows.filter(own).slice(0, 60).concat(rows.filter((r) => r.cx), rows.filter((r) => r.proj === COWORK).slice(0, 30)).sort((a, b) => b.mtime - a.mtime); // the 60 most recent Claude Code sessions as always, and up to 30 of each other tool beside them, Cowork included: none pushes another out
|
|
148
242
|
for (const r of top) {
|
|
149
243
|
if (r.cx) { const c = r.cx, m = r.src; delete r.cx; delete r.src; r.title = guard(() => m.title(c), '') || r.id; r.project = guard(() => m.projectLabel(c.cwd), '') || m.SOURCE; r.source = m.SOURCE; continue; }
|
|
150
244
|
// titles come from the cached tail read (custom title, then AI title, then first prompt): no whole-file reads
|
|
151
|
-
let t = null; try { const f = path.join(
|
|
152
|
-
r.title = t || r.id; r.project = r.proj.replace(/^-Users-[^-]+-/, '').replace(/-/g, '/');
|
|
245
|
+
let t = null; try { const f = path.join(projDir(r.proj, r.id), r.id + '.jsonl'); t = parseTail(f, fs.statSync(f)).title; } catch {}
|
|
246
|
+
r.title = coworkTitle(r.proj, r.id) || t || r.id; r.project = r.proj === COWORK ? 'Cowork' : r.proj.replace(/^-Users-[^-]+-/, '').replace(/-/g, '/');
|
|
153
247
|
}
|
|
154
248
|
return top;
|
|
155
249
|
}
|
|
156
250
|
|
|
157
251
|
function stamp(proj, id) {
|
|
158
|
-
const base =
|
|
252
|
+
const base = projDir(proj, id); let n = 0;
|
|
159
253
|
const add = (f) => { try { const s = fs.statSync(f); n += s.mtimeMs + s.size; } catch {} };
|
|
160
254
|
const sx = sourceOf(proj); add(sx ? guard(() => sx.fileOf(id), '') || '' : path.join(base, id + '.jsonl')); if (sx && sx.watch) for (const f of guard(() => sx.watch(id), [])) add(f);
|
|
161
255
|
const subs = subFilesOf(proj, id); // the transcripts and the folders they are in (a folder changes when a file appears in it, e.g. an agent's meta file), not every file around them
|
|
@@ -207,25 +301,46 @@ const readHead = (file, bytes) => { const fd = fs.openSync(file, 'r'); try { con
|
|
|
207
301
|
const APPROVAL = /^(Edit|Write|MultiEdit|NotebookEdit)/, ASKS = /^(AskUserQuestion|ExitPlanMode)/, SUBTOOL = /^(Task|Agent)$/;
|
|
208
302
|
const boardCache = new Map(); // file → { sig, parsed, title }
|
|
209
303
|
let boardMemo = { at: 0, rows: [] };
|
|
304
|
+
const PR_URL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+$/; // nothing else is given to the page as a link to open
|
|
305
|
+
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
|
|
306
|
+
// 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).
|
|
307
|
+
// 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.
|
|
308
|
+
// 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.
|
|
309
|
+
const NOT_TYPED = /<(system-reminder|browser_instruction|ide_selection|ide_opened_file|task-notification|local-command-stdout|local-command-caveat)>[\s\S]*?<\/\1>\s*/g;
|
|
310
|
+
function typedAt(r) {
|
|
311
|
+
if (!r || r.isSidechain) return 0;
|
|
312
|
+
if (r.type === 'attachment') { const q = r.attachment; return q && q.type === 'queued_command' && (q.origin ? q.origin.kind === 'human' : q.commandMode === 'prompt') ? Date.parse(r.timestamp) || 0 : 0; }
|
|
313
|
+
if (r.type !== 'user' || r.isMeta || r.isCompactSummary) return 0; const bl = blocks(r); if (bl.some((b) => b && b.type === 'tool_result')) return 0;
|
|
314
|
+
const t = bl.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n').replace(NOT_TYPED, '').trim();
|
|
315
|
+
return (t ? !/^(\[Request interrupted|<scheduled-task[\s>])/i.test(t) : bl.some((b) => b && b.type === 'image')) ? Date.parse(r.timestamp) || 0 : 0; // a picture sent alone is an order too
|
|
316
|
+
}
|
|
317
|
+
function typedBefore(file) { // the first look at a session whose last order is further back than what the list reads (a long turn, large outputs): looked for once, in its last megabytes
|
|
318
|
+
const { text, cut } = readTail(file, 4 * 1024 * 1024), lines = text.split('\n');
|
|
319
|
+
for (let i = lines.length - 1; i >= (cut ? 1 : 0); i--) { if (!lines[i].includes('"type":"user"') && !lines[i].includes('"queued_command"')) continue; try { const a = typedAt(JSON.parse(lines[i])); if (a) return a; } catch {} }
|
|
320
|
+
return 0;
|
|
321
|
+
}
|
|
210
322
|
function parseTail(file, st) {
|
|
211
323
|
const sig = st.mtimeMs + ':' + st.size, hit = boardCache.get(file); if (hit && hit.sig === sig) return hit;
|
|
212
324
|
const { text, cut } = readTail(file, 192 * 1024), lines = text.split('\n'); if (cut) lines.shift();
|
|
213
|
-
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;
|
|
325
|
+
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;
|
|
214
326
|
for (const l of lines) {
|
|
215
327
|
if (!l) continue; let r; try { r = JSON.parse(l); } catch { continue; }
|
|
328
|
+
const a = typedAt(r); if (a > asked) asked = a;
|
|
216
329
|
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
|
|
330
|
+
if (r.type === 'pr-link' && PR_URL.test(r.prUrl)) pr = { n: +r.prUrl.slice(r.prUrl.lastIndexOf('/') + 1), url: r.prUrl }; // the pull request Claude Code noted for the session: the latest one, shown on its card
|
|
217
331
|
const t = Date.parse(r.timestamp) || 0, bl = blocks(r);
|
|
218
332
|
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;
|
|
219
333
|
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
|
|
220
|
-
for (const b of bl) { if (b.type === 'tool_use') pend.set(b.id, { name: b.name, ts: t }); else if (b.type === 'tool_result') pend.delete(b.tool_use_id); }
|
|
334
|
+
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); }
|
|
221
335
|
}
|
|
222
336
|
if (!hit && !custom) { // first look at this file: a little further back than the lines read above, and without needing whole lines
|
|
223
337
|
const big = readTail(file, 256 * 1024).text, un = (m) => { try { return m ? JSON.parse('"' + m[1] + '"') : null; } catch { return null; } };
|
|
224
338
|
custom = un([...big.matchAll(/"type":"custom-title","customTitle":"((?:[^"\\]|\\.)*)"/g)].pop()); if (!ai) ai = un([...big.matchAll(/"type":"ai-title","aiTitle":"((?:[^"\\]|\\.)*)"/g)].pop());
|
|
225
339
|
}
|
|
226
340
|
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
|
|
227
|
-
|
|
228
|
-
|
|
341
|
+
if (!hit && !asked && cut) asked = typedBefore(file);
|
|
342
|
+
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
|
|
343
|
+
out.asked = asked; boardCache.set(file, out); if (boardCache.size > 200) boardCache.delete(boardCache.keys().next().value); return out;
|
|
229
344
|
}
|
|
230
345
|
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
|
|
231
346
|
const ONE = (t) => t.replace(/\s+/g, ' ').trim().slice(0, 90);
|
|
@@ -239,19 +354,18 @@ function firstPrompt(file) { // the first thing the person typed, read record
|
|
|
239
354
|
}
|
|
240
355
|
function boardRows() {
|
|
241
356
|
if (Date.now() - boardMemo.at < 1200) return boardMemo.rows; // several windows polling at once share one scan
|
|
242
|
-
const out = boardRows0(); boardMemo = { at: Date.now(), rows: out }; return out;
|
|
357
|
+
const out = withDone(boardRows0()); boardMemo = { at: Date.now(), rows: out }; return out;
|
|
243
358
|
}
|
|
244
359
|
function boardRows0() {
|
|
245
360
|
const now = Date.now(), rows = [];
|
|
246
361
|
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 });
|
|
247
|
-
for (const proj of
|
|
248
|
-
const
|
|
249
|
-
for (const f of files) { try { const st = fs.statSync(path.join(dir, f)); if (now - st.mtimeMs < 12 * 3600e3) rows.push({ proj, id: f.slice(0, -6), st }); } catch {} }
|
|
362
|
+
for (const proj of projects()) {
|
|
363
|
+
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 {} }
|
|
250
364
|
}
|
|
251
365
|
rows.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs);
|
|
252
|
-
return rows.filter((r) => !r.cx).slice(0, 40).concat(...SOURCES.map((m) => rows.filter((r) => r.src === m).slice(0, 20))).sort((a, b) => b.st.mtimeMs - a.st.mtimeMs).map(({ proj, id, st, cx, src }) => {
|
|
366
|
+
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 }) => {
|
|
253
367
|
if (cx) return guard(() => src.boardRow(cx, now), null);
|
|
254
|
-
const file = path.join(
|
|
368
|
+
const file = path.join(projDir(proj, id), id + '.jsonl'); let p; try { p = parseTail(file, st); } catch { p = { pending: [] }; }
|
|
255
369
|
const age = now - st.mtimeMs, lp = (p.pending || [])[(p.pending || []).length - 1]; let state = 'idle', tool = '', ageMs = age;
|
|
256
370
|
if (age < 30 * 60e3) {
|
|
257
371
|
if (lp) { ageMs = now - (lp.ts || st.mtimeMs); tool = lp.name;
|
|
@@ -263,38 +377,102 @@ function boardRows0() {
|
|
|
263
377
|
}
|
|
264
378
|
let subActive = 0, subTotal = 0;
|
|
265
379
|
for (const x of subFiles(proj, id)) { subTotal++; if (now - mtimeOf(x.file) < 90e3) subActive++; }
|
|
266
|
-
return { proj, id, title: p.title || id, mtime: st.mtimeMs, state, tool, ageMs, subActive, subTotal, ...(p.esc ? { cut: 1 } : {}) }; // cut: stopped by you, which is no news to tell you
|
|
380
|
+
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 } : {}) }; // cut: stopped by you, which is no news to tell you
|
|
267
381
|
}).filter(Boolean);
|
|
268
382
|
}
|
|
269
383
|
// 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).
|
|
270
384
|
const PREFS = process.env.AGENT_STANDUP_PREFS || (process.platform === 'win32' ? path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'agent-standup', 'prefs.json') : path.join(os.homedir(), '.config', 'agent-standup', 'prefs.json'));
|
|
385
|
+
// The sessions you put away as done (✓ on a card of the Sessions view): "project/id" → when the session had last moved at that time. Kept in a file of its own beside the settings and read again when it changes,
|
|
386
|
+
// so that every window agrees at once, whichever server it talks to. A session that moves again is no longer put away.
|
|
387
|
+
const DONE = path.join(path.dirname(PREFS), 'done.json'); let doneMemo = { sig: null, map: new Map() };
|
|
388
|
+
function doneMarks() {
|
|
389
|
+
let sig = ''; try { const st = fs.statSync(DONE); sig = st.mtimeMs + ':' + st.size; } catch {} if (sig === doneMemo.sig) return doneMemo.map;
|
|
390
|
+
const map = new Map(); try { for (const [k, v] of Object.entries(JSON.parse(fs.readFileSync(DONE, 'utf8')))) if (typeof v === 'number') map.set(k, v); } catch {}
|
|
391
|
+
doneMemo = { sig, map }; return map;
|
|
392
|
+
}
|
|
393
|
+
const canDone = (r) => r.state === 'turn' || r.state === 'idle'; // a session at work, or one that waits for you, is not put away
|
|
394
|
+
function withDone(rows) { const m = doneMarks(); for (const r of rows) { if (canDone(r) && m.get(r.proj + '/' + r.id) >= r.mtime) r.done = 1; else if (r.done) delete r.done; } return rows; }
|
|
395
|
+
function setDone(proj, id, on) {
|
|
396
|
+
const rows = boardRows0(), row = rows.find((r) => r.proj === proj && r.id === id); if (!row || (on && !canDone(row))) return false;
|
|
397
|
+
const m = new Map(doneMarks()), k = proj + '/' + id; if (on) m.set(k, row.mtime); else m.delete(k);
|
|
398
|
+
for (const [key, at] of m) { const r = rows.find((x) => x.proj + '/' + x.id === key); if (!r || r.mtime > at) m.delete(key); } // the marks of sessions that moved again, or left the board, are forgotten
|
|
399
|
+
fs.mkdirSync(path.dirname(DONE), { recursive: true }); const tmp = DONE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(Object.fromEntries(m), null, 1)); fs.renameSync(tmp, DONE);
|
|
400
|
+
doneMemo = { sig: null, map: m }; boardMemo.at = 0; return true;
|
|
401
|
+
}
|
|
271
402
|
function readPrefs() { try { const v = JSON.parse(fs.readFileSync(PREFS, 'utf8')); return v && typeof v === 'object' && !Array.isArray(v) ? v : null; } catch { return null; } }
|
|
272
403
|
function writePrefs(v) { fs.mkdirSync(path.dirname(PREFS), { recursive: true }); const tmp = PREFS + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(v, null, 1)); fs.renameSync(tmp, PREFS); }
|
|
273
|
-
//
|
|
274
|
-
|
|
404
|
+
// The app's own errors, kept on this computer only, in errors.log beside the settings: what the page, a request, a reader or the process could not do. Nothing is sent anywhere:
|
|
405
|
+
// ⚙ › Report a problem shows them and opens the draft of an issue that the person reads and sends themselves. One JSON line each: when, which version, where, the message and the top of the stack.
|
|
406
|
+
// tidy: the home folder is written "~" (also in the form Claude Code names its project folders) and the address of the page, which carries the project in its query, is written "page".
|
|
407
|
+
// The same error is written once an hour at most, 60 lines an hour at most, and the file loses its older half past 256 KB. Logging never throws.
|
|
408
|
+
const ERRLOG = path.join(path.dirname(PREFS), 'errors.log'), errSeen = new Map(), errRate = { at: 0, n: 0 };
|
|
409
|
+
const VERSION = (() => { for (const p of ['package.json', '../package.json']) try { const j = JSON.parse(fs.readFileSync(path.join(__dirname, p), 'utf8')); if (/agent-standup/.test(j.name)) return String(j.version || ''); } catch {} return ''; })(); // ../: the desktop app keeps this file in core/
|
|
410
|
+
// homeRe: the home folder in the forms a message or a stack writes it: as it is, with "/" for "\", with "\\" (inside JSON), and with "-" for every other character (a project folder of Claude Code).
|
|
411
|
+
// On Windows the case is not told apart: the editor writes the drive "c:" where the system says "C:". A home of a few letters ("/root") is not looked for in its dashed form, which would be found in any text.
|
|
412
|
+
function homeRe(home, win) {
|
|
413
|
+
try {
|
|
414
|
+
if (!home || home.length < 4) return null; const q = (f) => f.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), dashed = home.replace(/[^a-zA-Z0-9]/g, '-');
|
|
415
|
+
const plain = [...new Set([home, home.replace(/\\/g, '/'), home.replace(/\\/g, '\\\\')])].sort((a, b) => b.length - a.length).map((f) => q(f) + '(?!\\w)');
|
|
416
|
+
return new RegExp(plain.concat(dashed.length >= 8 ? [q(dashed)] : []).join('|'), win ? 'gi' : 'g');
|
|
417
|
+
} catch { return null; }
|
|
418
|
+
}
|
|
419
|
+
const HOME_RE = homeRe(os.homedir(), process.platform === 'win32');
|
|
420
|
+
function tidy(x, n, re = HOME_RE) {
|
|
421
|
+
let t = String(x == null ? '' : x); if (re) t = t.replace(re, '~');
|
|
422
|
+
t = t.replace(/(\/(?:Users|home)\/|[A-Za-z]:[\\\/]{1,2}Users[\\\/]{1,2})[^\/\\:*?"'<>|)\r\n]+/gi, '~'); // the home of anyone else, up to the next separator: a name may hold a space
|
|
423
|
+
t = t.replace(/https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?\/[^\s)"']*?(?=:\d+:\d+|[\s)"']|$)/gi, 'page').slice(0, n);
|
|
424
|
+
return t.replace(/[\uD800-\uDBFF]$/, ''); // a cut through the middle of an emoji leaves half a character, which a link cannot carry
|
|
425
|
+
}
|
|
426
|
+
function logError(where, e) {
|
|
427
|
+
try {
|
|
428
|
+
const msg = tidy(e && e.message != null ? e.message : e, 300), stack = tidy(String((e && e.stack) || '').split('\n').map((l) => l.trim()).filter((l) => /^at |@/.test(l)).slice(0, 8).join('\n'), 1500), now = Date.now();
|
|
429
|
+
const key = where + '|' + msg + '|' + stack.split('\n')[0]; if (!msg || now - (errSeen.get(key) || 0) < 3600e3) return;
|
|
430
|
+
if (now - errRate.at > 3600e3) { errRate.at = now; errRate.n = 0; } if (++errRate.n > 60) return;
|
|
431
|
+
if (errSeen.size > 300) errSeen.clear(); errSeen.set(key, now);
|
|
432
|
+
fs.mkdirSync(path.dirname(ERRLOG), { recursive: true });
|
|
433
|
+
try { if (fs.statSync(ERRLOG).size > 262144) { const all = fs.readFileSync(ERRLOG, 'utf8').split('\n'); fs.writeFileSync(ERRLOG, all.slice(all.length >> 1).join('\n')); } } catch {}
|
|
434
|
+
fs.appendFileSync(ERRLOG, JSON.stringify({ t: new Date().toISOString(), v: VERSION, where: tidy(where, 80), msg, stack }) + '\n');
|
|
435
|
+
} catch {}
|
|
436
|
+
}
|
|
437
|
+
function errorReport() { // what ⚙ › Report a problem shows: the app, the system and the last errors of the log
|
|
438
|
+
let errors = []; try { errors = fs.readFileSync(ERRLOG, 'utf8').split('\n').filter(Boolean).slice(-40).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter((x) => x && typeof x === 'object'); } catch {}
|
|
439
|
+
return { version: VERSION, host: String(process.env.AGENT_STANDUP_HOST || '').slice(0, 80), platform: `${process.platform} ${os.release()} ${process.arch}`, node: process.version, electron: process.versions.electron || '', file: tidy(ERRLOG, 300), errors };
|
|
440
|
+
}
|
|
441
|
+
// An exception nobody caught is written before the process does what it would have done anyway (the "monitor" event changes nothing to that). Inside an editor the process is shared with
|
|
442
|
+
// every other extension: there, only an error that went through this folder is ours. OWN: the process was started from this folder (node server.js, the command, the desktop app, a test).
|
|
443
|
+
const OWN = (() => { try { const m = require.main && require.main.filename; return !!m && (m.startsWith(__dirname + path.sep) || path.dirname(__dirname) === path.dirname(m)); } catch { return false; } })(); // the second: the desktop app, whose main file sits one folder above core/
|
|
444
|
+
process.on('uncaughtExceptionMonitor', (e, origin) => { try { if (OWN || String((e && e.stack) || '').includes(__dirname)) logError(origin === 'unhandledRejection' ? 'promise' : 'crash', e); } catch {} });
|
|
445
|
+
// The session the live call is in: the one you last touched. Typing in a session, or starting one, takes the call there. So does going to one by hand (pick: its tab, the visitor,
|
|
446
|
+
// the list, the tab of the editor), and that holds until you type somewhere. What the agents write moves nothing: with two sessions at work the call went back and forth, and there was a pin to stop it.
|
|
447
|
+
// 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
|
|
448
|
+
// goes to that one. A session you went to by hand is not left that way.
|
|
449
|
+
const STICK_MS = 90000;
|
|
275
450
|
function sessionMtime(proj, id) {
|
|
276
451
|
const sx = sourceOf(proj), r = sx ? guard(() => sx.row(id), null) : null; if (sx && (!r || !sx.subFiles)) return r ? r.mtime : 0;
|
|
277
|
-
let m = sx ? r.mtime : mtimeOf(path.join(
|
|
452
|
+
let m = sx ? r.mtime : mtimeOf(path.join(projDir(proj, id), id + '.jsonl')); if (!m) return 0; const subs = subFilesOf(proj, id);
|
|
278
453
|
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
|
|
279
454
|
}
|
|
280
|
-
function currentSession(projFilter,
|
|
281
|
-
const safe = (x) => typeof x === 'string' && /^[\w.\-]+$/.test(x) && x !== '..';
|
|
282
|
-
|
|
283
|
-
|
|
455
|
+
function currentSession(projFilter, pick, stick) { // 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
|
|
456
|
+
const safe = (x) => typeof x === 'string' && /^[\w.\-]+$/.test(x) && x !== '..', now = Date.now();
|
|
457
|
+
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')));
|
|
458
|
+
const inScope = (c) => !projFilter || 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
|
|
459
|
+
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;
|
|
460
|
+
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
|
|
461
|
+
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
|
|
462
|
+
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
|
|
463
|
+
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);
|
|
464
|
+
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
|
|
465
|
+
if (to) return { proj: to.proj, id: to.id, mtime: to.mtime, asked };
|
|
466
|
+
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
|
|
284
467
|
let best = null;
|
|
285
468
|
const consider = (proj, id, m) => { if (!best || m > best.mtime) best = { proj, id, mtime: m }; };
|
|
286
|
-
for (const m of SOURCES) for (const r of guard(() => m.sessions(), [])) if (
|
|
287
|
-
for (const proj of
|
|
288
|
-
if (projFilter && proj !== projFilter && !proj.startsWith(projFilter + '-')) continue; // the folder itself, or a folder inside it
|
|
289
|
-
const
|
|
290
|
-
try { files = fs.readdirSync(dir); } catch { continue; }
|
|
291
|
-
for (const f of files) {
|
|
292
|
-
if (!f.endsWith('.jsonl')) continue;
|
|
293
|
-
const m = sessionMtime(proj, f.slice(0, -6)); if (m) consider(proj, f.slice(0, -6), m); // 0: a link to a transcript that is gone
|
|
294
|
-
}
|
|
469
|
+
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);
|
|
470
|
+
for (const proj of projects()) {
|
|
471
|
+
if (projFilter && proj !== projFilter && !proj.startsWith(projFilter + '-')) 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)
|
|
472
|
+
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
|
|
295
473
|
}
|
|
296
|
-
if (!best && projFilter) return currentSession('',
|
|
297
|
-
return best
|
|
474
|
+
if (!best && projFilter) return { ...currentSession('', null, stick), wide: 1 }; // nothing in that folder (an editor open on another one than the sessions): the latest of anywhere, and the page is told, so its tabs follow the same rule
|
|
475
|
+
return best ? { ...best, asked } : {}; // a call that is opened while nobody is at work: the session that was written to last
|
|
298
476
|
}
|
|
299
477
|
|
|
300
478
|
// ---- Incremental transcript reader: each .jsonl is parsed once, then only the bytes appended since are read.
|
|
@@ -349,8 +527,8 @@ function parseRecord(st, r) {
|
|
|
349
527
|
for (const b of blocks(r)) if (b.type === 'tool_result' && wf) push({ ts, agent, kind: 'wfrun', toolId: b.tool_use_id, run: wf }); // the answer to a Workflow call names the run it started: its agents are in subagents/workflows/<run>/
|
|
350
528
|
for (const b of blocks(r)) if (b.type === 'tool_result' && (st.toolName[b.tool_use_id] === 'Agent' || st.toolName[b.tool_use_id] === 'Task') && !(st.bg && st.bg[b.tool_use_id]) && !/^\s*Async agent launched/i.test(resultText(b.content))) push({ ts, agent, kind: 'agentdone', toolId: b.tool_use_id }); // a synchronous call: the lead got the sub-agent's answer back, so it has finished (async launches answer immediately and are not a completion)
|
|
351
529
|
for (const b of blocks(r)) if (b.type === 'tool_result' && st.toolName[b.tool_use_id] && !NO_RESULT.has(st.toolName[b.tool_use_id])) {
|
|
352
|
-
const n = st.toolName[b.tool_use_id], img = resultImages(b.content).length, files = n === 'Bash' && !b.is_error ? docPaths(resultText(b.content), false).map((f) => absPath(f, r.cwd)) : [];
|
|
353
|
-
items.push({ id: b.tool_use_id, err: !!b.is_error, out: clip(resultText(b.content).replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trimEnd(), RESULT_MAX[n] || (/^mcp__/.test(n) ? 900 : 600)), ...(img ? { img } : {}), ...(files.length ? { files } : {}) }); // img: how many pictures came back; the page fetches them from /api/media · files: the documents a command says it made
|
|
530
|
+
const n = st.toolName[b.tool_use_id], img = resultImages(b.content).length, files = n === 'Bash' && !b.is_error ? docPaths(resultText(b.content), false).map((f) => absPath(f, r.cwd)) : [], art = !b.is_error && st.pubs && st.pubs.has(b.tool_use_id) ? artifactOf(r.toolUseResult) : null;
|
|
531
|
+
items.push({ id: b.tool_use_id, err: !!b.is_error, out: clip(resultText(b.content).replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trimEnd(), RESULT_MAX[n] || (/^mcp__/.test(n) ? 900 : 600)), ...(img ? { img } : {}), ...(files.length ? { files } : {}), ...(art ? { art } : {}) }); // img: how many pictures came back; the page fetches them from /api/media · files: the documents a command says it made
|
|
354
532
|
}
|
|
355
533
|
if (items.length) push({ ts, agent, kind: 'results', items });
|
|
356
534
|
const typed = blocks(r).filter((b) => b.type === 'text').map((b) => b.text).join('\n').replace(HARNESS, ''), cut = /^\s*\[Request interrupted[^\]]*\]/i.test(typed); // what the human typed, without the blocks the harness wraps around it
|
|
@@ -369,10 +547,11 @@ function parseRecord(st, r) {
|
|
|
369
547
|
for (const b of blocks(r)) {
|
|
370
548
|
if (b.type === 'thinking' && typeof b.thinking === 'string' && b.thinking.trim()) st.th = clip(b.thinking.replace(/[^\S\n]+/g, ' ').replace(/ ?\n[\n ]*/g, '\n').trim(), 900); // line breaks are kept: each line of its notes is a thought of its own
|
|
371
549
|
else if (b.type === 'text' && typeof b.text === 'string' && b.text.trim()) { said = push({ ts, agent, kind: 'say', text: b.text.trim(), ...th() }); st.act = st.raw.length - 1; st.sayOf = m.id; st.sayAt = st.act; }
|
|
550
|
+
else if (b.type === 'tool_use' && b.name === 'SubagentHandback' && agent !== 'main' && b.input && typeof b.input.message === 'string' && b.input.message.trim()) { said = push({ ts, agent, kind: 'say', text: b.input.message.trim(), ...th() }); st.act = st.raw.length - 1; st.sayOf = m.id; st.sayAt = st.act; } // since Claude Code 2.1.293 a sub-agent hands its report back through this call, and most write no sentence beside it: the message of the call is what it says last
|
|
372
551
|
else if (b.type === 'tool_use') {
|
|
373
552
|
st.toolName[b.id] = b.name; (st.out = st.out || new Set()).add(b.id); if (b.input && b.input.run_in_background) (st.bg = st.bg || {})[b.id] = true; // out: the calls that have no answer yet
|
|
374
553
|
if (b.name === 'Agent' || b.name === 'Task') push({ ts, agent, kind: 'agentcall', toolId: b.id, bg: !!(b.input && b.input.run_in_background), text: (b.input && b.input.prompt) || '', title: (b.input && b.input.description) || '', ...(b.input && typeof b.input.name === 'string' && b.input.name.trim() ? { nm: b.input.name.trim() } : {}) });
|
|
375
|
-
else { const tool = toolLabel(b, ts); if (tool.d && tool.d.outs) tool.d.outs = tool.d.outs.map((f) => absPath(f, r.cwd)); push({ ts, agent, kind: 'tool', tool, ...th() }); st.act = st.raw.length - 1; }
|
|
554
|
+
else { const tool = toolLabel(b, ts); if (tool.d && tool.d.outs) tool.d.outs = tool.d.outs.map((f) => absPath(f, r.cwd)); if (tool.d && tool.d.kind === 'artifact') (st.pubs = st.pubs || new Set()).add(b.id); push({ ts, agent, kind: 'tool', tool, ...th() }); st.act = st.raw.length - 1; }
|
|
376
555
|
}
|
|
377
556
|
}
|
|
378
557
|
if (agent === 'main' && (m.stop_reason === 'end_turn' || ((r.isApiErrorMessage || (m.model === '<synthetic>' && m.stop_reason === 'stop_sequence')) && !(st.out && st.out.size)))) { // also a turn that ends on a message Claude Code writes itself, in the place of the model's: the API is down, the limit is reached, the request was refused, or there was nothing to answer. Nothing follows it, unless a call of the lead is still out: the connection dropped while its agents worked, and it goes on when they answer. (A message of the model that a safety check cuts is not the end either: Claude Code tells the model, which goes on.) The lead's turn is over: Claude Code writes one record per content block, each with the message's stop reason, so the mark goes on the line this record carries (a thinking block carries none)
|
|
@@ -398,7 +577,7 @@ function readMeta(f) {
|
|
|
398
577
|
}
|
|
399
578
|
|
|
400
579
|
function buildTimeline(proj, id, files = []) {
|
|
401
|
-
const sx = sourceOf(proj), rec = recordOf(sx), base =
|
|
580
|
+
const sx = sourceOf(proj), rec = recordOf(sx), base = projDir(proj, id), mainFile = sx ? sx.fileOf(id) || '' : path.join(base, id + '.jsonl'); // a Codex or Vibe session is kept somewhere else, in another format (rec); from here on it is a session like any other (Codex without sub-agents)
|
|
402
581
|
if (!fs.existsSync(mainFile)) throw new Error('session not found');
|
|
403
582
|
const agents = { main: { id: 'main', role: 'Lead', type: 'main' } }; // the lead has the same name whatever tool runs the session: the page gives it
|
|
404
583
|
const states = [(sx && sx.state && guard(() => sx.state(id), null)) || readNew(mainFile, 'main', false, rec)], subs = subFilesOf(proj, id), runs = {}; files.push(mainFile); // sx.state: a format that is not read line by line hands over the events of the session whole // runs: workflow run → { agents (file name → agent id), by (who launched it), toolId, done }
|
|
@@ -520,17 +699,19 @@ function claudeMap(kind, instruction, texts) {
|
|
|
520
699
|
p.stdin.end(prompt);
|
|
521
700
|
})));
|
|
522
701
|
}
|
|
523
|
-
const translate = (texts) => translateFast(texts);
|
|
702
|
+
const translate = (texts, lang) => translateFast(texts, lang);
|
|
524
703
|
|
|
525
704
|
// Warm `claude` workers: after a slow first call each translation takes ~2-3 s (a cold `claude -p` costs ~6 s).
|
|
526
|
-
|
|
527
|
-
const
|
|
705
|
+
// The languages a call can be held in besides English (the page asks for one with `lang`; French when it says nothing, as it always was).
|
|
706
|
+
const TR_LANG = { fr: 'French', es: 'Spanish', pt: 'Brazilian Portuguese' }, trLang = (l) => (Object.hasOwn(TR_LANG, l) ? l : 'fr');
|
|
707
|
+
const trInstr = (lang) => `Translate each string of this JSON array into natural spoken ${TR_LANG[lang]}, as a teammate would say it in a meeting. Keep code identifiers, file paths, library names and numbers unchanged.`;
|
|
708
|
+
const trSys = (lang) => `You are a translation engine. Translate the user message into natural spoken ${TR_LANG[lang]}, as a colleague would say it in a meeting. Keep code identifiers, file paths, library names and numbers unchanged. Reply with ONLY the translation, nothing else.`;
|
|
528
709
|
class TrWorker {
|
|
529
|
-
constructor() { this.q = []; this.busy = false; this.n = 0; this.p = null; this.cur = null; this.buf = ''; }
|
|
530
|
-
start() {
|
|
531
|
-
const p = spawnClaude(['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--model', 'haiku', '--no-session-persistence', '--tools', '', '--system-prompt',
|
|
710
|
+
constructor() { this.q = []; this.busy = false; this.n = 0; this.p = null; this.cur = null; this.buf = ''; this.lang = 'fr'; }
|
|
711
|
+
start(lang = this.lang) { // the language is in the system prompt: a worker translates into one language, and is started again for another
|
|
712
|
+
const p = spawnClaude(['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--model', 'haiku', '--no-session-persistence', '--tools', '', '--system-prompt', trSys(lang)], { cwd: os.tmpdir() });
|
|
532
713
|
if (!p) return;
|
|
533
|
-
this.p = p; this.buf = ''; this.n = 0;
|
|
714
|
+
this.p = p; this.buf = ''; this.n = 0; this.lang = lang;
|
|
534
715
|
p.stderr.on('data', (d) => { lastTrError = String(d).slice(-300); });
|
|
535
716
|
p.stdout.on('data', (d) => {
|
|
536
717
|
this.buf += d; let i;
|
|
@@ -543,11 +724,11 @@ class TrWorker {
|
|
|
543
724
|
p.on('close', dead); p.on('error', dead);
|
|
544
725
|
}
|
|
545
726
|
finish(res) { const c = this.cur; this.cur = null; this.busy = false; if (c) { clearTimeout(c.timer); c.res(res); } this.pump(); }
|
|
546
|
-
ask(text) { return new Promise((res) => { this.q.push({ text, res }); this.pump(); }); }
|
|
727
|
+
ask(text, lang = 'fr') { return new Promise((res) => { this.q.push({ text, lang, res }); this.pump(); }); }
|
|
547
728
|
kill() { clearTimeout(this.idle); if (this.p) { const p = this.p; this.p = null; try { p.kill(); } catch {} } }
|
|
548
729
|
pump() {
|
|
549
730
|
if (this.busy || !this.q.length) return;
|
|
550
|
-
if (!this.p || this.n >= 30) { if (this.p) { const old = this.p; this.p = null; old.kill(); } this.start(); if (!this.p) { while (this.q.length) this.q.shift().res(null); return; } } // restart now and then: the conversation context grows
|
|
731
|
+
if (!this.p || this.n >= 30 || this.lang !== this.q[0].lang) { if (this.p) { const old = this.p; this.p = null; old.kill(); } this.start(this.q[0].lang); if (!this.p) { while (this.q.length) this.q.shift().res(null); return; } } // restart now and then: the conversation context grows
|
|
551
732
|
clearTimeout(this.idle); this.idle = setTimeout(() => { if (!this.busy && !this.q.length) this.kill(); }, 10 * 60 * 1000); // free the process when nothing was translated for 10 min
|
|
552
733
|
const job = this.q.shift(); this.busy = true; this.n++; this.cur = job;
|
|
553
734
|
job.timer = setTimeout(() => { if (this.cur === job && this.p) this.p.kill(); }, 45000);
|
|
@@ -558,15 +739,15 @@ const trWorkers = [new TrWorker(), new TrWorker()];
|
|
|
558
739
|
const shutdown = () => { trWorkers.forEach((w) => w.kill()); kokoro.shutdown(); };
|
|
559
740
|
process.on('exit', shutdown);
|
|
560
741
|
const pickWorker = () => trWorkers.reduce((a, b) => (a.q.length + a.busy <= b.q.length + b.busy ? a : b));
|
|
561
|
-
async function translateFast(texts) {
|
|
562
|
-
const need = [...new Set(texts.filter((t) => !cache.has('
|
|
742
|
+
async function translateFast(texts, lang = 'fr') {
|
|
743
|
+
const need = [...new Set(texts.filter((t) => !cache.has(lang + '|' + t)))];
|
|
563
744
|
if (need.length && need.length <= 3 && !process.env.ANTHROPIC_API_KEY) { // a few lines: warm workers in parallel; many lines: one batched call
|
|
564
|
-
await Promise.all(need.map(async (t) => { const r = await pickWorker().ask(t); if (r) cache.set('
|
|
565
|
-
return { texts: texts.map((t) => cache.get('
|
|
745
|
+
await Promise.all(need.map(async (t) => { const r = await pickWorker().ask(t, lang); if (r) cache.set(lang + '|' + t, r); }));
|
|
746
|
+
return { texts: texts.map((t) => cache.get(lang + '|' + t) || t), ok: texts.every((t) => cache.has(lang + '|' + t)) };
|
|
566
747
|
}
|
|
567
|
-
return claudeMap(
|
|
748
|
+
return claudeMap(lang, trInstr(lang), texts);
|
|
568
749
|
}
|
|
569
|
-
const quips = (texts, lang) => claudeMap('q' + lang, `Each string is a work report from a software agent. For each, write ONE short, deadpan, funny reaction (max 12 words) from a grumpy teammate in a South Park-style cartoon meeting, in ${lang
|
|
750
|
+
const quips = (texts, lang) => claudeMap('q' + lang, `Each string is a work report from a software agent. For each, write ONE short, deadpan, funny reaction (max 12 words) from a grumpy teammate in a South Park-style cartoon meeting, in ${TR_LANG[lang] || 'English'}. No emojis.`, texts);
|
|
570
751
|
|
|
571
752
|
// ---- text-to-speech, generated on the machine and cached as wav:
|
|
572
753
|
// macOS → `say`, Windows → System.Speech (SAPI voices) through PowerShell, Linux → espeak-ng.
|
|
@@ -616,7 +797,7 @@ function tts(text, voice, rate, engine, fb) {
|
|
|
616
797
|
if (ttsJobs.has(key)) return ttsJobs.get(key);
|
|
617
798
|
fs.mkdirSync(ttsDir, { recursive: true });
|
|
618
799
|
const tmp = file + '.part.wav';
|
|
619
|
-
const job = (kk ? kokoro.synth(text, voice, kokoro.speedFor(rate), tmp).catch((e) => { const vs = listVoices(), v = vs.voices.find((x) => x.name === fb) || vs.voices.find((x) => x.locale.startsWith(
|
|
800
|
+
const job = (kk ? kokoro.synth(text, voice, kokoro.speedFor(rate), tmp).catch((e) => { const vs = listVoices(), v = vs.voices.find((x) => x.name === fb) || vs.voices.find((x) => x.locale.startsWith(kokoro.localeOf(voice).slice(0, 3))); if (!v) throw e; return synthesize(v.name, rate, text, tmp); }) : synthesize(voice, rate, text, tmp)) // a line Kokoro cannot make goes to a system voice instead of being dropped: the one the page names (fb, its best system voice for this character), or else the first one of the same language
|
|
620
801
|
.then(() => { fs.renameSync(tmp, file); return file; }).finally(() => ttsJobs.delete(key));
|
|
621
802
|
ttsJobs.set(key, job); return job;
|
|
622
803
|
}
|
|
@@ -642,7 +823,7 @@ function listCharacters(pack) {
|
|
|
642
823
|
// the page cannot have any other path opened, nothing is read and nothing is run. A Codex or Vibe session may name a file from the folder it was started in.
|
|
643
824
|
// The same goes for a document one of its commands names (an export, a report made by a script), from the moment that command started: an older file by that name is not one of its files.
|
|
644
825
|
function sessionFile(proj, id, file) { // { fp: where it is, since: 0 for a file it wrote, else when the first command that names it started }
|
|
645
|
-
const sx = sourceOf(proj); if (!(sx ? guard(() => sx.fileOf(id), null) : fs.existsSync(path.join(
|
|
826
|
+
const sx = sourceOf(proj); if (!(sx ? guard(() => sx.fileOf(id), null) : fs.existsSync(path.join(projDir(proj, id), id + '.jsonl')))) return null;
|
|
646
827
|
const ev = timeline(proj, id).events, said = new Set(); let since = ev.some((e) => e.kind === 'tools' && e.tools.some((t) => t.d && t.d.kind === 'write' && t.d.file === file)) ? 0 : null;
|
|
647
828
|
if (since == null) {
|
|
648
829
|
for (const e of ev) if (e.kind === 'results') for (const it of e.items) if (it.files && it.files.includes(file)) said.add(it.id); // named in what a command printed: counted from when that command started
|
|
@@ -675,7 +856,7 @@ function start(port = PORT) {
|
|
|
675
856
|
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
|
|
676
857
|
// Endpoints with side effects (they spawn programs or claim the sound), and the one that serves pictures from a session, refuse requests that a browser marks as coming from another site, e.g. an <img> on a web page.
|
|
677
858
|
const sfs = req.headers['sec-fetch-site'];
|
|
678
|
-
if (sfs && sfs !== 'same-origin' && sfs !== 'none' && (req.method !== 'GET' || ['/api/translate', '/api/quips', '/api/warm', '/api/audio', '/api/tts', '/api/prefs', '/api/prefs.js', '/api/voices', '/api/kokoro', '/api/kokoro/install', '/api/media'].includes(url.pathname))) { res.writeHead(403); return res.end('forbidden'); }
|
|
859
|
+
if (sfs && sfs !== 'same-origin' && sfs !== 'none' && (req.method !== 'GET' || ['/api/translate', '/api/quips', '/api/warm', '/api/audio', '/api/tts', '/api/prefs', '/api/prefs.js', '/api/voices', '/api/kokoro', '/api/kokoro/install', '/api/media', '/api/artifact', '/api/errors'].includes(url.pathname))) { res.writeHead(403); return res.end('forbidden'); }
|
|
679
860
|
const readBody = (cb) => { // request bodies are small JSON: stop reading beyond 256 KB and give up after 10 s
|
|
680
861
|
const chunks = []; let size = 0, over = false; req.setTimeout(10000, () => req.destroy());
|
|
681
862
|
if (+req.headers['content-length'] > 262144) { res.writeHead(413); res.end('too large'); return req.destroy(); }
|
|
@@ -684,8 +865,8 @@ function start(port = PORT) {
|
|
|
684
865
|
};
|
|
685
866
|
const textList = (x) => (Array.isArray(x) ? x : []).slice(0, 200).map((t) => String(t).slice(0, 2000));
|
|
686
867
|
try {
|
|
687
|
-
if (url.pathname === '/api/translate' && req.method === 'POST') return readBody(async (body) => { try { json(await translate(textList(
|
|
688
|
-
if (url.pathname === '/api/quips' && req.method === 'POST') return readBody(async (body) => { try { const b = JSON.parse(body); json(await quips(textList(b.texts), b.lang
|
|
868
|
+
if (url.pathname === '/api/translate' && req.method === 'POST') return readBody(async (body) => { try { const b = JSON.parse(body); json(await translate(textList(b.texts), trLang(b.lang))); } catch (e) { json({ error: String(e) }, 400); } });
|
|
869
|
+
if (url.pathname === '/api/quips' && req.method === 'POST') return readBody(async (body) => { try { const b = JSON.parse(body); json(await quips(textList(b.texts), Object.hasOwn(TR_LANG, b.lang) ? b.lang : 'en')); } catch (e) { json({ error: String(e) }, 400); } });
|
|
689
870
|
if (url.pathname === '/api/sessions') return json(listSessions());
|
|
690
871
|
if (url.pathname === '/api/projects') { // projects (working folders) ordered by latest activity — lets the live view follow one of them
|
|
691
872
|
const m = new Map(); for (const r of listSessions()) { const p = m.get(r.proj) || { proj: r.proj, mtime: 0, sessions: 0 }; p.mtime = Math.max(p.mtime, r.mtime); p.sessions++; m.set(r.proj, p); }
|
|
@@ -699,7 +880,7 @@ function start(port = PORT) {
|
|
|
699
880
|
return json({ owner: audioOwner.id });
|
|
700
881
|
}
|
|
701
882
|
if (url.pathname === '/api/health') return json({ claude: findClaude(), apiKey: !!process.env.ANTHROPIC_API_KEY, trError: lastTrError, platform: process.platform });
|
|
702
|
-
if (url.pathname === '/api/warm') { trWorkers.forEach((w) => { if (!w.p) w.start(); }); return json({ ok: true }); }
|
|
883
|
+
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 }); }
|
|
703
884
|
if (url.pathname === '/api/voices') {
|
|
704
885
|
if (url.searchParams.get('engine') === 'kokoro') { const st = kokoro.status(); if (st.installed && !st.gaveUp) kokoro.warm(); return json({ available: st.installed && !st.gaveUp, ready: st.ready, voices: kokoro.voices(), platform: process.platform, engine: 'kokoro' }); }
|
|
705
886
|
return loadVoices().then((v) => json(v));
|
|
@@ -714,7 +895,10 @@ function start(port = PORT) {
|
|
|
714
895
|
if (url.pathname === '/api/prefs.js') { res.writeHead(200, { 'content-type': 'application/javascript', 'cache-control': 'no-store' }); return res.end('window.SAVED_PREFS = ' + JSON.stringify(readPrefs()).replace(/</g, '\\u003c') + ';'); }
|
|
715
896
|
if (url.pathname === '/api/prefs' && req.method === 'PUT') return readBody((body) => { try { const v = JSON.parse(body); if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('prefs must be an object'); writePrefs(v); json({ ok: true }); } catch (e) { json({ error: String(e.message || e) }, 400); } });
|
|
716
897
|
if (url.pathname === '/api/prefs') return json(readPrefs() || {});
|
|
717
|
-
if (url.pathname === '/api/
|
|
898
|
+
if (url.pathname === '/api/done' && req.method === 'POST') return readBody((body) => { try { const v = JSON.parse(body); json({ ok: setDone(String(v.proj || ''), String(v.id || ''), v.on !== false) }); } catch (e) { logError('done', e); json({ error: String(e.message || e) }, 400); } });
|
|
899
|
+
if (url.pathname === '/api/errors' && req.method === 'POST') return readBody((body) => { try { const b = JSON.parse(body) || {}; logError('page' + (typeof b.where === 'string' && b.where ? ' ' + b.where.slice(0, 40) : ''), { message: String(b.msg || ''), stack: String(b.stack || '') }); json({ ok: true }); } catch (e) { json({ error: String(e.message || e) }, 400); } }); // an error of the page, written to the local log
|
|
900
|
+
if (url.pathname === '/api/errors') return json(errorReport());
|
|
901
|
+
if (url.pathname === '/api/current') { const q = (k) => url.searchParams.get(k) || ''; return json(currentSession(q('proj'), q('pid') ? { proj: q('pproj'), id: q('pid'), since: q('since') ? +q('since') : NaN, pin: q('pin') === '1' } : null, { proj: q('sproj'), id: q('sid') })); }
|
|
718
902
|
if (url.pathname === '/api/board') return json(boardRows());
|
|
719
903
|
if (url.pathname === '/api/characters') return json(listCharacters(url.searchParams.get('pack') || ''));
|
|
720
904
|
if (url.pathname === '/api/packs') return json(Object.keys(PACKS).map((name) => ({ name, n: listCharacters(name).chars.length })));
|
|
@@ -734,10 +918,19 @@ function start(port = PORT) {
|
|
|
734
918
|
if (!im) { res.writeHead(bad ? 400 : 404); return res.end(bad ? 'bad request' : 'not found'); }
|
|
735
919
|
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);
|
|
736
920
|
}
|
|
921
|
+
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)
|
|
922
|
+
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;
|
|
923
|
+
if (bad) { res.writeHead(400); return res.end('bad request'); }
|
|
924
|
+
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);
|
|
925
|
+
if (q('check')) return json(page ? { ok: true, net: page.net } : { ok: false }, page ? 200 : 404);
|
|
926
|
+
if (!page) { res.writeHead(404); return res.end('not found'); }
|
|
927
|
+
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
|
|
928
|
+
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);
|
|
929
|
+
}
|
|
737
930
|
if (url.pathname === '/api/session') {
|
|
738
931
|
const proj = url.searchParams.get('proj') || '', sid = url.searchParams.get('id') || '', SAFE = /^[\w.\-]+$/;
|
|
739
932
|
if (!SAFE.test(proj) || !SAFE.test(sid) || proj === '..' || sid === '..' || proj.length > 200 || sid.length > 200) { res.writeHead(400); return res.end('bad request'); }
|
|
740
|
-
if (proj !== '_demo' && !(sourceOf(proj) ? sourceOf(proj).fileOf(sid) : fs.existsSync(path.join(
|
|
933
|
+
if (proj !== '_demo' && !(sourceOf(proj) ? sourceOf(proj).fileOf(sid) : fs.existsSync(path.join(projDir(proj, sid), sid + '.jsonl')))) return json({ error: 'session not found' }, 404);
|
|
741
934
|
const entry = proj === '_demo' ? demoEntry() : timelineEntry(proj, sid), tl = entry.tl; // built-in fictional session
|
|
742
935
|
const after = url.searchParams.get('after'), ep = url.searchParams.get('ep');
|
|
743
936
|
if (after == null) { // the whole timeline: serialize once per version, send gzip-compressed when the browser allows it (12 MB → ~1.5 MB)
|
|
@@ -762,12 +955,13 @@ function start(port = PORT) {
|
|
|
762
955
|
const file = path.join(PUBLIC, url.pathname === '/' ? 'index.html' : url.pathname);
|
|
763
956
|
let fst = null; try { fst = fs.statSync(file); } catch {}
|
|
764
957
|
if (!file.startsWith(PUBLIC + path.sep) || !fst || !fst.isFile()) { res.writeHead(404); return res.end('not found'); }
|
|
765
|
-
|
|
958
|
+
// 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.
|
|
959
|
+
res.writeHead(200, { 'content-type': MIME[path.extname(file)] || 'application/octet-stream', ...(path.extname(file) === '.html' ? { 'content-security-policy': "frame-src 'self'" } : {}) });
|
|
766
960
|
res.end(fs.readFileSync(file));
|
|
767
|
-
} catch (e) { if (res.headersSent) return res.destroy(); json({ error: String(e.message || e) }, 500); }
|
|
961
|
+
} catch (e) { logError(req.method + ' ' + url.pathname, e); if (res.headersSent) return res.destroy(); json({ error: String(e.message || e) }, 500); }
|
|
768
962
|
}).listen(port, '127.0.0.1', function () { console.log(`Agent Standup → http://localhost:${this.address().port}`); });
|
|
769
963
|
}
|
|
770
|
-
module.exports = { start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, _reveal: reveal };
|
|
964
|
+
module.exports = { start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, logError, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
|
|
771
965
|
if (require.main === module) {
|
|
772
966
|
start().on('error', (e) => {
|
|
773
967
|
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));
|