@double_geste/agent-standup 1.31.0 → 1.33.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/examples/vampire/README.txt +7 -0
- package/examples/vampire/you+sticker1-1.png +0 -0
- package/examples/vampire/you+sticker1-2.png +0 -0
- package/examples/vampire/you+sticker1-3.png +0 -0
- package/examples/vampire/you+sticker2-1.png +0 -0
- package/examples/vampire/you+sticker2-2.png +0 -0
- package/examples/vampire/you+sticker2-3.png +0 -0
- package/examples/vampire/you+sticker3-1.png +0 -0
- package/examples/vampire/you+sticker3-2.png +0 -0
- package/examples/vampire/you+sticker3-3.png +0 -0
- package/examples/vampire/you-bg.png +0 -0
- package/examples/vampire/you-desk-dark.png +0 -0
- package/examples/vampire/you-desk.png +0 -0
- package/examples/vampire/you-hands.png +0 -0
- package/examples/vampire/you-head.png +0 -0
- package/examples/vampire/you-talk.png +0 -0
- package/examples/vampire/you.png +0 -0
- package/kokoro-worker.js +35 -4
- package/kokoro.js +26 -10
- package/package.json +1 -1
- package/public/index.html +657 -230
- package/public/locales/README.md +2 -2
- package/public/locales/da.json +83 -14
- package/public/locales/de.json +83 -14
- package/public/locales/en.json +82 -13
- package/public/locales/es.json +83 -14
- package/public/locales/ja.json +83 -14
- package/public/locales/ko.json +83 -14
- package/public/locales/pt-BR.json +83 -14
- package/public/locales/zh-CN.json +83 -14
- package/public/locales/zh-TW.json +83 -14
- package/public/pack-halloween.jpg +0 -0
- package/server.js +374 -83
- 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 }) => {
|
|
253
|
-
if (cx)
|
|
254
|
-
const file = path.join(
|
|
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 }) => {
|
|
367
|
+
if (cx) { const r = guard(() => src.boardRow(cx, now), null); if (r && tmpKey(r.dir)) r.tmp = 1; return r; } // tmp: started in the temporary folder (see tmpKey)
|
|
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,109 @@ 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 } : {}), ...(tmpKey(proj) ? { tmp: 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;
|
|
450
|
+
// Sessions started in the system's temporary folder: a program running Claude Code there for a moment (a test, a script, a tool that makes a folder per run), not a session someone works in.
|
|
451
|
+
// When the call looks everywhere it leaves them out, unless there is nothing else; they have no tab then and send no visitor. They stay in the Sessions view, and a window open on such a folder follows it.
|
|
452
|
+
// macOS: /var/folders/… (/private/… once resolved) and /tmp; Linux: /tmp; Windows: …\AppData\Local\Temp; and wherever TMPDIR points. A key is a folder as Claude Code names it, every other character a "-".
|
|
453
|
+
const TMP_KEYS = [...new Set([os.tmpdir(), (() => { try { return fs.realpathSync(os.tmpdir()); } catch { return ''; } })()].filter((d) => d && d.length > 4).map((d) => d.replace(/[^a-zA-Z0-9]/g, '-')))];
|
|
454
|
+
const tmpKey = (k) => !!k && (/^-(private-)?(tmp|var-folders)(-|$)/.test(k) || /-AppData-Local-Temp(-|$)/i.test(k) || TMP_KEYS.some((t) => k === t || k.startsWith(t + '-')));
|
|
455
|
+
const tmpSession = (proj, id) => { const sx = sourceOf(proj); return sx ? tmpKey(String(guard(() => sx.cwd(id), '') || '').replace(/[^a-zA-Z0-9]/g, '-')) : tmpKey(proj); }; // a Codex or Vibe session: the folder it was started in
|
|
275
456
|
function sessionMtime(proj, id) {
|
|
276
457
|
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(
|
|
458
|
+
let m = sx ? r.mtime : mtimeOf(path.join(projDir(proj, id), id + '.jsonl')); if (!m) return 0; const subs = subFilesOf(proj, id);
|
|
278
459
|
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
460
|
}
|
|
280
|
-
function currentSession(projFilter,
|
|
281
|
-
const safe = (x) => typeof x === 'string' && /^[\w.\-]+$/.test(x) && x !== '..';
|
|
282
|
-
|
|
283
|
-
|
|
461
|
+
function currentSession(projFilter, pick, stick, anyTmp) { // pick: { proj, id, since } the session you went to by hand, and the latest order there was then · stick: the session the call is in · anyTmp: sessions in the temporary folder count too (see tmpKey)
|
|
462
|
+
const safe = (x) => typeof x === 'string' && /^[\w.\-]+$/.test(x) && x !== '..', now = Date.now();
|
|
463
|
+
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')));
|
|
464
|
+
const inScope = (c) => (!projFilter ? anyTmp || !tmpSession(c.proj, c.id) : c.proj === projFilter || c.proj.startsWith(projFilter + '-') || !!(sourceOf(c.proj) && guard(() => sourceOf(c.proj).inProject(c.id, projFilter), false))); // a Codex or Vibe session counts for a project when it was started in that folder
|
|
465
|
+
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;
|
|
466
|
+
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
|
|
467
|
+
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
|
|
468
|
+
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
|
|
469
|
+
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);
|
|
470
|
+
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
|
|
471
|
+
if (to) return { proj: to.proj, id: to.id, mtime: to.mtime, asked };
|
|
472
|
+
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
473
|
let best = null;
|
|
285
474
|
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
|
|
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
|
-
}
|
|
475
|
+
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);
|
|
476
|
+
for (const proj of projects()) {
|
|
477
|
+
if (projFilter ? proj !== projFilter && !proj.startsWith(projFilter + '-') : !anyTmp && tmpKey(proj)) continue; // the folder itself, or a folder inside it (a Cowork session is in no folder of yours: it counts when the call looks everywhere, or at Cowork)
|
|
478
|
+
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
479
|
}
|
|
296
|
-
if (!best && projFilter) return currentSession('',
|
|
297
|
-
|
|
480
|
+
if (!best && projFilter) return { ...currentSession('', null, stick), wide: 1 };
|
|
481
|
+
if (!best && !projFilter && !anyTmp) return currentSession('', pick, stick, true); // nothing but sessions in the temporary folder: one of them rather than an empty call // 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
|
|
482
|
+
return best ? { ...best, asked } : {}; // a call that is opened while nobody is at work: the session that was written to last
|
|
298
483
|
}
|
|
299
484
|
|
|
300
485
|
// ---- Incremental transcript reader: each .jsonl is parsed once, then only the bytes appended since are read.
|
|
@@ -349,8 +534,8 @@ function parseRecord(st, r) {
|
|
|
349
534
|
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
535
|
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
536
|
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
|
|
537
|
+
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;
|
|
538
|
+
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
539
|
}
|
|
355
540
|
if (items.length) push({ ts, agent, kind: 'results', items });
|
|
356
541
|
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 +554,11 @@ function parseRecord(st, r) {
|
|
|
369
554
|
for (const b of blocks(r)) {
|
|
370
555
|
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
556
|
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; }
|
|
557
|
+
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
558
|
else if (b.type === 'tool_use') {
|
|
373
559
|
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
560
|
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; }
|
|
561
|
+
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
562
|
}
|
|
377
563
|
}
|
|
378
564
|
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 +584,7 @@ function readMeta(f) {
|
|
|
398
584
|
}
|
|
399
585
|
|
|
400
586
|
function buildTimeline(proj, id, files = []) {
|
|
401
|
-
const sx = sourceOf(proj), rec = recordOf(sx), base =
|
|
587
|
+
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
588
|
if (!fs.existsSync(mainFile)) throw new Error('session not found');
|
|
403
589
|
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
590
|
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 +706,19 @@ function claudeMap(kind, instruction, texts) {
|
|
|
520
706
|
p.stdin.end(prompt);
|
|
521
707
|
})));
|
|
522
708
|
}
|
|
523
|
-
const translate = (texts) => translateFast(texts);
|
|
709
|
+
const translate = (texts, lang) => translateFast(texts, lang);
|
|
524
710
|
|
|
525
711
|
// Warm `claude` workers: after a slow first call each translation takes ~2-3 s (a cold `claude -p` costs ~6 s).
|
|
526
|
-
|
|
527
|
-
const
|
|
712
|
+
// 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).
|
|
713
|
+
const TR_LANG = { fr: 'French', es: 'Spanish', pt: 'Brazilian Portuguese' }, trLang = (l) => (Object.hasOwn(TR_LANG, l) ? l : 'fr');
|
|
714
|
+
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.`;
|
|
715
|
+
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
716
|
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',
|
|
717
|
+
constructor() { this.q = []; this.busy = false; this.n = 0; this.p = null; this.cur = null; this.buf = ''; this.lang = 'fr'; }
|
|
718
|
+
start(lang = this.lang) { // the language is in the system prompt: a worker translates into one language, and is started again for another
|
|
719
|
+
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
720
|
if (!p) return;
|
|
533
|
-
this.p = p; this.buf = ''; this.n = 0;
|
|
721
|
+
this.p = p; this.buf = ''; this.n = 0; this.lang = lang;
|
|
534
722
|
p.stderr.on('data', (d) => { lastTrError = String(d).slice(-300); });
|
|
535
723
|
p.stdout.on('data', (d) => {
|
|
536
724
|
this.buf += d; let i;
|
|
@@ -543,11 +731,11 @@ class TrWorker {
|
|
|
543
731
|
p.on('close', dead); p.on('error', dead);
|
|
544
732
|
}
|
|
545
733
|
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(); }); }
|
|
734
|
+
ask(text, lang = 'fr') { return new Promise((res) => { this.q.push({ text, lang, res }); this.pump(); }); }
|
|
547
735
|
kill() { clearTimeout(this.idle); if (this.p) { const p = this.p; this.p = null; try { p.kill(); } catch {} } }
|
|
548
736
|
pump() {
|
|
549
737
|
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
|
|
738
|
+
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
739
|
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
740
|
const job = this.q.shift(); this.busy = true; this.n++; this.cur = job;
|
|
553
741
|
job.timer = setTimeout(() => { if (this.cur === job && this.p) this.p.kill(); }, 45000);
|
|
@@ -558,15 +746,15 @@ const trWorkers = [new TrWorker(), new TrWorker()];
|
|
|
558
746
|
const shutdown = () => { trWorkers.forEach((w) => w.kill()); kokoro.shutdown(); };
|
|
559
747
|
process.on('exit', shutdown);
|
|
560
748
|
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('
|
|
749
|
+
async function translateFast(texts, lang = 'fr') {
|
|
750
|
+
const need = [...new Set(texts.filter((t) => !cache.has(lang + '|' + t)))];
|
|
563
751
|
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('
|
|
752
|
+
await Promise.all(need.map(async (t) => { const r = await pickWorker().ask(t, lang); if (r) cache.set(lang + '|' + t, r); }));
|
|
753
|
+
return { texts: texts.map((t) => cache.get(lang + '|' + t) || t), ok: texts.every((t) => cache.has(lang + '|' + t)) };
|
|
566
754
|
}
|
|
567
|
-
return claudeMap(
|
|
755
|
+
return claudeMap(lang, trInstr(lang), texts);
|
|
568
756
|
}
|
|
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
|
|
757
|
+
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
758
|
|
|
571
759
|
// ---- text-to-speech, generated on the machine and cached as wav:
|
|
572
760
|
// macOS → `say`, Windows → System.Speech (SAPI voices) through PowerShell, Linux → espeak-ng.
|
|
@@ -616,7 +804,7 @@ function tts(text, voice, rate, engine, fb) {
|
|
|
616
804
|
if (ttsJobs.has(key)) return ttsJobs.get(key);
|
|
617
805
|
fs.mkdirSync(ttsDir, { recursive: true });
|
|
618
806
|
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(
|
|
807
|
+
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
808
|
.then(() => { fs.renameSync(tmp, file); return file; }).finally(() => ttsJobs.delete(key));
|
|
621
809
|
ttsJobs.set(key, job); return job;
|
|
622
810
|
}
|
|
@@ -625,24 +813,108 @@ const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css
|
|
|
625
813
|
|
|
626
814
|
// ---- Custom characters: the person's own pixel art replaces the drawn characters. Plain image files in one folder, nothing else is ever served from it.
|
|
627
815
|
// lead.png / claude.png → the lead · you.png → the human · any other image → a pool for the sub-agents · name-talk.png → optional open-mouth frame of name.png
|
|
628
|
-
|
|
816
|
+
// name-bg.png → optional room of name.png: the whole picture behind it, desk included (its bottom sixth is drawn again in front of the character)
|
|
817
|
+
// name-head.png → optional head of name.png, drawn above it and nodding while it speaks: name.png is then the body, and name-talk.png the head with its mouth open
|
|
818
|
+
// name-hands.png → optional hands of name.png, on their own: they type while the agent works · name-desk.png, name-desk-dark.png… → optional laptops of name.png, drawn over its hands:
|
|
819
|
+
// the page gives each agent one of them, out now and then for a few seconds (all the time with ⚙ → Characters → laptop)
|
|
820
|
+
// name+hat-1.png, name+hat-2.png, name+glasses-1.png… → optional extras of name.png, by kind (the word after the +): pictures drawn over it. Each agent that gets this character wears one of each kind or none,
|
|
821
|
+
// so one character becomes many: it is the one given again when there are more agents than characters
|
|
822
|
+
// an extra whose kind starts with "sticker" (name+sticker1-2.png) is worn by the thing on the desk, not by the character: drawn over the laptop, under the hands
|
|
823
|
+
const CHAR_NAME = /^[\w][\w .()+\-]{0,78}\.(png|gif|webp|jpe?g)$/i, CHAR_MAX = 300 * 1024, CHAR_TYPES = { png: 'image/png', gif: 'image/gif', webp: 'image/webp', jpg: 'image/jpeg', jpeg: 'image/jpeg' };
|
|
629
824
|
const charactersDir = () => process.env.AGENT_STANDUP_CHARACTERS || path.join(os.homedir(), '.agent-standup', 'characters');
|
|
630
825
|
// lstat, not stat: a symlink is not a regular file, so it is skipped and never served
|
|
631
826
|
// Built-in character packs, shipped with the app (examples/<folder>): picked in ⚙ → Characters. examples/characters stays in the repository as a model for one's own folder; it is not shipped
|
|
632
|
-
const PACKS = { cats: 'cats'
|
|
827
|
+
const PACKS = { cats: 'cats', vampire: 'vampire' }; // vampire: the one character of the Halloween pack that everyone gets, as the human (see the page's charYou)
|
|
828
|
+
// Packs sold in the shop of the website (api/ in the repository): their pictures are neither in the app nor in the repository. A bought pack is unpacked in the packs folder and is then a pack like a built-in one.
|
|
829
|
+
const SHOP_PACKS = { halloween: { price: '2 €', artist: 'Fabien Coupas', artistUrl: 'https://www.instagram.com/fabien_coupas/' } }, // the artist is credited wherever the pack is shown
|
|
830
|
+
PACK_MAX = 20 * 1024 * 1024;
|
|
831
|
+
const shopUrl = () => (process.env.AGENT_STANDUP_STORE || 'https://agent-standup.com').replace(/\/+$/, ''), packsDir = () => process.env.AGENT_STANDUP_PACKS || path.join(os.homedir(), '.agent-standup', 'packs');
|
|
832
|
+
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k); // its own names only: 'constructor' or 'toString' is not a pack (they answered 500)
|
|
833
|
+
const packDir = (name) => (hasOwn(PACKS, name) ? path.join(__dirname, 'examples', PACKS[name]) : hasOwn(SHOP_PACKS, name) ? path.join(packsDir(), name) : null);
|
|
633
834
|
function listCharacters(pack) {
|
|
634
835
|
const dir = pack ? packDir(pack) : charactersDir(); let names = []; if (!dir) return { dir: '', max: CHAR_MAX, chars: [] }; try { names = fs.readdirSync(dir); } catch {}
|
|
635
|
-
const ok = names.filter((f) => CHAR_NAME.test(f)).filter((f) => { try { const st = fs.lstatSync(path.join(dir, f)); return st.isFile() && st.size <= CHAR_MAX; } catch { return false; } }).slice(0,
|
|
836
|
+
const ok = names.filter((f) => CHAR_NAME.test(f)).filter((f) => { try { const st = fs.lstatSync(path.join(dir, f)); return st.isFile() && st.size <= CHAR_MAX; } catch { return false; } }).sort().slice(0, 200);
|
|
636
837
|
const stem = (f) => f.replace(/\.[^.]+$/, ''), by = new Map(ok.map((f) => [stem(f).toLowerCase(), f]));
|
|
637
|
-
const
|
|
638
|
-
|
|
838
|
+
const extra = (f) => stem(f).match(/^(.+)\+([a-z]+\d*)[-_ ]?\w*$/i); // the kind may end with a number: sticker1, sticker2… are kinds of their own
|
|
839
|
+
const layer = (f) => { const m = stem(f).match(/^(.+)-(bg|head|hands|desk(-\w+)?)$/i); return !!(m && by.has(m[1].toLowerCase())); }; // a layer only when its character is there: help-desk.png alone is a character
|
|
840
|
+
const chars = ok.filter((f) => !/-talk$/i.test(stem(f)) && !layer(f) && !extra(f)).map((f) => { const st = stem(f), l = st.toLowerCase(), extras = {};
|
|
841
|
+
for (const x of ok) { const m = extra(x), k = m && m[1].toLowerCase() === l ? m[2].toLowerCase() : ''; if (k) (extras[k] = extras[k] || []).push(x); }
|
|
842
|
+
return { stem: st, file: f, talk: by.get(l + '-talk') || null, bg: by.get(l + '-bg') || null, desks: ok.filter((x) => { const s = stem(x).toLowerCase(); return s === l + '-desk' || s.startsWith(l + '-desk-'); }), head: by.get(l + '-head') || null, hands: by.get(l + '-hands') || null, extras: Object.keys(extras).length ? extras : null, role: /^(lead|claude)$/.test(l) ? 'lead' : /^(you|human|user)$/.test(l) ? 'you' : 'agent' }; }).sort((a, b) => a.stem.localeCompare(b.stem));
|
|
639
843
|
return { dir, max: CHAR_MAX, chars };
|
|
640
844
|
}
|
|
845
|
+
// ---- Buying a pack. The app never sees a card: it asks the shop for a payment page (Stripe's), opens it in the browser, then asks the shop for the pack with the code of that purchase until the shop,
|
|
846
|
+
// which asks Stripe, says it is paid. The code is kept beside the packs: it is the proof of the purchase, and what installs the pack on another computer. Nothing else is sent, and nothing is asked again once the pack is here.
|
|
847
|
+
const codesFile = () => path.join(packsDir(), 'codes.json');
|
|
848
|
+
const readCodes = () => { try { const v = JSON.parse(fs.readFileSync(codesFile(), 'utf8')); return v && typeof v === 'object' && !Array.isArray(v) ? v : {}; } catch { return {}; } };
|
|
849
|
+
const writeCode = (name, v) => { const all = readCodes(); all[name] = v; fs.mkdirSync(packsDir(), { recursive: true }); const tmp = codesFile() + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(all, null, 1), { mode: 0o600 }); fs.renameSync(tmp, codesFile()); };
|
|
850
|
+
const packList = () => [...Object.keys(PACKS).map((name) => ({ name, n: listCharacters(name).chars.length })),
|
|
851
|
+
...Object.keys(SHOP_PACKS).map((name) => { const c = readCodes()[name] || {}; return { name, n: listCharacters(name).chars.length, shop: true, price: SHOP_PACKS[name].price, artist: SHOP_PACKS[name].artist || '', artistUrl: SHOP_PACKS[name].artistUrl || '', code: c.short || c.code || '', waiting: !!(c.pending && c.pending.length) }; })]; // the code shown is the one for people when there is one
|
|
852
|
+
// A pack arrives as a zip of plain image files, read here without a library: stored or deflated entries only, kept under their bare name and only if a characters folder would accept that name, each within the size of a character.
|
|
853
|
+
function unzipImages(buf) {
|
|
854
|
+
let e = buf.length - 22; while (e >= 0 && buf.readUInt32LE(e) !== 0x06054b50) e--; if (e < 0) throw new Error('not a zip');
|
|
855
|
+
const n = buf.readUInt16LE(e + 10), out = []; let p = buf.readUInt32LE(e + 16); if (n > 400) throw new Error('too many files');
|
|
856
|
+
for (let i = 0; i < n; i++) {
|
|
857
|
+
if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) throw new Error('bad zip');
|
|
858
|
+
const method = buf.readUInt16LE(p + 10), csize = buf.readUInt32LE(p + 20), size = buf.readUInt32LE(p + 24), nl = buf.readUInt16LE(p + 28), off = buf.readUInt32LE(p + 42), name = buf.toString('utf8', p + 46, p + 46 + nl).split(/[\\/]/).pop();
|
|
859
|
+
p += 46 + nl + buf.readUInt16LE(p + 30) + buf.readUInt16LE(p + 32);
|
|
860
|
+
const note = /^(LICEN[CS]E|README)\.txt$/i.test(name); if (!note && !CHAR_NAME.test(name)) continue; // a folder, a hidden file, anything that is not a picture or the pack's two notes: left out
|
|
861
|
+
if (size > (note ? 65536 : CHAR_MAX) || off + 30 > buf.length) throw new Error('bad entry: ' + name);
|
|
862
|
+
const from = off + 30 + buf.readUInt16LE(off + 26) + buf.readUInt16LE(off + 28), raw = buf.subarray(from, from + csize);
|
|
863
|
+
const data = method === 0 ? raw : method === 8 ? zlib.inflateRawSync(raw, { maxOutputLength: CHAR_MAX }) : null; if (!data || data.length !== size) throw new Error('bad entry: ' + name);
|
|
864
|
+
if (!out.some((f) => f.name.toLowerCase() === name.toLowerCase())) out.push({ name, data });
|
|
865
|
+
}
|
|
866
|
+
if (!out.some((f) => CHAR_NAME.test(f.name))) throw new Error('no picture in the pack');
|
|
867
|
+
return out.slice(0, 200);
|
|
868
|
+
}
|
|
869
|
+
// ---- Pictures added from the page (⚙ → Characters → My folder): written in the characters folder under the name of their role, or under their own name for a sub-agent.
|
|
870
|
+
// The picture a new one replaces is moved to a "replaced" folder beside it, never deleted, and nothing but the four image types is written.
|
|
871
|
+
const IMG_MAGIC = [['png', (b) => b.length > 8 && b.readUInt32BE(0) === 0x89504e47], ['gif', (b) => b.toString('latin1', 0, 4) === 'GIF8'], ['webp', (b) => b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP'], ['jpg', (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff]];
|
|
872
|
+
const ROLE_FILES = { you: 'you', 'you-talk': 'you-talk', lead: 'lead', 'lead-talk': 'lead-talk' };
|
|
873
|
+
function putAside(dir, stem) { // the pictures of this name, whatever their type, go to dir/replaced/ under a name that says when
|
|
874
|
+
let names = []; try { names = fs.readdirSync(dir); } catch {} const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
875
|
+
for (const f of names) if (CHAR_NAME.test(f) && f.replace(/\.[^.]+$/, '').toLowerCase() === stem) { fs.mkdirSync(path.join(dir, 'replaced'), { recursive: true }); fs.renameSync(path.join(dir, f), path.join(dir, 'replaced', stamp + ' ' + f)); }
|
|
876
|
+
}
|
|
877
|
+
function addCharacter(role, name, b64) { // → { file } or throws a word the page can say: 'type', 'size', 'name'
|
|
878
|
+
const data = Buffer.from(String(b64 || ''), 'base64'), type = (IMG_MAGIC.find(([, ok]) => ok(data)) || [])[0]; if (!type) throw Object.assign(new Error('type'), { word: 'type' }); if (data.length > CHAR_MAX) throw Object.assign(new Error('size'), { word: 'size' });
|
|
879
|
+
const dir = charactersDir(); fs.mkdirSync(dir, { recursive: true });
|
|
880
|
+
let stem = ROLE_FILES[role]; if (!stem) { stem = String(name || '').replace(/\.[^.]*$/, '').replace(/[^\w .()\-]+/g, ' ').trim().slice(0, 60).replace(/^[^\w]+/, '') || 'agent'; if (/^(lead|claude|you|human|user)(-talk)?$/i.test(stem) || /-(talk|bg|head|hands|desk(-\w+)?)$/i.test(stem)) stem += ' 2'; } // a sub-agent never takes the name of a role
|
|
881
|
+
const file = stem + '.' + type; if (!CHAR_NAME.test(file)) throw Object.assign(new Error('name'), { word: 'name' });
|
|
882
|
+
if (!ROLE_FILES[role]) { let k = 2, f = file; while (fs.existsSync(path.join(dir, f))) f = `${stem} ${k++}.${type}`; fs.writeFileSync(path.join(dir, f), data); return { file: f }; } // a sub-agent's picture never replaces another one
|
|
883
|
+
putAside(dir, stem.toLowerCase()); if (!/-talk$/.test(stem)) for (const s of ['-talk', '-head', '-hands', '-bg', '-desk', '-desk-dark']) putAside(dir, stem + s); // a new face: the old open mouth and layers go aside with the old picture
|
|
884
|
+
fs.writeFileSync(path.join(dir, file), data); return { file };
|
|
885
|
+
}
|
|
886
|
+
function removeCharacter(file) { // moved to replaced/, with its open mouth and its room; only a picture the folder lists
|
|
887
|
+
const f = String(file || ''), dir = charactersDir(); if (!CHAR_NAME.test(f) || !listCharacters('').chars.some((c) => c.file === f)) return false;
|
|
888
|
+
const stem = f.replace(/\.[^.]+$/, '').toLowerCase(); for (const s of [stem, stem + '-talk', stem + '-head', stem + '-bg', stem + '-desk', stem + '-desk-dark', stem + '-hands']) putAside(dir, s); return true;
|
|
889
|
+
}
|
|
890
|
+
function installPack(name, zip) { // written beside its place first, then swapped in: a pack is never half there
|
|
891
|
+
const files = unzipImages(zip), dir = packDir(name), tmp = dir + '.' + process.pid + '.tmp'; fs.rmSync(tmp, { recursive: true, force: true }); fs.mkdirSync(tmp, { recursive: true });
|
|
892
|
+
for (const f of files) fs.writeFileSync(path.join(tmp, f.name), f.data); fs.rmSync(dir, { recursive: true, force: true }); fs.renameSync(tmp, dir);
|
|
893
|
+
}
|
|
894
|
+
const askShop = (p, body) => fetch(shopUrl() + p, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(30000) });
|
|
895
|
+
async function buyPack(name) { // → { status, url } the payment page to open, or { status, error }
|
|
896
|
+
let r; try { r = await askShop('/api/checkout', { pack: name }); } catch { return { status: 502, error: 'offline' }; }
|
|
897
|
+
const j = await r.json().catch(() => ({})); if (!r.ok) return { status: r.status, error: j.error || 'shop' };
|
|
898
|
+
if (typeof j.url !== 'string' || typeof j.code !== 'string' || !/^(https:\/\/|http:\/\/localhost[:/])/.test(j.url)) return { status: 502, error: 'shop' };
|
|
899
|
+
const c = readCodes()[name] || {}, pending = [j.code, ...(c.pending || [])].slice(0, 5), short = typeof j.short === 'string' && /^[A-Z]{2}-[\w-]{9}$/.test(j.short) ? j.short : '';
|
|
900
|
+
writeCode(name, { code: c.code || '', short: c.short || '', pending, shorts: Object.fromEntries(pending.map((k) => [k, k === j.code ? short : (c.shorts || {})[k] || ''])) }); return { status: 200, url: j.url }; // shorts: the code for people (HW-…) of each payment page opened // a few, in case the button was pressed more than once: any of them may be the one that gets paid
|
|
901
|
+
}
|
|
902
|
+
async function claimPack(name, typed) { // typed: a code the person pastes (another computer); else the purchases started here
|
|
903
|
+
const c = readCodes()[name] || {}, tries = typed ? [typed] : [c.code, ...(c.pending || [])].filter(Boolean); if (!tries.length) return { status: 400, error: 'code' };
|
|
904
|
+
let last = { status: 402, error: 'unpaid' };
|
|
905
|
+
for (const code of tries) {
|
|
906
|
+
let r; try { r = await askShop('/api/pack', { pack: name, code }); } catch { return { status: 502, error: 'offline' }; }
|
|
907
|
+
if (r.ok) { const zip = Buffer.from(await r.arrayBuffer()); if (zip.length > PACK_MAX) return { status: 502, error: 'shop' }; try { installPack(name, zip); } catch (e) { logError('pack ' + name, e); return { status: 502, error: 'shop' }; }
|
|
908
|
+
writeCode(name, { code, short: (c.shorts || {})[code] || (/^[A-Z]{2}-/i.test(code) ? code.toUpperCase() : c.short || ''), pending: [] }); return { status: 200, ok: true, n: listCharacters(name).chars.length }; }
|
|
909
|
+
last = { status: r.status, error: (await r.json().catch(() => ({}))).error || 'shop' }; if (r.status !== 402 && r.status !== 404) break; // not paid yet, or not a purchase of this pack: the next one may be; anything else is the shop's trouble
|
|
910
|
+
}
|
|
911
|
+
return last;
|
|
912
|
+
}
|
|
641
913
|
// ---- 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:
|
|
642
914
|
// 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
915
|
// 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
916
|
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(
|
|
917
|
+
const sx = sourceOf(proj); if (!(sx ? guard(() => sx.fileOf(id), null) : fs.existsSync(path.join(projDir(proj, id), id + '.jsonl')))) return null;
|
|
646
918
|
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
919
|
if (since == null) {
|
|
648
920
|
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,17 +947,17 @@ function start(port = PORT) {
|
|
|
675
947
|
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
948
|
// 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
949
|
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'); }
|
|
679
|
-
const readBody = (cb) => { // request bodies are small JSON: stop reading beyond 256 KB and give up after 10 s
|
|
950
|
+
if (sfs && sfs !== 'same-origin' && sfs !== 'none' && (req.method !== 'GET' || ['/api/translate', '/api/quips', '/api/warm', '/api/audio', '/api/tts', '/api/prefs', '/api/prefs.js', '/api/voices', '/api/kokoro', '/api/kokoro/install', '/api/media', '/api/artifact', '/api/errors', '/api/packs'].includes(url.pathname))) { res.writeHead(403); return res.end('forbidden'); }
|
|
951
|
+
const readBody = (cb, max = 262144) => { // request bodies are small JSON: stop reading beyond 256 KB (or max) and give up after 10 s
|
|
680
952
|
const chunks = []; let size = 0, over = false; req.setTimeout(10000, () => req.destroy());
|
|
681
|
-
if (+req.headers['content-length'] >
|
|
682
|
-
req.on('data', (d) => { if (over) return; size += d.length; if (size >
|
|
953
|
+
if (+req.headers['content-length'] > max) { res.writeHead(413); res.end('too large'); return req.destroy(); }
|
|
954
|
+
req.on('data', (d) => { if (over) return; size += d.length; if (size > max) { over = true; res.writeHead(413); res.end('too large'); req.destroy(); } else chunks.push(d); }); // bytes, not characters
|
|
683
955
|
req.on('end', () => { if (!over) cb(Buffer.concat(chunks).toString('utf8')); });
|
|
684
956
|
};
|
|
685
957
|
const textList = (x) => (Array.isArray(x) ? x : []).slice(0, 200).map((t) => String(t).slice(0, 2000));
|
|
686
958
|
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
|
|
959
|
+
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); } });
|
|
960
|
+
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
961
|
if (url.pathname === '/api/sessions') return json(listSessions());
|
|
690
962
|
if (url.pathname === '/api/projects') { // projects (working folders) ordered by latest activity — lets the live view follow one of them
|
|
691
963
|
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 +971,7 @@ function start(port = PORT) {
|
|
|
699
971
|
return json({ owner: audioOwner.id });
|
|
700
972
|
}
|
|
701
973
|
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 }); }
|
|
974
|
+
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
975
|
if (url.pathname === '/api/voices') {
|
|
704
976
|
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
977
|
return loadVoices().then((v) => json(v));
|
|
@@ -714,10 +986,19 @@ function start(port = PORT) {
|
|
|
714
986
|
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
987
|
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
988
|
if (url.pathname === '/api/prefs') return json(readPrefs() || {});
|
|
717
|
-
if (url.pathname === '/api/
|
|
989
|
+
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); } });
|
|
990
|
+
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
|
|
991
|
+
if (url.pathname === '/api/errors') return json(errorReport());
|
|
992
|
+
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
993
|
if (url.pathname === '/api/board') return json(boardRows());
|
|
719
994
|
if (url.pathname === '/api/characters') return json(listCharacters(url.searchParams.get('pack') || ''));
|
|
720
|
-
if (url.pathname === '/api/
|
|
995
|
+
if (url.pathname === '/api/characters/add' && req.method === 'POST') return readBody((body) => { try { const b = JSON.parse(body || '{}') || {}; json(addCharacter(String(b.role || ''), b.name, b.data)); } catch (e) { if (!e.word) logError('add character', e); json({ error: e.word || 'write' }, e.word ? 400 : 500); } }, 512 * 1024); // a picture of 300 KB is 400 KB once written as text
|
|
996
|
+
if (url.pathname === '/api/characters/remove' && req.method === 'POST') return readBody((body) => { let b = {}; try { b = JSON.parse(body || '{}') || {}; } catch {} try { json(removeCharacter(b.file) ? { ok: true } : { error: 'file' }, 200); } catch (e) { logError('remove character', e); json({ error: 'write' }, 500); } });
|
|
997
|
+
if (url.pathname === '/api/packs') return json(packList());
|
|
998
|
+
if ((url.pathname === '/api/packs/buy' || url.pathname === '/api/packs/claim') && req.method === 'POST') return readBody((body) => {
|
|
999
|
+
let b = {}; try { b = JSON.parse(body || '{}') || {}; } catch {} const name = String(b.pack || ''); if (!hasOwn(SHOP_PACKS, name)) return json({ error: 'pack' }, 404);
|
|
1000
|
+
(url.pathname.endsWith('/buy') ? buyPack(name) : claimPack(name, typeof b.code === 'string' ? b.code.trim().slice(0, 260) : '')).then((r) => json(r, r.status), (e) => { logError('shop', e); json({ error: 'shop' }, 500); });
|
|
1001
|
+
});
|
|
721
1002
|
if (url.pathname === '/api/reveal' && req.method === 'POST') return readBody((body) => { // 404: not a file this session created · 410: created, and no longer there
|
|
722
1003
|
try {
|
|
723
1004
|
let b = null; try { b = JSON.parse(body); } catch {} const SAFE = /^[\w.\-]+$/, ok = (v) => typeof v === 'string' && SAFE.test(v) && v !== '..' && v.length <= 200;
|
|
@@ -734,10 +1015,19 @@ function start(port = PORT) {
|
|
|
734
1015
|
if (!im) { res.writeHead(bad ? 400 : 404); return res.end(bad ? 'bad request' : 'not found'); }
|
|
735
1016
|
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
1017
|
}
|
|
1018
|
+
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)
|
|
1019
|
+
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;
|
|
1020
|
+
if (bad) { res.writeHead(400); return res.end('bad request'); }
|
|
1021
|
+
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);
|
|
1022
|
+
if (q('check')) return json(page ? { ok: true, net: page.net } : { ok: false }, page ? 200 : 404);
|
|
1023
|
+
if (!page) { res.writeHead(404); return res.end('not found'); }
|
|
1024
|
+
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
|
|
1025
|
+
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);
|
|
1026
|
+
}
|
|
737
1027
|
if (url.pathname === '/api/session') {
|
|
738
1028
|
const proj = url.searchParams.get('proj') || '', sid = url.searchParams.get('id') || '', SAFE = /^[\w.\-]+$/;
|
|
739
1029
|
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(
|
|
1030
|
+
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
1031
|
const entry = proj === '_demo' ? demoEntry() : timelineEntry(proj, sid), tl = entry.tl; // built-in fictional session
|
|
742
1032
|
const after = url.searchParams.get('after'), ep = url.searchParams.get('ep');
|
|
743
1033
|
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 +1052,13 @@ function start(port = PORT) {
|
|
|
762
1052
|
const file = path.join(PUBLIC, url.pathname === '/' ? 'index.html' : url.pathname);
|
|
763
1053
|
let fst = null; try { fst = fs.statSync(file); } catch {}
|
|
764
1054
|
if (!file.startsWith(PUBLIC + path.sep) || !fst || !fst.isFile()) { res.writeHead(404); return res.end('not found'); }
|
|
765
|
-
|
|
1055
|
+
// 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.
|
|
1056
|
+
res.writeHead(200, { 'content-type': MIME[path.extname(file)] || 'application/octet-stream', ...(path.extname(file) === '.html' ? { 'content-security-policy': "frame-src 'self'" } : {}) });
|
|
766
1057
|
res.end(fs.readFileSync(file));
|
|
767
|
-
} catch (e) { if (res.headersSent) return res.destroy(); json({ error: String(e.message || e) }, 500); }
|
|
1058
|
+
} catch (e) { logError(req.method + ' ' + url.pathname, e); if (res.headersSent) return res.destroy(); json({ error: String(e.message || e) }, 500); }
|
|
768
1059
|
}).listen(port, '127.0.0.1', function () { console.log(`Agent Standup → http://localhost:${this.address().port}`); });
|
|
769
1060
|
}
|
|
770
|
-
module.exports = { start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, _reveal: reveal };
|
|
1061
|
+
module.exports = { start, currentSession, shutdown, findClaude, bundledClaude, boardRows, sessionRows: listSessions, charactersDir, listCharacters, packsDir, installPack, logError, _reveal: reveal, _scrub: { tidy, homeRe }, _artifact: { page: artifactPage, csp: artifactCsp } };
|
|
771
1062
|
if (require.main === module) {
|
|
772
1063
|
start().on('error', (e) => {
|
|
773
1064
|
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));
|