@double_geste/agent-standup 1.30.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 +6 -4
- package/kokoro-worker.js +35 -4
- package/kokoro.js +26 -10
- package/package.json +1 -1
- package/public/index.html +582 -166
- package/public/locales/README.md +5 -2
- package/public/locales/da.json +44 -10
- package/public/locales/de.json +44 -10
- package/public/locales/en.json +42 -8
- package/public/locales/es.json +44 -10
- package/public/locales/ja.json +44 -10
- package/public/locales/ko.json +44 -10
- package/public/locales/pt-BR.json +44 -10
- package/public/locales/zh-CN.json +44 -10
- package/public/locales/zh-TW.json +44 -10
- package/server.js +342 -82
- package/vibe.js +12 -7
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;
|
|
@@ -24,6 +64,32 @@ const blocks = (rec) => {
|
|
|
24
64
|
return Array.isArray(c) ? c : [];
|
|
25
65
|
};
|
|
26
66
|
const clip = (x, n = 700) => String(x == null ? '' : x).slice(0, n);
|
|
67
|
+
// The documents a command names, in its text or in what it printed: an export, a report, a picture, a package. The call shows one under it when the lead names it too
|
|
68
|
+
// and it was written since (see sessionFile): a name is all that is taken here, nothing is read. cd: a command, where "cd dir &&" says from which folder the names that follow are given.
|
|
69
|
+
const OUT_EXT = /\.(html?|md|markdown|txt|rtf|pdf|docx?|pptx?|xlsx?|csv|tsv|png|jpe?g|gif|webp|svg|zip|tgz|vsix|mp4|mov|webm|mp3|wav|epub)$/i, ROOTED = /^([~\/\\]|[A-Za-z]:[\\/])/;
|
|
70
|
+
function noHere(t) { // a command without what its here-documents hold: that is a file's content, not the command (the rest of the line that opens one is: "> list.txt"). Read once from left to right, a few of them at most: a text full of "<<" (C++, shifts) costs nothing
|
|
71
|
+
let out = '', i = 0; const open = /<<-?[ \t]*(['"]?)(\w+)\1/y;
|
|
72
|
+
for (let n = 0; n < 8; n++) {
|
|
73
|
+
const j = t.indexOf('<<', i); if (j < 0) break; open.lastIndex = j; const m = t[j - 1] !== '<' && t[j + 2] !== '<' && open.exec(t); if (!m) { out += t.slice(i, j + 2); i = j + 2; continue; }
|
|
74
|
+
const eol = t.indexOf('\n', open.lastIndex); if (eol < 0) return out + t.slice(i, j) + ' ' + t.slice(open.lastIndex);
|
|
75
|
+
out += t.slice(i, j) + ' ' + t.slice(open.lastIndex, eol); i = t.length; // to the line that closes it, or to the end when none does
|
|
76
|
+
for (let a = eol + 1; a <= t.length;) { const b = t.indexOf('\n', a), line = t.slice(a, b < 0 ? t.length : b); if (line.trim() === m[2]) { i = b < 0 ? t.length : b; break; } if (b < 0) break; a = b + 1; }
|
|
77
|
+
}
|
|
78
|
+
return out + t.slice(i);
|
|
79
|
+
}
|
|
80
|
+
function docPaths(text, cd) {
|
|
81
|
+
const out = []; let dir = '';
|
|
82
|
+
const cmd = cd ? noHere(String(text || '').slice(0, 20000)) : String(text || '').slice(0, 20000);
|
|
83
|
+
for (const seg of cmd.split(cd ? /&&|\|\||;|\n/ : /\n/)) {
|
|
84
|
+
const m = cd && seg.match(/^\s*cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/); if (m) { const d = m[1] || m[2] || m[3]; dir = ROOTED.test(d) ? d : path.join(dir, d); continue; }
|
|
85
|
+
for (const t of seg.matchAll(/"([^"\n]+)"|'([^'\n]+)'|([^\s"'`|&;<>()=,]+)/g)) {
|
|
86
|
+
const f = (t[1] || t[2] || t[3]).replace(/[.:;!?)\]]+$/, ''); if (!OUT_EXT.test(f) || /:\/\/|[*?{}$\[]|^(\\\\|\/\/)/.test(f) || f.length > 400) continue; // not a link, a pattern or a variable, nor a path on another machine (the server would go and look there)
|
|
87
|
+
const full = dir && !ROOTED.test(f) ? path.join(dir, f) : f; if (!out.includes(full)) out.push(full); if (out.length >= 16) return out;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
const absPath = (f, cwd) => (/^~([\\/]|$)/.test(f) ? path.join(os.homedir(), f.slice(1)) : path.isAbsolute(f) ? path.normalize(f) : cwd ? path.resolve(cwd, f) : f); // cwd: the folder the session was in when it wrote that record
|
|
27
93
|
// What each tool call looks like on a screen ("d"), plus its id/timestamp so the result can be matched later.
|
|
28
94
|
const toolLabel = (b, ts) => {
|
|
29
95
|
const i = b.input || {};
|
|
@@ -31,7 +97,7 @@ const toolLabel = (b, ts) => {
|
|
|
31
97
|
const arg = i.file_path || i.notebook_path || i.path || i.pattern || i.command || i.url || i.query || i.skill || (q0 && q0.question) || i.description || firstStr || '';
|
|
32
98
|
const out = { id: b.id, ts, name: b.name, arg: String(arg).slice(0, 90) };
|
|
33
99
|
switch (b.name) {
|
|
34
|
-
case 'Bash': out.d = { kind: 'cmd', text: clip(i.command, 1200), note: clip(i.description, 140) }; break;
|
|
100
|
+
case 'Bash': { out.d = { kind: 'cmd', text: clip(i.command, 1200), note: clip(i.description, 140) }; const outs = docPaths(i.command, true); if (outs.length) out.d.outs = outs; break; }
|
|
35
101
|
case 'Read': out.d = { kind: 'read', file: i.file_path, offset: i.offset, limit: i.limit }; break;
|
|
36
102
|
case 'Edit': case 'MultiEdit': { const e = i.edits ? i.edits[0] || {} : i; out.d = { kind: 'edit', file: i.file_path, old: clip(e.old_string, 500), new: clip(e.new_string, 500) }; break; }
|
|
37
103
|
case 'Write': out.d = { kind: 'write', file: i.file_path, text: clip(i.content, 800) }; break;
|
|
@@ -44,10 +110,15 @@ const toolLabel = (b, ts) => {
|
|
|
44
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;
|
|
45
111
|
case 'Skill': out.d = { kind: 'text', what: 'skill', v: i.skill, text: clip(i.skill + (i.args ? ' ' + i.args : ''), 200) }; break;
|
|
46
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
|
|
47
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) };
|
|
48
116
|
}
|
|
49
117
|
return out;
|
|
50
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);
|
|
51
122
|
const resultText = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => x.text || '').join('\n') : '');
|
|
52
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.
|
|
53
124
|
const IMG_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']), mediaMemo = new Map();
|
|
@@ -56,7 +127,7 @@ const resultImages = (c) => (Array.isArray(c) ? c.filter(isImg) : []);
|
|
|
56
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
|
|
57
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).
|
|
58
129
|
function subFiles(proj, id) {
|
|
59
|
-
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 = [];
|
|
60
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
|
|
61
132
|
let names; try { names = fs.readdirSync(sd); } catch { return out; }
|
|
62
133
|
for (const f of names) if (f.endsWith('.jsonl')) add(sd, f, '');
|
|
@@ -70,7 +141,7 @@ function subFiles(proj, id) {
|
|
|
70
141
|
}
|
|
71
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
|
|
72
143
|
function mediaFile(proj, sid, agent) {
|
|
73
|
-
if (agent === 'main') return path.join(
|
|
144
|
+
if (agent === 'main') return path.join(projDir(proj, sid), sid + '.jsonl');
|
|
74
145
|
const hit = subFiles(proj, sid).find((x) => x.aid === agent);
|
|
75
146
|
return hit ? hit.file : null;
|
|
76
147
|
}
|
|
@@ -94,6 +165,59 @@ function toolImage(file, toolId, n) { // looks for the tool's result line in t
|
|
|
94
165
|
mediaMemo.delete(key); mediaMemo.set(key, found || { miss: size }); if (mediaMemo.size > 12) mediaMemo.delete(mediaMemo.keys().next().value);
|
|
95
166
|
return found;
|
|
96
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'";
|
|
97
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 };
|
|
98
222
|
const NO_RESULT = new Set(['Agent', 'Task', 'SendMessage', 'TodoWrite']); // internal bookkeeping, nothing to show
|
|
99
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
|
|
@@ -107,29 +231,25 @@ function listSessions() {
|
|
|
107
231
|
function listSessions0() {
|
|
108
232
|
const rows = [];
|
|
109
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 });
|
|
110
|
-
for (const proj of
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { continue; }
|
|
114
|
-
for (const f of files) {
|
|
115
|
-
const id = f.replace(/\.jsonl$/, '');
|
|
116
|
-
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
|
|
117
237
|
rows.push({ proj, id, mtime: st.mtimeMs, size: st.size, agents: subFiles(proj, id).length });
|
|
118
238
|
}
|
|
119
239
|
}
|
|
120
240
|
rows.sort((a, b) => b.mtime - a.mtime);
|
|
121
|
-
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
|
|
122
242
|
for (const r of top) {
|
|
123
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; }
|
|
124
244
|
// titles come from the cached tail read (custom title, then AI title, then first prompt): no whole-file reads
|
|
125
|
-
let t = null; try { const f = path.join(
|
|
126
|
-
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, '/');
|
|
127
247
|
}
|
|
128
248
|
return top;
|
|
129
249
|
}
|
|
130
250
|
|
|
131
251
|
function stamp(proj, id) {
|
|
132
|
-
const base =
|
|
252
|
+
const base = projDir(proj, id); let n = 0;
|
|
133
253
|
const add = (f) => { try { const s = fs.statSync(f); n += s.mtimeMs + s.size; } catch {} };
|
|
134
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);
|
|
135
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
|
|
@@ -181,24 +301,46 @@ const readHead = (file, bytes) => { const fd = fs.openSync(file, 'r'); try { con
|
|
|
181
301
|
const APPROVAL = /^(Edit|Write|MultiEdit|NotebookEdit)/, ASKS = /^(AskUserQuestion|ExitPlanMode)/, SUBTOOL = /^(Task|Agent)$/;
|
|
182
302
|
const boardCache = new Map(); // file → { sig, parsed, title }
|
|
183
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
|
+
}
|
|
184
322
|
function parseTail(file, st) {
|
|
185
323
|
const sig = st.mtimeMs + ':' + st.size, hit = boardCache.get(file); if (hit && hit.sig === sig) return hit;
|
|
186
324
|
const { text, cut } = readTail(file, 192 * 1024), lines = text.split('\n'); if (cut) lines.shift();
|
|
187
|
-
const pend = new Map(); let lastType = null, lastTool = 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;
|
|
188
326
|
for (const l of lines) {
|
|
189
327
|
if (!l) continue; let r; try { r = JSON.parse(l); } catch { continue; }
|
|
328
|
+
const a = typedAt(r); if (a > asked) asked = a;
|
|
190
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
|
|
191
331
|
const t = Date.parse(r.timestamp) || 0, bl = blocks(r);
|
|
192
|
-
if (r.type === 'assistant' || r.type === 'user') { lastType = r.type; lastTool = bl.some((b) => b.type === 'tool_use'); if (t) lastTs = t;
|
|
193
|
-
|
|
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;
|
|
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
|
|
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); }
|
|
194
335
|
}
|
|
195
336
|
if (!hit && !custom) { // first look at this file: a little further back than the lines read above, and without needing whole lines
|
|
196
337
|
const big = readTail(file, 256 * 1024).text, un = (m) => { try { return m ? JSON.parse('"' + m[1] + '"') : null; } catch { return null; } };
|
|
197
338
|
custom = un([...big.matchAll(/"type":"custom-title","customTitle":"((?:[^"\\]|\\.)*)"/g)].pop()); if (!ai) ai = un([...big.matchAll(/"type":"ai-title","aiTitle":"((?:[^"\\]|\\.)*)"/g)].pop());
|
|
198
339
|
}
|
|
199
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
|
|
200
|
-
|
|
201
|
-
|
|
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;
|
|
202
344
|
}
|
|
203
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
|
|
204
346
|
const ONE = (t) => t.replace(/\s+/g, ' ').trim().slice(0, 90);
|
|
@@ -212,60 +354,125 @@ function firstPrompt(file) { // the first thing the person typed, read record
|
|
|
212
354
|
}
|
|
213
355
|
function boardRows() {
|
|
214
356
|
if (Date.now() - boardMemo.at < 1200) return boardMemo.rows; // several windows polling at once share one scan
|
|
215
|
-
const out = boardRows0(); boardMemo = { at: Date.now(), rows: out }; return out;
|
|
357
|
+
const out = withDone(boardRows0()); boardMemo = { at: Date.now(), rows: out }; return out;
|
|
216
358
|
}
|
|
217
359
|
function boardRows0() {
|
|
218
360
|
const now = Date.now(), rows = [];
|
|
219
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 });
|
|
220
|
-
for (const proj of
|
|
221
|
-
const
|
|
222
|
-
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 {} }
|
|
223
364
|
}
|
|
224
365
|
rows.sort((a, b) => b.st.mtimeMs - a.st.mtimeMs);
|
|
225
|
-
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 }) => {
|
|
226
367
|
if (cx) return guard(() => src.boardRow(cx, now), null);
|
|
227
|
-
const file = path.join(
|
|
368
|
+
const file = path.join(projDir(proj, id), id + '.jsonl'); let p; try { p = parseTail(file, st); } catch { p = { pending: [] }; }
|
|
228
369
|
const age = now - st.mtimeMs, lp = (p.pending || [])[(p.pending || []).length - 1]; let state = 'idle', tool = '', ageMs = age;
|
|
229
370
|
if (age < 30 * 60e3) {
|
|
230
371
|
if (lp) { ageMs = now - (lp.ts || st.mtimeMs); tool = lp.name;
|
|
231
372
|
state = SUBTOOL.test(lp.name) ? 'waiting' : (ASKS.test(lp.name) && ageMs > 4000) || (APPROVAL.test(lp.name) && ageMs > 15000) ? 'blocked' : 'working'; }
|
|
232
|
-
else if (p.
|
|
373
|
+
else if (p.esc) state = 'turn'; // you stopped it (Esc): it is your turn there, not "working" for the next ten minutes
|
|
374
|
+
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.
|
|
375
|
+
// 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)
|
|
233
376
|
else state = age < 10 * 60e3 ? 'working' : 'idle';
|
|
234
377
|
}
|
|
235
378
|
let subActive = 0, subTotal = 0;
|
|
236
379
|
for (const x of subFiles(proj, id)) { subTotal++; if (now - mtimeOf(x.file) < 90e3) subActive++; }
|
|
237
|
-
return { proj, id, title: p.title || id, mtime: st.mtimeMs, state, tool, ageMs, subActive, subTotal };
|
|
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
|
|
238
381
|
}).filter(Boolean);
|
|
239
382
|
}
|
|
240
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).
|
|
241
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
|
+
}
|
|
242
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; } }
|
|
243
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); }
|
|
244
|
-
//
|
|
245
|
-
|
|
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;
|
|
246
450
|
function sessionMtime(proj, id) {
|
|
247
451
|
const sx = sourceOf(proj), r = sx ? guard(() => sx.row(id), null) : null; if (sx && (!r || !sx.subFiles)) return r ? r.mtime : 0;
|
|
248
|
-
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);
|
|
249
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
|
|
250
454
|
}
|
|
251
|
-
function currentSession(projFilter,
|
|
252
|
-
const safe = (x) => typeof x === 'string' && /^[\w.\-]+$/.test(x) && x !== '..';
|
|
253
|
-
|
|
254
|
-
|
|
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
|
|
255
467
|
let best = null;
|
|
256
468
|
const consider = (proj, id, m) => { if (!best || m > best.mtime) best = { proj, id, mtime: m }; };
|
|
257
|
-
for (const m of SOURCES) for (const r of guard(() => m.sessions(), [])) if (
|
|
258
|
-
for (const proj of
|
|
259
|
-
if (projFilter && proj !== projFilter && !proj.startsWith(projFilter + '-')) continue; // the folder itself, or a folder inside it
|
|
260
|
-
const
|
|
261
|
-
try { files = fs.readdirSync(dir); } catch { continue; }
|
|
262
|
-
for (const f of files) {
|
|
263
|
-
if (!f.endsWith('.jsonl')) continue;
|
|
264
|
-
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
|
|
265
|
-
}
|
|
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
|
|
266
473
|
}
|
|
267
|
-
if (!best && projFilter) return currentSession('',
|
|
268
|
-
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
|
|
269
476
|
}
|
|
270
477
|
|
|
271
478
|
// ---- Incremental transcript reader: each .jsonl is parsed once, then only the bytes appended since are read.
|
|
@@ -316,20 +523,22 @@ function parseRecord(st, r) {
|
|
|
316
523
|
}
|
|
317
524
|
if (r.type === 'user') {
|
|
318
525
|
const items = [], wf = r.toolUseResult && typeof r.toolUseResult === 'object' && typeof r.toolUseResult.runId === 'string' ? r.toolUseResult.runId : ''; // tool results: the real output that appeared on the agent's screen
|
|
526
|
+
if (st.out) for (const b of blocks(r)) if (b.type === 'tool_result') st.out.delete(b.tool_use_id);
|
|
319
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>/
|
|
320
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)
|
|
321
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])) {
|
|
322
|
-
const n = st.toolName[b.tool_use_id], img = resultImages(b.content).length;
|
|
323
|
-
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 } : {}) }); // img: how many pictures came back; the page fetches them from /api/media
|
|
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
|
|
324
532
|
}
|
|
325
533
|
if (items.length) push({ ts, agent, kind: 'results', items });
|
|
326
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
|
|
327
535
|
if (agent !== 'main') { if (!st.prompt && typed.trim() && !st.raw.length) st.prompt = { ts, text: typed.trim() }; return; } // a sub-agent's first user message is the order, emitted from the parent's side (kept here for the agents of a workflow, whose order is in no other file)
|
|
328
|
-
if (cut && st.act >= 0) st.raw[st.act].end = 1; // Esc: the turn stops there, without the end_turn mark. The last thing the lead said or did closes it
|
|
536
|
+
if (cut && st.out) st.out.clear(); if (cut && st.act >= 0) st.raw[st.act].end = 1; // Esc: the turn stops there, without the end_turn mark. The last thing the lead said or did closes it
|
|
329
537
|
const txt = typed.replace(/^\s*\[Request interrupted[^\]]*\]\s*/i, '').trim();
|
|
330
|
-
if (txt && !/^<(system-reminder|command-|local-command|task-notification)/.test(txt) && !r.isMeta && !r.isCompactSummary) push({ ts, agent: 'user', kind: 'user', text: txt }); // not the summary Claude Code writes when it compacts: thousands of characters the human never typed
|
|
538
|
+
if (txt && !/^<(system-reminder|command-|local-command|task-notification)/.test(txt) && !r.isMeta && !r.isCompactSummary) { if (st.out) st.out.clear(); push({ ts, agent: 'user', kind: 'user', text: txt }); } // a call that never got its answer is not waited for across your next message · not the summary Claude Code writes when it compacts: thousands of characters the human never typed
|
|
331
539
|
} else if (r.type === 'assistant') {
|
|
332
540
|
const m = r.message || {}; let said = null;
|
|
541
|
+
if (agent === 'main') { st.lead = 1; if (m.stop_reason) st.stops = 1; } // this transcript says why each message stopped: its turns end with a mark, and until one comes the lead is at work (see marks, below)
|
|
333
542
|
if (m.id && m.usage) { // the same message is repeated once per content block with identical numbers: keep one per message id
|
|
334
543
|
const u = m.usage, prev = st.msgUsage.get(m.id);
|
|
335
544
|
st.msgUsage.set(m.id, { ts: prev ? prev.ts : ts, u: { i: u.input_tokens || 0, o: u.output_tokens || 0, r: u.cache_read_input_tokens || 0, w: u.cache_creation_input_tokens || 0 }, model: m.model });
|
|
@@ -338,13 +547,14 @@ function parseRecord(st, r) {
|
|
|
338
547
|
for (const b of blocks(r)) {
|
|
339
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
|
|
340
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
|
|
341
551
|
else if (b.type === 'tool_use') {
|
|
342
|
-
st.toolName[b.id] = b.name; if (b.input && b.input.run_in_background) (st.bg = st.bg || {})[b.id] = true;
|
|
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
|
|
343
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() } : {}) });
|
|
344
|
-
else { push({ ts, agent, kind: 'tool', tool
|
|
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; }
|
|
345
555
|
}
|
|
346
556
|
}
|
|
347
|
-
if (agent === 'main' && m.stop_reason === 'end_turn') { // 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)
|
|
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)
|
|
348
558
|
if (!said && m.id && st.sayOf === m.id) said = st.raw[st.sayAt]; // ...or on the line the same message brought in an earlier record
|
|
349
559
|
if (said) said.end = 1;
|
|
350
560
|
}
|
|
@@ -367,7 +577,7 @@ function readMeta(f) {
|
|
|
367
577
|
}
|
|
368
578
|
|
|
369
579
|
function buildTimeline(proj, id, files = []) {
|
|
370
|
-
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)
|
|
371
581
|
if (!fs.existsSync(mainFile)) throw new Error('session not found');
|
|
372
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
|
|
373
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 }
|
|
@@ -420,7 +630,8 @@ function buildTimeline(proj, id, files = []) {
|
|
|
420
630
|
else { merged.push(e.kind === 'tool' ? { ts: e.ts, agent: e.agent, kind: 'tools', tools: [e.tool], ...(e.end ? { end: 1 } : {}), ...(e.th ? { th: e.th } : {}), k: e.k } : e); lastReal = merged.length - 1; }
|
|
421
631
|
}
|
|
422
632
|
const real = merged.find((e) => e.kind !== 'usage' && e.kind !== 'finish' && e.kind !== 'compact'), first = real ? real.ts : 0, last = merged.length ? merged[merged.length - 1].ts : 0; // time zero = the first thing said or done
|
|
423
|
-
|
|
633
|
+
const marks = !sx && states[0] && (states[0].stops || !states[0].lead) ? { marks: 1 } : {}; // a Claude Code session whose turns end with a mark, also before the lead has written anything: a session that has not closed a turn yet is not one without marks, and its lead is not "done" each time it thinks for a while
|
|
634
|
+
return { id, proj, agents: Object.values(agents), events: merged.map((e) => ({ ...e, t: Math.max(0, e.ts - first) })), durationMs: last - first, recentUntil, ...marks };
|
|
424
635
|
}
|
|
425
636
|
|
|
426
637
|
// Ask the local `claude` CLI (uses the user's existing login) to map a JSON array of strings to another array. Cached.
|
|
@@ -488,17 +699,19 @@ function claudeMap(kind, instruction, texts) {
|
|
|
488
699
|
p.stdin.end(prompt);
|
|
489
700
|
})));
|
|
490
701
|
}
|
|
491
|
-
const translate = (texts) => translateFast(texts);
|
|
702
|
+
const translate = (texts, lang) => translateFast(texts, lang);
|
|
492
703
|
|
|
493
704
|
// Warm `claude` workers: after a slow first call each translation takes ~2-3 s (a cold `claude -p` costs ~6 s).
|
|
494
|
-
|
|
495
|
-
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.`;
|
|
496
709
|
class TrWorker {
|
|
497
|
-
constructor() { this.q = []; this.busy = false; this.n = 0; this.p = null; this.cur = null; this.buf = ''; }
|
|
498
|
-
start() {
|
|
499
|
-
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() });
|
|
500
713
|
if (!p) return;
|
|
501
|
-
this.p = p; this.buf = ''; this.n = 0;
|
|
714
|
+
this.p = p; this.buf = ''; this.n = 0; this.lang = lang;
|
|
502
715
|
p.stderr.on('data', (d) => { lastTrError = String(d).slice(-300); });
|
|
503
716
|
p.stdout.on('data', (d) => {
|
|
504
717
|
this.buf += d; let i;
|
|
@@ -511,11 +724,11 @@ class TrWorker {
|
|
|
511
724
|
p.on('close', dead); p.on('error', dead);
|
|
512
725
|
}
|
|
513
726
|
finish(res) { const c = this.cur; this.cur = null; this.busy = false; if (c) { clearTimeout(c.timer); c.res(res); } this.pump(); }
|
|
514
|
-
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(); }); }
|
|
515
728
|
kill() { clearTimeout(this.idle); if (this.p) { const p = this.p; this.p = null; try { p.kill(); } catch {} } }
|
|
516
729
|
pump() {
|
|
517
730
|
if (this.busy || !this.q.length) return;
|
|
518
|
-
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
|
|
519
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
|
|
520
733
|
const job = this.q.shift(); this.busy = true; this.n++; this.cur = job;
|
|
521
734
|
job.timer = setTimeout(() => { if (this.cur === job && this.p) this.p.kill(); }, 45000);
|
|
@@ -526,15 +739,15 @@ const trWorkers = [new TrWorker(), new TrWorker()];
|
|
|
526
739
|
const shutdown = () => { trWorkers.forEach((w) => w.kill()); kokoro.shutdown(); };
|
|
527
740
|
process.on('exit', shutdown);
|
|
528
741
|
const pickWorker = () => trWorkers.reduce((a, b) => (a.q.length + a.busy <= b.q.length + b.busy ? a : b));
|
|
529
|
-
async function translateFast(texts) {
|
|
530
|
-
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)))];
|
|
531
744
|
if (need.length && need.length <= 3 && !process.env.ANTHROPIC_API_KEY) { // a few lines: warm workers in parallel; many lines: one batched call
|
|
532
|
-
await Promise.all(need.map(async (t) => { const r = await pickWorker().ask(t); if (r) cache.set('
|
|
533
|
-
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)) };
|
|
534
747
|
}
|
|
535
|
-
return claudeMap(
|
|
748
|
+
return claudeMap(lang, trInstr(lang), texts);
|
|
536
749
|
}
|
|
537
|
-
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);
|
|
538
751
|
|
|
539
752
|
// ---- text-to-speech, generated on the machine and cached as wav:
|
|
540
753
|
// macOS → `say`, Windows → System.Speech (SAPI voices) through PowerShell, Linux → espeak-ng.
|
|
@@ -584,7 +797,7 @@ function tts(text, voice, rate, engine, fb) {
|
|
|
584
797
|
if (ttsJobs.has(key)) return ttsJobs.get(key);
|
|
585
798
|
fs.mkdirSync(ttsDir, { recursive: true });
|
|
586
799
|
const tmp = file + '.part.wav';
|
|
587
|
-
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
|
|
588
801
|
.then(() => { fs.renameSync(tmp, file); return file; }).finally(() => ttsJobs.delete(key));
|
|
589
802
|
ttsJobs.set(key, job); return job;
|
|
590
803
|
}
|
|
@@ -606,6 +819,30 @@ function listCharacters(pack) {
|
|
|
606
819
|
return { stem: st, file: f, talk: by.get(l + '-talk') || null, role: /^(lead|claude)$/.test(l) ? 'lead' : /^(you|human|user)$/.test(l) ? 'you' : 'agent' }; }).sort((a, b) => a.stem.localeCompare(b.stem));
|
|
607
820
|
return { dir, max: CHAR_MAX, chars };
|
|
608
821
|
}
|
|
822
|
+
// ---- Shared files: a file the session created is shown in its folder (Finder, Explorer, the file manager) when the page asks. Only a file a Write call of that very session names, and only if it is still there:
|
|
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.
|
|
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.
|
|
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 }
|
|
826
|
+
const sx = sourceOf(proj); if (!(sx ? guard(() => sx.fileOf(id), null) : fs.existsSync(path.join(projDir(proj, id), id + '.jsonl')))) return null;
|
|
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;
|
|
828
|
+
if (since == null) {
|
|
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
|
|
830
|
+
for (const e of ev) if (e.kind === 'tools' && e.tools.some((t) => said.has(t.id) || (t.d && t.d.kind === 'cmd' && t.d.outs && t.d.outs.includes(file)))) since = since == null ? e.ts || 1 : Math.min(since, e.ts || 1);
|
|
831
|
+
}
|
|
832
|
+
if (since == null || (since && ev.some((e) => e.kind === 'tools' && e.tools.some((t) => t.d && t.d.kind === 'edit' && t.d.file === file)))) return null; // a file the session changed by hand is recent for that reason: a command that names it did not make it
|
|
833
|
+
if (path.isAbsolute(file)) return { fp: path.normalize(file), since };
|
|
834
|
+
const cwd = sx && sx.cwd ? guard(() => sx.cwd(id), '') : ''; return cwd ? { fp: path.resolve(cwd, file), since } : null;
|
|
835
|
+
}
|
|
836
|
+
const reveal = { // run and stat: replaced in the tests, which must not open a window nor write a file outside their folder
|
|
837
|
+
stat: (f) => fs.statSync(f),
|
|
838
|
+
cmds(file, platform = process.platform) { // one or two commands: the second is tried when the first fails
|
|
839
|
+
if (platform === 'darwin') return [['open', ['-R', file]]];
|
|
840
|
+
if (platform === 'win32') return [['explorer.exe', ['/select,"' + file + '"'], { windowsVerbatimArguments: true }]]; // Explorer wants the quotes around the path only (no file name holds a quote on Windows)
|
|
841
|
+
const dir = ['xdg-open', [path.dirname(file)]]; // Linux: the file manager is asked to select the file; one that cannot do it opens the folder (as does a name with a comma, which dbus-send would read as two files)
|
|
842
|
+
return file.includes(',') ? [dir] : [['dbus-send', ['--session', '--dest=org.freedesktop.FileManager1', '--type=method_call', '--print-reply', '/org/freedesktop/FileManager1', 'org.freedesktop.FileManager1.ShowItems', 'array:string:' + require('url').pathToFileURL(file).href, 'string:'], { timeout: 3000 }], dir];
|
|
843
|
+
},
|
|
844
|
+
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)); },
|
|
845
|
+
};
|
|
609
846
|
let audioOwner = { id: null, seen: 0 };
|
|
610
847
|
function start(port = PORT) {
|
|
611
848
|
return http.createServer((req, res) => {
|
|
@@ -619,7 +856,7 @@ function start(port = PORT) {
|
|
|
619
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
|
|
620
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.
|
|
621
858
|
const sfs = req.headers['sec-fetch-site'];
|
|
622
|
-
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'); }
|
|
623
860
|
const readBody = (cb) => { // request bodies are small JSON: stop reading beyond 256 KB and give up after 10 s
|
|
624
861
|
const chunks = []; let size = 0, over = false; req.setTimeout(10000, () => req.destroy());
|
|
625
862
|
if (+req.headers['content-length'] > 262144) { res.writeHead(413); res.end('too large'); return req.destroy(); }
|
|
@@ -628,8 +865,8 @@ function start(port = PORT) {
|
|
|
628
865
|
};
|
|
629
866
|
const textList = (x) => (Array.isArray(x) ? x : []).slice(0, 200).map((t) => String(t).slice(0, 2000));
|
|
630
867
|
try {
|
|
631
|
-
if (url.pathname === '/api/translate' && req.method === 'POST') return readBody(async (body) => { try { json(await translate(textList(
|
|
632
|
-
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); } });
|
|
633
870
|
if (url.pathname === '/api/sessions') return json(listSessions());
|
|
634
871
|
if (url.pathname === '/api/projects') { // projects (working folders) ordered by latest activity — lets the live view follow one of them
|
|
635
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); }
|
|
@@ -643,7 +880,7 @@ function start(port = PORT) {
|
|
|
643
880
|
return json({ owner: audioOwner.id });
|
|
644
881
|
}
|
|
645
882
|
if (url.pathname === '/api/health') return json({ claude: findClaude(), apiKey: !!process.env.ANTHROPIC_API_KEY, trError: lastTrError, platform: process.platform });
|
|
646
|
-
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 }); }
|
|
647
884
|
if (url.pathname === '/api/voices') {
|
|
648
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' }); }
|
|
649
886
|
return loadVoices().then((v) => json(v));
|
|
@@ -658,20 +895,42 @@ function start(port = PORT) {
|
|
|
658
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') + ';'); }
|
|
659
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); } });
|
|
660
897
|
if (url.pathname === '/api/prefs') return json(readPrefs() || {});
|
|
661
|
-
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') })); }
|
|
662
902
|
if (url.pathname === '/api/board') return json(boardRows());
|
|
663
903
|
if (url.pathname === '/api/characters') return json(listCharacters(url.searchParams.get('pack') || ''));
|
|
664
904
|
if (url.pathname === '/api/packs') return json(Object.keys(PACKS).map((name) => ({ name, n: listCharacters(name).chars.length })));
|
|
905
|
+
if (url.pathname === '/api/reveal' && req.method === 'POST') return readBody((body) => { // 404: not a file this session created · 410: created, and no longer there
|
|
906
|
+
try {
|
|
907
|
+
let b = null; try { b = JSON.parse(body); } catch {} const SAFE = /^[\w.\-]+$/, ok = (v) => typeof v === 'string' && SAFE.test(v) && v !== '..' && v.length <= 200;
|
|
908
|
+
if (!b || !ok(b.proj) || !ok(b.id) || typeof b.file !== 'string' || !b.file || b.file.length > 4096) return json({ error: 'bad request' }, 400);
|
|
909
|
+
const f = sessionFile(b.proj, b.id, b.file); if (!f) return json({ error: 'not a file of this session' }, 404);
|
|
910
|
+
let st = null; try { st = reveal.stat(f.fp); } catch {} if (!st || !st.isFile()) return json({ error: 'gone' }, 410);
|
|
911
|
+
if (f.since && st.mtimeMs < f.since - 2000) return json({ error: 'not a file of this session' }, 404); // a command names it, and it was there before: read, listed or removed, not made
|
|
912
|
+
if (b.check !== true) reveal.run(f.fp); json({ ok: true }); // check: the page asks whether a document a command names is there, before it shows it
|
|
913
|
+
} catch (e) { json({ error: String(e.message || e) }, 500); }
|
|
914
|
+
});
|
|
665
915
|
if (url.pathname === '/api/media') {
|
|
666
916
|
const q = (k) => url.searchParams.get(k) || '', SAFE = /^[\w.\-]+$/, n = +q('n') || 0, bad = [q('proj'), q('id'), q('agent'), q('tool')].some((v) => !SAFE.test(v) || v === '..' || v.length > 200) || q('tool').length < 6; // no tool call has an id that short, and looking for one meant reading the whole transcript
|
|
667
917
|
const file = bad || !Number.isInteger(n) || n < 0 || n > 9 ? null : mediaFile(q('proj'), q('id'), q('agent')), im = file && toolImage(file, q('tool'), n);
|
|
668
918
|
if (!im) { res.writeHead(bad ? 400 : 404); return res.end(bad ? 'bad request' : 'not found'); }
|
|
669
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);
|
|
670
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
|
+
}
|
|
671
930
|
if (url.pathname === '/api/session') {
|
|
672
931
|
const proj = url.searchParams.get('proj') || '', sid = url.searchParams.get('id') || '', SAFE = /^[\w.\-]+$/;
|
|
673
932
|
if (!SAFE.test(proj) || !SAFE.test(sid) || proj === '..' || sid === '..' || proj.length > 200 || sid.length > 200) { res.writeHead(400); return res.end('bad request'); }
|
|
674
|
-
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);
|
|
675
934
|
const entry = proj === '_demo' ? demoEntry() : timelineEntry(proj, sid), tl = entry.tl; // built-in fictional session
|
|
676
935
|
const after = url.searchParams.get('after'), ep = url.searchParams.get('ep');
|
|
677
936
|
if (after == null) { // the whole timeline: serialize once per version, send gzip-compressed when the browser allows it (12 MB → ~1.5 MB)
|
|
@@ -683,8 +942,8 @@ function start(port = PORT) {
|
|
|
683
942
|
}
|
|
684
943
|
if (ep == null) return json({ id: tl.id, agents: tl.agents, total: tl.events.length, events: tl.events.slice(+after) }); // a page loaded before 1.25.7 still asks by position
|
|
685
944
|
const a = +after; if (ep !== tl.ep || !(a >= 0 && a <= tl.seq)) return json({ resync: true }); // not the feed this page was following (restart, session dropped from memory, transcript rewritten): it loads the session again
|
|
686
|
-
if (a === tl.seq) { if (!entry.idle) entry.idle = JSON.stringify({ id: tl.id, agents: tl.agents, ep: tl.ep, seq: tl.seq, events: [] }); res.writeHead(200, { 'content-type': 'application/json' }); return res.end(entry.idle); } // nothing new, which is the answer to nearly every poll: written once
|
|
687
|
-
return json({ id: tl.id, agents: tl.agents, ep: tl.ep, seq: tl.seq, events: feedSince(entry, a) }); // new events and changed ones alike, whole, under the key they always had
|
|
945
|
+
if (a === tl.seq) { if (!entry.idle) entry.idle = JSON.stringify({ id: tl.id, agents: tl.agents, ep: tl.ep, seq: tl.seq, marks: tl.marks, events: [] }); res.writeHead(200, { 'content-type': 'application/json' }); return res.end(entry.idle); } // nothing new, which is the answer to nearly every poll: written once
|
|
946
|
+
return json({ id: tl.id, agents: tl.agents, ep: tl.ep, seq: tl.seq, marks: tl.marks, events: feedSince(entry, a) }); // new events and changed ones alike, whole, under the key they always had
|
|
688
947
|
}
|
|
689
948
|
const pk = url.pathname.match(/^\/packs\/([a-z]+)\/(.*)$/);
|
|
690
949
|
if (url.pathname.startsWith('/characters/') || (pk && packDir(pk[1]))) { // only plain image files of the characters folder (or of a built-in pack), by exact name
|
|
@@ -696,12 +955,13 @@ function start(port = PORT) {
|
|
|
696
955
|
const file = path.join(PUBLIC, url.pathname === '/' ? 'index.html' : url.pathname);
|
|
697
956
|
let fst = null; try { fst = fs.statSync(file); } catch {}
|
|
698
957
|
if (!file.startsWith(PUBLIC + path.sep) || !fst || !fst.isFile()) { res.writeHead(404); return res.end('not found'); }
|
|
699
|
-
|
|
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'" } : {}) });
|
|
700
960
|
res.end(fs.readFileSync(file));
|
|
701
|
-
} 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); }
|
|
702
962
|
}).listen(port, '127.0.0.1', function () { console.log(`Agent Standup → http://localhost:${this.address().port}`); });
|
|
703
963
|
}
|
|
704
|
-
module.exports = { start, currentSession, shutdown, findClaude, bundledClaude, boardRows, charactersDir, listCharacters };
|
|
964
|
+
module.exports = { start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, logError, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
|
|
705
965
|
if (require.main === module) {
|
|
706
966
|
start().on('error', (e) => {
|
|
707
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));
|