thuthi-plugin 0.0.0-stage → 0.1.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.
Files changed (115) hide show
  1. package/.claude-plugin/marketplace.json +55 -0
  2. package/README.md +13 -2
  3. package/bin/parallel-browser.js +109 -0
  4. package/extension/background.js +1329 -0
  5. package/extension/config.json +1 -0
  6. package/extension/guard.js +44 -0
  7. package/extension/manifest.json +10 -0
  8. package/extension/overlay.js +104 -0
  9. package/extension/popup.html +34 -0
  10. package/extension/popup.js +39 -0
  11. package/extension-reloader/manifest.json +13 -0
  12. package/extension-reloader/sw.js +17 -0
  13. package/package.json +13 -4
  14. package/plugins/thuthi/.claude-plugin/plugin.json +8 -0
  15. package/plugins/thuthi/context.md +3 -0
  16. package/plugins/thuthi/hooks/hooks.json +15 -0
  17. package/plugins/thuthi/skills/setup/SKILL.md +55 -0
  18. package/plugins/thuthi/skills/setup/scripts/doctor.py +249 -0
  19. package/plugins/thuthi/skills/setup/scripts/selftest.py +188 -0
  20. package/plugins/thuthi/tools/claude-switch/claude_switch.py +8 -0
  21. package/plugins/thuthi/tools/legacy_launcher.py +65 -0
  22. package/plugins/thuthi/tools/statusline/statusline.py +8 -0
  23. package/plugins/thuthi-accounts/.claude-plugin/plugin.json +9 -0
  24. package/plugins/thuthi-accounts/bin/claude-switch +5 -0
  25. package/plugins/thuthi-accounts/bin/claude-switch.cmd +4 -0
  26. package/plugins/thuthi-accounts/hooks/hooks.json +15 -0
  27. package/plugins/thuthi-accounts/lib/tls.py +68 -0
  28. package/plugins/thuthi-accounts/lib/usage_store.py +150 -0
  29. package/plugins/thuthi-accounts/setup_check.py +21 -0
  30. package/plugins/thuthi-accounts/skills/claude-switch/SKILL.md +48 -0
  31. package/plugins/thuthi-accounts/tools/claude-switch/claude-switch-tui.py +397 -0
  32. package/plugins/thuthi-accounts/tools/claude-switch/claude_switch.py +1204 -0
  33. package/plugins/thuthi-accounts/tools/claude-switch/credstore.py +417 -0
  34. package/plugins/thuthi-accounts/tools/claude-switch/install.py +301 -0
  35. package/plugins/thuthi-accounts/tools/claude-switch/tests/selftest.py +491 -0
  36. package/plugins/thuthi-accounts/tools/statusline/statusline.py +212 -0
  37. package/plugins/thuthi-agenda-picker/.claude-plugin/plugin.json +9 -0
  38. package/plugins/thuthi-agenda-picker/context.md +3 -0
  39. package/plugins/thuthi-agenda-picker/hooks/hooks.json +15 -0
  40. package/plugins/thuthi-agenda-picker/lib/pbpage.py +397 -0
  41. package/plugins/thuthi-agenda-picker/setup_check.py +18 -0
  42. package/plugins/thuthi-agenda-picker/skills/agenda-picker/SKILL.md +280 -0
  43. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/design-rules.md +110 -0
  44. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/diagram/base.css +33 -0
  45. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/agenda.json +146 -0
  46. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-dark.svg +5 -0
  47. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/A-light.svg +5 -0
  48. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-dark.svg +5 -0
  49. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/B-light.svg +5 -0
  50. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-dark.svg +5 -0
  51. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/C-light.svg +5 -0
  52. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/base.css +33 -0
  53. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/name-B.html +15 -0
  54. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-dark.svg +5 -0
  55. package/plugins/thuthi-agenda-picker/skills/agenda-picker/references/example/shots/now-light.svg +5 -0
  56. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/picker.py +1286 -0
  57. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/selftest.py +771 -0
  58. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/shot.py +117 -0
  59. package/plugins/thuthi-agenda-picker/skills/agenda-picker/scripts/template.html +1029 -0
  60. package/plugins/thuthi-arch-diagram/.claude-plugin/plugin.json +9 -0
  61. package/plugins/thuthi-arch-diagram/lib/pbpage.py +397 -0
  62. package/plugins/thuthi-arch-diagram/lib/tls.py +68 -0
  63. package/plugins/thuthi-arch-diagram/setup_check.py +10 -0
  64. package/plugins/thuthi-arch-diagram/skills/arch-diagram/SKILL.md +125 -0
  65. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/design-rules.md +110 -0
  66. package/plugins/thuthi-arch-diagram/skills/arch-diagram/references/example-shop.py +167 -0
  67. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/check.py +194 -0
  68. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/diagramkit.py +682 -0
  69. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/interact_test.py +115 -0
  70. package/plugins/thuthi-arch-diagram/skills/arch-diagram/scripts/render.py +113 -0
  71. package/plugins/thuthi-browser/.claude-plugin/plugin.json +9 -0
  72. package/plugins/thuthi-browser/context.md +3 -0
  73. package/plugins/thuthi-browser/hooks/hooks.json +15 -0
  74. package/plugins/thuthi-browser/lib/pbpage.py +397 -0
  75. package/plugins/thuthi-browser/setup_check.py +93 -0
  76. package/plugins/thuthi-browser/skills/parallel-browser/SKILL.md +271 -0
  77. package/plugins/thuthi-browser/skills/parallel-browser/references/api.md +243 -0
  78. package/plugins/thuthi-browser/skills/parallel-browser/references/install.md +106 -0
  79. package/plugins/thuthi-demo-video/.claude-plugin/plugin.json +9 -0
  80. package/plugins/thuthi-demo-video/lib/pbpage.py +397 -0
  81. package/plugins/thuthi-demo-video/setup_check.py +14 -0
  82. package/plugins/thuthi-demo-video/skills/demo-video/SKILL.md +261 -0
  83. package/plugins/thuthi-demo-video/skills/demo-video/scripts/caption.html +16 -0
  84. package/plugins/thuthi-demo-video/skills/demo-video/scripts/cursor.js +132 -0
  85. package/plugins/thuthi-demo-video/skills/demo-video/scripts/demo_video.py +2416 -0
  86. package/plugins/thuthi-demo-video/skills/demo-video/scripts/example_scenario.py +97 -0
  87. package/plugins/thuthi-demo-video/skills/demo-video/scripts/frame.html +95 -0
  88. package/plugins/thuthi-demo-video/skills/demo-video/scripts/overlay.js +129 -0
  89. package/plugins/thuthi-demo-video/skills/demo-video/scripts/title.html +30 -0
  90. package/plugins/thuthi-no-more-slop/.claude-plugin/plugin.json +9 -0
  91. package/plugins/thuthi-no-more-slop/setup_check.py +10 -0
  92. package/plugins/thuthi-no-more-slop/skills/no-more-slop/LICENSE +21 -0
  93. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SKILL.md +235 -0
  94. package/plugins/thuthi-no-more-slop/skills/no-more-slop/SOURCE.txt +1 -0
  95. package/plugins/thuthi-no-more-slop/skills/no-more-slop/agents/openai.yaml +6 -0
  96. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/examples.md +289 -0
  97. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/tokens.md +46 -0
  98. package/plugins/thuthi-no-more-slop/skills/no-more-slop/references/unslop-fallback.md +36 -0
  99. package/plugins/thuthi-no-more-slop/skills/no-more-slop/scripts/count_tells.py +426 -0
  100. package/plugins/thuthi-orca/.claude-plugin/plugin.json +9 -0
  101. package/plugins/thuthi-orca/context.md +5 -0
  102. package/plugins/thuthi-orca/hooks/hooks.json +18 -0
  103. package/plugins/thuthi-orca/hooks/orca-team-grid.ts +21 -0
  104. package/plugins/thuthi-orca/setup_check.py +12 -0
  105. package/plugins/thuthi-orca/skills/orca-new-work/SKILL.md +492 -0
  106. package/plugins/thuthi-orca/tools/orca-team-grid/bin/tmux +338 -0
  107. package/plugins/thuthi-orca/tools/orca-team-grid/tests/selftest.py +299 -0
  108. package/runtime/client.js +69 -0
  109. package/runtime/daemon.js +503 -0
  110. package/runtime/focus-monitor.js +53 -0
  111. package/runtime/keys.js +86 -0
  112. package/runtime/owner.js +64 -0
  113. package/runtime/recorder.js +267 -0
  114. package/runtime/relay.js +95 -0
  115. package/runtime/session.js +1599 -0
