@double_geste/agent-standup 1.45.0 → 1.47.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/README.md +1 -1
- package/bin/agent-standup.js +117 -5
- package/boards.js +258 -0
- package/codex.js +2 -1
- package/kokoro-worker.js +13 -6
- package/kokoro.js +92 -27
- package/package.json +4 -1
- package/public/index.html +224 -58
- package/public/locales/README.md +1 -1
- package/public/locales/da.json +6 -1
- package/public/locales/de.json +6 -1
- package/public/locales/en.json +5 -0
- package/public/locales/es.json +6 -1
- package/public/locales/ja.json +6 -1
- package/public/locales/ko.json +6 -1
- package/public/locales/pt-BR.json +6 -1
- package/public/locales/zh-CN.json +6 -1
- package/public/locales/zh-TW.json +6 -1
- package/server.js +27 -17
- package/supertonic-worker.js +82 -0
- package/zh-g2p.js +175 -0
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Agent Standup (command line)
|
|
2
2
|
|
|
3
|
-
Your Claude Code, Codex and Mistral Vibe sessions as a live team call, without any editor. Free, MIT, and by default it never calls Claude: it reads the session files Claude Code, Codex, Mistral Vibe and Cowork already write, and calls Claude only to translate a call held in French, Spanish or Brazilian Portuguese, or for the optional jokes.
|
|
3
|
+
Your Claude Code, Codex and Mistral Vibe sessions as a live team call, without any editor. Free, MIT, and by default it never calls Claude: it reads the session files Claude Code, Codex, Mistral Vibe and Cowork already write, and calls Claude only to translate a call held in another language (French, Spanish or Brazilian Portuguese, or German, Danish, Japanese, Korean or Chinese once you say yes), or for the optional jokes.
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
6
|
npx @double_geste/agent-standup # then open http://localhost:4747 (add --open to open it for you)
|
package/bin/agent-standup.js
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
// agent-standup [serve] [--port 4747] [--open] start the local server and (optionally) open the page
|
|
4
4
|
// agent-standup status [--here] [--json] [--titles] counts of working / needs you / your turn
|
|
5
5
|
// agent-standup statusline same, one short line; reads Claude Code's statusLine JSON on stdin
|
|
6
|
-
//
|
|
6
|
+
// agent-standup report [--day D] [--here] [--json] [--titles] what each session did that day: time worked, time it waited for you, calls, files (the plugin's whiteboard and timesheet skills read it)
|
|
7
|
+
// agent-standup credits [--session ID] [--here] [--json] a line for a pull request: who was on the call (the lead and its sub-agents, named as the call names them) and what they did (the plugin's credits skill)
|
|
8
|
+
// Everything reads the local session files Claude Code already writes. Nothing is sent anywhere unless the call is in French, Spanish or Brazilian Portuguese (or German, Danish, Japanese, Korean or Chinese, once you say yes) or you turn on the jokes (they use your own Claude login or ANTHROPIC_API_KEY).
|
|
7
9
|
const path = require('path'), { spawn } = require('child_process');
|
|
8
10
|
const pkg = require('../package.json');
|
|
9
11
|
const argv = process.argv.slice(2), flags = {}, rest = [];
|
|
@@ -11,7 +13,7 @@ for (let i = 0; i < argv.length; i++) {
|
|
|
11
13
|
const a = argv[i], val = () => argv[++i];
|
|
12
14
|
if (a === '--port') flags.port = val(); else if (a === '--projects') flags.projects = val(); else if (a === '--codex') flags.codex = val(); else if (a === '--vibe') flags.vibe = val(); else if (a === '--cowork') flags.cowork = val(); else if (a === '--characters') flags.characters = val(); else if (a === '--config-dir') flags.config = val();
|
|
13
15
|
else if (a === '--reply') flags.reply = /^(0|1|on|off|yes|no|true|false)$/i.test(argv[i + 1] || '') ? val() : 'on'; // alone or followed by on / off
|
|
14
|
-
else if (a === '--from') flags.from = val(); else if (a === '--open') flags.open = true; else if (a === '--here') flags.here = true; else if (a === '--json') flags.json = true; else if (a === '--titles') flags.titles = true; else if (a === '--config') flags.config = val();
|
|
16
|
+
else if (a === '--from') flags.from = val(); else if (a === '--open') flags.open = true; else if (a === '--here') flags.here = true; else if (a === '--json') flags.json = true; else if (a === '--titles') flags.titles = true; else if (a === '--config') flags.config = val(); else if (a === '--day') flags.day = val(); else if (a === '--session') flags.session = val();
|
|
15
17
|
else if (a === '-h' || a === '--help') flags.help = true; else if (a === '-v' || a === '--version') flags.version = true; else rest.push(a);
|
|
16
18
|
}
|
|
17
19
|
const cmd = rest[0] || 'serve';
|
|
@@ -21,6 +23,8 @@ Usage
|
|
|
21
23
|
agent-standup [serve] [--port 4747] [--open] start the local server (http://localhost:4747)
|
|
22
24
|
agent-standup status [--here] [--json] what is going on right now (--here: only the current folder)
|
|
23
25
|
agent-standup statusline one short line for a status bar (reads Claude Code's JSON on stdin)
|
|
26
|
+
agent-standup report [--day D] [--json] what each session did that day: time worked, waits for you, calls, files
|
|
27
|
+
agent-standup credits [--session ID] [--json] a credits line for a pull request: the lead and sub-agents of a session, its time and calls
|
|
24
28
|
|
|
25
29
|
Options
|
|
26
30
|
--port N port of the local server (default 4747)
|
|
@@ -37,9 +41,12 @@ Options
|
|
|
37
41
|
--characters DIR folder with your own pixel-art characters (default ~/.agent-standup/characters)
|
|
38
42
|
--from plugin how the Claude Code plugin starts it (its usage, if you agree to share it, is counted apart); also AGENT_STANDUP_FROM=plugin,
|
|
39
43
|
which older versions ignore instead of refusing
|
|
40
|
-
--here status: only sessions of the current folder (matched on its real path, as Claude Code names it)
|
|
41
|
-
--json status: machine-readable output
|
|
44
|
+
--here status, report: only sessions of the current folder (matched on its real path, as Claude Code names it)
|
|
45
|
+
--json status, report: machine-readable output
|
|
46
|
+
--day D report: the day to tell, YYYY-MM-DD, today (the default) or yesterday, in local time
|
|
42
47
|
--titles include session titles, questions, commands and errors
|
|
48
|
+
--session ID credits: the session to credit (default: the Claude Code session it runs in, $CLAUDE_CODE_SESSION_ID;
|
|
49
|
+
with --here and no id, the current folder's latest session)
|
|
43
50
|
`;
|
|
44
51
|
if (flags.help || cmd === 'help') { process.stdout.write(HELP); process.exit(0); }
|
|
45
52
|
if (flags.version || cmd === 'version') { console.log(pkg.version); process.exit(0); }
|
|
@@ -71,10 +78,115 @@ const line = (s, short) => {
|
|
|
71
78
|
if (!s.needsYou && !s.working && s.free) p.push(short ? '✓' : '✓ your turn'); return p.join(short ? ' ' : ' · ') || (short ? '' : 'idle');
|
|
72
79
|
};
|
|
73
80
|
|
|
74
|
-
|
|
81
|
+
// What each session did in one day, from the timelines the call is drawn from: what the plugin's whiteboard (the standup, drawn) and timesheet (a row a session) skills fill their artifact with.
|
|
82
|
+
// Time is told from the gaps between a session's events, all its agents together (sub-agents working side by side are not counted twice): a gap of up to 10 minutes inside a turn is work; the gap
|
|
83
|
+
// before your next message, and a longer one inside a turn (most often a question or a permission menu, sometimes a long command), is time it waited for you, an hour at most each (a session left for the night did not wait all night).
|
|
84
|
+
const GAP_WORK = 10 * 60e3, GAP_WAIT = 60 * 60e3, pad = (n) => String(n).padStart(2, '0');
|
|
85
|
+
const ymd = (t) => { const d = new Date(t); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }, hm = (t) => { const d = new Date(t); return `${pad(d.getHours())}:${pad(d.getMinutes())}`; };
|
|
86
|
+
const dur = (min) => (min >= 60 ? `${Math.floor(min / 60)}h${pad(min % 60)}` : `${min}m`), clipT = (t, n) => { t = String(t || '').replace(/\s+/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1) + '…' : t; };
|
|
87
|
+
function dayRange(d) { // [start, end) of a local day
|
|
88
|
+
const t = new Date(); t.setHours(0, 0, 0, 0);
|
|
89
|
+
if (d === 'yesterday') t.setDate(t.getDate() - 1);
|
|
90
|
+
else if (d && d !== 'today') { const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(d); if (!m || +m[2] < 1 || +m[2] > 12 || +m[3] < 1 || +m[3] > 31) { console.error(`Invalid --day "${d}": use YYYY-MM-DD, today or yesterday.`); process.exit(2); } t.setFullYear(+m[1], +m[2] - 1, +m[3]); if (t.getMonth() !== +m[2] - 1) { console.error(`Invalid --day "${d}": there is no such day.`); process.exit(2); } }
|
|
91
|
+
const end = new Date(t); end.setDate(end.getDate() + 1); return [+t, +end];
|
|
92
|
+
}
|
|
93
|
+
const TOOLS = { codex: 'Codex', vibe: 'Mistral Vibe', cowork: 'Cowork' }, projLabel = (p) => (path.isAbsolute(String(p)) ? String(p).split(/[\\/]+/).filter(Boolean).slice(-2).join('/') : p); // a folder written whole (Codex, Vibe): its last two names, as Claude Code's projects read
|
|
94
|
+
const CALLS = { cmd: 'commands', edit: 'edits', write: 'edits', read: 'reads', web: 'web', browser: 'browser', artifact: 'artifacts' };
|
|
95
|
+
async function report(day, dir, titles) {
|
|
96
|
+
const [from, to] = dayRange(day);
|
|
97
|
+
if (server.sessionsSince) { server.sessionsSince(from); for (let i = 0; i < 600 && server.codexPending && server.codexPending(); i++) await new Promise((r) => setTimeout(r, 100)); } // Codex's compressed threads are read in the background: wait for them (a minute at most) before listing
|
|
98
|
+
const live = new Map(server.boardRows().map((r) => [r.proj + '/' + r.id, r])), home = require('os').homedir(), short = (f) => (f.startsWith(home + path.sep) ? '~' + f.slice(home.length) : f), rows = [];
|
|
99
|
+
for (const r of (server.sessionsSince ? server.sessionsSince(from) : server.sessionRows())) { // every session written since that day began, not only the most recent ones
|
|
100
|
+
if (r.mtime < from) continue;
|
|
101
|
+
if (!r.source && r.proj !== '_demo') { try { const fs = require('fs'), fd = fs.openSync(server.transcriptFile(r.proj, r.id), 'r'), b = Buffer.alloc(32768), n = fs.readSync(fd, b, 0, b.length, 0); fs.closeSync(fd); const m = /"timestamp":"([^"]{10,40})"/.exec(b.toString('utf8', 0, n)), t0 = m ? Date.parse(m[1]) : NaN; if (t0 >= to) continue; } catch {} } // a Claude Code session whose first record is after that day has nothing of it (its first record says when it began; a copied file's dates do not)
|
|
102
|
+
const b = live.get(r.proj + '/' + r.id);
|
|
103
|
+
if (dir && !(fold(r.proj) === fold(projKey(dir)) || (b && b.dir && fold(b.dir) === fold(projKey(dir))))) continue;
|
|
104
|
+
let tl; try { tl = server.timeline(r.proj, r.id); } catch { continue; } // a session that cannot be read costs that session only
|
|
105
|
+
const ev = tl.events.filter((e) => e.ts >= from && e.ts < to).sort((x, y) => x.ts - y.ts); if (!ev.length) continue;
|
|
106
|
+
let work = 0, wait = 0, turns = 0, asked = '', said = ''; const calls = {}, files = new Set(), subs = new Set(), arts = new Map();
|
|
107
|
+
ev.forEach((e, i) => {
|
|
108
|
+
if (e.kind === 'user') { turns++; if (!asked) asked = e.text; }
|
|
109
|
+
if (e.kind === 'say' && e.agent === 'main') said = e.text;
|
|
110
|
+
if (e.agent !== 'main' && e.agent !== 'user') subs.add(e.agent);
|
|
111
|
+
if (e.kind === 'tools') for (const t of e.tools) { const k = CALLS[t.d && t.d.kind] || 'other'; calls[k] = (calls[k] || 0) + 1; if (t.d && (t.d.kind === 'edit' || t.d.kind === 'write') && typeof t.d.file === 'string' && t.d.file) files.add(short(t.d.file)); }
|
|
112
|
+
if (e.kind === 'results') for (const it of e.items) if (it.art && it.art.url) arts.set(it.art.url, it.art.title || (arts.get(it.art.url) || ''));
|
|
113
|
+
if (i) { const gap = ev[i].ts - ev[i - 1].ts; if (e.kind === 'user' || gap > GAP_WORK) wait += Math.min(gap, GAP_WAIT); else work += gap; }
|
|
114
|
+
});
|
|
115
|
+
const tool = TOOLS[r.source] || r.source || (r.project === 'Cowork' ? 'Cowork' : 'Claude Code');
|
|
116
|
+
rows.push({ project: projLabel(String(r.project || r.proj).replace(/^(Codex|Mistral Vibe|Vibe) · /, '')), tool, id: r.id, state: b ? b.state : 'idle', start: hm(ev[0].ts), end: hm(ev[ev.length - 1].ts), t0: ev[0].ts,
|
|
117
|
+
workMin: Math.round(work / 60e3), waitMin: Math.round(wait / 60e3), turns, subAgents: subs.size, calls, filesChanged: files.size,
|
|
118
|
+
...(titles ? { title: clipT(r.title, 120), asked: clipT(asked, 240), said: clipT(said, 400), files: [...files].slice(0, 30), artifacts: [...arts].map(([url, title]) => ({ title: clipT(title, 120), url })) } : {}) });
|
|
119
|
+
}
|
|
120
|
+
rows.sort((a, b) => a.t0 - b.t0); rows.forEach((r) => delete r.t0);
|
|
121
|
+
return { day: ymd(from), sessions: rows.length, workMin: rows.reduce((n, r) => n + r.workMin, 0), waitMin: rows.reduce((n, r) => n + r.waitMin, 0), rows };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// The cast of one session, named as the call names it: the lead (the editor's setting, this project's, the global one, or Margot), then each sub-agent in the order it was born, a fork after
|
|
125
|
+
// the lead (Margot 2), a name of its own when the person turned those on, a tool's own name (Codex's nicknames) unless they gave a list, otherwise a name drawn from its id.
|
|
126
|
+
// A copy of public/index.html (NAMES, hash, cleanLead, uniqueName, subName, twinOf): keep the two in step; test/cli-credits.test.js checks the list against the page's.
|
|
127
|
+
const NAMES = ['Ada','Linus','Grace','Alan','Margaret','Dennis','Barbara','Ken','Radia','Tim','Hedy','Guido','Frances','Bjarne','Katherine','Brian','Sophie','Niklaus','Annie','Donald','Joan','Edsger','Lynn','Vint','Mae','Rob','Zoe','Ivan','Nina','Otto','Lena','Hugo','Ines','Théo','Maya','Jules','Alma','Remy','Cleo','Noah','Iris','Leo','Mira','Axel','Nora','Eli','Lou','Gaby'];
|
|
128
|
+
const fnv = (s) => { let h = 2166136261; for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 16777619); return h >>> 0; };
|
|
129
|
+
const cleanName = (v) => Array.from(String(v == null ? '' : v).replace(/'/g, '’').replace(/[\u0000-\u001f\u007f-\u009f<>&"`\\]/g, '').replace(/\s+/g, ' ').trim()).slice(0, 24).join('').trim();
|
|
130
|
+
function castOf(agents, prefs, key) {
|
|
131
|
+
prefs = prefs && typeof prefs === 'object' ? prefs : {};
|
|
132
|
+
const lead = cleanName(process.env.AGENT_STANDUP_LEAD_NAME) || (key && cleanName(prefs['leadName:' + key])) || cleanName(prefs.leadName) || 'Margot', low = (n) => String(n).toLocaleLowerCase();
|
|
133
|
+
const isLead = (n) => { const l = low(lead), s = low(n || ''); return !!n && (s === l || (s.startsWith(l + ' ') && /^\d+$/.test(s.slice(l.length + 1)))); };
|
|
134
|
+
const list = []; { const seen = new Set(); for (const v of (typeof prefs.subNames === 'string' ? prefs.subNames : '').split(/[,;\n]+/)) { const n = cleanName(v), k = low(n); if (n && !seen.has(k) && list.length < 200) { seen.add(k); list.push(n); } } }
|
|
135
|
+
const book = {}, names = {};
|
|
136
|
+
const unique = (id, h) => {
|
|
137
|
+
const taken = new Set(Object.values(book).map(low)); taken.add(low(lead));
|
|
138
|
+
const own = list.filter((n) => !isLead(n)), pool = own.length ? own : NAMES, at = own.length ? 0 : h;
|
|
139
|
+
for (let k = 0; k < pool.length; k++) { const n = pool[(at + k) % pool.length]; if (!taken.has(low(n))) return (book[id] = n); }
|
|
140
|
+
for (let r = 2; ; r++) for (let k = 0; k < pool.length; k++) { const b = pool[(at + k) % pool.length]; if (isLead(b)) continue; const n = b + ' ' + r; if (!taken.has(low(n))) return (book[id] = n); }
|
|
141
|
+
};
|
|
142
|
+
const ownFree = (a) => { const taken = new Set(Object.keys(book).filter((k) => k !== a.id).map((k) => low(book[k]))); let n = a.own; for (let r = 2; taken.has(low(n)); r++) n = a.own + ' ' + r; return n; };
|
|
143
|
+
let twins = 0;
|
|
144
|
+
const subs = (agents || []).filter((a) => a && a.id && a.id !== 'main' && a.id !== 'user').map((a, j) => ({ a, j })).sort((x, y) => (x.a.born || Infinity) - (y.a.born || Infinity) || x.j - y.j).map((x) => x.a);
|
|
145
|
+
for (const a of subs) {
|
|
146
|
+
const twinN = /^fork$/i.test(a.type || '') && !('given' in a) && !(a.own && prefs.ownNames) ? 2 + twins++ : 0, given = twinN ? lead + ' ' + twinN : 'given' in a ? a.given : a.name;
|
|
147
|
+
names[a.id] = a.own && prefs.ownNames && !isLead(a.own) ? (book[a.id] = ownFree(a)) : ((twinN || (!isLead(given) && !list.length)) && given) || unique(a.id, fnv(a.id));
|
|
148
|
+
}
|
|
149
|
+
return { lead, names };
|
|
150
|
+
}
|
|
151
|
+
const SITE = 'https://agent-standup.com';
|
|
152
|
+
function credits(id, dir) {
|
|
153
|
+
const want = (r) => (id ? r.id === id : !dir || fold(r.proj) === fold(projKey(dir)));
|
|
154
|
+
let r = server.sessionRows().filter(want).sort((a, b) => b.mtime - a.mtime)[0];
|
|
155
|
+
if (!r && server.sessionsSince) r = server.sessionsSince(0).filter(want).sort((a, b) => b.mtime - a.mtime)[0]; // an older session than the recent list holds
|
|
156
|
+
if (!r) return null;
|
|
157
|
+
const tl = server.timeline(r.proj, r.id), ev = tl.events.slice().sort((x, y) => x.ts - y.ts), busy = new Set(), files = new Set(); let work = 0, commands = 0, edits = 0;
|
|
158
|
+
ev.forEach((e, i) => {
|
|
159
|
+
if (e.agent && e.agent !== 'main' && e.agent !== 'user') busy.add(e.agent);
|
|
160
|
+
if (e.kind === 'tools') for (const t of e.tools) { const k = t.d && t.d.kind; if (k === 'cmd') commands++; if (k === 'edit' || k === 'write') { edits++; if (typeof t.d.file === 'string' && t.d.file) files.add(t.d.file); } }
|
|
161
|
+
if (i && e.kind !== 'user') { const gap = e.ts - ev[i - 1].ts; if (gap <= GAP_WORK) work += gap; } // as report counts it: the gaps within a turn, up to 10 minutes each
|
|
162
|
+
});
|
|
163
|
+
const cast = castOf(tl.agents, server.readPrefs ? server.readPrefs() : null, server.leadKey ? server.leadKey(r.proj, r.id) : ''), subs = (tl.agents || []).filter((a) => a && busy.has(a.id)).map((a) => cast.names[a.id]).filter(Boolean);
|
|
164
|
+
const shown = subs.length > 5 ? [...subs.slice(0, 4), `${subs.length - 4} others`] : subs, who = [cast.lead, ...shown].reduce((s, n, i, all) => (i ? s + (i === all.length - 1 ? ' and ' : ', ') : '') + n, '');
|
|
165
|
+
const workMin = Math.round(work / 60e3), plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
|
|
166
|
+
const facts = [workMin ? `${dur(workMin)} of work` : '', commands ? plural(commands, 'command') : '', edits ? plural(edits, 'edit') + (files.size ? ` in ${plural(files.size, 'file')}` : '') : ''].filter(Boolean);
|
|
167
|
+
const md = (s) => s.replace(/[\\`*_[\]~|#<>]/g, '\\$&'); // names are the person's own words: plain text in the line
|
|
168
|
+
return { session: r.id, project: projLabel(String(r.project || r.proj)), lead: cast.lead, subAgents: subs, workMin, commands, edits, filesChanged: files.size,
|
|
169
|
+
markdown: `<sub><a href="${SITE}"><img src="${SITE}/brand/team-strip.svg" height="16" align="absmiddle" alt="The Agent Standup cast"></a> Built on an <a href="${SITE}">Agent Standup</a> call by ${md(who)}${facts.map((f) => ' · ' + f).join('')}</sub>`,
|
|
170
|
+
text: `Built on an Agent Standup call by ${who}${facts.map((f) => ' · ' + f).join('')} · ${SITE}` };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (cmd === 'credits') {
|
|
174
|
+
const id = flags.session || (flags.here ? '' : process.env.CLAUDE_CODE_SESSION_ID || '');
|
|
175
|
+
if (!id && !flags.here) { console.error('No session to credit: run it from inside a Claude Code session, or pass --session <id> or --here (the current folder\'s latest session).'); process.exit(2); }
|
|
176
|
+
let c; try { c = credits(id, flags.here ? process.cwd() : ''); } catch (e) { console.error('Could not read that session: ' + (e && e.message)); process.exit(1); }
|
|
177
|
+
if (!c) { console.error(id ? `No session ${id} in the session files.` : 'No session in this folder.'); process.exit(1); }
|
|
178
|
+
process.stdout.write((flags.json ? JSON.stringify(c, null, 2) : c.markdown) + '\n', () => process.exit(0));
|
|
179
|
+
} else if (cmd === 'status') {
|
|
75
180
|
const s = snapshot(flags.here ? process.cwd() : '');
|
|
76
181
|
if (flags.json) console.log(JSON.stringify({ needsYou: s.needsYou, working: s.working, yourTurn: s.yourTurn, idle: s.idle, sessions: s.rows.map((r) => ({ project: r.proj, id: r.id, state: r.state, tool: r.tool, ageMs: Math.round(r.ageMs), subAgentsActive: r.subActive, subAgents: r.subTotal, ...(r.since ? { since: r.since } : {}), ...(r.ran ? { ran: r.ran } : {}), ...(r.limit ? { limit: r.limit } : {}), ...(r.auth ? { auth: 1 } : {}), ...(flags.titles ? { title: r.title, ...(r.ask ? { ask: r.ask } : {}), ...(r.menu && r.menu.about ? { about: r.menu.about } : {}), ...(r.gave ? { gave: r.gave } : {}) } : {}) })) }, null, 2)); // since: when it started to wait, ran: how long it worked before · with --titles only, what the sessions say (it can hold a path, a command or a secret): ask, the question or command that waits for you, about, what that command is for, gave, the error it stopped on
|
|
77
182
|
else console.log(line(s, false));
|
|
183
|
+
} else if (cmd === 'report') {
|
|
184
|
+
report(flags.day, flags.here ? process.cwd() : '', flags.titles).then((rep) => {
|
|
185
|
+
const callLine = (c) => Object.entries(c).sort((x, y) => y[1] - x[1]).map(([k, n]) => `${n} ${n === 1 ? k.replace(/s$/, '') : k}`).join(' · ');
|
|
186
|
+
const text = flags.json ? JSON.stringify(rep, null, 2) : [`${rep.day} · ${rep.sessions} session${rep.sessions === 1 ? '' : 's'} · ${dur(rep.workMin)} worked · ${dur(rep.waitMin)} waited for you`,
|
|
187
|
+
...rep.rows.map((r) => ` ${r.start}–${r.end} ${(r.tool + ' · ' + r.project).padEnd(36).slice(0, 36)} ${dur(r.workMin).padStart(5)} worked ${dur(r.waitMin).padStart(5)} waited ${callLine(r.calls)}${r.title ? '\n ' + r.title : ''}`)].join('\n');
|
|
188
|
+
process.stdout.write(text + '\n', () => process.exit(0)); // the timelines leave timers behind: once written, it is done
|
|
189
|
+
});
|
|
78
190
|
} else if (cmd === 'statusline') {
|
|
79
191
|
let raw = ''; const go = () => { let dir = ''; try { const j = JSON.parse(raw); dir = (j.workspace && j.workspace.current_dir) || j.cwd || ''; } catch {} console.log(line(snapshot(dir), true)); process.exit(0); };
|
|
80
192
|
if (process.stdin.isTTY) go(); else { process.stdin.setEncoding('utf8'); process.stdin.on('data', (d) => (raw += d)); process.stdin.on('end', go); setTimeout(go, 800); }
|
package/boards.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// Claude Whiteboards and Claude Sheets on the shared screen. Neither sends a page when it is made: a board keeps its content in its own store (the ArtifactData tool's writes) and a Sheet
|
|
2
|
+
// keeps its cells on Anthropic's server (the Claude Docs connector's applyEdits). The call cannot fetch either, and does not try: like the pages of other artifacts, each is put together again
|
|
3
|
+
// from what the session file holds, the writes of that session up to the one asked for, in order, those that were refused left out. The result is a still picture (no script runs in it),
|
|
4
|
+
// close to what the person saw on claude.ai at that moment: what someone else drew on the same board, or typed in the same Sheet, is not in this session's file and so not in the picture.
|
|
5
|
+
'use strict';
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
|
|
8
|
+
const LIVE_MAX = 32 * 1024 * 1024; // a session file read further than this for one picture is not read whole: the picture is drawn from what was read
|
|
9
|
+
const memo = new Map();
|
|
10
|
+
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
11
|
+
const blocksOf = (r) => { const c = r && r.message && r.message.content; return Array.isArray(c) ? c : []; };
|
|
12
|
+
const textOf = (c) => (typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => (x && typeof x.text === 'string' ? x.text : '')).join('\n') : '');
|
|
13
|
+
const BOARD_WRITES = new Set(['set', 'update', 'delete', 'str_replace', 'batch']);
|
|
14
|
+
const boardDoc = (w) => !!w && (String(w.collection || '') === 'elements' || (String(w.collection || '') === 'board' && /^(meta|claim-[a-z0-9]{1,40})$/.test(String(w.doc_id || ''))));
|
|
15
|
+
const onBoard = (i) => (i.action === 'batch' ? Array.isArray(i.writes) && i.writes.some(boardDoc) : boardDoc(i)); // a Whiteboard keeps its content in board/meta and elements/<id>: another page's own database (a tracker, a sign-up sheet) is not a board
|
|
16
|
+
const docsTool = (name) => { const m = /^mcp__(.+?)__(update|read)$/.exec(name || ''); return m && /(^|_)Claude_Docs$/.test(m[1]) ? m[2] : ''; };
|
|
17
|
+
|
|
18
|
+
// What a call does to a board or a Sheet, or null: { key, kind: 'board' | 'sheet', op: 'write' | 'read' }. key: the board's address, or the Sheet's project in Claude Docs.
|
|
19
|
+
function liveCall(name, i) {
|
|
20
|
+
if (!i || typeof i !== 'object') return null;
|
|
21
|
+
if (name === 'ArtifactData' && BOARD_WRITES.has(i.action) && typeof i.url === 'string' && onBoard(i)) return { key: i.url, kind: 'board', op: 'write' };
|
|
22
|
+
const d = docsTool(name), proj = i.container && typeof i.container.id === 'string' ? i.container.id : '', p = i.payload && typeof i.payload === 'object' ? i.payload : null;
|
|
23
|
+
if (!d || !proj || i.engine !== 'workbook' || !p) return null;
|
|
24
|
+
if (d === 'update' && p.kind === 'applyEdits' && Array.isArray(p.edits)) return { key: proj, kind: 'sheet', op: 'write' };
|
|
25
|
+
if (d === 'read' && p.kind === 'readCells') return { key: proj, kind: 'sheet', op: 'read' };
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// One pass over the session file: the calls on the same board or Sheet as toolId, up to toolId's answer, each with whether it went through (and, for a read of cells, what they came to).
|
|
30
|
+
function collect(file, toolId) {
|
|
31
|
+
const ops = [], byId = new Map(); let target = null, done = false, tail = false, fd, pos = 0, size = 0, carry = Buffer.alloc(0);
|
|
32
|
+
const marks = [Buffer.from('"ArtifactData"'), Buffer.from('Claude_Docs__'), Buffer.from('"tool_result"')];
|
|
33
|
+
try {
|
|
34
|
+
fd = fs.openSync(file, 'r'); size = fs.fstatSync(fd).size;
|
|
35
|
+
while (pos < size && pos < LIVE_MAX && !done) {
|
|
36
|
+
const buf = Buffer.alloc(Math.min(8 * 1024 * 1024, size - pos)); fs.readSync(fd, buf, 0, buf.length, pos); pos += buf.length;
|
|
37
|
+
const all = carry.length ? Buffer.concat([carry, buf]) : buf; let a = 0;
|
|
38
|
+
for (let b; !done && (b = all.indexOf(10, a)) >= 0; a = b + 1) {
|
|
39
|
+
const line = all.subarray(a, b);
|
|
40
|
+
if (line.indexOf(marks[0]) < 0 && line.indexOf(marks[1]) < 0 && !(byId.size && line.indexOf(marks[2]) >= 0)) continue;
|
|
41
|
+
let r; try { r = JSON.parse(line.toString('utf8')); } catch { continue; }
|
|
42
|
+
for (const blk of blocksOf(r)) {
|
|
43
|
+
if (blk.type === 'tool_use') { const c = liveCall(blk.name, blk.input); if (!c) continue;
|
|
44
|
+
if (tail && (c.key !== target.key || c.op !== 'read')) { if (c.key === target.key) done = true; continue; } /* after the write: only the reads of the same Sheet, up to its next write */
|
|
45
|
+
const op = { id: blk.id, ...c, i: blk.input, ok: null }; ops.push(op); byId.set(blk.id, op); if (blk.id === toolId) target = op; }
|
|
46
|
+
else if (blk.type === 'tool_result' && byId.has(blk.tool_use_id)) {
|
|
47
|
+
const op = byId.get(blk.tool_use_id), text = textOf(blk.content);
|
|
48
|
+
if (blk.is_error) op.ok = false;
|
|
49
|
+
else if (op.kind === 'board') op.ok = !/\bnothing (was )?written\b|\brefused\b/i.test(text.slice(0, 400));
|
|
50
|
+
else { const j = docsJson(text); op.ok = !!(j && j.verdict !== 'deny' && (op.op === 'read' ? j.value && j.value.rows : j.data && Number.isFinite(+j.data.revision))); if (op.ok && op.op === 'read') op.value = j.value; }
|
|
51
|
+
byId.delete(blk.tool_use_id); if (blk.tool_use_id === toolId) { if (op.kind === 'sheet' && op.ok) tail = true; else done = true; } /* a Sheet: what the formulas came to is told by a read that follows */
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
carry = Buffer.from(all.subarray(a));
|
|
56
|
+
}
|
|
57
|
+
} catch {} finally { if (fd != null) fs.closeSync(fd); }
|
|
58
|
+
if (!target || target.op !== 'write' || !(done || tail) || !target.ok) return null; // a write that was refused, or whose answer is not written yet, has no picture of its own
|
|
59
|
+
return { kind: target.kind, ops: ops.filter((o) => o.key === target.key && o.kind === target.kind && o.ok), size };
|
|
60
|
+
}
|
|
61
|
+
function docsJson(text) { // the connector's answer: a line that says it comes from others, then the JSON
|
|
62
|
+
const s = text.indexOf('{"verdict"'); if (s < 0) return null;
|
|
63
|
+
try { return JSON.parse(text.slice(s)); } catch {}
|
|
64
|
+
try { return JSON.parse(text.slice(s, text.lastIndexOf('}') + 1)); } catch { return null; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---- The board: its store, as the writes left it, then drawn as one SVG.
|
|
68
|
+
const DEL = (v) => v && typeof v === 'object' && v.__delete__ === true, BAD_KEY = new Set(['__proto__', 'constructor', 'prototype']);
|
|
69
|
+
const clean = (v) => JSON.parse(JSON.stringify(v), (k, x) => (BAD_KEY.has(k) ? undefined : x)); // a copy with no key that could reach a prototype: a session's records must not change the server's objects
|
|
70
|
+
function merge(into, data, depth = 0) {
|
|
71
|
+
for (const [k, v] of Object.entries(data || {})) {
|
|
72
|
+
if (BAD_KEY.has(k)) continue;
|
|
73
|
+
if (DEL(v)) delete into[k];
|
|
74
|
+
else if (depth < 40 && v && typeof v === 'object' && !Array.isArray(v) && into[k] && typeof into[k] === 'object' && !Array.isArray(into[k])) merge(into[k], v, depth + 1);
|
|
75
|
+
else into[k] = v;
|
|
76
|
+
}
|
|
77
|
+
return into;
|
|
78
|
+
}
|
|
79
|
+
function boardStore(ops) {
|
|
80
|
+
let room = 4e6; // what str_replace may add to the board's texts in all: a board holds 2 MB
|
|
81
|
+
const docs = new Map(), one = (w) => {
|
|
82
|
+
if (!boardDoc(w)) return; // only the board's own documents
|
|
83
|
+
const key = String(w.collection || '') + '/' + String(w.doc_id || ''), data = w.data && typeof w.data === 'object' ? w.data : null;
|
|
84
|
+
if (w.op === 'delete' || w.action === 'delete') docs.delete(key);
|
|
85
|
+
else if ((w.op || w.action) === 'set' && data) docs.set(key, clean(data));
|
|
86
|
+
else if ((w.op || w.action) === 'update' && data) docs.set(key, merge(docs.get(key) || {}, clean(data)));
|
|
87
|
+
else if (w.action === 'str_replace' && docs.has(key) && !BAD_KEY.has(w.field)) { const d = docs.get(key), f = w.field; if (typeof d[f] === 'string' && typeof w.old_str === 'string' && w.old_str) { const n = w.replace_all ? d[f].split(w.old_str).length - 1 : 1, grows = String(w.new_str || '').length - w.old_str.length; if (d[f].length + n * grows <= 100000 && (grows <= 0 || (room -= n * grows) >= 0)) d[f] = w.replace_all ? d[f].split(w.old_str).join(w.new_str || '') : d[f].replace(w.old_str, () => w.new_str || ''); } } /* a text that would grow past what a board holds is not grown (doubling it could end the process) */
|
|
88
|
+
};
|
|
89
|
+
for (const o of ops) { if (o.i.action === 'batch') for (const w of Array.isArray(o.i.writes) ? o.i.writes : []) one(w); else one(o.i); }
|
|
90
|
+
return docs;
|
|
91
|
+
}
|
|
92
|
+
const FILL = { yellow: '#fff1b3', peach: '#ffd9bf', pink: '#ffd3e4', green: '#d3f2da', blue: '#d4e6ff', purple: '#e6dbff', white: '#ffffff' };
|
|
93
|
+
const INK = { ink: '#1f1f22', terracotta: '#c2613d', blue: '#2f6fdb', green: '#2e8b57', purple: '#7b4fd6' };
|
|
94
|
+
const HEX = /^#[0-9a-f]{6}$/i, fillOf = (c, dflt) => (HEX.test(c || '') ? c : FILL[c] || dflt), inkOf = (c) => (HEX.test(c || '') ? c : INK[c] || INK.ink);
|
|
95
|
+
const SIZE = { small: 14, body: 16, large: 28, title: 48, huge: 96 };
|
|
96
|
+
const num = (v, d = 0) => (Number.isFinite(+v) ? Math.max(-1e6, Math.min(1e6, +v)) : d);
|
|
97
|
+
function inline(t) { // the few marks a board's text has: **bold**, *italic*, `code`, [label](link), and lists, on escaped text
|
|
98
|
+
return String(t || '').slice(0, 4000).split('\n').map((ln) => {
|
|
99
|
+
const li = /^(- |\d+\. )/.exec(ln), body = esc(li ? ln.slice(li[0].length) : ln)
|
|
100
|
+
.replace(/`([^`]+)`/g, '<code>$1</code>').replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>').replace(/\*([^*]+)\*/g, '<i>$1</i>').replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<u>$1</u>');
|
|
101
|
+
return li ? `<div class="li">${li[0].trim() === '-' ? '•' : esc(li[0].trim())} ${body}</div>` : `<div>${body || ' '}</div>`;
|
|
102
|
+
}).join('');
|
|
103
|
+
}
|
|
104
|
+
const fo = (x, y, w, h, cls, style, html) => `<foreignObject x="${x}" y="${y}" width="${Math.max(1, w)}" height="${Math.max(1, h)}"><div xmlns="http://www.w3.org/1999/xhtml" class="${cls}" style="${style}">${html}</div></foreignObject>`;
|
|
105
|
+
function tableSize(el) {
|
|
106
|
+
const cols = Object.entries(el.cols || {}).sort((a, b) => num(a[1] && a[1].at) - num(b[1] && b[1].at)).slice(0, 30).map(([k]) => k), rows = Object.values(el.rows || {}).filter((r) => r && typeof r === 'object').sort((a, b) => num(a.at) - num(b.at)).slice(0, 200);
|
|
107
|
+
const widths = cols.map((c) => Math.min(320, Math.max(60, ...rows.map((r) => String(r[c] == null ? '' : r[c]).length * 8 + 24))));
|
|
108
|
+
return { cols, rows, widths, w: widths.reduce((a, b) => a + b, 0), h: rows.length * 34 };
|
|
109
|
+
}
|
|
110
|
+
function drawBoard(docs) {
|
|
111
|
+
const meta = docs.get('board/meta') || {}, els = new Map(); for (const [k, v] of docs) if (k.startsWith('elements/') && v && typeof v === 'object') els.set(k.slice(9), v);
|
|
112
|
+
const order = (Array.isArray(meta.order) ? meta.order.filter((id) => els.has(id)) : []), ids = [...new Set([...order, ...els.keys()])].slice(0, 800);
|
|
113
|
+
const box = new Map(); let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; const grow = (x, y, w, h) => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x + w); y1 = Math.max(y1, y + h); };
|
|
114
|
+
for (const id of ids) { // where each thing stands, for the arrows and the frame
|
|
115
|
+
const e = els.get(id), x = num(e.x), y = num(e.y);
|
|
116
|
+
if (e.type === 'text') { const s = SIZE[e.size] || 16, lines = String(e.text || '').split('\n'), w = e.wrap ? num(e.wrap, 300) : lines.reduce((m, l) => Math.max(m, l.length), 0) * s * 0.56 + 8, h = (e.wrap ? Math.ceil(String(e.text || '').length * s * 0.55 / w) + lines.length - 1 : lines.length) * s * 1.4; box.set(id, { x, y, w, h }); grow(x, y, w, h); }
|
|
117
|
+
else if (e.type === 'table') { const t = tableSize(e); box.set(id, { x, y, w: t.w, h: t.h, t }); grow(x, y, t.w, t.h); }
|
|
118
|
+
else if (e.type === 'link') { box.set(id, { x, y, w: 320, h: 56 }); grow(x, y, 320, 56); }
|
|
119
|
+
else if (e.type === 'stroke') { const p = Array.isArray(e.points) ? e.points.slice(0, 8000).map((v) => num(v)) : []; for (let k = 0; k + 1 < p.length; k += 2) grow(x + p[k], y + p[k + 1], 1, 1); }
|
|
120
|
+
else if (e.type !== 'arrow' && e.type !== 'sticker') { const w = num(e.w, 160), h = num(e.h, 80); box.set(id, { x, y, w, h }); grow(x, y - (e.type === 'container' ? 34 : 0), w, h + (e.type === 'container' ? 34 : 0)); }
|
|
121
|
+
}
|
|
122
|
+
if (!docs.has('board/meta') && !els.size) return null; // nothing of a board: no picture (the call shows the artifact's card)
|
|
123
|
+
if (x0 > x1) return page('board', esc(meta.title || ''), '<div class="empty">The board is empty so far.</div>');
|
|
124
|
+
const out = [], P = 40;
|
|
125
|
+
for (const id of ids) {
|
|
126
|
+
const e = els.get(id), b = box.get(id), x = num(e.x), y = num(e.y);
|
|
127
|
+
if (e.type === 'container') { out.push(`<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="18" fill="${fillOf(e.color, '#f4f4f1')}" fill-opacity="${e.color ? 0.45 : 1}" stroke="#d9d9d3"/>`); if (e.text) out.push(fo(x, y - 34, b.w, 30, 'ct', '', inline(String(e.text).split('\n')[0]))); }
|
|
128
|
+
else if (e.type === 'shape') {
|
|
129
|
+
const w = b.w, h = b.h, fill = e.hollow ? 'none' : fillOf(e.color, FILL.green), st = e.stroke ? ` stroke="${inkOf(e.stroke)}" stroke-width="2"` : ' stroke="rgba(0,0,0,.08)"', k = e.kind;
|
|
130
|
+
out.push(k === 'ellipse' ? `<ellipse cx="${x + w / 2}" cy="${y + h / 2}" rx="${w / 2}" ry="${h / 2}" fill="${fill}"${st}/>` : k === 'diamond' ? `<polygon points="${x + w / 2},${y} ${x + w},${y + h / 2} ${x + w / 2},${y + h} ${x},${y + h / 2}" fill="${fill}"${st}/>`
|
|
131
|
+
: k === 'hexagon' ? `<polygon points="${x + w * 0.2},${y} ${x + w * 0.8},${y} ${x + w},${y + h / 2} ${x + w * 0.8},${y + h} ${x + w * 0.2},${y + h} ${x},${y + h / 2}" fill="${fill}"${st}/>`
|
|
132
|
+
: k === 'parallelogram' ? `<polygon points="${x + w * 0.15},${y} ${x + w},${y} ${x + w * 0.85},${y + h} ${x},${y + h}" fill="${fill}"${st}/>`
|
|
133
|
+
: `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${k === 'pill' ? h / 2 : k === 'rect' ? 4 : 14}" fill="${fill}"${st}/>`);
|
|
134
|
+
const inset = k === 'diamond' || k === 'ellipse' ? 0.18 : 0.04;
|
|
135
|
+
if (e.text) out.push(fo(x + w * inset + 6, y + 4, w * (1 - 2 * inset) - 12, h - 8, 'sh', `font-size:${SIZE[e.size] || 15}px;text-align:${['left', 'right'].includes(e.textAlign) ? e.textAlign : 'center'};justify-content:${e.textAlign === 'left' ? 'flex-start' : e.textAlign === 'right' ? 'flex-end' : 'center'}`, inline(e.text)));
|
|
136
|
+
}
|
|
137
|
+
else if (e.type === 'note') { out.push(`<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="6" fill="${FILL.yellow}" stroke="rgba(0,0,0,.08)"/>`); if (e.text) out.push(fo(x + 8, y + 6, b.w - 16, b.h - 12, 'sh', 'font-size:15px;text-align:left;justify-content:flex-start', inline(e.text))); }
|
|
138
|
+
else if (e.type === 'text') out.push(fo(x, y, b.w + 40, b.h + 20, 'tx', `font-size:${SIZE[e.size] || 16}px;color:${inkOf(e.color)};${e.wrap ? '' : 'white-space:pre;'}text-align:${['center', 'right'].includes(e.textAlign) ? e.textAlign : 'left'};${e.size === 'title' || e.size === 'huge' ? 'font-weight:700;' : ''}`, inline(e.text)));
|
|
139
|
+
else if (e.type === 'stroke') { const p = Array.isArray(e.points) ? e.points.slice(0, 8000).map((v) => num(v)) : [], pts = []; for (let k = 0; k + 1 < p.length; k += 2) pts.push(`${x + p[k]},${y + p[k + 1]}`); if (pts.length > 1) out.push(`<polyline points="${pts.join(' ')}" fill="none" stroke="${inkOf(e.color)}" stroke-width="${Math.min(20, num(e.width, 3))}" stroke-linecap="round" stroke-linejoin="round"/>`); }
|
|
140
|
+
else if (e.type === 'image') { const src = typeof e.src === 'string' && /^data:image\/(png|jpeg|webp|gif|svg\+xml)[;,]/.test(e.src) && e.src.length < 400000 ? e.src : ''; out.push(src ? `<image x="${x}" y="${y}" width="${b.w}" height="${b.h}" href="${esc(src)}" preserveAspectRatio="xMidYMid meet"/>` : `<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="10" fill="#ececea"/>` + fo(x, y, b.w, b.h, 'sh muted', 'font-size:14px', 'picture')); }
|
|
141
|
+
else if (e.type === 'html') { out.push(`<rect x="${x}" y="${y}" width="${b.w}" height="${b.h}" rx="10" fill="#fff" stroke="#cfcfca"/>`); const t = /<title>([^<]{1,80})<\/title>/i.exec(String(e.html || '')); out.push(fo(x, y, b.w, b.h, 'sh muted', 'font-size:14px', '▶ ' + esc(t ? t[1] : 'embed'))); }
|
|
142
|
+
else if (e.type === 'link') { out.push(`<rect x="${x}" y="${y}" width="320" height="56" rx="12" fill="#fff" stroke="#cfcfca"/>`); out.push(fo(x + 14, y + 4, 292, 48, 'sh', 'font-size:15px;text-align:left;justify-content:flex-start', '↗ ' + esc(String(e.title || e.href || '').slice(0, 80)))); }
|
|
143
|
+
else if (e.type === 'table') { const t = b.t; out.push(fo(x, y, t.w + 2, t.h + 2, 'tb', '', `<table>${t.rows.map((r, n) => `<tr>${t.cols.map((c, k) => `<${n ? 'td' : 'th'} style="width:${t.widths[k]}px">${inline(r[c] == null ? '' : String(r[c]).split('\n')[0])}</${n ? 'td' : 'th'}>`).join('')}</tr>`).join('')}</table>`)); }
|
|
144
|
+
}
|
|
145
|
+
const side = (bx, s) => (s === 'top' ? [bx.x + bx.w / 2, bx.y] : s === 'bottom' ? [bx.x + bx.w / 2, bx.y + bx.h] : s === 'left' ? [bx.x, bx.y + bx.h / 2] : [bx.x + bx.w, bx.y + bx.h / 2]);
|
|
146
|
+
const end = (v, s, other) => { // an end of an arrow: a point, or the middle of a side of what it joins (the side facing the other end when none is named)
|
|
147
|
+
if (Array.isArray(v)) return { p: [num(v[0]), num(v[1])], s: '' };
|
|
148
|
+
const bx = box.get(v); if (!bx) return null; if (s) return { p: side(bx, s), s };
|
|
149
|
+
const o = other || [bx.x + bx.w + 100, bx.y], cx = bx.x + bx.w / 2, cy = bx.y + bx.h / 2, dx = o[0] - cx, dy = o[1] - cy;
|
|
150
|
+
const f = Math.abs(dx) * bx.h > Math.abs(dy) * bx.w ? (dx > 0 ? 'right' : 'left') : dy > 0 ? 'bottom' : 'top'; return { p: side(bx, f), s: f };
|
|
151
|
+
};
|
|
152
|
+
const centre = (v) => (Array.isArray(v) ? [num(v[0]), num(v[1])] : box.has(v) ? [box.get(v).x + box.get(v).w / 2, box.get(v).y + box.get(v).h / 2] : null);
|
|
153
|
+
for (const id of ids) {
|
|
154
|
+
const e = els.get(id); if (e.type !== 'arrow') continue;
|
|
155
|
+
const ca = centre(e.from), cb = centre(e.to); if (!ca || !cb) continue;
|
|
156
|
+
const a = end(e.from, e.fromSide, cb), z = end(e.to, e.toSide, ca); if (!a || !z) continue;
|
|
157
|
+
const [ax, ay] = a.p, [zx, zy] = z.p, flat = (s) => s === 'left' || s === 'right', pts = [[ax, ay]];
|
|
158
|
+
if (Math.abs(ax - zx) > 2 && Math.abs(ay - zy) > 2) { if (flat(a.s || 'right')) { const mx = (ax + zx) / 2; pts.push([mx, ay], [mx, zy]); } else { const my = (ay + zy) / 2; pts.push([ax, my], [zx, my]); } }
|
|
159
|
+
pts.push([zx, zy]);
|
|
160
|
+
const heads = Array.isArray(e.heads) ? e.heads : e.head === 'both' ? ['arrow', 'arrow'] : e.head === 'none' ? ['none', 'none'] : ['none', 'arrow'], col = inkOf(e.color);
|
|
161
|
+
out.push(`<polyline points="${pts.map((p) => p.join(',')).join(' ')}" fill="none" stroke="${col}" stroke-width="2.2"${e.dash ? ' stroke-dasharray="7 6"' : ''}${heads[1] === 'arrow' ? ' marker-end="url(#ah)"' : ''}${heads[0] === 'arrow' ? ' marker-start="url(#ahs)"' : ''}/>`);
|
|
162
|
+
if (e.label) { const m = pts[Math.floor((pts.length - 1) / 2)], n = pts[Math.floor((pts.length - 1) / 2) + 1] || m, lx = (m[0] + n[0]) / 2, ly = (m[1] + n[1]) / 2; out.push(fo(lx - 80, ly - 14, 160, 28, 'al', '', inline(String(e.label).split('\n')[0]))); }
|
|
163
|
+
}
|
|
164
|
+
const vb = [x0 - P, y0 - P, x1 - x0 + 2 * P, y1 - y0 + 2 * P].map((v) => Math.round(v));
|
|
165
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${vb.join(' ')}" preserveAspectRatio="xMidYMin meet"><defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M0,0L10,5L0,10z" fill="${INK.ink}"/></marker><marker id="ahs" viewBox="0 0 10 10" refX="1" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M10,0L0,5L10,10z" fill="${INK.ink}"/></marker></defs>${out.join('')}</svg>`;
|
|
166
|
+
return page('board', esc(meta.title || ''), svg);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ---- The Sheet: its sheets and cells as the edits left them, the values the reads gave the formulas, then the sheet edited last drawn as a grid.
|
|
170
|
+
const colNum = (s) => { let n = 0; for (const ch of String(s).toUpperCase()) n = n * 26 + ch.charCodeAt(0) - 64; return n; };
|
|
171
|
+
const colName = (n) => { let s = ''; for (; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + ((n - 1) % 26)) + s; return s; };
|
|
172
|
+
const addr = (a) => { const m = /^([A-Z]{1,3})(\d{1,7})$/i.exec(String(a || '').trim()); return m ? [+m[2], colNum(m[1])] : null; };
|
|
173
|
+
function rangeOf(rg, sh) { // "A1:C4", "B2", "3:4", "B:C" → [r0, c0, r1, c1], bounded by what the sheet holds
|
|
174
|
+
const s = String(rg || '').trim(), [p, q = p] = s.split(':'), MAXR = Math.max(sh.maxR, 1), MAXC = Math.max(sh.maxC, 1);
|
|
175
|
+
if (/^\d+$/.test(p) && /^\d+$/.test(q)) return [+p, 1, Math.min(+q, +p + 2000, R_MAX), Math.min(Math.max(MAXC + 5, 40), C_MAX)]; /* whole rows, whole columns: as far as the sheet holds anything, not the million rows of the Sheet */
|
|
176
|
+
if (/^[A-Z]+$/i.test(p) && /^[A-Z]+$/i.test(q)) return [1, colNum(p), Math.min(Math.max(MAXR + 50, 400), R_MAX), Math.min(colNum(q), colNum(p) + 60, C_MAX)];
|
|
177
|
+
const a = addr(p), b = addr(q) || a; if (!a) return null;
|
|
178
|
+
return [Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.min(Math.max(a[0], b[0]), a[0] + 2000), Math.min(Math.max(a[1], b[1]), a[1] + 60)];
|
|
179
|
+
}
|
|
180
|
+
const R_MAX = 2400, C_MAX = 240, inGrid = (r, c) => r >= 1 && c >= 1 && r <= R_MAX && c <= C_MAX; // the picture shows 400 rows and 40 columns: what lies far past them is not kept
|
|
181
|
+
function sheetState(ops) {
|
|
182
|
+
let budget = 400000; const spend = (n) => (budget -= n) > 0; // one budget for the whole replay (cells written, formatted, moved, fitted, read): records made to be slow cost their own picture only
|
|
183
|
+
const book = [], find = (n) => book.find((s) => s.name === n), mk = (name) => { const s = { name: String(name).slice(0, 100), cells: new Map(), fmt: new Map(), widths: new Map(), head: 0, maxR: 0, maxC: 0 }; book.push(s); return s; };
|
|
184
|
+
let last = null; mk('Sheet1').phantom = true; // a new Sheet starts with Sheet1; a Sheet made in another session is known only by the sheets its edits and reads name
|
|
185
|
+
const named = (n, make) => { if (typeof n !== 'string' || !n) return null; let s = find(n); if (!s && make && book.length < 200) s = mk(n); /* a workbook has 200 sheets at most */ if (s) s.phantom = false; return s; };
|
|
186
|
+
const shift = (s, at, n, rows) => { if (!spend(s.cells.size + s.fmt.size)) return; for (const m of [s.cells, s.fmt]) { const moved = new Map(); for (const [k, v] of m) { const [r, c] = k.split(',').map(Number), key = rows ? (r >= at ? `${r + n},${c}` : n < 0 && r >= at + n ? null : k) : c >= at ? `${r},${c + n}` : n < 0 && c >= at + n ? null : k; /* a delete: what lay in the deleted rows goes, what lay after moves up */ if (key) moved.set(key, v); } m.clear(); for (const [k, v] of moved) m.set(k, v); } };
|
|
187
|
+
for (const o of ops) {
|
|
188
|
+
if (o.op === 'read') { const v = o.value, rg = v && typeof v.range === 'string' ? addr(v.range.split(':')[0]) : null, s = rg && v.rows && typeof v.rows === 'object' ? named(v.sheet, true) : null; if (!s) continue;
|
|
189
|
+
for (const [rn, row] of Object.entries(v.rows).slice(0, 5000)) if (Array.isArray(row) && +rn > 0 && spend(row.length)) row.slice(0, 200).forEach((cell, k) => { const key = `${+rn},${rg[1] + k}`, mine = s.cells.get(key); if (cell == null || !inGrid(+rn, rg[1] + k)) return;
|
|
190
|
+
if (!s.cells.has(key)) { s.cells.set(key, cell); s.maxR = Math.max(s.maxR, +rn); s.maxC = Math.max(s.maxC, rg[1] + k); } /* what a read shows of cells this session did not write */
|
|
191
|
+
else if (typeof cell === 'object' && 'formula' in cell && typeof mine === 'string' && mine.trim().toUpperCase() === String(cell.formula).trim().toUpperCase()) s.cells.set(key, { formula: mine, value: cell.value }); });
|
|
192
|
+
continue; }
|
|
193
|
+
for (const e of o.i.payload.edits.slice(0, 64)) {
|
|
194
|
+
if (budget <= 0) break; if (!e || typeof e !== 'object') continue; const s = named(e.sheet, e.kind !== 'deleteSheet' && e.kind !== 'restoreSheet');
|
|
195
|
+
if (e.kind === 'renameSheet' && s && typeof e.name === 'string') { s.name = e.name.slice(0, 100); last = s; }
|
|
196
|
+
else if (e.kind === 'addSheet' && typeof e.name === 'string' && !find(e.name)) last = named(e.name, true) || last;
|
|
197
|
+
else if (e.kind === 'deleteSheet' && s) { book.splice(book.indexOf(s), 1); if (last === s) last = null; }
|
|
198
|
+
else if (e.kind === 'restoreSheet' && typeof e.sheet === 'string' && !find(e.name || e.sheet)) last = named(e.name || e.sheet, true) || last;
|
|
199
|
+
else if (e.kind === 'writeCells' && s && Array.isArray(e.rows)) { const a = addr(e.topLeft); if (!a) continue; last = s;
|
|
200
|
+
e.rows.slice(0, 5000).forEach((row, i) => Array.isArray(row) && spend(row.length) && row.slice(0, 200).forEach((v, k) => { const key = `${a[0] + i},${a[1] + k}`; if (!inGrid(a[0] + i, a[1] + k)) return; if (v == null) s.cells.delete(key); else { s.cells.set(key, v); s.maxR = Math.max(s.maxR, a[0] + i); s.maxC = Math.max(s.maxC, a[1] + k); } })); }
|
|
201
|
+
else if (e.kind === 'formatCells' && s && Array.isArray(e.ranges) && e.format) { last = s; const f = e.format, look = {}; if (f.font && typeof f.font.bold === 'boolean') look.b = f.font.bold; if (f.font && typeof f.font.italic === 'boolean') look.i = f.font.italic; if (f.fillColor && HEX.test(f.fillColor.hex || '')) look.fill = f.fillColor.hex; if (f.fillColor && f.fillColor.kind === 'none') look.fill = '';
|
|
202
|
+
if (Object.keys(look).length) for (const rg of e.ranges.slice(0, 40)) { const R = rangeOf(rg, s); if (R) for (let r = R[0]; r <= Math.min(R[2], R_MAX) && budget > 0; r++) for (let c = R[1]; c <= Math.min(R[3], C_MAX) && budget-- > 0; c++) s.fmt.set(`${r},${c}`, { ...(s.fmt.get(`${r},${c}`) || {}), ...look }); } }
|
|
203
|
+
else if (e.kind === 'setColumnWidths' && s && typeof e.columns === 'string') { const [p, q = p] = e.columns.split(':'); for (let c = colNum(p); c <= colNum(q) && c < colNum(p) + 200; c++) s.widths.set(c, Math.max(20, Math.min(800, num(e.widthInPixels, 104)))); }
|
|
204
|
+
else if (e.kind === 'fitColumns' && s && typeof e.columns === 'string') { const [p, q = p] = e.columns.split(':'); for (let c = colNum(p); c <= colNum(q) && c < colNum(p) + 200 && spend(s.maxR); c++) { let w = 40; for (let r = 1; r <= Math.min(s.maxR, 2000); r++) { const v = s.cells.get(`${r},${c}`); if (v != null && !(typeof v === 'string' && v.length > 60 && !s.cells.has(`${r},${c + 1}`))) w = Math.max(w, (typeof v === 'string' && v[0] === '=' ? 8 : cellText(v).t.length) * 7.4 + 18); /* a formula: what it comes to, most often a short number */ } s.widths.set(c, Math.min(360, Math.round(w))); } }
|
|
205
|
+
else if (e.kind === 'setCellTable' && s) s.head = e.cellTable && e.cellTable.headerRows ? +String(e.cellTable.headerRows).split(':').pop() || 0 : 0;
|
|
206
|
+
else if ((e.kind === 'insertRows' || e.kind === 'insertColumns') && s) { const n = Math.min(1000, num(e.count, 1)), at = e.kind === 'insertRows' ? num(e.besideRow) + (e.side === 'below' ? 1 : 0) : colNum(e.besideColumn) + (e.side === 'right' ? 1 : 0); shift(s, at, n, e.kind === 'insertRows'); if (e.kind === 'insertRows') s.maxR += n; else s.maxC += n; last = s; }
|
|
207
|
+
else if ((e.kind === 'deleteRows' || e.kind === 'deleteColumns') && s) { const [p, q = p] = String(e.rows || e.columns || '').split(':'), rows = e.kind === 'deleteRows', a = rows ? +p : colNum(p), b = rows ? +q : colNum(q); if (a > 0 && b >= a) { shift(s, b + 1, -(b - a + 1), rows); last = s; } }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const shown = book.filter((x) => !x.phantom);
|
|
211
|
+
return { book: shown, last: last && shown.includes(last) ? last : shown[0] || null };
|
|
212
|
+
}
|
|
213
|
+
function cellText(v) { // what a cell shows, as far as the session knows it: a formula it never read shows as written
|
|
214
|
+
if (v == null) return { t: '' };
|
|
215
|
+
if (typeof v === 'number') return { t: v.toLocaleString('en-US', { maximumFractionDigits: 6 }), n: 1 };
|
|
216
|
+
if (typeof v === 'boolean') return { t: v ? '☑' : '☐', c: 1 };
|
|
217
|
+
if (typeof v === 'string') { if (/^=/.test(v)) return { t: v, f: 1 }; if (/^'/.test(v)) return { t: v.slice(1) }; return /^[-+]?[\d,]*\.?\d+%?$|^[$€£]\s?[\d,.]+$/.test(v.trim()) ? { t: v, n: 1 } : /^\d{1,2}:\d{2}(:\d{2})?(\s?[AP]M)?$/i.test(v.trim()) ? { t: v, n: 1 } : { t: v }; }
|
|
218
|
+
if (Array.isArray(v)) return { t: v.map((x) => (x && x.name) || '').join(', ') };
|
|
219
|
+
if (typeof v === 'object') {
|
|
220
|
+
if ('formula' in v) { const r = cellText(v.value); return r.t === '' && v.value == null ? { t: String(v.formula), f: 1 } : r; }
|
|
221
|
+
if ('error' in v) return { t: String(v.error), c: 1 };
|
|
222
|
+
if ('shown' in v) return { t: String(v.shown), n: 1 }; if ('date' in v) return { t: String(v.date), n: 1 }; if ('time' in v) return { t: String(v.time).replace(/:00$/, ''), n: 1 }; if ('dateTime' in v) return { t: String(v.dateTime).replace('T', ' ').replace(/:00$/, ''), n: 1 };
|
|
223
|
+
if ('markdown' in v) return { t: String(v.markdown).replace(/\*\*|~~|<\/?u>|\\/g, '').replace(/(^|[^*])\*([^*]+)\*/g, '$1$2').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') };
|
|
224
|
+
if ('name' in v) return { t: String(v.name) };
|
|
225
|
+
}
|
|
226
|
+
return { t: '' };
|
|
227
|
+
}
|
|
228
|
+
function drawSheet(st) {
|
|
229
|
+
const s = st.last; if (!s) return null; // no sheet any edit named: no picture (the call shows the artifact's card)
|
|
230
|
+
const R = Math.min(Math.max(s.maxR, 12), 400), C = Math.min(Math.max(s.maxC, 6), 40), head = [`<tr><th class="corner"></th>${Array.from({ length: C }, (_, k) => `<th style="width:${s.widths.get(k + 1) || 104}px">${colName(k + 1)}</th>`).join('')}</tr>`];
|
|
231
|
+
for (let r = 1; r <= R; r++) {
|
|
232
|
+
const tds = []; for (let c = 1; c <= C; c++) { const v = cellText(s.cells.get(`${r},${c}`)); let span = 1; if (v.t && !v.n && !v.c) while (c + span <= C && span < 16 && !s.cells.has(`${r},${c + span}`) && v.t.length * 7.2 > Array.from({ length: span }, (_, k) => s.widths.get(c + k) || 104).reduce((x, y) => x + y, 0)) span++; /* text runs on over the empty cells beside it, as in the Sheet */
|
|
233
|
+
const f = s.fmt.get(`${r},${c}`) || {}, cls = [v.n ? 'n' : '', v.c ? 'c' : '', v.f ? 'f' : '', r === s.head ? 'h' : ''].filter(Boolean).join(' '), sty = (f.fill ? `background:${f.fill};` : '') + (f.b ? 'font-weight:700;' : '') + (f.i ? 'font-style:italic;' : '');
|
|
234
|
+
tds.push(`<td${span > 1 ? ` colspan="${span}"` : ''}${cls ? ` class="${cls}"` : ''}${sty ? ` style="${sty}"` : ''}>${esc(v.t.slice(0, 400))}</td>`); c += span - 1; }
|
|
235
|
+
head.push(`<tr><th>${r}</th>${tds.join('')}</tr>`);
|
|
236
|
+
}
|
|
237
|
+
const tabs = st.book.slice(0, 30).map((x) => `<span class="${x === s ? 'on' : ''}">${esc(x.name)}</span>`).join('');
|
|
238
|
+
const tw = 38 + Array.from({ length: C }, (_, k) => s.widths.get(k + 1) || 104).reduce((x, y) => x + y, 0);
|
|
239
|
+
return page('sheet', '', `<div class="grid"><table style="width:${tw}px">${head.join('')}</table></div><div class="tabs">${tabs}</div>`);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const STYLE = {
|
|
243
|
+
board: 'html,body{margin:0;background:#fbfbf8;font:15px/1.35 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1f1f22}svg{display:block;width:100%;height:auto;max-height:100vh}.sh{height:100%;display:flex;flex-direction:column;justify-content:center;overflow:hidden;line-height:1.3}.sh>div{width:100%}.tx{line-height:1.4}.ct{font-weight:600;font-size:16px;color:#55554f;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.al{font-size:13px;text-align:center;background:#fbfbf8;border-radius:6px}.muted{color:#8a8a84}.li{padding-left:2px}code{font:13px ui-monospace,Menlo,monospace;background:rgba(0,0,0,.06);padding:0 3px;border-radius:3px}.tb table{border-collapse:collapse;background:#fff;font-size:14px}.tb th,.tb td{border:1px solid #deded8;padding:6px 10px;text-align:left;height:21px;overflow:hidden;white-space:nowrap}.tb th{background:#f1f1ed}.empty{padding:80px;text-align:center;color:#8a8a84}',
|
|
244
|
+
sheet: 'html,body{margin:0;height:100%;background:#fff;font:13px/1.2 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1f1f22}body{display:flex;flex-direction:column}.grid{flex:1;overflow:auto}table{border-collapse:collapse;table-layout:fixed}th,td{border:1px solid #e3e3e0;height:27px;padding:0 6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:800px}th{background:#f6f6f4;color:#77776f;font-weight:500;position:sticky;top:0;z-index:1}th.corner{width:38px}tr th:first-child{position:sticky;left:0;text-align:center;z-index:2}th.corner{z-index:3}td.n{text-align:right;font-variant-numeric:tabular-nums}td.c{text-align:center}td.f{color:#8a8a84;font-style:italic}td.h{font-weight:600}.tabs{display:flex;gap:2px;padding:6px 8px 8px;background:#f6f6f4;border-top:1px solid #e3e3e0}.tabs span{padding:5px 12px;border-radius:6px;color:#66665f}.tabs span.on{background:#fff;color:#1f1f22;font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.12)}.empty{padding:80px;text-align:center;color:#8a8a84}',
|
|
245
|
+
};
|
|
246
|
+
const page = (kind, title, body) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${title ? `<title>${title}</title>` : ''}<style>${STYLE[kind]}</style>${body}`;
|
|
247
|
+
|
|
248
|
+
// The picture of the board or the Sheet as the write toolId left it, or null (not such a write, refused, or not answered yet).
|
|
249
|
+
function livePage(file, toolId) {
|
|
250
|
+
let size = 0; try { size = fs.statSync(file).size; } catch { return null; }
|
|
251
|
+
const key = file + '|' + toolId, hit = memo.get(key); if (hit && hit.size === size) return hit.page;
|
|
252
|
+
let html = null; const got = collect(file, toolId);
|
|
253
|
+
try { html = got ? (got.kind === 'board' ? drawBoard(boardStore(got.ops.filter((o) => o.op === 'write'))) : drawSheet(sheetState(got.ops))) : null; } catch { html = null; } // records too odd to draw cost that picture only
|
|
254
|
+
const out = html ? { html, net: false } : null;
|
|
255
|
+
memo.delete(key); memo.set(key, { size, page: out }); if (memo.size > 24) memo.delete(memo.keys().next().value);
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
module.exports = { liveCall, livePage, _draw: { board: (ops) => drawBoard(boardStore(ops)), sheet: (ops) => drawSheet(sheetState(ops)) } };
|
package/codex.js
CHANGED
|
@@ -388,4 +388,5 @@ function image(id, toolId, n, user, agent = 'main') { // { type, buf } or null
|
|
|
388
388
|
imgMemo.set(key, out); if (imgMemo.size > 12) imgMemo.delete(imgMemo.keys().next().value);
|
|
389
389
|
return out;
|
|
390
390
|
}
|
|
391
|
-
|
|
391
|
+
const zPending = () => zBusy || zQueue.length > 0; // compressed threads still being read in the background (the day report waits for them)
|
|
392
|
+
module.exports = { zPending, PROJ, SOURCE, home, dirKey, sessions, row, fileOf, cwd, inProject, projectLabel, title, boardRow, subFiles, subCount, state, parser, image };
|
package/kokoro-worker.js
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
// writes a 16-bit WAV to `out` and answers { id, ok, seconds } or { id, ok: false, error }. Started by kokoro.js.
|
|
4
4
|
const fs = require('fs'), path = require('path'), readline = require('readline'), { createRequire } = require('module'), { pathToFileURL } = require('url');
|
|
5
5
|
const MODEL = 'onnx-community/Kokoro-82M-v1.0-ONNX';
|
|
6
|
+
// Chinese is another model of the same family, Kokoro-82M-v1.1-zh, in full precision: on an M1 Pro the 8-bit file was twice as slow, and the half-precision one returned silence (NaN) for most voices.
|
|
7
|
+
// kokoro.js puts its files, checked, where transformers.js keeps what it downloads, so loading it here reads them from disk. Its phonemes come from zh-g2p.js, its voices from <dir>/zh-voices.
|
|
8
|
+
const ZH_MODEL = 'onnx-community/Kokoro-82M-v1.1-zh-ONNX', ZH_DTYPE = 'fp32';
|
|
6
9
|
const send = (o) => fs.writeSync(1, JSON.stringify(o) + '\n');
|
|
7
10
|
const finite = (samples) => { for (let i = 0; i < samples.length; i++) if (samples[i] !== samples[i]) return false; return true; }; // a quantised model can return NaN for a whole line, which would be written as silence
|
|
8
11
|
function wav(samples, rate) { // Float32 in [-1, 1] → 16-bit mono WAV
|
|
@@ -15,7 +18,7 @@ const FILE = { q8: 'model_quantized', q4: 'model_q4', fp32: 'model', fp16: 'mode
|
|
|
15
18
|
// The model takes 510 phonemes per call (about 480 letters of plain English, 300 when the line is full of numbers) and kokoro-js cuts the rest without a word:
|
|
16
19
|
// a line that does not fit is made in parts and joined. LONG is what the tokenizer throws instead of cutting (see main).
|
|
17
20
|
const LONG = new Error('too long for one call'), QUIET = 0.003;
|
|
18
|
-
const CUTS = [[/[.!?…]+["'”’»)\]]*\s+(?![\sa-zà-ÿ])|\s*\n\s*/g, 0.45], [/[,;:—–]\s
|
|
21
|
+
const CUTS = [[/[.!?…]+["'”’»)\]]*\s+(?![\sa-zà-ÿ])|\s*\n\s*|[。!?]+[”’」』)]*\s*/g, 0.45], [/[,;:—–]\s+|[,、;:]\s*/g, 0.2], [/\s+/g, 0.05]]; // where a line may be cut, best first, each with the pause it gets in seconds at speed 1: the end of a sentence, a comma, a space (Chinese marks need no space after them)
|
|
19
22
|
function halve(s) { // two parts at the cut nearest the middle, so no part is a stray word; a text with no space at all is cut in the middle
|
|
20
23
|
for (const [re, gap] of CUTS) { let at = 0; for (const m of s.matchAll(re)) { const i = m.index + m[0].length; if (i < s.length && Math.abs(i - s.length / 2) < Math.abs(at - s.length / 2)) at = i; } if (at) return [s.slice(0, at), s.slice(at), gap]; }
|
|
21
24
|
const at = Math.ceil(s.length / 2); return [s.slice(0, at), s.slice(at), 0];
|
|
@@ -59,13 +62,17 @@ async function main() {
|
|
|
59
62
|
for (const ext of ['.onnx', '.onnx_data']) { try { fs.unlinkSync(path.join(onnx, name + ext)); dropped++; } catch {} }
|
|
60
63
|
if (!dropped) throw e; console.error('kokoro: the ' + dtype + ' model could not be loaded (' + String((e && e.message) || e).slice(0, 80) + '); fetching it again'); tts = await load();
|
|
61
64
|
}
|
|
62
|
-
const tok =
|
|
63
|
-
|
|
64
|
-
const packs = new Map(), pack = (n) => { if (!packs.has(n)) { const b = fs.readFileSync(path.join(dir, 'node_modules', 'kokoro-js', 'voices', n + '.bin')); packs.set(n, new Float32Array(b.buffer.slice(b.byteOffset, b.byteOffset + b.length))); } return packs.get(n); }; // a voice: 510 styles of 256 numbers, one per length of line. All 54 come with kokoro-js
|
|
65
|
+
const strict = (m) => { const tok = m.tokenizer; if (tok) m.tokenizer = (t, o) => { const r = tok(t, { ...o, truncation: false }); if (r.input_ids.dims.at(-1) > (tok.model_max_length || 512)) throw LONG; return r; }; return m; };
|
|
66
|
+
strict(tts); // kokoro-js calls the tokenizer with truncation on, which drops every phoneme past the model's limit and says nothing: count them all here and refuse instead
|
|
67
|
+
const packs = new Map(), pack = (n) => { if (!packs.has(n)) { const b = fs.readFileSync(/^z[fm]_/.test(n) ? path.join(dir, 'zh-voices', n + '.bin') : path.join(dir, 'node_modules', 'kokoro-js', 'voices', n + '.bin')); packs.set(n, new Float32Array(b.buffer.slice(b.byteOffset, b.byteOffset + b.length))); } return packs.get(n); }; // a voice: 510 styles of 256 numbers, one per length of line. All 54 of v1.0 come with kokoro-js; the Chinese ones are fetched by kokoro.js
|
|
68
|
+
let zh = null; // the Chinese model and its phonemizer, loaded on the first Chinese line: whoever never hears one never loads them
|
|
69
|
+
const zhLoad = async () => zh || (zh = { tts: strict(await KokoroTTS.from_pretrained(ZH_MODEL, { dtype: ZH_DTYPE, device: 'cpu' })), g2p: require(path.join(__dirname, 'zh-g2p.js')).make(req('pinyin-pro'), req('jieba-wasm'), req('opencc-js').Converter({ from: 'tw', to: 'cn' })) });
|
|
65
70
|
const foreign = async (text, o) => { // what kokoro-js' generate_from_ids does, with a style that can be a mix of several voices (o.mix: [[voice, share], …])
|
|
66
|
-
const
|
|
71
|
+
const z = o.lang === 'zh' ? await zhLoad() : null, m = z ? z.tts : tts; // Chinese: its own model; an English word inside the line is said from its English phonemes
|
|
72
|
+
const ph = z ? await z.g2p(text, (w) => phonemes(dir, w, 'en-us')) : await phonemes(dir, text, o.lang);
|
|
73
|
+
const { input_ids } = m.tokenizer(ph, { truncation: true }), at = 256 * Math.min(Math.max(input_ids.dims.at(-1) - 2, 0), 509), style = new Float32Array(256);
|
|
67
74
|
for (const [name, share] of o.mix) { const v = pack(name); for (let i = 0; i < 256; i++) style[i] += share * v[at + i]; }
|
|
68
|
-
const { waveform } = await
|
|
75
|
+
const { waveform } = await m.model({ input_ids, style: new tf.Tensor('float32', style, [1, 256]), speed: new tf.Tensor('float32', [o.speed], [1]) });
|
|
69
76
|
return { audio: waveform.data, sampling_rate: 24000 };
|
|
70
77
|
};
|
|
71
78
|
const say = (text, o) => (o.lang ? foreign(text, o) : tts.generate(text, { voice: o.voice, speed: o.speed }));
|