deictic 0.3.0 → 0.4.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 (175) hide show
  1. package/API.md +31 -19
  2. package/README.md +6 -26
  3. package/dist/annotations/client.d.ts +1 -1
  4. package/dist/annotations/client.js +1 -1
  5. package/dist/annotations/index.d.ts +2 -101
  6. package/dist/annotations/index.js +1 -22
  7. package/dist/astro.d.ts +1 -1
  8. package/dist/astro.js +1 -1
  9. package/dist/cli.d.ts +1 -0
  10. package/dist/cli.js +37 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/index.js +1 -10
  13. package/dist/logs/client.d.ts +1 -1
  14. package/dist/logs/client.js +1 -1
  15. package/dist/logs/index.d.ts +2 -18
  16. package/dist/logs/index.js +1 -21
  17. package/dist/network/client.d.ts +1 -1
  18. package/dist/network/client.js +1 -1
  19. package/dist/network/index.d.ts +1 -1
  20. package/dist/network/index.js +1 -37
  21. package/dist/recommended/index.d.ts +7 -7
  22. package/dist/recommended/index.js +1 -26
  23. package/dist/recordings/client.d.ts +1 -1
  24. package/dist/recordings/client.js +1 -1
  25. package/dist/recordings/index.d.ts +1 -1
  26. package/dist/screenshots/client.d.ts +1 -1
  27. package/dist/screenshots/client.js +1 -108
  28. package/dist/screenshots/dom.d.ts +1 -1
  29. package/dist/screenshots/dom.js +1 -1
  30. package/dist/screenshots/index.d.ts +1 -1
  31. package/dist/screenshots/index.js +1 -98
  32. package/dist/screenshots/rrweb.d.ts +2 -1
  33. package/dist/screenshots/rrweb.d.ts.map +1 -1
  34. package/dist/screenshots/rrweb.js +6 -2
  35. package/dist/screenshots/rrweb.js.map +1 -1
  36. package/dist/shared/annotations.js +22 -0
  37. package/dist/shared/annotations.js.map +1 -0
  38. package/dist/shared/board.js +190 -0
  39. package/dist/shared/board.js.map +1 -0
  40. package/dist/shared/client.js +108 -0
  41. package/dist/{screenshots → shared}/client.js.map +1 -1
  42. package/dist/shared/endpoints.js +4 -1
  43. package/dist/shared/endpoints.js.map +1 -1
  44. package/dist/shared/find.js +156 -0
  45. package/dist/shared/find.js.map +1 -0
  46. package/dist/shared/frame.js +75 -0
  47. package/dist/shared/frame.js.map +1 -0
  48. package/dist/shared/index.d.ts +5 -0
  49. package/dist/shared/index.d.ts.map +1 -1
  50. package/dist/shared/index2.d.ts +85 -84
  51. package/dist/shared/index2.d.ts.map +1 -1
  52. package/dist/shared/index3.d.ts +83 -89
  53. package/dist/shared/index3.d.ts.map +1 -1
  54. package/dist/shared/index4.d.ts +98 -50
  55. package/dist/shared/index4.d.ts.map +1 -1
  56. package/dist/shared/index5.d.ts +13 -215
  57. package/dist/shared/index5.d.ts.map +1 -1
  58. package/dist/shared/index6.d.ts +55 -61
  59. package/dist/shared/index6.d.ts.map +1 -1
  60. package/dist/shared/index7.d.ts +224 -0
  61. package/dist/shared/index7.d.ts.map +1 -0
  62. package/dist/shared/index8.d.ts +52 -0
  63. package/dist/shared/index8.d.ts.map +1 -0
  64. package/dist/shared/index9.d.ts +70 -0
  65. package/dist/shared/index9.d.ts.map +1 -0
  66. package/dist/shared/init.js +472 -0
  67. package/dist/shared/init.js.map +1 -0
  68. package/dist/shared/local.js +165 -0
  69. package/dist/shared/local.js.map +1 -0
  70. package/dist/shared/logs.js +22 -0
  71. package/dist/shared/logs.js.map +1 -0
  72. package/dist/shared/network.js +39 -0
  73. package/dist/shared/network.js.map +1 -0
  74. package/dist/shared/packages.js +125 -0
  75. package/dist/shared/packages.js.map +1 -0
  76. package/dist/shared/playwright.js +36 -9
  77. package/dist/shared/playwright.js.map +1 -1
  78. package/dist/shared/recommended.js +26 -0
  79. package/dist/shared/recommended.js.map +1 -0
  80. package/dist/shared/recording.js +316 -0
  81. package/dist/shared/recording.js.map +1 -0
  82. package/dist/shared/recordings.js +2 -1
  83. package/dist/shared/recordings.js.map +1 -1
  84. package/dist/shared/screenshots.js +108 -0
  85. package/dist/shared/screenshots.js.map +1 -0
  86. package/dist/shared/src.js +10 -0
  87. package/dist/shared/src.js.map +1 -0
  88. package/dist/shared/task.js +108 -0
  89. package/dist/shared/task.js.map +1 -0
  90. package/dist/shared/tasks.js +33 -191
  91. package/dist/shared/tasks.js.map +1 -1
  92. package/dist/shared/transcribe.js +128 -0
  93. package/dist/shared/transcribe.js.map +1 -0
  94. package/dist/shared/vb.js +13 -0
  95. package/dist/shared/vb.js.map +1 -0
  96. package/dist/shared/vite.d.ts +16 -0
  97. package/dist/shared/vite.d.ts.map +1 -0
  98. package/dist/shared/vite.js +61 -0
  99. package/dist/shared/vite.js.map +1 -0
  100. package/dist/shared/voice.js +84 -0
  101. package/dist/{voice/index.js.map → shared/voice.js.map} +1 -1
  102. package/dist/shared/voice2.js +90 -0
  103. package/dist/shared/voice2.js.map +1 -0
  104. package/dist/shared/watch.js +209 -0
  105. package/dist/shared/watch.js.map +1 -0
  106. package/dist/shared/watchers.js +62 -0
  107. package/dist/shared/watchers.js.map +1 -0
  108. package/dist/tailwind/client.d.ts +1 -1
  109. package/dist/tailwind/client.js +1 -1
  110. package/dist/tailwind/index.d.ts +1 -1
  111. package/dist/tailwind/index.js +1 -1
  112. package/dist/tasks/client.d.ts +1 -1
  113. package/dist/tasks/client.d.ts.map +1 -1
  114. package/dist/tasks/client.js +45 -8
  115. package/dist/tasks/client.js.map +1 -1
  116. package/dist/tasks/index.d.ts +1 -1
  117. package/dist/tasks/index.js +3 -1
  118. package/dist/vite.d.ts +2 -15
  119. package/dist/vite.js +2 -60
  120. package/dist/voice/client.d.ts +1 -1
  121. package/dist/voice/client.js +1 -1
  122. package/dist/voice/index.d.ts +2 -52
  123. package/dist/voice/index.js +1 -84
  124. package/package.json +6 -9
  125. package/skills/deictic/SKILL.md +27 -42
  126. package/skills/deictic/references/recordings.md +9 -108
  127. package/skills/deictic/references/tasks.md +21 -107
  128. package/skills/deictic/references/watch.md +13 -66
  129. package/src/cli/board.ts +204 -0
  130. package/src/cli/bun.ts +133 -0
  131. package/src/cli/edit.ts +56 -0
  132. package/src/cli/find.ts +147 -0
  133. package/src/cli/frame.ts +90 -0
  134. package/src/cli/init.ts +388 -0
  135. package/src/cli/recording.ts +383 -0
  136. package/src/cli/task.ts +126 -0
  137. package/src/cli/transcribe.ts +129 -0
  138. package/src/cli/vb.ts +11 -0
  139. package/src/cli/voice.ts +59 -0
  140. package/src/cli/watch.ts +221 -0
  141. package/src/cli.ts +37 -0
  142. package/src/index.ts +5 -0
  143. package/src/plugins/logs/index.ts +1 -0
  144. package/src/plugins/network/index.ts +1 -0
  145. package/src/plugins/recordings/index.ts +1 -0
  146. package/src/plugins/screenshots/client.ts +3 -2
  147. package/src/plugins/screenshots/index.ts +10 -3
  148. package/src/plugins/screenshots/playwright.ts +34 -7
  149. package/src/plugins/screenshots/rrweb.ts +5 -1
  150. package/src/plugins/tasks/client.ts +62 -7
  151. package/src/plugins/tasks/index.ts +41 -20
  152. package/src/plugins/tasks/local.ts +19 -6
  153. package/src/plugins/tasks/watchers.ts +41 -6
  154. package/src/tools/endpoints.ts +3 -0
  155. package/src/tools/packages.ts +107 -0
  156. package/dist/annotations/index.d.ts.map +0 -1
  157. package/dist/annotations/index.js.map +0 -1
  158. package/dist/index.js.map +0 -1
  159. package/dist/logs/index.d.ts.map +0 -1
  160. package/dist/logs/index.js.map +0 -1
  161. package/dist/network/index.js.map +0 -1
  162. package/dist/recommended/index.js.map +0 -1
  163. package/dist/screenshots/index.js.map +0 -1
  164. package/dist/vite.d.ts.map +0 -1
  165. package/dist/vite.js.map +0 -1
  166. package/dist/voice/index.d.ts.map +0 -1
  167. package/skills/deictic/references/install.md +0 -103
  168. package/skills/deictic/scripts/frame.mjs +0 -62
  169. package/skills/deictic/scripts/lib.mjs +0 -277
  170. package/skills/deictic/scripts/recording.mjs +0 -266
  171. package/skills/deictic/scripts/task.mjs +0 -113
  172. package/skills/deictic/scripts/transcribe.mjs +0 -93
  173. package/skills/deictic/scripts/vb.mjs +0 -12
  174. package/skills/deictic/scripts/voice.mjs +0 -50
  175. package/skills/deictic/scripts/watch.mjs +0 -115
