deictic 0.3.1 → 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 (165) hide show
  1. package/API.md +26 -17
  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 -103
  32. package/dist/screenshots/rrweb.d.ts +1 -1
  33. package/dist/screenshots/rrweb.js +1 -1
  34. package/dist/shared/annotations.js +22 -0
  35. package/dist/shared/annotations.js.map +1 -0
  36. package/dist/shared/board.js +190 -0
  37. package/dist/shared/board.js.map +1 -0
  38. package/dist/shared/client.js +108 -0
  39. package/dist/shared/endpoints.js +4 -1
  40. package/dist/shared/endpoints.js.map +1 -1
  41. package/dist/shared/find.js +156 -0
  42. package/dist/shared/find.js.map +1 -0
  43. package/dist/shared/frame.js +75 -0
  44. package/dist/shared/frame.js.map +1 -0
  45. package/dist/shared/index.d.ts +5 -0
  46. package/dist/shared/index.d.ts.map +1 -1
  47. package/dist/shared/index2.d.ts +85 -88
  48. package/dist/shared/index2.d.ts.map +1 -1
  49. package/dist/shared/index3.d.ts +83 -89
  50. package/dist/shared/index3.d.ts.map +1 -1
  51. package/dist/shared/index4.d.ts +98 -50
  52. package/dist/shared/index4.d.ts.map +1 -1
  53. package/dist/shared/index5.d.ts +13 -219
  54. package/dist/shared/index5.d.ts.map +1 -1
  55. package/dist/shared/index6.d.ts +55 -61
  56. package/dist/shared/index6.d.ts.map +1 -1
  57. package/dist/shared/index7.d.ts +224 -0
  58. package/dist/shared/index7.d.ts.map +1 -0
  59. package/dist/shared/index8.d.ts +52 -0
  60. package/dist/shared/index8.d.ts.map +1 -0
  61. package/dist/shared/index9.d.ts +70 -0
  62. package/dist/shared/index9.d.ts.map +1 -0
  63. package/dist/shared/init.js +472 -0
  64. package/dist/shared/init.js.map +1 -0
  65. package/dist/shared/local.js +165 -0
  66. package/dist/shared/local.js.map +1 -0
  67. package/dist/shared/logs.js +22 -0
  68. package/dist/shared/logs.js.map +1 -0
  69. package/dist/shared/network.js +39 -0
  70. package/dist/shared/network.js.map +1 -0
  71. package/dist/shared/packages.js +125 -0
  72. package/dist/shared/packages.js.map +1 -0
  73. package/dist/shared/recommended.js +26 -0
  74. package/dist/shared/recommended.js.map +1 -0
  75. package/dist/shared/recording.js +316 -0
  76. package/dist/shared/recording.js.map +1 -0
  77. package/dist/shared/recordings.js +2 -1
  78. package/dist/shared/recordings.js.map +1 -1
  79. package/dist/shared/screenshots.js +108 -0
  80. package/dist/shared/screenshots.js.map +1 -0
  81. package/dist/shared/src.js +10 -0
  82. package/dist/shared/src.js.map +1 -0
  83. package/dist/shared/task.js +108 -0
  84. package/dist/shared/task.js.map +1 -0
  85. package/dist/shared/tasks.js +7 -180
  86. package/dist/shared/tasks.js.map +1 -1
  87. package/dist/shared/transcribe.js +128 -0
  88. package/dist/shared/transcribe.js.map +1 -0
  89. package/dist/shared/vb.js +13 -0
  90. package/dist/shared/vb.js.map +1 -0
  91. package/dist/shared/vite.d.ts +16 -0
  92. package/dist/shared/vite.d.ts.map +1 -0
  93. package/dist/shared/vite.js +61 -0
  94. package/dist/shared/vite.js.map +1 -0
  95. package/dist/shared/voice.js +84 -0
  96. package/dist/{voice/index.js.map → shared/voice.js.map} +1 -1
  97. package/dist/shared/voice2.js +90 -0
  98. package/dist/shared/voice2.js.map +1 -0
  99. package/dist/shared/watch.js +209 -0
  100. package/dist/shared/watch.js.map +1 -0
  101. package/dist/shared/watchers.js +62 -0
  102. package/dist/shared/watchers.js.map +1 -0
  103. package/dist/tailwind/client.d.ts +1 -1
  104. package/dist/tailwind/client.js +1 -1
  105. package/dist/tailwind/index.d.ts +1 -1
  106. package/dist/tailwind/index.js +1 -1
  107. package/dist/tasks/client.d.ts +1 -1
  108. package/dist/tasks/client.js +1 -1
  109. package/dist/tasks/index.d.ts +1 -1
  110. package/dist/tasks/index.js +3 -1
  111. package/dist/vite.d.ts +2 -15
  112. package/dist/vite.js +2 -60
  113. package/dist/voice/client.d.ts +1 -1
  114. package/dist/voice/client.js +1 -1
  115. package/dist/voice/index.d.ts +2 -52
  116. package/dist/voice/index.js +1 -84
  117. package/package.json +6 -9
  118. package/skills/deictic/SKILL.md +27 -42
  119. package/skills/deictic/references/recordings.md +9 -108
  120. package/skills/deictic/references/tasks.md +21 -112
  121. package/skills/deictic/references/watch.md +13 -68
  122. package/src/cli/board.ts +204 -0
  123. package/src/cli/bun.ts +133 -0
  124. package/src/cli/edit.ts +56 -0
  125. package/src/cli/find.ts +147 -0
  126. package/src/cli/frame.ts +90 -0
  127. package/src/cli/init.ts +388 -0
  128. package/src/cli/recording.ts +383 -0
  129. package/src/cli/task.ts +126 -0
  130. package/src/cli/transcribe.ts +129 -0
  131. package/src/cli/vb.ts +11 -0
  132. package/src/cli/voice.ts +59 -0
  133. package/src/cli/watch.ts +221 -0
  134. package/src/cli.ts +37 -0
  135. package/src/index.ts +5 -0
  136. package/src/plugins/logs/index.ts +1 -0
  137. package/src/plugins/network/index.ts +1 -0
  138. package/src/plugins/recordings/index.ts +1 -0
  139. package/src/plugins/screenshots/index.ts +5 -1
  140. package/src/plugins/tasks/index.ts +3 -2
  141. package/src/plugins/tasks/local.ts +19 -6
  142. package/src/plugins/tasks/watchers.ts +41 -6
  143. package/src/tools/endpoints.ts +3 -0
  144. package/src/tools/packages.ts +107 -0
  145. package/dist/annotations/index.d.ts.map +0 -1
  146. package/dist/annotations/index.js.map +0 -1
  147. package/dist/index.js.map +0 -1
  148. package/dist/logs/index.d.ts.map +0 -1
  149. package/dist/logs/index.js.map +0 -1
  150. package/dist/network/index.js.map +0 -1
  151. package/dist/recommended/index.js.map +0 -1
  152. package/dist/screenshots/index.js.map +0 -1
  153. package/dist/vite.d.ts.map +0 -1
  154. package/dist/vite.js.map +0 -1
  155. package/dist/voice/index.d.ts.map +0 -1
  156. package/skills/deictic/references/install.md +0 -103
  157. package/skills/deictic/scripts/frame.mjs +0 -62
  158. package/skills/deictic/scripts/lib.mjs +0 -283
  159. package/skills/deictic/scripts/recording.mjs +0 -266
  160. package/skills/deictic/scripts/task.mjs +0 -120
  161. package/skills/deictic/scripts/transcribe.mjs +0 -93
  162. package/skills/deictic/scripts/vb.mjs +0 -12
  163. package/skills/deictic/scripts/voice.mjs +0 -50
  164. package/skills/deictic/scripts/watch.mjs +0 -152
  165. /package/dist/{screenshots → shared}/client.js.map +0 -0
