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,69 @@
1
+ // CLI-side client of the daemon. Same surface as Relay (call / on('event:*')) so Session
2
+ // works unchanged. Spawns the daemon on demand.
3
+ import { EventEmitter } from 'node:events';
4
+ import { connect } from 'node:net';
5
+ import { spawn } from 'node:child_process';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { DEFAULT_CTRL_PORT } from './daemon.js';
8
+
9
+ const DAEMON_PATH = fileURLToPath(new URL('./daemon.js', import.meta.url));
10
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
11
+
12
+ export class DaemonClient extends EventEmitter {
13
+ constructor(socket) {
14
+ super();
15
+ this.isDaemon = true;
16
+ this.socket = socket;
17
+ this.nextId = 1;
18
+ this.pending = new Map();
19
+ this.setMaxListeners(200);
20
+ let buf = '';
21
+ socket.on('data', (chunk) => {
22
+ buf += chunk.toString();
23
+ let idx;
24
+ while ((idx = buf.indexOf('\n')) >= 0) {
25
+ const line = buf.slice(0, idx); buf = buf.slice(idx + 1);
26
+ if (!line.trim()) continue;
27
+ let msg; try { msg = JSON.parse(line); } catch { continue; }
28
+ if (msg.type === 'event') { this.emit('event', msg.event, msg.params); this.emit(`event:${msg.event}`, msg.params); continue; }
29
+ const p = this.pending.get(msg.id);
30
+ if (!p) continue;
31
+ this.pending.delete(msg.id);
32
+ clearTimeout(p.timer);
33
+ if (msg.error) p.reject(new Error(msg.error)); else p.resolve(msg.result);
34
+ }
35
+ });
36
+ socket.on('close', () => {
37
+ for (const [id, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error('daemon connection closed')); this.pending.delete(id); }
38
+ this.emit('closed');
39
+ });
40
+ socket.on('error', () => {});
41
+ }
42
+
43
+ static async connect({ port = +(process.env.PC_CTRL_PORT || DEFAULT_CTRL_PORT), autoSpawn = true, timeout = 10000 } = {}) {
44
+ const tryConnect = () => new Promise((resolve, reject) => {
45
+ const s = connect({ port, host: '127.0.0.1' }, () => resolve(s));
46
+ s.once('error', reject);
47
+ });
48
+ try { return new DaemonClient(await tryConnect()); } catch { if (!autoSpawn) throw new Error(`daemon not running on 127.0.0.1:${port}`); }
49
+ const child = spawn(process.execPath, [DAEMON_PATH], { detached: true, stdio: 'ignore', env: process.env });
50
+ child.unref();
51
+ const deadline = Date.now() + timeout;
52
+ while (Date.now() < deadline) {
53
+ await sleep(150);
54
+ try { return new DaemonClient(await tryConnect()); } catch { /* not yet */ }
55
+ }
56
+ throw new Error('daemon did not start');
57
+ }
58
+
59
+ call(method, params = {}, { timeout = 30000 } = {}) {
60
+ const id = this.nextId++;
61
+ return new Promise((resolve, reject) => {
62
+ const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`timeout after ${timeout}ms: ${method}${method === 'cdp' ? ' ' + params.method : ''}`)); }, timeout);
63
+ this.pending.set(id, { resolve, reject, timer });
64
+ this.socket.write(JSON.stringify({ id, method, params: { ...params, __timeout: timeout } }) + '\n');
65
+ });
66
+ }
67
+
68
+ close() { this.socket.end(); }
69
+ }
@@ -0,0 +1,503 @@
1
+ // parallel-browser daemon: owns the single relay connection to the browser extension and
2
+ // multiplexes any number of CLI clients over a local TCP control socket (JSON lines).
3
+ // Recording runs here so start/stop can span separate CLI invocations.
4
+ //
5
+ // PC_RELAY_PORT (default 9333) where the extension connects
6
+ // PC_CTRL_PORT (default 9336) where CLI clients connect
7
+ // PB_OWNER_GRACE_MS (default 0) extra time a session outlives its last owner process (it is noticed within 5 s)
8
+ //
9
+ // Updates apply themselves (watchUpdates): when the runtime files on disk change, the daemon
10
+ // restarts itself once nobody is connected; when the extension's files differ from what the
11
+ // browser runs, it asks the extension to reload from disk.
12
+ import { createServer } from 'node:net';
13
+ import { createHash } from 'node:crypto';
14
+ import { execFileSync, spawn } from 'node:child_process';
15
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
16
+ import { homedir } from 'node:os';
17
+ import { dirname, join, relative } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { Relay } from './relay.js';
20
+ import { Recorder } from './recorder.js';
21
+ import { isAlive } from './owner.js';
22
+
23
+ export const DEFAULT_CTRL_PORT = 9336;
24
+ const OWNER_POLL_MS = 5000;
25
+ // Screencast frames are ~100 KB each at the display rate. A client this far behind on reading gets
26
+ // no more of them until it catches up; otherwise the unsent lines pile up in this process, which is
27
+ // shared by every agent (aidu-test's copy of this daemon ran out of memory 3.5 hours into a recording,
28
+ // 2026-11-02). High on purpose: a client that records acks each frame it gets, and a dropped frame
29
+ // is never acked, so this is only for a client that has stopped reading altogether.
30
+ const FRAME_BACKLOG_BYTES = 64 * 1024 * 1024;
31
+ // Kept on disk so a restarted daemon (`daemon stop` after an update) still closes what it watched.
32
+ // It holds session keys, so it is readable by this user only.
33
+ // A daemon on another relay port (spikes, test copies) keeps its own files, so it never edits the
34
+ // real watch list or writes into the real event log (2026-11-23: spike daemons on 9335 did both).
35
+ const STATE_DIR = process.platform === 'win32'
36
+ ? join(process.env.LOCALAPPDATA || homedir(), 'parallel-browser')
37
+ : join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'parallel-browser');
38
+ const PORT_SUFFIX = (process.env.PC_RELAY_PORT || '9333') === '9333' ? '' : `-${process.env.PC_RELAY_PORT}`;
39
+ const OWNERS_FILE = process.env.PB_OWNERS_FILE || join(STATE_DIR, `owners${PORT_SUFFIX}.json`);
40
+
41
+ // What happened, one JSON line per event, so "why did my session/tab/recording break?" has an
42
+ // answer after the fact (2026-11-20: three days of use left nothing to tell a frozen tab from a
43
+ // swapped or closed one). Sessions are named by id only — never a key — and addresses by host.
44
+ // Readable by this user only; rotated to events.log.1 past EVENTS_MAX_BYTES.
45
+ const EVENTS_FILE = process.env.PB_EVENTS_FILE || join(STATE_DIR, `events${PORT_SUFFIX}.log`);
46
+ const EVENTS_MAX_BYTES = 5 * 1024 * 1024;
47
+ function logEvent(ev, fields = {}) {
48
+ try {
49
+ mkdirSync(dirname(EVENTS_FILE), { recursive: true, mode: 0o700 });
50
+ try { if (statSync(EVENTS_FILE).size > EVENTS_MAX_BYTES) renameSync(EVENTS_FILE, `${EVENTS_FILE}.1`); } catch { /* not there yet */ }
51
+ appendFileSync(EVENTS_FILE, JSON.stringify({ t: new Date().toISOString(), ev, ...fields }) + '\n', { mode: 0o600 });
52
+ } catch { /* a log must never break the daemon */ }
53
+ }
54
+ /** Event params as logged: no keys, hosts instead of full addresses (paths and queries can carry data). */
55
+ function loggable(params) {
56
+ const out = {};
57
+ for (const [k, v] of Object.entries(params || {})) {
58
+ if (/key|token|secret|password/i.test(k)) continue;
59
+ if (/url|href/i.test(k)) { if (typeof v === 'string') { try { out[k] = new URL(v).host || v.split(':')[0]; } catch { out[k] = '?'; } } continue; }
60
+ out[k] = v;
61
+ }
62
+ return out;
63
+ }
64
+ // Extension events not worth a line: page traffic, and the per-command trace unless it failed.
65
+ const QUIET_EVENTS = new Set(['cdp.event', 'session.watched', 'debugger.attached', 'frame.attached', 'frame.detached']);
66
+
67
+ export async function startDaemon({ relayPort = +(process.env.PC_RELAY_PORT || 9333), ctrlPort = +(process.env.PC_CTRL_PORT || DEFAULT_CTRL_PORT), log = () => {} } = {}) {
68
+ const relay = await new Relay({ port: relayPort }).start();
69
+ const clients = new Set();
70
+ const debug = process.env.PC_DEBUG ? (m) => log(`[${new Date().toISOString().slice(11, 23)}] ${m}`) : () => {};
71
+ relay.on('hello', (h) => debug(`browser connected: worker=${h.workerStartedAt} sessions=${h.sessions?.length}`));
72
+ relay.on('disconnected', () => debug('browser disconnected'));
73
+ logEvent('daemon.start', { pid: process.pid, relayPort, ctrlPort, runtime: codeHashOf(join(ROOT, 'runtime')) });
74
+ relay.on('hello', (h) => logEvent('browser.hello', {
75
+ worker: h.workerStartedAt ? new Date(h.workerStartedAt).toISOString() : null, sessions: h.sessionCount,
76
+ lost: (h.lost || []).map((l) => l.id), codeHash: h.codeHash ?? null, browser: (h.userAgent || '').match(/(Edg|Chrome)\/[\d.]+/g)?.pop() || null,
77
+ }));
78
+ relay.on('disconnected', () => logEvent('browser.disconnected'));
79
+ relay.on('event', (event, params) => {
80
+ if (QUIET_EVENTS.has(event) || (event === 'debug.cdp' && params?.phase !== 'error')) return;
81
+ logEvent(event, loggable(params));
82
+ });
83
+ relay.on('event', (event, params) => {
84
+ if (event === 'cdp.event') return; // far too chatty (Network.*)
85
+ if (event === 'debug.cdp') return debug(` ext ${params.phase.padEnd(5)} ${params.method}${params.ms !== undefined ? ' ' + params.ms + 'ms' : ''}${params.workerStartedAt ? ' worker=' + params.workerStartedAt : ''}${params.error ? ' ' + params.error : ''}`);
86
+ debug(` evt ${event} ${JSON.stringify(params).slice(0, 140)}`);
87
+ });
88
+ const recorders = new Map(); // `${sessionId}:${tabId}` -> Recorder
89
+ // Recordings being finished or just finished, by output path. The video is encoded while it is
90
+ // filmed, so finishing is a copy into an ordinary mp4: seconds even for hours. It is still a job
91
+ // the caller can ask about, so a slow disk never turns into a timeout (2026-11-24: 12 `record.stop`
92
+ // timeouts in six runs, when everything was encoded at the end), and nothing restarts the daemon under it.
93
+ const encodes = new Map(); // outMp4 -> { sessionKey, sessionId, state: 'encoding'|'done'|'failed', summary, error, promise, at }
94
+ const ENCODE_KEEP_MS = 60 * 60 * 1000;
95
+ const encoding = () => [...encodes.values()].filter((j) => j.state === 'encoding').length;
96
+ function startEncode(rec, sessionId, out, summary) {
97
+ const t0 = Date.now();
98
+ const job = { sessionKey: rec.sessionKey, sessionId, state: 'encoding', summary, error: null, at: t0 };
99
+ job.promise = rec.encode(out).then(
100
+ (r) => { job.state = 'done'; job.summary = { ...summary, ...r }; logEvent('record.encoded', { sessionId, out, frames: summary.frames, bytes: r.bytes, ms: Date.now() - t0 }); },
101
+ (e) => { job.state = 'failed'; job.error = String(e.message || e).slice(0, 500); logEvent('record.failed', { sessionId, out, frames: summary.frames, dir: rec.dir, ms: Date.now() - t0, error: job.error }); },
102
+ ).finally(() => { job.at = Date.now(); });
103
+ for (const [k, j] of encodes) if (j.state !== 'encoding' && Date.now() - j.at > ENCODE_KEEP_MS) encodes.delete(k);
104
+ encodes.set(out, job);
105
+ return job;
106
+ }
107
+ const jobView = (out, job) => job.state === 'done' ? { ...job.summary, encoding: false }
108
+ : job.state === 'failed' ? { ...job.summary, encoding: false, error: job.error }
109
+ : { ...job.summary, encoding: true, out };
110
+ /** End a recording whose session is going away without a stopRecording: keep what was filmed. */
111
+ function abandon(sessionId, rec, why) {
112
+ const out = `${rec.dir.replace(/\/+$/, '')}-unfinished.mp4`;
113
+ rec.end().then((summary) => {
114
+ logEvent('record.abandoned', { sessionId, why, frames: summary.frames, seconds: summary.seconds, out: summary.frames ? out : null });
115
+ if (summary.frames) startEncode(rec, sessionId, out, summary);
116
+ }).catch(() => {});
117
+ }
118
+ // A session closed while it was being recorded (close() without stopRecording, or its tabs were
119
+ // closed): nobody can stop that recording any more, and left in the map it would hold off every
120
+ // daemon update. Save what was filmed.
121
+ relay.on('event:session.closed', ({ sessionId }) => {
122
+ for (const [k, rec] of recorders) {
123
+ if (!k.startsWith(`${sessionId}:`)) continue;
124
+ recorders.delete(k);
125
+ abandon(sessionId, rec, 'session closed');
126
+ }
127
+ });
128
+ const owners = watchOwners({ relay, recorders, abandon, log: debug, graceMs: +(process.env.PB_OWNER_GRACE_MS || 0) });
129
+
130
+ relay.on('event', (event, params) => broadcast({ type: 'event', event, params }));
131
+ relay.on('hello', (h) => broadcast({ type: 'event', event: 'browser.connected', params: { userAgent: h.userAgent } }));
132
+ relay.on('disconnected', () => broadcast({ type: 'event', event: 'browser.disconnected', params: {} }));
133
+
134
+ /**
135
+ * Events name a session, and every agent on this machine shares this daemon, so an unfiltered
136
+ * fan-out would let anyone watch anyone else's pages go by. An event about a session only
137
+ * reaches the clients that have proved they hold its key; anything not tied to a session
138
+ * (the browser connecting, for instance) still goes to everyone.
139
+ */
140
+ function broadcast(msg) {
141
+ const sessionId = msg.params?.sessionId;
142
+ // A tab this daemon records needs its frames only here (the recorder acks them itself).
143
+ const frame = msg.event === 'cdp.event' && msg.params?.method === 'Page.screencastFrame';
144
+ if (frame && recorders.has(`${sessionId}:${msg.params.tabId}`)) return;
145
+ let line = null;
146
+ for (const c of clients) {
147
+ if (sessionId && !c.__pcOwned?.has(sessionId)) continue;
148
+ if (frame && c.writableLength > FRAME_BACKLOG_BYTES) continue;
149
+ c.write(line ??= JSON.stringify(msg) + '\n');
150
+ }
151
+ }
152
+
153
+ // A minimal Session-shaped adapter so Recorder can run inside the daemon. tabId moves when the
154
+ // browser swaps the recorded tab for a new one (tab.replaced below).
155
+ function recorderTarget(sessionId, sessionKey, tabId) {
156
+ const listeners = new Map();
157
+ const t = {
158
+ tabId,
159
+ cdp: (method, params = {}) => relay.call('cdp', { sessionId, key: sessionKey, tabId: t.tabId, method, params }),
160
+ on(event, fn) {
161
+ const h = (p) => { if (p.sessionId === sessionId && p.tabId === t.tabId && p.method === event) fn(p.params, p.tabId); };
162
+ listeners.set(fn, h);
163
+ relay.on('event:cdp.event', h);
164
+ },
165
+ off(event, fn) { const h = listeners.get(fn); if (h) relay.off('event:cdp.event', h); listeners.delete(fn); },
166
+ };
167
+ return t;
168
+ }
169
+ const replacedKeys = new Map(); // `${sessionId}:${oldTabId}` -> `${sessionId}:${tabId}`, for callers still holding the old id
170
+ const recKey = (sessionId, tabId) => { let k = `${sessionId}:${tabId}`; while (replacedKeys.has(k)) k = replacedKeys.get(k); return k; };
171
+ relay.on('event:tab.replaced', ({ sessionId, oldTabId, tabId }) => {
172
+ replacedKeys.set(`${sessionId}:${oldTabId}`, `${sessionId}:${tabId}`);
173
+ const rec = recorders.get(`${sessionId}:${oldTabId}`);
174
+ if (!rec) return;
175
+ recorders.delete(`${sessionId}:${oldTabId}`);
176
+ recorders.set(`${sessionId}:${tabId}`, rec);
177
+ rec.session.tabId = tabId;
178
+ rec.replaced().catch((e) => debug(`record: could not resume on replaced tab ${tabId}: ${e.message}`));
179
+ });
180
+
181
+ async function handle(method, params) {
182
+ // While the extension reloads for an update, hold requests until it is back instead of failing
183
+ // them with "browser disconnected" (an agent's next call can land in that second and a half).
184
+ if (method !== 'daemon.stop') await updates.settled();
185
+ switch (method) {
186
+ case 'daemon.status': return { connected: relay.connected, userAgent: relay.hello?.userAgent || null, relayPort, ctrlPort, clients: clients.size, recordings: [...recorders.keys()], encoding: [...encodes].filter(([, j]) => j.state === 'encoding').map(([out]) => out), extension: updates.status() };
187
+ // Only the daemon decides when the extension reloads (watchUpdates): a reload drops every
188
+ // debugger attachment for a moment, which no agent should be able to do to the others.
189
+ case 'ext.update': throw new Error('the daemon updates the extension by itself when nobody is using it');
190
+ case 'daemon.stop': setTimeout(() => process.exit(0), 50); return { stopping: true };
191
+ case 'daemon.waitForBrowser': await relay.waitForExtension(params.timeout ?? 15000); return { connected: true, userAgent: relay.hello?.userAgent };
192
+ case 'record.start': {
193
+ const key = recKey(params.sessionId, params.tabId);
194
+ if (recorders.has(key)) throw new Error('already recording this tab');
195
+ const rec = new Recorder(recorderTarget(params.sessionId, params.key, Number(key.split(':')[1])), { dir: params.dir || `/tmp/parallel-browser-rec-${Date.now()}`, width: params.width, height: params.height, fps: params.fps, crf: params.crf });
196
+ rec.sessionKey = params.key;
197
+ // A frame that cannot be written (folder deleted, disk full) ends that recording, not the daemon.
198
+ rec.onError = (e) => logEvent('record.failed', { sessionId: params.sessionId, dir: rec.dir, frames: rec.frames, error: String(e.message || e).slice(0, 300) });
199
+ await rec.start();
200
+ recorders.set(key, rec);
201
+ logEvent('record.start', { sessionId: params.sessionId, tabId: Number(key.split(':')[1]), dir: rec.dir });
202
+ return { started: true, dir: rec.dir };
203
+ }
204
+ case 'record.stop': {
205
+ const key = recKey(params.sessionId, params.tabId);
206
+ const rec = recorders.get(key);
207
+ if (!rec) throw new Error('not recording this tab');
208
+ // The recording belongs to the agent that started it, like the session itself.
209
+ if (rec.sessionKey !== params.key) throw new Error('not your recording');
210
+ recorders.delete(key);
211
+ const summary = await rec.end();
212
+ logEvent('record.stop', { sessionId: params.sessionId, frames: summary.frames, dropped: summary.dropped, seconds: summary.seconds, fps: summary.fps, out: params.out || null, ...(summary.error ? { error: summary.error } : {}) });
213
+ if (!params.out) return summary;
214
+ if (summary.error) throw new Error(`${summary.error} (what was filmed is in ${rec.dir})`);
215
+ if (!summary.frames) return summary;
216
+ // Answer when it is encoded, or after `wait` ms with encoding:true — never a timeout error.
217
+ const job = startEncode(rec, params.sessionId, params.out, summary);
218
+ await Promise.race([job.promise, new Promise((r) => setTimeout(r, Math.max(0, params.wait ?? 100000)).unref())]);
219
+ if (job.state === 'failed') throw new Error(`could not write ${params.out}: ${job.error} (what was filmed is in ${rec.dir})`);
220
+ return jobView(params.out, job);
221
+ }
222
+ // Change a running recording: how many frames a second it keeps, or stop and start filming.
223
+ case 'record.fps': case 'record.pause': case 'record.resume': {
224
+ const rec = recorders.get(recKey(params.sessionId, params.tabId));
225
+ if (!rec) throw new Error('not recording this tab');
226
+ if (rec.sessionKey !== params.key) throw new Error('not your recording');
227
+ const r = method === 'record.fps' ? rec.setFps(params.fps) : method === 'record.pause' ? await rec.pause() : await rec.unpause();
228
+ logEvent(method, { sessionId: params.sessionId, ...r });
229
+ return r;
230
+ }
231
+ // The latest frame of a running recording, as a JPEG file: what the video shows right now.
232
+ case 'record.frame': {
233
+ const rec = recorders.get(recKey(params.sessionId, params.tabId));
234
+ if (!rec) throw new Error('not recording this tab');
235
+ if (rec.sessionKey !== params.key) throw new Error('not your recording');
236
+ return rec.frameTo(params.out);
237
+ }
238
+ // How an encoding started by record.stop is doing; `wait` holds the answer until it ends.
239
+ case 'record.status': {
240
+ const job = encodes.get(params.out);
241
+ if (!job || job.sessionKey !== params.key) throw new Error(`no recording was stopped into ${params.out}`);
242
+ if (job.state === 'encoding' && params.wait) await Promise.race([job.promise, new Promise((r) => setTimeout(r, params.wait).unref())]);
243
+ return jobView(params.out, job);
244
+ }
245
+ // The process whose exit closes this session (see owner.js). The key is proven to the
246
+ // extension first, so nobody can make the daemon close a session they do not hold.
247
+ case 'session.owner': {
248
+ const info = await relay.call('session.attach', { sessionId: params.sessionId, key: params.key });
249
+ owners.set(params.sessionId, params.key, params.owner);
250
+ return { sessionId: info.id, owner: params.owner };
251
+ }
252
+ // Expire just before the client does, so the client sees the real error rather than its own timeout.
253
+ default: return relay.call(method, params, { timeout: Math.max(1000, (params?.__timeout || 30000) - 750) });
254
+ }
255
+ }
256
+
257
+ const server = createServer((socket) => {
258
+ clients.add(socket);
259
+ let buf = '';
260
+ // Line framing is synchronous; each request is handled independently so a slow command
261
+ // never blocks (or races with) the next chunk on the same socket.
262
+ socket.__pcOwned = new Set(); // sessions this client has proved it owns, for event routing
263
+ const dispatch = (line) => {
264
+ let msg; try { msg = JSON.parse(line); } catch { return; }
265
+ const t0 = Date.now();
266
+ const label = msg.method === 'cdp' ? `cdp ${msg.params?.method}` : msg.method;
267
+ handle(msg.method, msg.params || {}).then(
268
+ (result) => {
269
+ // A keyed call that the extension accepted is the proof; creating a session is the
270
+ // other way in, since the key comes back in the reply.
271
+ if (msg.params?.sessionId && msg.params?.key) socket.__pcOwned.add(msg.params.sessionId);
272
+ if (result?.sessionId && result?.key) socket.__pcOwned.add(result.sessionId);
273
+ if (msg.method === 'session.create') logEvent('session.created', { sessionId: result?.sessionId, name: msg.params?.name, placement: result?.placement, tabId: result?.tabId });
274
+ debug(`ok ${label} ${Date.now() - t0}ms`); socket.write(JSON.stringify({ id: msg.id, result }) + '\n'); },
275
+ (e) => {
276
+ debug(`err ${label} ${Date.now() - t0}ms ${e.message}`);
277
+ // CDP failures inside the browser are logged from the extension's debug.cdp (which also sees
278
+ // the daemon's own recorder calls); this is for the rest: timeouts, unknown sessions, guards.
279
+ if (msg.method !== 'cdp' || /timeout|disconnected/.test(e.message)) {
280
+ logEvent('request.failed', { method: label, sessionId: msg.params?.sessionId, tabId: msg.params?.tabId, ms: Date.now() - t0, error: String(e.message || e).slice(0, 300) });
281
+ }
282
+ socket.write(JSON.stringify({ id: msg.id, error: String(e.message || e) }) + '\n');
283
+ },
284
+ );
285
+ };
286
+ socket.on('data', (chunk) => {
287
+ buf += chunk.toString();
288
+ let idx;
289
+ while ((idx = buf.indexOf('\n')) >= 0) {
290
+ const line = buf.slice(0, idx); buf = buf.slice(idx + 1);
291
+ if (line.trim()) dispatch(line);
292
+ }
293
+ });
294
+ socket.on('close', () => clients.delete(socket));
295
+ socket.on('error', () => clients.delete(socket));
296
+ });
297
+ const close = async () => {
298
+ owners.stop(); updates.stop();
299
+ for (const c of clients) c.destroy(); // server.close() would otherwise wait for them
300
+ await new Promise((r) => server.close(() => r()));
301
+ await relay.close();
302
+ };
303
+ const updates = watchUpdates({ relay, clients, recorders, encoding, log: debug, restart: async () => { await close(); respawn(); process.exit(0); } });
304
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(ctrlPort, '127.0.0.1', resolve); });
305
+ log(`daemon: relay ws://127.0.0.1:${relayPort}/ext, control tcp://127.0.0.1:${ctrlPort}`);
306
+ return { relay, server, ctrlPort, relayPort, close };
307
+ }
308
+
309
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
310
+ const UPDATE_POLL_MS = +(process.env.PB_UPDATE_POLL_MS || 30000);
311
+
312
+ /** A short hash of every file under dir (names and contents), so any edit changes it. */
313
+ function codeHashOf(dir, skip = new Set()) {
314
+ const h = createHash('sha256');
315
+ const walk = (d) => {
316
+ for (const name of readdirSync(d).sort()) {
317
+ const p = join(d, name);
318
+ if (statSync(p).isDirectory()) walk(p);
319
+ else if (!skip.has(name)) { h.update(relative(dir, p)); h.update(readFileSync(p)); }
320
+ }
321
+ };
322
+ try { walk(dir); return h.digest('hex').slice(0, 16); } catch { return null; }
323
+ }
324
+
325
+ /**
326
+ * Whether runtime/ and extension/ have edits not yet committed. On the PC where this repo is
327
+ * developed the checkout is also what runs, and a half-written file would otherwise go live the
328
+ * moment it is saved (2026-11-23: the daemon restarted twice into code still being edited). Updates
329
+ * wait for the commit. Not a git checkout, or no git: nothing to wait for.
330
+ */
331
+ function uncommitted() {
332
+ try {
333
+ return execFileSync('git', ['-C', ROOT, 'status', '--porcelain', '--', 'runtime', 'extension'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() !== '';
334
+ } catch { return false; }
335
+ }
336
+
337
+ /** A new daemon in the background, as the CLI starts one. */
338
+ function respawn() {
339
+ spawn(process.execPath, [fileURLToPath(import.meta.url)], { detached: true, stdio: 'ignore', env: process.env }).unref();
340
+ }
341
+
342
+ /**
343
+ * Apply updates without anyone running `daemon stop` or reloading the extension by hand. Both wait
344
+ * until nobody is connected and nothing is recording or being encoded, so no running script loses its connection
345
+ * (a demo-video recording keeps its client connected the whole time).
346
+ * - runtime/ changed since this daemon started → restart: close, start a new one, exit. Sessions
347
+ * live in the extension and the owner list in a file, so nothing is lost.
348
+ * - extension/ differs from what the browser runs (the hash the extension reports in hello) →
349
+ * ask it to reload from disk (ext.update). A worker restart does not do this; see
350
+ * extension-reloader/. At most twice for the same files, so a reload that does not take
351
+ * cannot loop.
352
+ */
353
+ function watchUpdates({ relay, clients, recorders, encoding, log, restart }) {
354
+ const RUNTIME = join(ROOT, 'runtime'), EXTENSION = join(ROOT, 'extension');
355
+ const startedWith = codeHashOf(RUNTIME);
356
+ const tries = new Map(); // extension hash on disk -> reload requests made for it
357
+ let note = null; // why the extension could not be updated, for the CLI to show
358
+ let busy = false;
359
+ let reloading = null; // resolves once the extension says hello again after a reload request
360
+ const expectReload = () => {
361
+ const before = relay.hello?.workerStartedAt;
362
+ reloading = new Promise((resolve) => {
363
+ const done = () => { relay.off('hello', onHello); clearTimeout(timer); reloading = null; resolve(); };
364
+ const onHello = (h) => { if (h.workerStartedAt !== before) done(); };
365
+ const timer = setTimeout(done, 15000);
366
+ relay.on('hello', onHello);
367
+ });
368
+ };
369
+ const tick = async () => {
370
+ if (busy || clients.size || recorders.size || encoding()) return;
371
+ busy = true;
372
+ try {
373
+ if (uncommitted()) return;
374
+ const now = codeHashOf(RUNTIME);
375
+ if (now && startedWith && now !== startedWith) { log(`update: runtime changed (${startedWith} → ${now}), restarting`); logEvent('daemon.restart', { from: startedWith, to: now }); await restart(); return; }
376
+ if (!relay.connected) return;
377
+ const disk = codeHashOf(EXTENSION, new Set(['config.json']));
378
+ if (!disk || relay.hello?.codeHash === disk) { note = null; return; }
379
+ const n = tries.get(disk) || 0;
380
+ if (n >= 2) { note = note || 'the browser did not load the new extension files after two reloads: reload parallel-browser on the extensions page'; return; }
381
+ tries.set(disk, n + 1);
382
+ try {
383
+ expectReload();
384
+ const r = await relay.call('ext.update', { codeHash: disk }, { timeout: 5000 });
385
+ if (!r?.reloading) reloading = null;
386
+ note = r?.reloading ? null : r?.reason || null;
387
+ if (!r?.reloading) tries.set(disk, 2); // it said why; asking again changes nothing
388
+ log(`update: extension ${relay.hello?.codeHash} → ${disk}: ${JSON.stringify(r)}`);
389
+ logEvent('ext.update', { from: relay.hello?.codeHash ?? null, to: disk, ...r });
390
+ } catch (e) {
391
+ // A bridge from before ext.update existed. On Edge its debug.reload loads the files from
392
+ // disk (measured 2026-11-16, Edge 157, sessions kept); elsewhere that left it gone.
393
+ if (/unknown method ext\.update/.test(e.message) && /\bEdg\//.test(relay.hello?.userAgent || '')) {
394
+ log('update: old extension, reloading it through debug.reload (Edge)');
395
+ logEvent('ext.update', { from: null, to: disk, reloading: true, via: 'debug.reload (old extension)' });
396
+ relay.call('debug.reload', {}, { timeout: 5000 }).catch(() => {});
397
+ } else {
398
+ reloading = null;
399
+ note = 'this extension predates self-update: reload parallel-browser on the extensions page once';
400
+ logEvent('ext.update', { to: disk, reloading: false, reason: note, error: e.message });
401
+ tries.set(disk, 2);
402
+ }
403
+ }
404
+ } finally { busy = false; }
405
+ };
406
+ const timer = setInterval(() => { tick().catch((e) => log(`update: ${e.message}`)); }, UPDATE_POLL_MS);
407
+ timer.unref();
408
+ return {
409
+ settled: () => reloading || Promise.resolve(),
410
+ status: () => {
411
+ const disk = codeHashOf(EXTENSION, new Set(['config.json']));
412
+ return { running: relay.hello?.codeHash || null, onDisk: disk, upToDate: !!disk && relay.hello?.codeHash === disk, note };
413
+ },
414
+ stop() { clearInterval(timer); },
415
+ };
416
+ }
417
+
418
+ /**
419
+ * Close sessions whose owner processes are all gone. Agents are told to close() what they open,
420
+ * but they forget, and one that is killed or crashes never gets the chance. Each session keeps the
421
+ * pids that claimed it (whoever created it, plus anyone it was handed to); once none is alive
422
+ * it is closed at the next look (every 5 s). There used to be a minute's grace for an owner guessed
423
+ * too narrowly; in four days of logs it rescued nothing, and what it did do was keep 778 sessions
424
+ * of a server with a dead owner alive just long enough to hide that they were all being thrown away.
425
+ *
426
+ * There are no exceptions. Sessions left open on purpose (keepOpen) and sessions paused when the
427
+ * time came used to be dropped from the watch, and then nothing ever closed them. In every one of
428
+ * the 35 hand-overs on record (2026-09-16 to 11-23) the agent was still running when the user
429
+ * answered, so the exception for paused sessions never once applied.
430
+ */
431
+ function watchOwners({ relay, recorders, abandon, log, graceMs }) {
432
+ const watched = new Map(); // sessionId -> { key, pids: Set<number>, orphanSince: number|null }
433
+ try {
434
+ for (const [id, w] of Object.entries(JSON.parse(readFileSync(OWNERS_FILE, 'utf8')))) {
435
+ watched.set(id, { key: w.key, pids: new Set(w.pids), orphanSince: w.orphanSince ?? null });
436
+ }
437
+ } catch { /* first run, or unreadable: start empty */ }
438
+
439
+ const save = () => {
440
+ try {
441
+ mkdirSync(dirname(OWNERS_FILE), { recursive: true, mode: 0o700 });
442
+ const obj = Object.fromEntries([...watched].map(([id, w]) => [id, { key: w.key, pids: [...w.pids], orphanSince: w.orphanSince }]));
443
+ writeFileSync(OWNERS_FILE, JSON.stringify(obj), { mode: 0o600 });
444
+ } catch (e) { log(`owners: cannot save ${OWNERS_FILE}: ${e.message}`); }
445
+ };
446
+
447
+ relay.on('event:session.closed', (p) => { if (watched.delete(p.sessionId)) save(); });
448
+
449
+ let busy = false;
450
+ const tick = async () => {
451
+ if (busy) return;
452
+ busy = true;
453
+ try {
454
+ let changed = false;
455
+ for (const [id, w] of watched) {
456
+ for (const pid of w.pids) if (!isAlive(pid)) { w.pids.delete(pid); changed = true; }
457
+ if (w.pids.size) { if (w.orphanSince) { w.orphanSince = null; changed = true; } continue; }
458
+ if (!w.orphanSince) { w.orphanSince = Date.now(); changed = true; }
459
+ if (Date.now() - w.orphanSince < graceMs || !relay.connected) continue;
460
+ try { await relay.call('session.attach', { sessionId: id, key: w.key }); }
461
+ catch (e) {
462
+ if (/unknown session|not your session/.test(e.message)) { watched.delete(id); changed = true; }
463
+ continue; // the browser went away mid-call: try again next tick
464
+ }
465
+ for (const [k, rec] of recorders) {
466
+ if (!k.startsWith(`${id}:`)) continue;
467
+ recorders.delete(k);
468
+ abandon(id, rec, 'owner exited');
469
+ }
470
+ try { await relay.call('session.close', { sessionId: id, key: w.key }); log(`owners: closed ${id}, its owners exited`); logEvent('owner.closed', { sessionId: id, graceMs }); }
471
+ catch (e) { if (!/unknown session/.test(e.message)) continue; }
472
+ watched.delete(id); changed = true;
473
+ }
474
+ if (changed) save();
475
+ } finally { busy = false; }
476
+ };
477
+ const timer = setInterval(() => { tick().catch((e) => log(`owners: ${e.message}`)); }, OWNER_POLL_MS);
478
+ timer.unref();
479
+
480
+ return {
481
+ /** owner: a pid to add. */
482
+ set(sessionId, key, owner) {
483
+ if (!Number.isInteger(owner) || owner <= 1) throw new Error(`owner must be a process id, got ${JSON.stringify(owner)}`);
484
+ // Every CLI call registers its owner again; only a change is worth a line (it was a quarter of the log).
485
+ if (!watched.get(sessionId)?.pids.has(owner)) logEvent('owner.set', { sessionId, owner });
486
+ const w = watched.get(sessionId) || { key, pids: new Set(), orphanSince: null };
487
+ w.key = key;
488
+ w.pids.add(owner);
489
+ w.orphanSince = null;
490
+ watched.set(sessionId, w);
491
+ save();
492
+ },
493
+ stop() { clearInterval(timer); },
494
+ };
495
+ }
496
+
497
+ // run directly: `node runtime/daemon.js`
498
+ // Windows 는 process.argv[1] 이 역슬래시 경로라 '/' 로만 나누면 판정이 늘 거짓이 되어 데몬이 안 뜬다 (Windows 실측)
499
+ if (process.argv[1] && import.meta.url.endsWith(process.argv[1].split(/[\\/]/).pop())) {
500
+ // Every agent on this machine shares this process: one promise nobody handled must not end it.
501
+ process.on('unhandledRejection', (e) => { logEvent('daemon.error', { error: String(e?.stack || e).slice(0, 600) }); console.error('daemon: unhandled rejection:', e); });
502
+ startDaemon({ log: console.error }).catch((e) => { console.error('daemon failed:', e.message); process.exit(1); });
503
+ }
@@ -0,0 +1,53 @@
1
+ // macOS focus monitor: samples the frontmost application so spikes can prove
2
+ // the browser never took keyboard/mouse focus while a session was working.
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+
6
+ const execFileP = promisify(execFile);
7
+ const isMac = process.platform === 'darwin';
8
+
9
+ export async function frontmostApp() {
10
+ if (!isMac) return 'unknown';
11
+ const { stdout } = await execFileP('osascript', ['-e', 'tell application "System Events" to get name of first application process whose frontmost is true']);
12
+ return stdout.trim();
13
+ }
14
+
15
+ export async function activateApp(name) {
16
+ if (!isMac) return;
17
+ await execFileP('osascript', ['-e', `tell application "${name.replace(/"/g, '\\"')}" to activate`]).catch(() => {});
18
+ }
19
+
20
+ export class FocusMonitor {
21
+ constructor({ intervalMs = 200 } = {}) {
22
+ this.intervalMs = intervalMs;
23
+ this.samples = 0;
24
+ this.changes = [];
25
+ this.timer = null;
26
+ this.last = null;
27
+ this.started = 0;
28
+ }
29
+
30
+ async start() {
31
+ this.started = Date.now();
32
+ this.last = await frontmostApp();
33
+ this.initial = this.last;
34
+ const tick = async () => {
35
+ try {
36
+ const app = await frontmostApp();
37
+ this.samples++;
38
+ if (app !== this.last) {
39
+ this.changes.push({ at: Date.now() - this.started, from: this.last, to: app });
40
+ this.last = app;
41
+ }
42
+ } catch { /* ignore */ }
43
+ if (this.timer !== null) this.timer = setTimeout(tick, this.intervalMs);
44
+ };
45
+ this.timer = setTimeout(tick, this.intervalMs);
46
+ }
47
+
48
+ stop() {
49
+ clearTimeout(this.timer);
50
+ this.timer = null;
51
+ return { initial: this.initial, final: this.last, samples: this.samples, changes: this.changes };
52
+ }
53
+ }