@@ -0,0 +1,59 @@
1
+ /**
2
+ * `deictic voice`: when something was said: the stretches of speech in voice clips, found by ffmpeg's silence
3
+ * detection. For a recording, in the recording's time, to line up with its timeline; for a task, each voice note on
4
+ * it too. `--wav` writes each clip as 16 kHz mono WAV, what speech-to-text tools take.
5
+ */
6
+ import { mkdirSync } from 'node:fs';
7
+ import { join, resolve } from 'node:path';
8
+
9
+ import { clock, parseArgs } from './board.ts';
10
+ import { ffmpeg, voiceClips } from './find.ts';
11
+
12
+ export const usage =
13
+ 'voice <task | replay URL | recording ID | file | clip ID> [--noise -35] [--gap 0.4] [--wav dir] [--json] when speech happens';
14
+
15
+ export async function run(args: string[]): Promise<void> {
16
+ const { values, positionals } = parseArgs(args, {
17
+ noise: { type: 'string', default: '-35' },
18
+ gap: { type: 'string', default: '0.4' },
19
+ wav: { type: 'string' },
20
+ json: { type: 'boolean' },
21
+ });
22
+ const noise = Number(values.noise);
23
+ const gap = Number(values.gap);
24
+ const wav = values.wav === undefined ? undefined : resolve(values.wav);
25
+
26
+ const results = [];
27
+ for (const c of await voiceClips(positionals[0])) {
28
+ // ffmpeg reports silence; speech is what's between. MediaRecorder's webm has no duration, so it's measured.
29
+ const log = ffmpeg(['-i', c.file, '-af', `silencedetect=noise=${noise}dB:d=${gap}`, '-f', 'null', '-']).log;
30
+ const starts = [...log.matchAll(/silence_start: (-?[\d.]+)/g)].map((m) => Number(m[1]) * 1000);
31
+ const ends = [...log.matchAll(/silence_end: (-?[\d.]+)/g)].map((m) => Number(m[1]) * 1000);
32
+ const times = [...log.matchAll(/time=(\d+):(\d+):([\d.]+)/g)].at(-1);
33
+ const length = times ? (Number(times[1]) * 3600 + Number(times[2]) * 60 + Number(times[3])) * 1000 : Math.max(0, ...ends);
34
+ const speech: [number, number][] = [];
35
+ let from = 0;
36
+ for (const [i, start] of starts.entries()) {
37
+ if (start - from > 150) speech.push([from, start]);
38
+ from = ends[i] ?? length;
39
+ }
40
+ if (length - from > 150) speech.push([from, length]);
41
+ if (wav !== undefined) {
42
+ mkdirSync(wav, { recursive: true });
43
+ ffmpeg(['-y', '-loglevel', 'error', '-i', c.file, '-ar', '16000', '-ac', '1', '-sample_fmt', 's16', join(wav, `${c.id}.wav`)]);
44
+ }
45
+ results.push({ ...c, length, speech: speech.map(([a, b]) => ({ from: c.at + a, to: c.at + b })) });
46
+ }
47
+
48
+ if (values.json) {
49
+ console.log(JSON.stringify(results, null, 2));
50
+ return;
51
+ }
52
+ for (const r of results) {
53
+ const where = r.recording === undefined ? 'a voice note' : `in recording ${r.recording}, from ${clock(r.at)}`;
54
+ console.log(`clip ${r.id} (${where}), ${clock(r.length)} long: ${r.file}`);
55
+ if (r.speech.length === 0) console.log(' no speech found: try a lower --noise, like -45');
56
+ for (const s of r.speech) console.log(` ${clock(s.from).padStart(6)} – ${clock(s.to).padStart(6)} speech`);
57
+ if (wav !== undefined) console.log(` wav: ${join(wav, `${r.id}.wav`)}`);
58
+ }
59
+ }
@@ -0,0 +1,221 @@
1
+ /**
2
+ * `deictic watch`: the board's tasks for deictic, one line per thing to act on: the tasks ready now as it starts,
3
+ * then each new task, a reply on one, and one canceled (undone in the page, say). Made for an agent's monitor (each
4
+ * line an event). A board that goes away (the dev server restarted, and its board with it) is waited for and followed
5
+ * again from where it was left; it says so, and ends only if none comes back. It ends by itself once nothing has
6
+ * happened on the channel for `--idle` (20m): a watch nobody feeds isn't started again, so no agent watches for ever.
7
+ * With `--once` it ends at the first thing to act on, for a harness that's woken only when a command exits. It ends,
8
+ * too, when the process that started it does: nobody reads its lines then.
9
+ *
10
+ * While it runs the project's Task tab shows who watches (`watcherAt`). Replies the watcher wrote itself are left out
11
+ * where it has a name of its own (BOARD_PROFILE): with none it writes as the person. Exits 0 after `--once`'s event,
12
+ * 2 when idle, 1 when the board went away.
13
+ */
14
+ import { type ChildProcess, spawn, spawnSync } from 'node:child_process';
15
+ import { createInterface } from 'node:readline';
16
+
17
+ import { watcherAt } from '#src/plugins/tasks/watchers.ts';
18
+
19
+ import { answers, boardIn, boardUrl, deicticDirs, duration, parseArgs, vb, vbCommand, whoami } from './board.ts';
20
+
21
+ export const usage = 'watch [channel] [--idle 20m] [--once] [--label k=v] a line per new task, reply and cancellation';
22
+
23
+ /** What `vb tail --json` prints, one per line. */
24
+ interface Tailed {
25
+ type: string;
26
+ cursor?: string;
27
+ payload?: {
28
+ id?: number;
29
+ thread?: number;
30
+ re?: number | null;
31
+ text?: string;
32
+ reason?: string;
33
+ labels?: Record<string, string>;
34
+ by?: { actor: string };
35
+ };
36
+ message?: { author?: { handle?: string } };
37
+ }
38
+
39
+ /** How long a board that went away is waited for: a dev server's restart takes a few seconds. */
40
+ const BACK = 60_000;
41
+ /** A tail that ends sooner than this after it's started again isn't started a third time: the board isn't the trouble. */
42
+ const SOON = 10_000;
43
+
44
+ /** Each process's parent, by ID, asked of the system once: empty where it can't say. */
45
+ function parents(): Map<number, number> {
46
+ const run =
47
+ process.platform === 'win32'
48
+ ? spawnSync(
49
+ 'powershell',
50
+ ['-NoProfile', '-Command', 'Get-CimInstance Win32_Process | % { "$($_.ProcessId) $($_.ParentProcessId)" }'],
51
+ {
52
+ encoding: 'utf8',
53
+ },
54
+ )
55
+ : spawnSync('ps', ['-A', '-o', 'pid=', '-o', 'ppid='], { encoding: 'utf8' });
56
+ const map = new Map<number, number>();
57
+ for (const line of (run.stdout ?? '').split('\n')) {
58
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);
59
+ if (pid !== undefined && ppid !== undefined && Number.isInteger(pid) && Number.isInteger(ppid)) map.set(pid, ppid);
60
+ }
61
+ return map;
62
+ }
63
+
64
+ /**
65
+ * The processes above this one's parent, the nearest `count` of them. A runner (`npx`, `pnpm exec`, and on Windows the
66
+ * shell and the bin's `.cmd` shim it runs) sits between the watch and the shell that ran it, and outlives that shell.
67
+ */
68
+ function ancestors(count: number): number[] {
69
+ const of = parents();
70
+ const out: number[] = [];
71
+ for (let pid = of.get(process.ppid); pid !== undefined && pid > 1 && out.length < count && !out.includes(pid); pid = of.get(pid))
72
+ out.push(pid);
73
+ return out;
74
+ }
75
+
76
+ /** Whether a process is gone. On Windows a dead parent's ID stays a child's `ppid`, so the system is asked. */
77
+ function gone(pid: number): boolean {
78
+ try {
79
+ process.kill(pid, 0);
80
+ return false;
81
+ } catch (e) {
82
+ return (e as { code?: string }).code === 'ESRCH';
83
+ }
84
+ }
85
+
86
+ export function run(args: string[]): void {
87
+ const { values, positionals } = parseArgs(args, {
88
+ idle: { type: 'string', default: '20m' },
89
+ once: { type: 'boolean' },
90
+ label: { type: 'string', multiple: true },
91
+ });
92
+ const channel = positionals[0] ?? 'deictic';
93
+ const labels = (values.label ?? []).flatMap((l) => ['--label', l]);
94
+ const idle = duration(values.idle);
95
+ const say = (line: string) => console.log(line.replace(/\s+/g, ' ').trim());
96
+ const first = (text: string) => (text.split('\n---')[0] ?? '').trim().slice(0, 160);
97
+
98
+ const ready = vb(['tasks', channel, '--state', 'ready', ...labels]).trim();
99
+ const me = whoami();
100
+ // In the `.deictic/` whose board this is, or in each one near here where the board is the environment's.
101
+ const url = boardUrl();
102
+ const dirs = deicticDirs();
103
+ const own = dirs.filter((dir) => boardIn(dir) === url);
104
+ const unseen = watcherAt(own.length > 0 ? own : dirs, me.profile ?? me.name ?? me.handle ?? me.actor, channel);
105
+ let tail: ChildProcess | undefined;
106
+ const end = (code: number) => {
107
+ unseen();
108
+ tail?.removeAllListeners('exit');
109
+ tail?.kill();
110
+ process.exit(code);
111
+ };
112
+ // Stopped by its monitor, where the system says so: the page isn't left thinking someone watches.
113
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.on(signal, () => end(0));
114
+
115
+ // Whoever started the watch reads its lines. With that gone (a session that ended and left the watch behind) no one
116
+ // does, and the page mustn't go on saying an agent watches. Run through a runner, the shell is a few processes up,
117
+ // so those are watched too: any gone, and the watch ends. A dead parent shows as another parent's ID, except on
118
+ // Windows, where the system is asked whether it's still a process.
119
+ const parent = process.ppid;
120
+ const above = ancestors(3);
121
+ const orphaned = () => process.ppid !== parent || gone(parent) || above.some(gone);
122
+ setInterval(() => orphaned() && end(0), 5000);
123
+
124
+ say(`watching ${channel} on ${url ?? "the team's board"} as ${me.handle ?? me.actor}`);
125
+ // With no profile (an agent `profileOf` doesn't know), the person's replies and the watcher's own are one actor's:
126
+ // none can be left out.
127
+ if (me.profile === null) {
128
+ say(
129
+ `you write as ${me.handle ?? me.actor}, the person's own identity, as nothing here says which agent you are: set BOARD_PROFILE=<your name> (claude, codex) on every command, this watch too, and start it again`,
130
+ );
131
+ }
132
+ const waiting = (ready ? ready.split('\n') : []).filter((line) => /^#\d+/.test(line));
133
+ for (const line of waiting) say(`ready: ${line}`);
134
+ if (values.once && waiting.length > 0) end(0);
135
+
136
+ /** One thing to act on: all `--once` waits for. */
137
+ const event = (line: string) => {
138
+ say(line);
139
+ if (values.once) end(0);
140
+ };
141
+
142
+ // Anything on the channel puts the end off, the watcher's own claims and replies too: it's being worked.
143
+ let quiet: ReturnType<typeof setTimeout> | undefined;
144
+ const heard = () => {
145
+ clearTimeout(quiet);
146
+ quiet = setTimeout(() => {
147
+ say(
148
+ `idle: nothing on ${channel} in ${values.idle}, so the watch is over. Don't start it again by yourself: tell the person in a line that you've stopped watching, and watch again when they ask. Only if you're working a task now, start it once more when that's done.`,
149
+ );
150
+ end(2);
151
+ }, idle);
152
+ };
153
+ heard();
154
+
155
+ // What the board says about each thread: its root's first line and where, to name it when a task is made.
156
+ const roots = new Map<number, string>();
157
+ // The last event heard, which a tail started again follows from: nothing left while the board was away is missed.
158
+ let cursor: string | undefined;
159
+ const heardOf = (line: string) => {
160
+ let e: Tailed;
161
+ try {
162
+ e = JSON.parse(line) as Tailed;
163
+ } catch {
164
+ return;
165
+ }
166
+ if (e.cursor !== undefined) cursor = e.cursor;
167
+ heard();
168
+ const p = e.payload ?? {};
169
+ const label = (key: string) => p.labels?.[key];
170
+ if (e.type === 'message.posted' && p.re === null && p.thread !== undefined) {
171
+ const at = label('deictic.at');
172
+ const page = label('deictic.page');
173
+ const project = label('deictic.project');
174
+ roots.set(p.thread, `"${first(p.text ?? '')}"${at ? ` at ${at}` : ''}${page ? ` on ${page}` : ''}${project ? ` in ${project}` : ''}`);
175
+ }
176
+ if (e.type === 'task.created') event(`new task #${p.id}: ${roots.get(p.thread ?? -1) ?? ''}. Read it: npx deictic task ${p.id}`);
177
+ if (e.type === 'message.posted' && p.re !== null && p.re !== undefined) {
178
+ if (me.profile !== null && p.by?.actor === me.actor) return;
179
+ const by = e.message?.author?.handle ?? p.by?.actor ?? 'someone';
180
+ event(`reply on #${p.re} by ${by}: ${first(p.text ?? '')}`);
181
+ }
182
+ if (e.type === 'task.canceled')
183
+ event(`task #${p.id} canceled: ${p.reason ?? ''}. Stop work on it, and put back what you changed for it.`);
184
+ };
185
+
186
+ const over = (code: number | null) => {
187
+ say(`watch ended (vb tail exited ${code}): start it again`);
188
+ end(1);
189
+ };
190
+
191
+ /** Follows the channel, from `cursor` on where there is one, and again when the board comes back after going away. */
192
+ const follow = (again: boolean) => {
193
+ const started = Date.now();
194
+ const from = cursor === undefined ? [] : ['--after', cursor];
195
+ const [command, argv, options] = vbCommand(['tail', channel, ...labels, ...from, '--json']);
196
+ const child = spawn(command, argv, { env: options.env, shell: options.shell, stdio: ['ignore', 'pipe', 'inherit'] });
197
+ tail = child;
198
+ createInterface({ input: child.stdout }).on('line', heardOf);
199
+ child.on('exit', (code) => {
200
+ if (again && Date.now() - started < SOON) return over(code);
201
+ say(`the board went away (vb tail exited ${code}): waiting for it to come back`);
202
+ const until = Date.now() + BACK;
203
+ const tried = () => {
204
+ // Asked anew each time: a board started again may be at another URL, and the CLI gets itself a new token for it.
205
+ if (answers()) {
206
+ say(`the board is back on ${boardUrl() ?? "the team's board"}: watching ${channel} again`);
207
+ // With nothing heard before it went, what's ready is all there is to go by.
208
+ if (cursor === undefined) {
209
+ const now = vb(['tasks', channel, '--state', 'ready', ...labels]).trim();
210
+ for (const l of now.split('\n').filter((l) => /^#\d+/.test(l) && !waiting.includes(l))) event(`ready: ${l}`);
211
+ }
212
+ return follow(true);
213
+ }
214
+ if (Date.now() > until) return over(code);
215
+ setTimeout(tried, 2000);
216
+ };
217
+ setTimeout(tried, 2000);
218
+ });
219
+ };
220
+ follow(false);
221
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The `deictic` command. `init` sets a project up, for the person; the rest are for the agent that works the tasks,
4
+ * as the skill says: the board, a watch, a task, and what a task carries. Each in `cli/`, loaded when it's run, so
5
+ * `deictic task` doesn't load the parser `init` edits configs with. Run in the project, where its board and
6
+ * `.deictic/` are: `npx deictic <command>`.
7
+ */
8
+ const COMMANDS = {
9
+ init: () => import('./cli/init.ts'),
10
+ vb: () => import('./cli/vb.ts'),
11
+ watch: () => import('./cli/watch.ts'),
12
+ task: () => import('./cli/task.ts'),
13
+ recording: () => import('./cli/recording.ts'),
14
+ frame: () => import('./cli/frame.ts'),
15
+ voice: () => import('./cli/voice.ts'),
16
+ transcribe: () => import('./cli/transcribe.ts'),
17
+ };
18
+
19
+ type Name = keyof typeof COMMANDS;
20
+ const isName = (name: string | undefined): name is Name => name !== undefined && Object.hasOwn(COMMANDS, name);
21
+
22
+ async function help(): Promise<string> {
23
+ const lines = await Promise.all(Object.values(COMMANDS).map(async (load) => ` ${(await load()).usage}`));
24
+ return `Usage: deictic <command>\n\nSetting up:\n${lines[0]}\n\nFor the agent that works the tasks (the skill):\n${lines.slice(1).join('\n')}\n`;
25
+ }
26
+
27
+ const [name, ...args] = process.argv.slice(2);
28
+ if (!isName(name)) {
29
+ const asked = name === undefined || name === '-h' || name === '--help' || name === 'help';
30
+ (asked ? process.stdout : process.stderr).write(`${asked ? '' : `deictic: no command "${name}"\n\n`}${await help()}`);
31
+ process.exit(asked ? 0 : 1);
32
+ }
33
+ if (name !== 'vb' && (args.includes('-h') || args.includes('--help'))) {
34
+ process.stdout.write(`Usage: deictic ${(await COMMANDS[name]()).usage}\n`);
35
+ process.exit(0);
36
+ }
37
+ await (await COMMANDS[name]()).run(args);
package/src/index.ts CHANGED
@@ -122,6 +122,11 @@ export interface ServerPlugin<Model = unknown, Op = unknown, Record = unknown, A
122
122
  shortcut?: Shortcut;
123
123
  /** The plugins it can't do without, by name: the dev server won't start without them. */
124
124
  needs?: string[];
125
+ /**
126
+ * The packages it imports that the project installs itself (optional peers), by name: as the dev server starts,
127
+ * it says how to install any that's missing, rather than failing when first used.
128
+ */
129
+ packages?: string[];
125
130
  /** Runs once, as the dev server starts and before it answers anything. Answers the plugin's API to the others. */
126
131
  setup?(context: ServerContext): Maybe<Api>;
127
132
  /** Routes of its own, by their first segment under `/__deictic/plugins/<name>/`. */
@@ -48,6 +48,7 @@ export function logs(options: LogsOptions = {}) {
48
48
  return definePlugin<never, never>({
49
49
  name: 'logs',
50
50
  client: 'deictic/logs/client',
51
+ packages: ['@rrweb/rrweb-plugin-console-record'],
51
52
  clientOptions: { levels: options.levels },
52
53
  });
53
54
  }
@@ -56,6 +56,7 @@ export function network(options: NetworkOptions = {}) {
56
56
  return definePlugin<never, never>({
57
57
  name: 'network',
58
58
  client: 'deictic/network/client',
59
+ packages: ['@rrweb/rrweb-plugin-network-record'],
59
60
  clientOptions: {
60
61
  initiators: options.initiators ?? ['fetch', 'xmlhttprequest'],
61
62
  headers: options.headers ?? false,
@@ -188,6 +188,7 @@ export function recordings(options: RecordingsOptions = {}) {
188
188
  return definePlugin<never, never, never, Recordings>({
189
189
  name: 'recordings',
190
190
  client: 'deictic/recordings/client',
191
+ packages: ['rrweb', 'rrweb-player'],
191
192
  clientOptions: {
192
193
  masking: {
193
194
  blockClass: options.blockClass ?? 'rr-block',
@@ -76,9 +76,10 @@ export function screenshotsClient(capture: PageCapture) {
76
76
  const add = async (body: Blob | string, type: string, { box, size }: Pick<Shot, 'box' | 'size'>): Promise<Shot> => {
77
77
  const res = await request('add', { method: 'POST', headers: { 'content-type': type }, body });
78
78
  // `url`: where the shot is, said by what keeps it with no server to serve it from (a `standalone` build).
79
- const { id, url, problem } = (await res.json()) as { id?: string; url?: string; problem?: string };
79
+ // `box`: where the element is in a shot drawn again elsewhere, which is what's true of the PNG.
80
+ const { id, url, problem, box: drawn } = (await res.json()) as { id?: string; url?: string; problem?: string; box?: Box };
80
81
  if (id === undefined) throw new Error(`screenshots: ${problem ?? res.statusText}`);
81
- return { id, url: url ?? `${base}__deictic/plugins/screenshots/shot/${id}`, box, size };
82
+ return { id, url: url ?? `${base}__deictic/plugins/screenshots/shot/${id}`, box: drawn ?? box, size };
82
83
  };
83
84
  return {
84
85
  capture: async (element, { area = 'viewport' } = {}) => {
@@ -92,7 +92,10 @@ export interface Renderer {
92
92
  client: string;
93
93
  /** What the page half gets, besides the masking. */
94
94
  clientOptions?: unknown;
95
- render?(input: unknown): Promise<Uint8Array>;
95
+ /** The packages it imports that the project installs, as a plugin's `packages`. */
96
+ packages?: string[];
97
+ /** The PNG, or with it the element's `box` in it, where it's not where the page said (the page was drawn again elsewhere). */
98
+ render?(input: unknown): Promise<Uint8Array | { png: Uint8Array; box?: Box }>;
96
99
  }
97
100
 
98
101
  /** Where `rrweb()` finds a browser: any Chromium renders the snapshot as the page's own would. */
@@ -104,7 +107,7 @@ export interface BrowserOptions {
104
107
  }
105
108
 
106
109
  /** Draws the page in the page, from its DOM (`modern-screenshot`): no server needed, but text may lay out a little differently. */
107
- export const dom = (): Renderer => ({ client: 'deictic/screenshots/dom' });
110
+ export const dom = (): Renderer => ({ client: 'deictic/screenshots/dom', packages: ['modern-screenshot'] });
108
111
 
109
112
  /**
110
113
  * Snapshots the page's DOM in the page (`rrweb-snapshot`, masking as rrweb does) and renders it in a
@@ -112,6 +115,7 @@ export const dom = (): Renderer => ({ client: 'deictic/screenshots/dom' });
112
115
  */
113
116
  export const rrweb = (options: BrowserOptions = {}): Renderer => ({
114
117
  client: 'deictic/screenshots/rrweb',
118
+ packages: ['rrweb-snapshot', 'playwright-core'],
115
119
  // Loaded on the first shot, so a project rendering in the page needn't install Playwright.
116
120
  render: async (input) => (await import('./playwright.ts')).render(input, options),
117
121
  });
@@ -154,6 +158,7 @@ export function screenshots(options: ScreenshotsOptions = {}) {
154
158
  return definePlugin<never, never, never, Screenshots>({
155
159
  name: 'screenshots',
156
160
  client: renderer.client,
161
+ packages: renderer.packages,
157
162
  clientOptions: {
158
163
  masking: {
159
164
  blockClass: options.blockClass ?? 'rr-block',
@@ -178,7 +183,9 @@ export function screenshots(options: ScreenshotsOptions = {}) {
178
183
  if (renderer.render === undefined || !type.startsWith('application/json'))
179
184
  return Response.json({ problem: 'send the shot as image/png' }, { status: 415 });
180
185
  try {
181
- return Response.json({ id: keepShot(await renderer.render(JSON.parse(new TextDecoder().decode(body)))) });
186
+ const made = await renderer.render(JSON.parse(new TextDecoder().decode(body)));
187
+ if (made instanceof Uint8Array) return Response.json({ id: keepShot(made) });
188
+ return Response.json({ id: keepShot(made.png), ...(made.box === undefined ? {} : { box: made.box }) });
182
189
  } catch (e) {
183
190
  return Response.json({ problem: e instanceof Error ? e.message : String(e) }, { status: 500 });
184
191
  }
@@ -31,7 +31,9 @@ export interface Snapshot {
31
31
  window?: { width: number; height: number };
32
32
  scroll: { x: number; y: number };
33
33
  scale: number;
34
- /** The part of the viewport to keep, for a shot of an element alone. */
34
+ /** The element the shot is of, as the snapshot numbers its nodes: found again in the rebuilt page, for where it is there. */
35
+ element?: number;
36
+ /** The part of the viewport to keep, for a shot of an element alone: where the element was in the page. */
35
37
  clip?: Box;
36
38
  /** An SVG the viewport's size, drawn over the page: the annotations, where there are any. */
37
39
  overlay?: string;
@@ -79,7 +81,12 @@ async function launch({ executablePath, channel }: BrowserOptions): Promise<Brow
79
81
  /** The rrweb-snapshot bundle that defines `rrwebSnapshot` in a page: its CommonJS entry is that bundle. */
80
82
  const bundle = () => createRequire(import.meta.url).resolve('rrweb-snapshot');
81
83
 
82
- export async function render(input: unknown, options: BrowserOptions): Promise<Uint8Array> {
84
+ /**
85
+ * The PNG, and where the element is in it. That's measured in the rebuilt page, not taken from the live one: the
86
+ * two can lay out a few pixels apart (a font that loaded differently, a panel's own scroll), and an outline drawn
87
+ * at the live page's box would then cross the element.
88
+ */
89
+ export async function render(input: unknown, options: BrowserOptions): Promise<{ png: Uint8Array; box?: Box }> {
83
90
  const shot = input as Snapshot;
84
91
  if (typeof shot?.url !== 'string' || typeof shot.snapshot !== 'object' || typeof shot.viewport?.width !== 'number')
85
92
  throw new Error('screenshots: that is not a snapshot the rrweb() renderer took');
@@ -91,13 +98,14 @@ export async function render(input: unknown, options: BrowserOptions): Promise<U
91
98
  await page.route(host, (route) => route.fulfill({ contentType: 'text/html', body: HOST }));
92
99
  await page.goto(host);
93
100
  await page.addScriptTag({ path: bundle() });
94
- await page.evaluate(async ({ snapshot, scroll, overlay }) => {
101
+ const found = await page.evaluate(async ({ snapshot, scroll, overlay, element }) => {
95
102
  const { rebuildIntoSandboxedIframe, createCache, createMirror } = (globalThis as unknown as { rrwebSnapshot: typeof Rrweb })
96
103
  .rrwebSnapshot;
104
+ const mirror = createMirror();
97
105
  const { iframe } = rebuildIntoSandboxedIframe(snapshot, {
98
106
  root: document.body,
99
107
  cache: createCache(),
100
- mirror: createMirror(),
108
+ mirror,
101
109
  iframeAttributes: { style: 'border:0;position:fixed;inset:0;width:100vw;height:100vh' },
102
110
  });
103
111
  const doc = iframe.contentDocument;
@@ -105,16 +113,35 @@ export async function render(input: unknown, options: BrowserOptions): Promise<U
105
113
  await doc.fonts.ready;
106
114
  await Promise.all([...doc.images].map((img) => img.decode().catch(() => {})));
107
115
  iframe.contentWindow?.scrollTo(scroll.x, scroll.y);
108
- if (overlay === undefined) return;
116
+ // rrweb scrolled each element as it built it, before the fonts and images gave its content its height:
117
+ // one that couldn't scroll that far yet is scrolled again now.
118
+ // By its kind: the iframe's elements aren't instances of this page's `Element`.
119
+ const isElement = (node: Node | null): node is Element => node?.nodeType === 1;
120
+ for (const id of mirror.getIds()) {
121
+ const node = mirror.getNode(id);
122
+ const meta = node === null ? null : mirror.getMeta(node);
123
+ if (!isElement(node) || meta === null || !('attributes' in meta)) continue;
124
+ const { rr_scrollTop: top, rr_scrollLeft: left } = meta.attributes;
125
+ if (typeof top === 'number') node.scrollTop = top;
126
+ if (typeof left === 'number') node.scrollLeft = left;
127
+ }
128
+ const node = element === undefined ? null : mirror.getNode(element);
129
+ // The iframe fills the page from its top left, so a box in it is one in the shot.
130
+ const rect = isElement(node) ? node.getBoundingClientRect() : undefined;
131
+ const box = rect === undefined ? undefined : { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
132
+ if (overlay === undefined) return box;
109
133
  // Over the page and its scroll: the SVG is the viewport's, already where it scrolled to.
110
134
  const marks = document.createElement('div');
111
135
  marks.style.cssText = 'position:fixed;inset:0;z-index:1;pointer-events:none';
112
136
  marks.innerHTML = overlay;
113
137
  document.body.append(marks);
138
+ return box;
114
139
  }, shot);
115
140
  // Without the scrollbars: a shot is what the page is drawn in, which is what an element's box is from.
116
- const clip = clamp(shot.clip ?? { x: 0, y: 0, ...shot.viewport }, shot.viewport);
117
- return new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));
141
+ // A shot of the element alone is cut where the element is here.
142
+ const clip = clamp(shot.clip === undefined ? { x: 0, y: 0, ...shot.viewport } : (found ?? shot.clip), shot.viewport);
143
+ const png = new Uint8Array(await page.screenshot({ type: 'png', ...(clip === undefined ? {} : { clip }) }));
144
+ return { png, ...(found === undefined || shot.clip !== undefined ? {} : { box: found }) };
118
145
  } finally {
119
146
  await context.close();
120
147
  }
@@ -2,6 +2,7 @@
2
2
  * The `rrweb()` renderer's page half: a snapshot of the page's DOM with `rrweb-snapshot` (imported on the
3
3
  * first shot), masked as rrweb masks, without deictic's overlay, sent with what the server's browser needs
4
4
  * to show it as the page does: the viewport and the window around it, where it's scrolled to, the pixel density, the page's URL.
5
+ * And which node of the snapshot the element is, so the server says where it is in what it drew.
5
6
  */
6
7
 
7
8
  import { boxOf, screenshotsClient } from './client.ts';
@@ -15,10 +16,12 @@ function withoutOurs(node: SnapshotNode): SnapshotNode {
15
16
  }
16
17
 
17
18
  export default screenshotsClient(async (element, { area, masking, overlay }) => {
18
- const { snapshot } = await import('rrweb-snapshot').catch((e: unknown) => {
19
+ const { snapshot, createMirror } = await import('rrweb-snapshot').catch((e: unknown) => {
19
20
  throw new Error('the rrweb() renderer needs rrweb-snapshot: add it to your devDependencies', { cause: e });
20
21
  });
22
+ const mirror = createMirror();
21
23
  const taken = snapshot(document, {
24
+ mirror,
22
25
  inlineStylesheet: true,
23
26
  blockClass: masking.blockClass,
24
27
  blockSelector: masking.blockSelector ?? null,
@@ -33,6 +36,7 @@ export default screenshotsClient(async (element, { area, masking, overlay }) =>
33
36
  const marks = overlay({ x: 0, y: 0, ...viewport });
34
37
  const body: Snapshot = {
35
38
  snapshot: withoutOurs(taken),
39
+ ...(mirror.getId(element) === -1 ? {} : { element: mirror.getId(element) }),
36
40
  url: location.href,
37
41
  viewport,
38
42
  window: { width: innerWidth, height: innerHeight },
@@ -189,17 +189,72 @@ const parentOf = (el: Element): Element | undefined => {
189
189
  return root instanceof ShadowRoot ? root.host : undefined;
190
190
  };
191
191
 
192
- /** How many places a chain names after the element's own. */
193
- const CHAIN = 5;
192
+ /** How many places a chain names after the element's own: who uses it, and who uses that. Further out is the app's shell. */
193
+ const CHAIN = 3;
194
194
 
195
195
  /**
196
- * The source `el` rendered through, after its own file, nearest first, each a `file:line`: a shared component's
197
- * own line is the same wherever it's used, and what uses it is the next file out (or a component between them,
198
- * which is why there are several). Read off the marks around it, the only trace of source the page has: each
199
- * place is the nearest element the next file wrote, which is where, in that file, the one before is used.
196
+ * What React keeps, in development, of who wrote an element: a fiber (its `type` the component), or for a server
197
+ * component its `name`. Each has the one that wrote it in turn.
198
+ */
199
+ interface Owner {
200
+ name?: unknown;
201
+ type?: unknown;
202
+ alternate?: Owner | null;
203
+ owner?: Owner | null;
204
+ _debugOwner?: Owner | null;
205
+ }
206
+
207
+ /** React's fiber of an element it rendered, which it keeps on the element under a key of its own. */
208
+ const fiberOf = (el: Element): Owner | undefined => {
209
+ const key = Object.keys(el).find((k) => k.startsWith('__reactFiber$'));
210
+ return key === undefined ? undefined : (el as unknown as Record<string, Owner>)[key];
211
+ };
212
+
213
+ const ownerOf = (of: Owner | undefined): Owner | undefined => of?._debugOwner ?? of?.owner ?? undefined;
214
+
215
+ /** A component's name, through `memo` and `forwardRef`, or nothing for one written without. */
216
+ function componentOf(owner: Owner): string | undefined {
217
+ if (typeof owner.name === 'string') return owner.name === '' ? undefined : owner.name;
218
+ let type = owner.type as { displayName?: unknown; name?: unknown; render?: unknown; type?: unknown } | null | undefined;
219
+ for (let depth = 0; depth < 4 && type !== null && type !== undefined; depth++) {
220
+ // A function's own name, where it has no `displayName`; a `memo` or `forwardRef` object has neither.
221
+ const name = type.displayName ?? type.name;
222
+ if (typeof name === 'string' && name !== '') return name;
223
+ type = (type.render ?? type.type) as typeof type;
224
+ }
225
+ return undefined;
226
+ }
227
+
228
+ /**
229
+ * The source `el` rendered through, after its own place, nearest first: a shared component's own line is the same
230
+ * wherever it's used, and the change is most often in what uses it, or in what uses that.
231
+ *
232
+ * With React in development, those are the components that wrote it, each the one whose JSX has the one before:
233
+ * `Field (src/Field.tsx:20)`, its line the nearest element around `el` that the component wrote, or the name alone
234
+ * for one with no element of its own around it (it wraps what it uses only in other components), which the marks
235
+ * can't show at all. A layout component the element was only passed through isn't among them.
236
+ *
237
+ * Without (another framework, a production build) it's read off the marks around it, each a `file:line`: the
238
+ * nearest element each next file wrote.
200
239
  */
201
240
  function chainOf(el: Element, file: string): NonNullable<Op['chain']> {
202
241
  const found: NonNullable<Op['chain']> = [];
242
+ const wrote = ownerOf(fiberOf(el));
243
+ if (wrote !== undefined) {
244
+ for (let owner = ownerOf(wrote); owner !== undefined && found.length < CHAIN; owner = ownerOf(owner)) {
245
+ const name = componentOf(owner);
246
+ let place: string | undefined;
247
+ for (let at = parentOf(el); at !== undefined && place === undefined; at = parentOf(at)) {
248
+ const by = ownerOf(fiberOf(at));
249
+ // A component's fiber is one of two, by turns: an element may name either.
250
+ if (by === undefined || (by !== owner && by !== owner.alternate)) continue;
251
+ place = at.getAttribute('data-deictic')?.replace(/:\d+$/, '');
252
+ }
253
+ if (name !== undefined) found.push(place === undefined ? name : `${name} (${place})`);
254
+ else if (place !== undefined) found.push(place);
255
+ }
256
+ if (found.length > 0) return found;
257
+ }
203
258
  let last = file;
204
259
  for (let at = parentOf(el); at !== undefined && found.length < CHAIN; at = parentOf(at)) {
205
260
  const mark = at.getAttribute('data-deictic');
@@ -632,7 +687,7 @@ export default defineClientPlugin<Model, Change>({
632
687
  /** A task's row: its state, its ID, a link where it has a page, its title, and where it's from when that's said. */
633
688
  const rowOf = (t: Task, from?: HTMLElement) => {
634
689
  const item = element('li');
635
- const state = element('span', { className: `state ${t.state}`, title: t.state });
690
+ const state = element('span', { className: `state ${t.state}`, title: t.by === undefined ? t.state : `${t.state} by ${t.by}` });
636
691
  state.role = 'img';
637
692
  const id = element('code', { textContent: `#${t.id}` });
638
693
  const title = element('button', { type: 'button', className: 'title' });