@@ -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',
@@ -92,6 +92,8 @@ export interface Renderer {
92
92
  client: string;
93
93
  /** What the page half gets, besides the masking. */
94
94
  clientOptions?: unknown;
95
+ /** The packages it imports that the project installs, as a plugin's `packages`. */
96
+ packages?: string[];
95
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). */
96
98
  render?(input: unknown): Promise<Uint8Array | { png: Uint8Array; box?: Box }>;
97
99
  }
@@ -105,7 +107,7 @@ export interface BrowserOptions {
105
107
  }
106
108
 
107
109
  /** Draws the page in the page, from its DOM (`modern-screenshot`): no server needed, but text may lay out a little differently. */
108
- export const dom = (): Renderer => ({ client: 'deictic/screenshots/dom' });
110
+ export const dom = (): Renderer => ({ client: 'deictic/screenshots/dom', packages: ['modern-screenshot'] });
109
111
 
110
112
  /**
111
113
  * Snapshots the page's DOM in the page (`rrweb-snapshot`, masking as rrweb does) and renders it in a
@@ -113,6 +115,7 @@ export const dom = (): Renderer => ({ client: 'deictic/screenshots/dom' });
113
115
  */
114
116
  export const rrweb = (options: BrowserOptions = {}): Renderer => ({
115
117
  client: 'deictic/screenshots/rrweb',
118
+ packages: ['rrweb-snapshot', 'playwright-core'],
116
119
  // Loaded on the first shot, so a project rendering in the page needn't install Playwright.
117
120
  render: async (input) => (await import('./playwright.ts')).render(input, options),
118
121
  });