@@ -0,0 +1,86 @@
1
+ // Keyboard helpers for Input.dispatchKeyEvent.
2
+ // Modifiers bitmask (CDP): Alt=1, Control=2, Meta=4, Shift=8
3
+
4
+ const KEYS = {
5
+ Enter: { code: 'Enter', keyCode: 13, text: '\r' },
6
+ Tab: { code: 'Tab', keyCode: 9 },
7
+ Escape: { code: 'Escape', keyCode: 27 },
8
+ Backspace: { code: 'Backspace', keyCode: 8 },
9
+ Delete: { code: 'Delete', keyCode: 46 },
10
+ Space: { code: 'Space', keyCode: 32, key: ' ', text: ' ' },
11
+ ArrowUp: { code: 'ArrowUp', keyCode: 38 },
12
+ ArrowDown: { code: 'ArrowDown', keyCode: 40 },
13
+ ArrowLeft: { code: 'ArrowLeft', keyCode: 37 },
14
+ ArrowRight: { code: 'ArrowRight', keyCode: 39 },
15
+ Home: { code: 'Home', keyCode: 36 },
16
+ End: { code: 'End', keyCode: 35 },
17
+ PageUp: { code: 'PageUp', keyCode: 33 },
18
+ PageDown: { code: 'PageDown', keyCode: 34 },
19
+ F1: { code: 'F1', keyCode: 112 }, F2: { code: 'F2', keyCode: 113 }, F3: { code: 'F3', keyCode: 114 }, F4: { code: 'F4', keyCode: 115 },
20
+ F5: { code: 'F5', keyCode: 116 }, F6: { code: 'F6', keyCode: 117 }, F7: { code: 'F7', keyCode: 118 }, F8: { code: 'F8', keyCode: 119 },
21
+ F9: { code: 'F9', keyCode: 120 }, F10: { code: 'F10', keyCode: 121 }, F11: { code: 'F11', keyCode: 122 }, F12: { code: 'F12', keyCode: 123 },
22
+ // Modifiers are also keys in their own right: keyboard.down('Shift') holds Shift.
23
+ Shift: { code: 'ShiftLeft', keyCode: 16, self: 8 },
24
+ Control: { code: 'ControlLeft', keyCode: 17, self: 2 },
25
+ Alt: { code: 'AltLeft', keyCode: 18, self: 1 },
26
+ Meta: { code: 'MetaLeft', keyCode: 91, self: 4 },
27
+ Command: { code: 'MetaLeft', keyCode: 91, key: 'Meta', self: 4 },
28
+ ControlOrMeta: { code: 'ControlLeft', keyCode: 17, key: 'Control', self: 2, mac: { code: 'MetaLeft', keyCode: 91, key: 'Meta', self: 4 } },
29
+ };
30
+
31
+ const MOD = { Alt: 1, Control: 2, Ctrl: 2, Meta: 4, Command: 4, Cmd: 4, Shift: 8 };
32
+
33
+ // On macOS the browser does not turn Cmd+key into editing actions by itself when the event
34
+ // arrives over CDP; the matching editing command has to be passed explicitly.
35
+ const MAC_EDITING = {
36
+ 'Meta+a': ['selectAll'], 'Meta+c': ['copy'], 'Meta+v': ['paste'], 'Meta+x': ['cut'], 'Meta+z': ['undo'], 'Meta+Shift+z': ['redo'],
37
+ 'Meta+ArrowLeft': ['moveToBeginningOfLine'], 'Meta+ArrowRight': ['moveToEndOfLine'],
38
+ 'Meta+Shift+ArrowLeft': ['moveToBeginningOfLineAndModifySelection'], 'Meta+Shift+ArrowRight': ['moveToEndOfLineAndModifySelection'],
39
+ 'Meta+ArrowUp': ['moveToBeginningOfDocument'], 'Meta+ArrowDown': ['moveToEndOfDocument'],
40
+ 'Meta+Backspace': ['deleteToBeginningOfLine'], 'Alt+Backspace': ['deleteWordBackward'], 'Alt+Delete': ['deleteWordForward'],
41
+ 'Alt+ArrowLeft': ['moveWordLeft'], 'Alt+ArrowRight': ['moveWordRight'],
42
+ 'Alt+Shift+ArrowLeft': ['moveWordLeftAndModifySelection'], 'Alt+Shift+ArrowRight': ['moveWordRightAndModifySelection'],
43
+ };
44
+
45
+ /** "ControlOrMeta+a" → { key, code, keyCode, text, modifiers, commands } */
46
+ export function parseKey(combo, platform = process.platform) {
47
+ const k = parseKeyInner(combo, platform);
48
+ if (platform === 'darwin') {
49
+ const names = [];
50
+ if (k.modifiers & MOD.Meta) names.push('Meta');
51
+ if (k.modifiers & MOD.Alt) names.push('Alt');
52
+ if (k.modifiers & MOD.Shift) names.push('Shift');
53
+ const sig = [...names, k.key.length === 1 ? k.key.toLowerCase() : k.key].join('+');
54
+ if (MAC_EDITING[sig]) k.commands = MAC_EDITING[sig];
55
+ }
56
+ return k;
57
+ }
58
+
59
+ function parseKeyInner(combo, platform) {
60
+ const parts = combo.split('+').map((p) => p.trim()).filter(Boolean);
61
+ const keyPart = parts.pop();
62
+ let modifiers = 0;
63
+ for (const m of parts) {
64
+ if (m === 'ControlOrMeta') modifiers |= platform === 'darwin' ? MOD.Meta : MOD.Control;
65
+ else if (MOD[m] !== undefined) modifiers |= MOD[m];
66
+ else throw new Error(`unknown modifier ${m}`);
67
+ }
68
+ if (KEYS[keyPart]) {
69
+ const k = platform === 'darwin' && KEYS[keyPart].mac ? { ...KEYS[keyPart], ...KEYS[keyPart].mac } : KEYS[keyPart];
70
+ // Holding a modifier reports itself as held, which is what the page expects.
71
+ if (k.self) modifiers |= k.self;
72
+ return { key: k.key || keyPart, code: k.code, keyCode: k.keyCode, text: k.text, modifiers };
73
+ }
74
+ if (keyPart.length === 1) {
75
+ const ch = keyPart;
76
+ const upper = ch.toUpperCase();
77
+ const isLetter = /[a-z]/i.test(ch);
78
+ const isDigit = /[0-9]/.test(ch);
79
+ const code = isLetter ? `Key${upper}` : isDigit ? `Digit${ch}` : undefined;
80
+ const keyCode = isLetter || isDigit ? upper.charCodeAt(0) : ch.charCodeAt(0);
81
+ // with Control/Meta held, no text is inserted
82
+ const text = modifiers & (MOD.Control | MOD.Meta) ? undefined : ch;
83
+ return { key: modifiers & MOD.Shift && isLetter ? upper : ch, code, keyCode, text, modifiers };
84
+ }
85
+ throw new Error(`unknown key ${keyPart}`);
86
+ }
@@ -0,0 +1,64 @@
1
+ // Who a session belongs to: the long-lived process whose exit should close it. Agents forget
2
+ // close(), and an agent that is killed or crashes never gets to call it, so the daemon watches
3
+ // this process instead and closes the session once it is gone.
4
+ //
5
+ // The CLI itself is no owner: every `parallel-browser nodejs` is a fresh process that exits in
6
+ // seconds while the session is meant to outlive it. The owner is whatever ran the shell that ran
7
+ // the CLI — the agent, in practice (Claude Code: node → zsh → claude).
8
+ import { execFileSync } from 'node:child_process';
9
+ import { basename } from 'node:path';
10
+
11
+ // Where a person types. A shell sitting directly under one of these was started by a human in a
12
+ // terminal, not by an agent, and nothing should close their session when the terminal app quits.
13
+ const TERMINAL_HOSTS = /^(-?(login|sshd|tmux.*|screen|launchd|init|systemd)|Terminal|iTerm2|thuminald|ghostty|kitty|alacritty|wezterm-gui|xterm|gnome-terminal.*|konsole|(Code|Cursor) Helper.*)$/i;
14
+
15
+ /**
16
+ * A pid, or null when `v` names none. Throws on garbage. There is no "leave it unwatched" any
17
+ * more: `false` / `none` / `off` (what keepOpen() and pbpage's keep=True used to pass) say nothing,
18
+ * so the next rule picks the owner.
19
+ */
20
+ export function parseOwner(v, what = 'owner') {
21
+ if (v === undefined || v === null || v === '' || v === false || /^(false|none|0|off)$/i.test(String(v))) return null;
22
+ const pid = Number(v);
23
+ if (!Number.isInteger(pid) || pid <= 1) throw new Error(`${what} must be a process id (an integer > 1), got ${JSON.stringify(v)}`);
24
+ return pid;
25
+ }
26
+
27
+ /**
28
+ * The owner to register for a session, most specific first:
29
+ * 1. `explicit` session(label, { owner }) — a pid
30
+ * 2. PB_OWNER_PID set by whatever spawns the CLI (pbpage.py sets its own pid)
31
+ * 3. CLAUDE_PID Claude Code puts its own pid in every shell it runs (skipped when that process is gone)
32
+ * 4. the shell's parent any other agent that runs commands through a shell
33
+ * null when none applies (run by hand in a terminal, or no `ps` on this platform): unwatched,
34
+ * exactly as before owners existed.
35
+ */
36
+ export function resolveOwner(explicit, env = process.env) {
37
+ const fromOpt = parseOwner(explicit);
38
+ if (fromOpt !== null) return fromOpt;
39
+ const fromEnv = parseOwner(env.PB_OWNER_PID, 'PB_OWNER_PID');
40
+ if (fromEnv !== null) return fromEnv;
41
+ // CLAUDE_PID is inherited, so a server started from a Claude session keeps the pid long after
42
+ // that session ended, and every session it opened was "orphaned" the moment it was made
43
+ // (2026-11: worky, 778 sessions in four days, each closed a minute after it was created and
44
+ // opened again). A dead one names nobody.
45
+ const claude = parseOwner(env.CLAUDE_PID, 'CLAUDE_PID');
46
+ if (claude !== null && isAlive(claude)) return claude;
47
+ return shellParent();
48
+ }
49
+
50
+ function shellParent() {
51
+ if (process.platform === 'win32') return null;
52
+ try {
53
+ const ps = (pid, field) => execFileSync('ps', ['-o', `${field}=`, '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }).trim();
54
+ const pid = Number(ps(process.ppid, 'ppid'));
55
+ if (!Number.isInteger(pid) || pid <= 1) return null;
56
+ if (TERMINAL_HOSTS.test(basename(ps(pid, 'comm')))) return null;
57
+ return pid;
58
+ } catch { return null; }
59
+ }
60
+
61
+ /** Alive unless the OS says there is no such process. EPERM (a sandbox, another user) counts as alive: guessing wrong must never close a session. */
62
+ export function isAlive(pid) {
63
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
64
+ }
@@ -0,0 +1,267 @@
1
+ // Records a session tab: Page.startScreencast frames go straight into one ffmpeg that encodes while
2
+ // the page is being filmed. Nothing but the video is on disk.
3
+ //
4
+ // It used to keep every JPEG until the recording was stopped and encode then (2026-11-24: six
5
+ // parallel runs, 200,000 files and 14 GB per 47 minutes, minutes of encoding behind a 120 s timeout,
6
+ // two videos cut short by cleaning up frame folders still being read). Measured 2026-11-25, three
7
+ // minutes at 1280×800: 516 MB of frames against 26 MB for the video alone, 5.6 s to stop against 0.1 s.
8
+ //
9
+ // The browser sends a frame for every paint — a spinner alone is the display rate — and none while
10
+ // the page sits still. At most `fps` a second are kept; the picture holds through a still stretch
11
+ // because every frame carries the time it arrived.
12
+ import { mkdir, writeFile, rm, rmdir, stat } from 'node:fs/promises';
13
+ import { dirname, join } from 'node:path';
14
+ import { execFile, spawn } from 'node:child_process';
15
+ import { promisify } from 'node:util';
16
+
17
+ const execFileP = promisify(execFile);
18
+ export const MAX_FPS = 30;
19
+ /** JPEG quality of the frames the browser sends. Fixed: 100 doubles the bytes for a difference nobody sees after x264. */
20
+ export const QUALITY = 80;
21
+ // ffmpeg not keeping up (a starved machine) must not pile frames up in this process, which every
22
+ // agent shares: past this many unwritten bytes, frames are dropped until it catches up.
23
+ const BACKLOG_BYTES = 48 * 1024 * 1024;
24
+
25
+ /** Pixel size of a JPEG, from its SOF marker. */
26
+ function jpegSize(buf) {
27
+ for (let i = 2; i + 9 < buf.length;) {
28
+ if (buf[i] !== 0xFF) break;
29
+ const m = buf[i + 1], len = buf.readUInt16BE(i + 2);
30
+ if (m >= 0xC0 && m <= 0xC2) return [buf.readUInt16BE(i + 7), buf.readUInt16BE(i + 5)];
31
+ i += 2 + len;
32
+ }
33
+ return [0, 0];
34
+ }
35
+
36
+ export class Recorder {
37
+ /**
38
+ * width × height: the largest frame to ask the browser for (it sends the page's own size when
39
+ * that is smaller). fps: frames kept per second at most. crf: x264 quality, lower is better.
40
+ */
41
+ constructor(session, { dir, width = 1920, height = 1080, fps = MAX_FPS, crf = 23 } = {}) {
42
+ this.session = session;
43
+ this.dir = dir;
44
+ this.opts = { width, height, fps: Math.min(Math.max(1, fps), 60), crf };
45
+ this.file = join(dir, 'recording.mp4'); // the part being written; a pause closes it and the next one follows
46
+ this.parts = []; // finished or running parts with at least one frame, in order
47
+ this.partFrames = 0;
48
+ this.paused = false;
49
+ this.pauses = []; // { at: seconds into the video, from, to: epoch s } — the time that is not in the video
50
+ this.activeMs = 0; // filmed time, pauses left out
51
+ this.frames = 0; // frames in the video
52
+ this.received = 0; // frames the browser sent
53
+ this.dropped = 0; // left out by the fps cap
54
+ this.droppedBusy = 0; // left out because ffmpeg was behind
55
+ this.visibility = [];
56
+ this.events = []; // { type: 'size'|'nav'|'replaced', t (epoch s), ... } in the order they happened
57
+ this.started = 0;
58
+ this.t0 = null; // epoch s of the first frame: second 0 of the video
59
+ this.error = null; // why the recording ended early
60
+ this.last = null; // the latest frame the browser sent (see frameTo)
61
+ this.nextDue = -Infinity; // page-clock time (ms) from which the next frame is kept
62
+ this.size = [0, 0];
63
+ this.mainFrame = null;
64
+ this.onFrame = (p) => this.#handleFrame(p);
65
+ this.onVisibility = ({ visible }) => { this.visibility.push({ visible, at: Date.now() - this.started }); };
66
+ this.onNavigated = ({ frame }) => { if (!frame.parentId) { this.mainFrame = frame.id; this.#nav(frame.url + (frame.urlFragment || '')); } };
67
+ this.onNavigatedWithin = ({ frameId, url }) => { if (!this.mainFrame || frameId === this.mainFrame) this.#nav(url); };
68
+ }
69
+
70
+ async start() {
71
+ await mkdir(this.dir, { recursive: true });
72
+ this.started = Date.now();
73
+ await this.#spawn();
74
+ this.partStarted = Date.now();
75
+ try { this.mainFrame = (await this.session.cdp('Page.getFrameTree')).frameTree?.frame?.id ?? null; } catch { /* addresses are a nicety */ }
76
+ this.session.on('Page.screencastFrame', this.onFrame);
77
+ this.session.on('Page.screencastVisibilityChanged', this.onVisibility);
78
+ this.session.on('Page.frameNavigated', this.onNavigated);
79
+ this.session.on('Page.navigatedWithinDocument', this.onNavigatedWithin);
80
+ await this.#screencast();
81
+ }
82
+
83
+ /** (Re)start the screencast: at start, after a pause, and on a tab the browser swapped in for the recorded one. */
84
+ #screencast() {
85
+ return this.session.cdp('Page.startScreencast', {
86
+ format: 'jpeg', quality: QUALITY, maxWidth: this.opts.width, maxHeight: this.opts.height, everyNthFrame: 1,
87
+ });
88
+ }
89
+
90
+ /** The browser replaced the recorded tab with a new one (it had discarded it): the page starts over there. */
91
+ replaced() { this.events.push({ type: 'replaced', t: Date.now() / 1000 }); return this.paused ? Promise.resolve() : this.#screencast(); }
92
+
93
+ /** Keep at most this many frames a second from now on (1–60). Few while only waiting, more while something is shown. */
94
+ setFps(fps) {
95
+ if (!Number.isFinite(+fps)) throw new Error(`fps must be a number, got ${JSON.stringify(fps)}`);
96
+ this.opts.fps = Math.min(Math.max(1, +fps), 60);
97
+ this.nextDue = -Infinity;
98
+ return { fps: this.opts.fps };
99
+ }
100
+
101
+ /**
102
+ * Stop filming until unpause(). The time in between is not in the video at all: the picture
103
+ * jumps from the last frame before to the first frame after. Nothing runs meanwhile — the browser
104
+ * sends no frames and no ffmpeg is waiting.
105
+ */
106
+ async pause() {
107
+ if (this.ended || this.error) throw new Error('this recording is over');
108
+ if (this.paused) return { paused: true };
109
+ this.paused = true;
110
+ try { await this.session.cdp('Page.stopScreencast', {}, { timeout: 5000 }); } catch { /* tab may be gone */ }
111
+ const from = Date.now();
112
+ await this.#closePart();
113
+ this.activeMs += from - this.partStarted;
114
+ this.pauses.push({ at: +(this.activeMs / 1000).toFixed(3), from: from / 1000, to: null });
115
+ return { paused: true };
116
+ }
117
+
118
+ async unpause() {
119
+ if (this.ended || this.error) throw new Error('this recording is over');
120
+ if (!this.paused) return { paused: false };
121
+ this.file = join(this.dir, `recording-${this.pauses.length}.mp4`);
122
+ this.partFrames = 0;
123
+ await this.#spawn();
124
+ this.partStarted = Date.now();
125
+ this.pauses[this.pauses.length - 1].to = this.partStarted / 1000;
126
+ this.paused = false;
127
+ this.nextDue = -Infinity;
128
+ await this.#screencast(); // the browser sends the page as it is now straight away
129
+ return { paused: false };
130
+ }
131
+
132
+ /** End the part being written: hold its last picture until now, let ffmpeg finish. */
133
+ async #closePart() {
134
+ if (!this.error) {
135
+ if (this.last && this.partFrames) this.#write(this.last);
136
+ this.ff.stdin.end();
137
+ }
138
+ await this.exited;
139
+ if (!this.partFrames) await rm(this.file, { force: true }); // paused again before anything was painted
140
+ }
141
+
142
+ #nav(url) { this.events.push({ type: 'nav', t: Date.now() / 1000, url }); }
143
+
144
+ #spawn() {
145
+ // Each frame gets the time ffmpeg read it, so the video keeps real time without a frame rate.
146
+ // The frames go in as multipart JPEG, which says how long each one is: a bare JPEG stream is
147
+ // only cut where the next picture starts, so every frame was stamped with the arrival of the
148
+ // one after it — the last picture before a still stretch showed up when the page moved again.
149
+ // Fragmented, so what was filmed is a playable file even if this process dies; stop() rewrites it
150
+ // as an ordinary mp4. Limited-range BT.601, what the JPEGs are once converted.
151
+ // No B-frames: with them the file's length is counted from decode times, which run a few frames
152
+ // behind, and a long still stretch at the end was left out of it (4.5 s filmed, 1.5 s reported).
153
+ const ff = spawn('ffmpeg', [
154
+ '-y', '-loglevel', 'error', '-f', 'mpjpeg', '-strict_mime_boundary', '0', '-use_wallclock_as_timestamps', '1', '-i', '-',
155
+ '-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2:out_range=tv:out_color_matrix=bt601,format=yuv420p',
156
+ '-fps_mode', 'vfr', '-enc_time_base', '1/90000', '-c:v', 'libx264', '-preset', 'veryfast', '-bf', '0', '-crf', String(this.opts.crf),
157
+ '-movflags', '+frag_keyframe+empty_moov+default_base_moof', '-frag_duration', '2000000', this.file,
158
+ ], { stdio: ['pipe', 'ignore', 'pipe'] });
159
+ this.ff = ff;
160
+ let stderr = '';
161
+ ff.stderr.on('data', (c) => { stderr = (stderr + c).slice(-600); });
162
+ ff.stdin.on('error', () => {}); // EPIPE when ffmpeg is gone: its exit says why
163
+ this.exited = new Promise((resolve) => ff.on('close', (code) => {
164
+ // A part that was given nothing (paused again before the page painted) ends with an error of its own: not a failure.
165
+ if (code !== 0 && !this.error && this.partFrames) this.#fail(new Error(`ffmpeg ended (${code}): ${stderr.trim() || 'no message'}`));
166
+ resolve();
167
+ }));
168
+ return new Promise((resolve, reject) => {
169
+ ff.once('spawn', resolve);
170
+ ff.once('error', (e) => reject(new Error(e.code === 'ENOENT' ? 'ffmpeg is not installed (brew install ffmpeg)' : `ffmpeg did not start: ${e.message}`)));
171
+ });
172
+ }
173
+
174
+ /** Never throws: this runs as an event listener in the daemon every agent shares. */
175
+ #handleFrame({ data, metadata, sessionId }) {
176
+ // ack first so the browser keeps streaming
177
+ this.session.cdp('Page.screencastFrameAck', { sessionId }).catch(() => {});
178
+ this.received++;
179
+ if (this.error || this.ended || this.paused) return;
180
+ try {
181
+ const buf = Buffer.from(data, 'base64');
182
+ this.last = buf;
183
+ const [w, h] = jpegSize(buf);
184
+ if (w && (w !== this.size[0] || h !== this.size[1])) { this.size = [w, h]; this.events.push({ type: 'size', t: Date.now() / 1000, width: w, height: h }); }
185
+ const t = Number.isFinite(metadata?.timestamp) ? metadata.timestamp * 1000 : Date.now();
186
+ // A fixed schedule rather than "33 ms since the last kept frame": frames arrive on the display's
187
+ // own grid (13 ms at 75 Hz), and measuring from the last kept one would keep every third (25 fps).
188
+ const step = 1000 / this.opts.fps;
189
+ if (t < this.nextDue) { this.dropped++; return; }
190
+ this.nextDue = t - this.nextDue > 2 * step ? t + step : this.nextDue + step;
191
+ if (this.ff.stdin.writableLength > BACKLOG_BYTES) { this.droppedBusy++; return; }
192
+ if (this.t0 === null) this.t0 = Date.now() / 1000;
193
+ if (!this.partFrames) this.parts.push(this.file);
194
+ this.#write(buf);
195
+ this.frames++;
196
+ this.partFrames++;
197
+ } catch (e) { this.#fail(e); }
198
+ }
199
+
200
+ #write(jpeg) {
201
+ this.ff.stdin.write(Buffer.concat([Buffer.from(`--frame\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`), jpeg, Buffer.from('\r\n')]));
202
+ }
203
+
204
+ #fail(e) {
205
+ if (this.error) return;
206
+ this.error = e;
207
+ if (!this.ended) this.session.cdp('Page.stopScreencast', {}, { timeout: 5000 }).catch(() => {});
208
+ try { this.ff.stdin.end(); } catch { /* already closed */ }
209
+ this.onError?.(e);
210
+ }
211
+
212
+ /** Write the latest frame the browser sent to `path` (what the video shows right now). */
213
+ async frameTo(path) {
214
+ if (!this.last) throw new Error('no frame yet: the page has not painted since the recording started');
215
+ await writeFile(path, this.last);
216
+ return { path, width: this.size[0], height: this.size[1] };
217
+ }
218
+
219
+ /** Stop filming and let ffmpeg finish what it has. */
220
+ async end() {
221
+ if (this.ended) return this.summary;
222
+ this.ended = true;
223
+ try { await this.session.cdp('Page.stopScreencast', {}, { timeout: 5000 }); } catch { /* tab may be gone */ }
224
+ for (const [ev, fn] of [['Page.screencastFrame', this.onFrame], ['Page.screencastVisibilityChanged', this.onVisibility], ['Page.frameNavigated', this.onNavigated], ['Page.navigatedWithinDocument', this.onNavigatedWithin]]) this.session.off(ev, fn);
225
+ const tEnd = Date.now();
226
+ if (this.paused) this.pauses[this.pauses.length - 1].to = tEnd / 1000;
227
+ else {
228
+ // The same picture once more, now: the last frame stays on screen until the recording was stopped.
229
+ await this.#closePart();
230
+ this.activeMs += tEnd - this.partStarted;
231
+ }
232
+ const seconds = this.activeMs / 1000;
233
+ this.summary = {
234
+ frames: this.frames, received: this.received, dropped: this.dropped, ...(this.droppedBusy ? { droppedBusy: this.droppedBusy } : {}),
235
+ seconds: +seconds.toFixed(2), fps: +(this.frames / seconds).toFixed(2), width: this.size[0], height: this.size[1],
236
+ t0: this.t0, tEnd: tEnd / 1000, ...(this.pauses.length ? { pauses: this.pauses } : {}), visibility: this.visibility, events: this.events,
237
+ ...(this.error ? { error: `recording stopped early: ${this.error.message}` } : {}),
238
+ };
239
+ return this.summary;
240
+ }
241
+
242
+ /** Turn what was recorded into an ordinary mp4 at outMp4 and remove the working folder. A copy, not an encode. */
243
+ async encode(outMp4) {
244
+ if (!this.frames) throw new Error('no frame was recorded: the tab was gone, or never painted');
245
+ if (this.error) throw new Error(`${this.summary?.error || this.error.message} (what was filmed is in ${this.dir})`);
246
+ for (const f of this.parts) await stat(f); // gone with the folder (the caller cleaned up): fail here rather than recreate it
247
+ await mkdir(dirname(outMp4), { recursive: true });
248
+ let input = ['-i', this.parts[0]];
249
+ const list = join(this.dir, 'parts.ffconcat');
250
+ if (this.parts.length > 1) { // one part per stretch between pauses, joined end to end
251
+ await writeFile(list, ['ffconcat version 1.0', ...this.parts.map((f) => `file '${f.replace(/'/g, "'\\''")}'`)].join('\n') + '\n');
252
+ input = ['-f', 'concat', '-safe', '0', '-i', list];
253
+ }
254
+ await execFileP('ffmpeg', ['-y', '-loglevel', 'error', ...input, '-c', 'copy', '-movflags', '+faststart', outMp4]);
255
+ const { size } = await stat(outMp4);
256
+ await Promise.all([...this.parts, list].map((f) => rm(f, { force: true })));
257
+ await rmdir(this.dir).catch(() => {}); // only if that leaves it empty
258
+ return { mp4: outMp4, bytes: size };
259
+ }
260
+
261
+ /** @returns {{frames:number, received:number, dropped:number, seconds:number, fps:number, t0:number, tEnd:number, pauses?:Array, visibility:Array, events:Array, mp4?:string, bytes?:number}} */
262
+ async stop(outMp4) {
263
+ const summary = { ...(await this.end()) };
264
+ if (outMp4 && this.frames) Object.assign(summary, await this.encode(outMp4));
265
+ return summary;
266
+ }
267
+ }
@@ -0,0 +1,95 @@
1
+ // WebSocket relay server: the extension connects here; the runtime sends requests.
2
+ import { EventEmitter } from 'node:events';
3
+ import { WebSocketServer } from 'ws';
4
+
5
+ export class Relay extends EventEmitter {
6
+ constructor({ port = 9333, host = '127.0.0.1' } = {}) {
7
+ super();
8
+ this.port = port;
9
+ this.host = host;
10
+ this.wss = null;
11
+ this.ext = null;
12
+ this.hello = null;
13
+ this.nextId = 1;
14
+ this.pending = new Map();
15
+ this.setMaxListeners(200);
16
+ }
17
+
18
+ async start() {
19
+ this.wss = new WebSocketServer({ port: this.port, host: this.host, path: '/ext' });
20
+ await new Promise((resolve, reject) => {
21
+ this.wss.once('listening', resolve);
22
+ this.wss.once('error', reject);
23
+ });
24
+ this.wss.on('connection', (socket) => this.#onConnection(socket));
25
+ return this;
26
+ }
27
+
28
+ #onConnection(socket) {
29
+ if (this.ext) { try { this.ext.close(); } catch { /* ignore */ } }
30
+ this.ext = socket;
31
+ this.hello = null;
32
+ socket.on('message', (raw) => {
33
+ let msg;
34
+ try { msg = JSON.parse(raw.toString()); } catch { return; }
35
+ if (msg.type === 'hello') {
36
+ this.hello = msg;
37
+ this.emit('hello', msg);
38
+ return;
39
+ }
40
+ if (msg.type === 'event') {
41
+ this.emit('event', msg.event, msg.params);
42
+ this.emit(`event:${msg.event}`, msg.params);
43
+ return;
44
+ }
45
+ if (msg.id !== undefined) {
46
+ const p = this.pending.get(msg.id);
47
+ if (!p) return;
48
+ this.pending.delete(msg.id);
49
+ clearTimeout(p.timer);
50
+ if (msg.error) p.reject(new Error(msg.error));
51
+ else p.resolve(msg.result);
52
+ }
53
+ });
54
+ socket.on('close', () => {
55
+ if (this.ext === socket) { this.ext = null; this.hello = null; }
56
+ for (const [id, p] of this.pending) {
57
+ clearTimeout(p.timer);
58
+ p.reject(new Error('browser disconnected (extension socket closed)'));
59
+ this.pending.delete(id);
60
+ }
61
+ this.emit('disconnected');
62
+ });
63
+ }
64
+
65
+ get connected() {
66
+ return !!this.ext && !!this.hello;
67
+ }
68
+
69
+ waitForExtension(timeoutMs = 30000) {
70
+ if (this.connected) return Promise.resolve(this.hello);
71
+ return new Promise((resolve, reject) => {
72
+ const timer = setTimeout(() => { this.off('hello', onHello); reject(new Error(`extension did not connect within ${timeoutMs}ms`)); }, timeoutMs);
73
+ const onHello = (h) => { clearTimeout(timer); resolve(h); };
74
+ this.once('hello', onHello);
75
+ });
76
+ }
77
+
78
+ call(method, params = {}, { timeout = 30000 } = {}) {
79
+ if (!this.ext) return Promise.reject(new Error('browser disconnected (no extension connection)'));
80
+ const id = this.nextId++;
81
+ return new Promise((resolve, reject) => {
82
+ const timer = setTimeout(() => {
83
+ this.pending.delete(id);
84
+ reject(new Error(`timeout after ${timeout}ms: ${method}${method === 'cdp' ? ' ' + params.method : ''}`));
85
+ }, timeout);
86
+ this.pending.set(id, { resolve, reject, timer });
87
+ this.ext.send(JSON.stringify({ id, method, params }));
88
+ });
89
+ }
90
+
91
+ async close() {
92
+ if (this.ext) { try { this.ext.close(); } catch { /* ignore */ } }
93
+ await new Promise((r) => this.wss?.close(() => r()));
94
+ }
95
+ }