@@ -155,6 +158,7 @@ export function screenshots(options: ScreenshotsOptions = {}) {
155
158
  return definePlugin<never, never, never, Screenshots>({
156
159
  name: 'screenshots',
157
160
  client: renderer.client,
161
+ packages: renderer.packages,
158
162
  clientOptions: {
159
163
  masking: {
160
164
  blockClass: options.blockClass ?? 'rr-block',
@@ -104,7 +104,7 @@ export interface Model {
104
104
  /** Tasks about the file's other elements, by line, canceled ones left out: each with its `at`. */
105
105
  elsewhere: Task[];
106
106
  /**
107
- * Who watches the channel, by name (`claude`): the agents whose watch (the skill's `watch.mjs`) is running in
107
+ * Who watches the channel, by name (`claude`): the agents whose watch (`deictic watch`) is running in
108
108
  * this project, as a board can't say, and those holding a claim on one of the channel's tasks, which it can.
109
109
  * Empty where none is and the board is this machine's own;
110
110
  * left out where none is and the board is another, which an agent may watch from elsewhere.
@@ -341,6 +341,7 @@ export function tasks(options: TasksOptions = {}) {
341
341
  return definePlugin<Model, Change, Kept>({
342
342
  name: 'tasks',
343
343
  client: 'deictic/tasks/client',
344
+ packages: ['@vercel/board'],
344
345
  // Only where it's turned off: the page half sends the HTML unless told not to.
345
346
  ...(options.html === false ? { clientOptions: { html: false } } : {}),
346
347
  shortcut: options.shortcut,
@@ -394,7 +395,7 @@ export function tasks(options: TasksOptions = {}) {
394
395
  else if (once && at.tag === target.tag && message.labels['deictic.line'] === clip(line, LABEL)) tasks.push({ ...task, at });
395
396
  else elsewhere.push({ ...task, at });
396
397
  }
397
- // An agent at work on a task is here too, though its watch may be over until the task is (`watch.mjs --once`).
398
+ // An agent at work on a task is here too, though its watch may be over until the task is (`deictic watch --once`).
398
399
  const working = agentsOf(actors, claims);
399
400
  const watching = [...new Set([...watchersOf(root ?? process.cwd(), channel), ...working])].sort();
400
401
  // A board of this machine's own is watched from here or not at all.
@@ -70,7 +70,7 @@ export async function localBoard(root: string, options: LocalOptions = {}): Prom
70
70
  const flags = [...(options.inspect === false ? ['--no-inspect'] : []), ...(options.args ?? [])];
71
71
  const as = JSON.stringify([options.port ?? null, dir, flags]);
72
72
 
73
- const running = read(file);
73
+ const running = runningAt(file);
74
74
  if (running !== undefined && alive(running.pid) && (await answers(running.url))) {
75
75
  if (running.as === as) return { url: running.url, fresh: false, dir, stop: () => {} };
76
76
  process.kill(running.pid);
@@ -79,7 +79,9 @@ export async function localBoard(root: string, options: LocalOptions = {}): Prom
79
79
 
80
80
  const port = options.port ?? (await free(PORT));
81
81
  const url = `http://127.0.0.1:${port}/api/board`;
82
- const child = spawn(process.execPath, [cli(), 'serve', '--port', String(port), '--no-open', '--dir', dir, ...flags], {
82
+ const script = vbScript();
83
+ if (script === undefined) throw new Error('@vercel/board is missing: add it to your devDependencies');
84
+ const child = spawn(process.execPath, [script, 'serve', '--port', String(port), '--no-open', '--dir', dir, ...flags], {
83
85
  stdio: ['ignore', 'ignore', 'pipe'],
84
86
  });
85
87
  let said = '';
@@ -101,12 +103,23 @@ export async function localBoard(root: string, options: LocalOptions = {}): Prom
101
103
  return { url, fresh: true, dir, stop };
102
104
  }
103
105
 
104
- /** `vb`'s script in the project's `@vercel/board`, run with this process's own runtime: no shim, no shell. */
105
- function cli(): string {
106
- return join(dirname(createRequire(import.meta.url).resolve('@vercel/board/package.json')), 'dist', 'cli.mjs');
106
+ /**
107
+ * `vb`'s script in the project's `@vercel/board`, by its `bin`, to run with this process's own runtime: no shim, no
108
+ * shell. Nothing where it isn't installed.
109
+ */
110
+ export function vbScript(): string | undefined {
111
+ try {
112
+ const manifest = createRequire(import.meta.url).resolve('@vercel/board/package.json');
113
+ const { bin } = JSON.parse(readFileSync(manifest, 'utf8')) as { bin?: string | { vb?: string } };
114
+ const entry = typeof bin === 'string' ? bin : bin?.vb;
115
+ return entry === undefined ? undefined : join(dirname(manifest), entry);
116
+ } catch {
117
+ return undefined;
118
+ }
107
119
  }
108
120
 
109
- function read(file: string): Running | undefined {
121
+ /** What a `.deictic/board.json` says, where it says it. */
122
+ export function runningAt(file: string): Running | undefined {
110
123
  try {
111
124
  const { url, pid, as } = JSON.parse(readFileSync(file, 'utf8')) as Partial<Running>;
112
125
  return typeof url === 'string' && typeof pid === 'number' ? { url, pid, as: as ?? '' } : undefined;
@@ -1,16 +1,51 @@
1
1
  /**
2
2
  * Who watches the channel for tasks. A board can't say (it knows who claimed a task, not who's listening), so a
3
- * watch says it itself: the skill's `watch.mjs` keeps a file under `.deictic/watchers` while it runs, written
4
- * again every 20 seconds, and the Task tab shows the names, so a person knows whether a task they add is taken up.
3
+ * watch says it itself: `deictic watch` keeps a file under `.deictic/watchers` while it runs (`watcherAt`), written
4
+ * again every `BEAT`, and the Task tab shows the names, so a person knows whether a task they add is taken up.
5
5
  * (An agent holding a claim is one more, which the board does say: `agentsOf`, in `index.ts`.)
6
6
  */
7
- import { readdirSync, readFileSync, rmSync } from 'node:fs';
8
- import { join } from 'node:path';
7
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
9
 
10
10
  import { keptIn } from '#src/tools/kept.ts';
11
11
 
12
+ /** How often a watch says it's still there, and so how soon the page knows of one that was killed (three missed). */
13
+ export const BEAT = 20_000;
12
14
  /** How old a watch's last word may be: three of its beats, as one killed says nothing more. */
13
- const FRESH = 60_000;
15
+ const FRESH = 3 * BEAT;
16
+
17
+ /** What a watch keeps in a `.deictic/watchers` while it runs: one file per process. */
18
+ export interface Watcher {
19
+ name: string;
20
+ channel: string;
21
+ pid: number;
22
+ at: number;
23
+ }
24
+
25
+ /**
26
+ * A watch's file in each of `dirs` (`.deictic/` folders), written now and again every `BEAT`. Answers what takes
27
+ * it back, as the watch ends.
28
+ */
29
+ export function watcherAt(dirs: readonly string[], name: string, channel: string): () => void {
30
+ const files = dirs.map((dir) => join(dir, 'watchers', `${process.pid}.json`));
31
+ const beat = () => {
32
+ const watcher: Watcher = { name, channel, pid: process.pid, at: Date.now() };
33
+ for (const file of files) {
34
+ try {
35
+ mkdirSync(dirname(file), { recursive: true });
36
+ writeFileSync(file, `${JSON.stringify(watcher)}\n`);
37
+ } catch {
38
+ // A folder that can't be written to: the watch goes on, unseen.
39
+ }
40
+ }
41
+ };
42
+ beat();
43
+ const timer = setInterval(beat, BEAT);
44
+ return () => {
45
+ clearInterval(timer);
46
+ for (const file of files) rmSync(file, { force: true });
47
+ };
48
+ }
14
49
 
15
50
  /** The names watching `channel` from this project now, each once, in order. */
16
51
  export function watchersOf(root: string, channel: string, now = Date.now()): string[] {
@@ -25,7 +60,7 @@ export function watchersOf(root: string, channel: string, now = Date.now()): str
25
60
  for (const file of files) {
26
61
  const path = join(dir, file);
27
62
  try {
28
- const { name, channel: of, at } = JSON.parse(readFileSync(path, 'utf8')) as { name?: unknown; channel?: unknown; at?: unknown };
63
+ const { name, channel: of, at } = JSON.parse(readFileSync(path, 'utf8')) as Partial<Watcher>;
29
64
  if (typeof at !== 'number' || now - at > FRESH) rmSync(path, { force: true });
30
65
  else if (of === channel && typeof name === 'string') names.add(name);
31
66
  } catch {
@@ -18,6 +18,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
18
18
  import { type Loc, Refusal, type ServerPlugin, type Target } from '#src/index.ts';
19
19
 
20
20
  import { History, type Scope } from './history.ts';
21
+ import { missingMessage } from './packages.ts';
21
22
  import { setUp } from './plugins.ts';
22
23
  import { applyEdits, resolveFile, sourceAt } from './source.ts';
23
24
 
@@ -48,6 +49,8 @@ export function endpoints({ root, plugins, base = '/', open, history = new Histo
48
49
  const prefix = `${base}__deictic/`;
49
50
  // Started now, awaited by every request: a plugin's API is there before anything asks for it.
50
51
  const ready = setUp(root, plugins);
52
+ const gone = missingMessage(root, plugins);
53
+ if (gone !== undefined) console.warn(gone);
51
54
 
52
55
  const pluginOf = (name: string) => {
53
56
  const plugin = byName.get(name);
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The packages plugins import that the project installs itself (`ServerPlugin.packages`: deictic's optional peers,
3
+ * or a plugin's own), and how to install them with the project's package manager. A missing one is said as the dev
4
+ * server starts, with the command that installs it, not on the first shot or recording, where it would fail.
5
+ */
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { createRequire } from 'node:module';
8
+ import { dirname, join } from 'node:path';
9
+
10
+ import manifest from '#package.json' with { type: 'json' };
11
+ import type { ServerPlugin } from '#src/index.ts';
12
+
13
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
14
+
15
+ /** Each package manager's lockfiles, in the order they're looked for in a folder. */
16
+ const LOCKS: [string, PackageManager][] = [
17
+ ['bun.lock', 'bun'],
18
+ ['bun.lockb', 'bun'],
19
+ ['pnpm-lock.yaml', 'pnpm'],
20
+ ['yarn.lock', 'yarn'],
21
+ ['package-lock.json', 'npm'],
22
+ ];
23
+ const MANAGERS: PackageManager[] = ['npm', 'pnpm', 'yarn', 'bun'];
24
+
25
+ /**
26
+ * The project's package manager: its `packageManager` field, or the lockfile nearest the root (a workspace's is
27
+ * above it), or the one running this (`npm_config_user_agent`), or npm. The lockfile wins over what runs this,
28
+ * as `npx deictic init` runs under npm in a project of any manager's.
29
+ */
30
+ export function packageManager(root: string, agent = process.env.npm_config_user_agent): PackageManager {
31
+ for (let dir = root; ; dir = dirname(dir)) {
32
+ const field = fieldOf(dir);
33
+ if (field !== undefined) return field;
34
+ const lock = LOCKS.find(([file]) => existsSync(join(dir, file)));
35
+ if (lock !== undefined) return lock[1];
36
+ if (dirname(dir) === dir) break;
37
+ }
38
+ const running = agent?.split('/')[0];
39
+ return MANAGERS.find((m) => m === running) ?? 'npm';
40
+ }
41
+
42
+ /** A package.json's `packageManager` (`pnpm@9.1.0`), by its manager's name. */
43
+ function fieldOf(dir: string): PackageManager | undefined {
44
+ const field = readJson(join(dir, 'package.json'))?.packageManager;
45
+ const name = typeof field === 'string' ? field.split('@')[0] : undefined;
46
+ return MANAGERS.find((m) => m === name);
47
+ }
48
+
49
+ export function readJson(path: string): Record<string, unknown> | undefined {
50
+ try {
51
+ return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * A package as the install command names it: with deictic's range for it where it's one of deictic's peers (rrweb's
59
+ * packages must agree), or deictic's own version for deictic. Quoted, as `>` and `^` are a shell's.
60
+ */
61
+ export function specOf(name: string): string {
62
+ const range = name === manifest.name ? `^${manifest.version}` : (manifest.peerDependencies as Record<string, string>)[name];
63
+ return range === undefined ? name : `"${name}@${range}"`;
64
+ }
65
+
66
+ /** The command that adds `names` to the project's dev dependencies. A pnpm workspace's root takes them only with `-w`. */
67
+ export function installCommand(manager: PackageManager, names: readonly string[], root: string): string {
68
+ const add = {
69
+ npm: 'npm install -D',
70
+ pnpm: existsSync(join(root, 'pnpm-workspace.yaml')) ? 'pnpm add -D -w' : 'pnpm add -D',
71
+ yarn: 'yarn add -D',
72
+ bun: 'bun add -d',
73
+ }[manager];
74
+ return [add, ...names.map(specOf)].join(' ');
75
+ }
76
+
77
+ /** What runs a package's CLI without installing it, for the manager: `npx`, `bunx`. */
78
+ export const runnerOf = (manager: PackageManager) => ({ npm: 'npx', pnpm: 'pnpm dlx', yarn: 'npx', bun: 'bunx' })[manager];
79
+
80
+ /** Whether the project can import `name`: it's found from the root, as the bundler and deictic's own imports find it. */
81
+ export function installed(root: string, name: string): boolean {
82
+ try {
83
+ createRequire(join(root, 'package.json')).resolve(`${name}/package.json`);
84
+ return true;
85
+ } catch (e) {
86
+ // There, but its `exports` don't name its package.json: only "not found" means it's missing.
87
+ return (e as { code?: string }).code !== 'MODULE_NOT_FOUND';
88
+ }
89
+ }
90
+
91
+ /** Each plugin with the packages it imports that the project hasn't installed, where it has any. */
92
+ export function missing(root: string, plugins: readonly ServerPlugin[]): { plugin: string; packages: string[] }[] {
93
+ return plugins.flatMap(({ name, packages = [] }) => {
94
+ const gone = packages.filter((p) => !installed(root, p));
95
+ return gone.length === 0 ? [] : [{ plugin: name, packages: gone }];
96
+ });
97
+ }
98
+
99
+ /** What to say as the dev server starts when plugins' packages are missing: which, and the command that installs them. */
100
+ export function missingMessage(root: string, plugins: readonly ServerPlugin[]): string | undefined {
101
+ const gone = missing(root, plugins);
102
+ if (gone.length === 0) return undefined;
103
+ const names = [...new Set(gone.flatMap((g) => g.packages))];
104
+ const which = gone.map((g) => g.plugin);
105
+ const who = which.length === 1 ? which[0] : `${which.slice(0, -1).join(', ')} and ${which.at(-1)}`;
106
+ return `deictic: install what ${who} ${which.length === 1 ? 'needs' : 'need'}: ${installCommand(packageManager(root), names, root)}`;
107
+ }