deictic 0.4.0 → 0.6.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 (69) hide show
  1. package/API.md +19 -8
  2. package/dist/cli.js +34 -28
  3. package/dist/cli.js.map +1 -1
  4. package/dist/shared/board.js +8 -19
  5. package/dist/shared/board.js.map +1 -1
  6. package/dist/shared/clean.js +105 -0
  7. package/dist/shared/clean.js.map +1 -0
  8. package/dist/shared/endpoints.js +35 -9
  9. package/dist/shared/endpoints.js.map +1 -1
  10. package/dist/shared/find.js +3 -2
  11. package/dist/shared/find.js.map +1 -1
  12. package/dist/shared/frame.js +4 -18
  13. package/dist/shared/frame.js.map +1 -1
  14. package/dist/shared/index.d.ts +8 -4
  15. package/dist/shared/index.d.ts.map +1 -1
  16. package/dist/shared/index7.d.ts +2 -0
  17. package/dist/shared/index7.d.ts.map +1 -1
  18. package/dist/shared/init.js +17 -24
  19. package/dist/shared/init.js.map +1 -1
  20. package/dist/shared/local.js +2 -1
  21. package/dist/shared/local.js.map +1 -1
  22. package/dist/shared/packages.js +9 -2
  23. package/dist/shared/packages.js.map +1 -1
  24. package/dist/shared/recording.js +4 -27
  25. package/dist/shared/recording.js.map +1 -1
  26. package/dist/shared/src.js.map +1 -1
  27. package/dist/shared/task.js +43 -10
  28. package/dist/shared/task.js.map +1 -1
  29. package/dist/shared/tasks.js +109 -115
  30. package/dist/shared/tasks.js.map +1 -1
  31. package/dist/shared/transcribe.js +1 -128
  32. package/dist/shared/transcribe2.js +119 -0
  33. package/dist/shared/transcribe2.js.map +1 -0
  34. package/dist/shared/vb.js +2 -3
  35. package/dist/shared/vb.js.map +1 -1
  36. package/dist/shared/voice2.js +4 -17
  37. package/dist/shared/voice2.js.map +1 -1
  38. package/dist/shared/watch.js +56 -39
  39. package/dist/shared/watch.js.map +1 -1
  40. package/dist/tailwind/index.js +6 -2
  41. package/dist/tailwind/index.js.map +1 -1
  42. package/dist/tasks/client.d.ts.map +1 -1
  43. package/dist/tasks/client.js +4 -5
  44. package/dist/tasks/client.js.map +1 -1
  45. package/dist/tasks/index.js +1 -1
  46. package/package.json +2 -1
  47. package/skills/deictic/SKILL.md +5 -3
  48. package/skills/deictic/references/tasks.md +6 -5
  49. package/src/cli/board.ts +7 -13
  50. package/src/cli/clean.ts +104 -0
  51. package/src/cli/find.ts +3 -1
  52. package/src/cli/frame.ts +3 -13
  53. package/src/cli/init.ts +16 -20
  54. package/src/cli/recording.ts +15 -21
  55. package/src/cli/task.ts +49 -10
  56. package/src/cli/transcribe.ts +13 -16
  57. package/src/cli/vb.ts +0 -2
  58. package/src/cli/voice.ts +3 -12
  59. package/src/cli/watch.ts +58 -29
  60. package/src/cli.ts +130 -31
  61. package/src/index.ts +8 -4
  62. package/src/plugins/tailwind/index.ts +6 -2
  63. package/src/plugins/tasks/client.ts +4 -5
  64. package/src/plugins/tasks/index.ts +113 -124
  65. package/src/plugins/tasks/local.ts +2 -1
  66. package/src/tools/endpoints.ts +18 -7
  67. package/src/tools/packages.ts +3 -0
  68. package/src/tools/source.ts +25 -5
  69. package/dist/shared/transcribe.js.map +0 -1
package/src/cli/init.ts CHANGED
@@ -16,9 +16,9 @@ import { recommended } from '#src/plugins/recommended/index.ts';
16
16
 
17
17
  import { installCommand, packageManager, readJson, runnerOf } from '#src/tools/packages.ts';
18
18
 
19
- import { fail, parseArgs } from './board.ts';
19
+ import { fail } from './board.ts';
20
20
  import { addToBunfig, addToServer, BY_HAND, MODULE, PLUGIN, serverOf } from './bun.ts';
21
- import { addFirst, addImports, eolOf, indentAt } from './edit.ts';
21
+ import { addFirst, addImports } from './edit.ts';
22
22
 
23
23
  export type Bundler = 'next' | 'astro' | 'vite' | 'rspack' | 'webpack' | 'bun';
24
24
 
@@ -62,7 +62,7 @@ const SETUPS: Record<Exclude<Bundler, 'bun'>, Setup> = {
62
62
  name: 'deictic',
63
63
  list: 'plugins',
64
64
  value: `deictic(${PLUGINS})`,
65
- snippet: `export default defineConfig({ plugins: [react(), deictic(${PLUGINS})] });`,
65
+ snippet: `export default defineConfig({ plugins: [deictic(${PLUGINS}), react()] });`,
66
66
  },
67
67
  rspack: {
68
68
  files: extensions('rspack.config'),
@@ -177,7 +177,7 @@ function exportedOf(program: Program): { value: Expression; commonjs: boolean }
177
177
 
178
178
  /**
179
179
  * The config with deictic added, or nothing where it can't tell where: deictic's import beside the config's, and its
180
- * plugin last in the list (`plugins`, `integrations`), or the config wrapped (Next's). Written in the config's quotes,
180
+ * plugin first in the list (`plugins`, `integrations`), as its marks count lines and columns in the code it's given, or the config wrapped (Next's). Written in the config's quotes,
181
181
  * semicolons and line endings.
182
182
  */
183
183
  export function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code: string): string | undefined {
@@ -186,7 +186,6 @@ export function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code
186
186
  if (errors.length > 0) return undefined;
187
187
  const exported = exportedOf(program);
188
188
  if (exported === undefined) return undefined;
189
- const eol = eolOf(code);
190
189
  const out = new MagicString(code);
191
190
 
192
191
  if (setup.wrap) {
@@ -194,7 +193,7 @@ export function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code
194
193
  out.appendRight(exported.value.end, `, ${setup.value})`);
195
194
  } else {
196
195
  const object = objectOf(exported.value, program);
197
- if (object === undefined || !addTo(out, code, object, setup.list!, setup.value, eol)) return undefined;
196
+ if (object === undefined || !addTo(out, code, object, setup.list!, setup.value)) return undefined;
198
197
  }
199
198
 
200
199
  const lines: [string, string][] = [
@@ -205,8 +204,12 @@ export function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code
205
204
  return out.toString();
206
205
  }
207
206
 
208
- /** Adds `value` last in the object's array `list`, or the list with it, as the object is laid out. False where `list` isn't an array. */
209
- function addTo(out: MagicString, code: string, object: ObjectExpression, list: string, value: string, eol: string): boolean {
207
+ /**
208
+ * Adds `value` first in the object's array `list`, or the list with it, as the object is laid out. False where `list`
209
+ * isn't an array. First, since a plugin before deictic's that changes a module (both `pre` under Vite) leaves the
210
+ * page's marks pointing at its code, not the file.
211
+ */
212
+ function addTo(out: MagicString, code: string, object: ObjectExpression, list: string, value: string): boolean {
210
213
  const property = object.properties.find(
211
214
  (p) =>
212
215
  p.type === 'Property' &&
@@ -218,13 +221,12 @@ function addTo(out: MagicString, code: string, object: ObjectExpression, list: s
218
221
  let array = property.value;
219
222
  while (array.type === 'TSAsExpression' || array.type === 'TSSatisfiesExpression') array = array.expression;
220
223
  if (array.type !== 'ArrayExpression') return false;
221
- const last = array.elements.findLast((e) => e !== null);
222
- if (last == null) {
224
+ const first = array.elements.find((e) => e !== null);
225
+ if (first == null) {
223
226
  out.appendLeft(array.start + 1, value);
224
227
  return true;
225
228
  }
226
- const multiline = code.slice(array.start, array.end).includes('\n');
227
- out.appendLeft(last.end, multiline ? `,${eol}${indentAt(code, last.start)}${value}` : `, ${value}`);
229
+ addFirst(out, code, array.start, first, value);
228
230
  return true;
229
231
  }
230
232
  addFirst(out, code, object.start, object.properties[0], `${list}: [${value}]`);
@@ -357,11 +359,6 @@ function configureBun(root: string, dryRun: boolean, log: (line: string) => void
357
359
  log(`deictic: ${did} its routes to ${name}`);
358
360
  }
359
361
 
360
- export const usage = `init [--dry-run] [--no-install] [--skill | --no-skill] sets deictic up in this project
361
- --dry-run says what it would do, and does none of it
362
- --no-install doesn't install: says the command instead
363
- --skill adds the agent skill without asking; --no-skill says the command instead`;
364
-
365
362
  /** Asks a yes-or-no question on the terminal, yes by default. */
366
363
  async function ask(question: string): Promise<boolean> {
367
364
  const lines = createInterface({ input: process.stdin, output: process.stdout });
@@ -372,14 +369,13 @@ async function ask(question: string): Promise<boolean> {
372
369
  }
373
370
  }
374
371
 
375
- export async function run(args: string[]): Promise<void> {
376
- const { values } = parseArgs(args, { 'dry-run': { type: 'boolean' }, install: { type: 'boolean' }, skill: { type: 'boolean' } });
372
+ export async function run(values: { dryRun?: boolean; install: boolean; skill?: boolean }): Promise<void> {
377
373
  try {
378
374
  await init({
379
375
  cwd: process.cwd(),
380
376
  install: values.install,
381
377
  skill: values.skill,
382
- dryRun: values['dry-run'],
378
+ dryRun: values.dryRun,
383
379
  ask: process.stdin.isTTY && process.stdout.isTTY ? ask : undefined,
384
380
  });
385
381
  } catch (e) {
@@ -6,16 +6,9 @@
6
6
  */
7
7
  import type { Shape } from '#src/plugins/annotations/index.ts';
8
8
 
9
- import { clock, fail, ME, parseArgs } from './board.ts';
9
+ import { clock, fail, ME } from './board.ts';
10
10
  import { loadRecording } from './find.ts';
11
11
 
12
- export const usage = `recording <task | replay URL | recording ID | file> [--nth 2] [--json] a recording as a timeline
13
- --only console,request these kinds of line (also page, click, input, scroll, resize, marks, voice)
14
- --problems errors, warnings and requests that failed
15
- --from 10 --to 15 a stretch, in seconds; --around 12 is the 3 seconds either side
16
- --grep text lines with this in them, in any case
17
- --full all of each line: where it was logged from, a request's headers and bodies`;
18
-
19
12
  /** A node of rrweb's snapshot. */
20
13
  interface SnapNode {
21
14
  id: number;
@@ -302,19 +295,20 @@ function timelineOf(events: Event[], voice: { id: string; at: number; duration:
302
295
  return timeline.sort((a, b) => a.t - b.t);
303
296
  }
304
297
 
305
- export async function run(args: string[]): Promise<void> {
306
- const { values, positionals } = parseArgs(args, {
307
- nth: { type: 'string', default: '1' },
308
- json: { type: 'boolean' },
309
- only: { type: 'string', multiple: true },
310
- problems: { type: 'boolean' },
311
- from: { type: 'string' },
312
- to: { type: 'string' },
313
- around: { type: 'string' },
314
- grep: { type: 'string' },
315
- full: { type: 'boolean' },
316
- });
317
- const { kept, id, replay, task } = await loadRecording(positionals[0], Number(values.nth));
298
+ export interface Options {
299
+ nth: string;
300
+ json?: boolean;
301
+ only?: string[];
302
+ problems?: boolean;
303
+ from?: string;
304
+ to?: string;
305
+ around?: string;
306
+ grep?: string;
307
+ full?: boolean;
308
+ }
309
+
310
+ export async function run(named: string, values: Options): Promise<void> {
311
+ const { kept, id, replay, task } = await loadRecording(named, Number(values.nth));
318
312
  const events = kept.events as Event[];
319
313
  if (!Array.isArray(events) || events.length === 0) fail(`Recording ${id} has no events.`);
320
314
  const timeline = timelineOf(events, kept.voice ?? []);
package/src/cli/task.ts CHANGED
@@ -5,17 +5,13 @@
5
5
  import { existsSync, mkdirSync, readFileSync } from 'node:fs';
6
6
  import { dirname, join, resolve } from 'node:path';
7
7
 
8
- import { deicticDirs, download, fail, ME, type Message, parseArgs, read, vbJson } from './board.ts';
9
-
10
- export const usage = 'task <id> [--out dir] a task briefly; --out downloads what is attached';
8
+ import { deicticDirs, download, ME, type Message, read, vbJson } from './board.ts';
11
9
 
12
10
  /** An actor by the profile its ID ends in (`…+claude`), or the ID of one that writes as itself. */
13
11
  const nameOf = (actor: string) => (actor.includes('+') ? actor.slice(actor.lastIndexOf('+') + 1) : actor);
14
12
 
15
- export function run(args: string[]): void {
16
- const { values, positionals } = parseArgs(args, { out: { type: 'string' } });
17
- if (positionals[0] === undefined) fail(`Name a task: ${ME} task 68`);
18
- const { message: root, replies } = read(positionals[0]);
13
+ export function run(id: string, values: { out?: string }): void {
14
+ const { message: root, replies } = read(id);
19
15
  const [asked = '', where = ''] = root.text.split(/\n---\n/);
20
16
  const label = (key: string) => root.labels[key];
21
17
  const at = label('deictic.at');
@@ -24,8 +20,9 @@ export function run(args: string[]): void {
24
20
  console.log(`#${root.id} ${root.task?.state ?? 'not a task'}, asked by ${root.author?.handle ?? root.by.actor}, ${root.createdAt}`);
25
21
  const claim = root.task?.claim;
26
22
  if (claim) console.log(`Claimed by ${nameOf(claim.actor)} until ${claim.until}`);
27
- if (root.task?.result !== undefined) console.log(`Result: ${root.task.result}`);
28
- if (root.task?.reason !== undefined) console.log(`Reason: ${root.task.reason}`);
23
+ // A task not over yet has them, as null.
24
+ if (root.task?.result != null) console.log(`Result: ${root.task.result}`);
25
+ if (root.task?.reason != null) console.log(`Reason: ${root.task.reason}`);
29
26
  console.log(`\nAsked:\n${asked.trim()}\n`);
30
27
  // The part inside the element that was pointed at, where nothing marked it: what the person means.
31
28
  const pointed = /\nPointed at, inside it: `([^`]*)`\n`{3,}\w*\n([\s\S]*?)\n`{3,}/.exec(where);
@@ -33,9 +30,12 @@ export function run(args: string[]): void {
33
30
  const facts: [string, (v: string) => string | undefined][] = [
34
31
  ['deictic.project', (v) => `Project ${v}`],
35
32
  ['deictic.at', (v) => `${v} <${label('deictic.tag') ?? '?'}>`],
33
+ // From its own line out: before the label, tasks said it in their text, which is printed below as it is.
34
+ ['deictic.source', (v) => `Source: ${at?.replace(/:\d+$/, '') ?? '?'} ← ${v}`],
36
35
  ['deictic.url', (v) => v],
37
36
  ['deictic.viewport', (v) => `Viewport ${v}`],
38
37
  ['deictic.count', (v) => (v === '1' ? undefined : `${v} elements on the page come from that line`)],
38
+ // A task added before shots were numbered had its one shot's place here.
39
39
  ['deictic.position', (v) => `In the screenshot at x,y ${v}, ${label('deictic.size') ?? '?'} (CSS pixels from its top left)`],
40
40
  ];
41
41
  for (const [key, say] of facts) {
@@ -43,10 +43,16 @@ export function run(args: string[]): void {
43
43
  const line = value === undefined ? undefined : say(value);
44
44
  if (line !== undefined) console.log(line);
45
45
  }
46
- // What no label holds: what's attached and drawn on it.
46
+ for (const line of drawn(root)) console.log(line);
47
+ // A task added before these were labels says them after its words.
47
48
  const told = (pointed ? where.slice(0, pointed.index) : where).trim();
48
49
  if (told !== '') console.log(told);
49
50
  if (pointed) console.log(`\nPointed at, inside it: ${pointed[1]}\n ${pointed[2]}`);
51
+ const path = label('deictic.pointed');
52
+ if (path !== undefined) {
53
+ const file = root.attachments.some((a) => a.name === 'pointed.html') ? 'pointed.html' : 'element.html';
54
+ console.log(`\nPointed at, inside it: ${path} (its HTML is in ${file})`);
55
+ }
50
56
 
51
57
  if (at !== undefined) placeOf(at, label('deictic.line'));
52
58
  attachments(root, values.out === undefined ? undefined : resolve(values.out));
@@ -56,6 +62,39 @@ export function run(args: string[]): void {
56
62
  others(root);
57
63
  }
58
64
 
65
+ /**
66
+ * What the attached files don't say, from the numbered labels: where the element is in each shot and the notes on it, the
67
+ * notes drawn on the page, where each recording replays, and what wasn't kept any more.
68
+ */
69
+ function drawn({ labels, attachments }: Message): string[] {
70
+ const numbered = (prefix: string) => {
71
+ const out: string[] = [];
72
+ for (let n = 1; labels[`${prefix}.${n}`] !== undefined; n++) out.push(labels[`${prefix}.${n}`]!);
73
+ return out;
74
+ };
75
+ const notes = (prefix: string) => numbered(`${prefix}.note`).map((note) => JSON.stringify(note));
76
+ const lines: string[] = [];
77
+ // `deictic.screenshot.N` is the Nth PNG attached, `deictic.recording.N` the Nth recording.
78
+ for (const [i, { name }] of attachments.filter((a) => a.type === 'image/png').entries()) {
79
+ const shot = `deictic.screenshot.${i + 1}`;
80
+ const position = labels[`${shot}.position`];
81
+ if (position === undefined) continue;
82
+ const said = notes(shot);
83
+ lines.push(
84
+ `${name}: the element at x,y ${position}, ${labels[`${shot}.size`] ?? '?'} (CSS pixels from its top left)${said.length === 0 ? '' : `; notes drawn on it: ${said.join(', ')}`}`,
85
+ );
86
+ }
87
+ const onPage = notes('deictic');
88
+ if (onPage.length > 0) lines.push(`Notes drawn on the page: ${onPage.join(', ')}`);
89
+ for (const [i, { name }] of attachments.filter((a) => a.name.startsWith('recording-')).entries()) {
90
+ const replay = labels[`deictic.recording.${i + 1}.replay`];
91
+ if (replay !== undefined) lines.push(`${name} replays at ${replay}`);
92
+ }
93
+ const dropped = numbered('deictic.dropped');
94
+ if (dropped.length > 0) lines.push(`Not attached, as it wasn't kept any more: ${dropped.join(', ')}`);
95
+ return lines;
96
+ }
97
+
59
98
  /** The place as the task saw it, against the file now: the element's opening tag may have moved or changed. */
60
99
  function placeOf(at: string, first: string | undefined): void {
61
100
  const file = at.replace(/:\d+:\d+$/, '');
@@ -4,7 +4,7 @@
4
4
  * model is downloaded.
5
5
  *
6
6
  * `--setup` puts @huggingface/transformers and the model in ~/.cache/deictic/transcribe (DEICTIC_CACHE moves it),
7
- * outside the project; an agent asks the person first. Models: tiny (~40 MB), base (~77 MB, the default), small
7
+ * outside the project; an agent asks the person first, and `deictic clean transcribe` deletes it. Models: tiny (~40 MB), base (~77 MB, the default), small
8
8
  * (~250 MB), large-v3-turbo (~800 MB), or any ONNX Whisper on Hugging Face by its ID. Needs ffmpeg on the PATH.
9
9
  */
10
10
  import { spawnSync } from 'node:child_process';
@@ -14,12 +14,9 @@ import { homedir } from 'node:os';
14
14
  import { join } from 'node:path';
15
15
  import { pathToFileURL } from 'node:url';
16
16
 
17
- import { clock, fail, ME, parseArgs } from './board.ts';
17
+ import { clock, fail, ME } from './board.ts';
18
18
  import { ffmpeg, voiceClips } from './find.ts';
19
19
 
20
- export const usage = `transcribe <task | replay URL | recording ID | file | clip ID> [--model base] [--language en] [--json] what was said
21
- transcribe --setup [--model base] installs it, outside the project: ask the person first`;
22
-
23
20
  // Pinned, so a setup installs what this was written against; move it on deliberately.
24
21
  const TRANSFORMERS = '@huggingface/transformers@4.3.2';
25
22
  const MODELS: Record<string, string> = {
@@ -44,18 +41,18 @@ interface Transformers {
44
41
  >;
45
42
  }
46
43
 
47
- export async function run(args: string[]): Promise<void> {
48
- const { values, positionals } = parseArgs(args, {
49
- setup: { type: 'boolean' },
50
- json: { type: 'boolean' },
51
- model: { type: 'string', default: 'base' },
52
- language: { type: 'string' },
53
- });
44
+ /** Where `--setup` installs it, outside any project: `deictic clean transcribe` deletes it. */
45
+ export const transcribeDir = () => join(process.env.DEICTIC_CACHE ?? join(homedir(), '.cache', 'deictic'), 'transcribe');
46
+
47
+ export async function run(
48
+ ref: string | undefined,
49
+ values: { setup?: boolean; json?: boolean; model: string; language?: string },
50
+ ): Promise<void> {
54
51
  const size = values.model;
55
52
  const named = MODELS[size];
56
53
  if (!size.includes('/') && named === undefined) fail(`--model is one of ${Object.keys(MODELS).join(', ')}, or a model ID`);
57
54
  const model = named === undefined ? size : `onnx-community/${named}`;
58
- const dir = join(process.env.DEICTIC_CACHE ?? join(homedir(), '.cache', 'deictic'), 'transcribe');
55
+ const dir = transcribeDir();
59
56
  const models = join(dir, 'models');
60
57
  const installed = existsSync(join(dir, 'node_modules', '@huggingface', 'transformers', 'package.json'));
61
58
  const downloaded = existsSync(join(models, ...model.split('/')));
@@ -92,12 +89,12 @@ export async function run(args: string[]): Promise<void> {
92
89
  if (values.setup) console.log(`Downloading ${model} (quantized) into ${models}…`);
93
90
  const asr = await transformers.pipeline('automatic-speech-recognition', model, { dtype: 'q8' });
94
91
  if (values.setup) {
95
- console.log(`Ready: ${again} <task>${sized}`);
96
- if (positionals[0] === undefined) return;
92
+ console.log(`Ready: ${again} <task>${sized}. ${ME} clean transcribe deletes it.`);
93
+ if (ref === undefined) return;
97
94
  }
98
95
 
99
96
  const results = [];
100
- for (const c of await voiceClips(positionals[0])) {
97
+ for (const c of await voiceClips(ref)) {
101
98
  // Whisper takes 16 kHz mono samples; ffmpeg decodes the clip (webm, ogg or mp4) to them.
102
99
  const raw = ffmpeg(['-loglevel', 'error', '-i', c.file, '-f', 'f32le', '-ac', '1', '-ar', '16000', '-']).stdout;
103
100
  const audio = new Float32Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength - (raw.byteLength % 4)));
package/src/cli/vb.ts CHANGED
@@ -4,8 +4,6 @@
4
4
  */
5
5
  import { vbHere } from './board.ts';
6
6
 
7
- export const usage = 'vb <anything vb takes> the board on the dev server: vb whoami, vb tasks claim 68 --lease 30m';
8
-
9
7
  export function run(args: string[]): void {
10
8
  process.exit(vbHere(args));
11
9
  }
package/src/cli/voice.ts CHANGED
@@ -6,25 +6,16 @@
6
6
  import { mkdirSync } from 'node:fs';
7
7
  import { join, resolve } from 'node:path';
8
8
 
9
- import { clock, parseArgs } from './board.ts';
9
+ import { clock } from './board.ts';
10
10
  import { ffmpeg, voiceClips } from './find.ts';
11
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
- });
12
+ export async function run(ref: string, values: { noise: string; gap: string; wav?: string; json?: boolean }): Promise<void> {
22
13
  const noise = Number(values.noise);
23
14
  const gap = Number(values.gap);
24
15
  const wav = values.wav === undefined ? undefined : resolve(values.wav);
25
16
 
26
17
  const results = [];
27
- for (const c of await voiceClips(positionals[0])) {
18
+ for (const c of await voiceClips(ref)) {
28
19
  // ffmpeg reports silence; speech is what's between. MediaRecorder's webm has no duration, so it's measured.
29
20
  const log = ffmpeg(['-i', c.file, '-af', `silencedetect=noise=${noise}dB:d=${gap}`, '-f', 'null', '-']).log;
30
21
  const starts = [...log.matchAll(/silence_start: (-?[\d.]+)/g)].map((m) => Number(m[1]) * 1000);
package/src/cli/watch.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * `deictic watch`: the board's tasks for deictic, one line per thing to act on: the tasks ready now as it starts,
3
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
4
+ * line an event). A board that goes away (the dev server restarted, and its board with it, maybe on another port) is
5
+ * waited for and followed again from where it was left; it says so, and ends only if none comes back. It ends by itself once nothing has
6
6
  * happened on the channel for `--idle` (20m): a watch nobody feeds isn't started again, so no agent watches for ever.
7
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
8
  * too, when the process that started it does: nobody reads its lines then.
@@ -16,9 +16,7 @@ import { createInterface } from 'node:readline';
16
16
 
17
17
  import { watcherAt } from '#src/plugins/tasks/watchers.ts';
18
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';
19
+ import { answers, boardIn, boardUrl, deicticDirs, duration, ME, vb, vbCommand, vbJson, whoami } from './board.ts';
22
20
 
23
21
  /** What `vb tail --json` prints, one per line. */
24
22
  interface Tailed {
@@ -83,18 +81,34 @@ function gone(pid: number): boolean {
83
81
  }
84
82
  }
85
83
 
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';
84
+ /** What `vb` said as it failed: its JSON's `message`, or its last line. */
85
+ function reasonOf(said: string): string | undefined {
86
+ const last = said.trim().split('\n').at(-1)?.trim();
87
+ if (last === undefined || last === '') return undefined;
88
+ try {
89
+ const { message } = JSON.parse(last) as { message?: unknown };
90
+ return typeof message === 'string' ? message : last;
91
+ } catch {
92
+ return last;
93
+ }
94
+ }
95
+
96
+ export function run(channel: string, values: { idle: string; once?: boolean; label?: string[] }): void {
93
97
  const labels = (values.label ?? []).flatMap((l) => ['--label', l]);
94
98
  const idle = duration(values.idle);
95
99
  const say = (line: string) => console.log(line.replace(/\s+/g, ' ').trim());
96
100
  const first = (text: string) => (text.split('\n---')[0] ?? '').trim().slice(0, 160);
97
101
 
102
+ // A board nothing has posted to yet has no channel, and won't list or follow one it hasn't: made here, as the first
103
+ // task would make it. One that's there stays as it is; where the board won't let this make one, `vb tasks` says so.
104
+ const made = () => {
105
+ const [command, argv, options] = vbCommand(['channels', 'create', channel]);
106
+ spawnSync(command, argv, options);
107
+ };
108
+ made();
109
+ // Where the channel is now, taken before what's ready is: followed from here, nothing posted between is missed, and
110
+ // a tail started again after the board went away follows on from what this one heard, never from a list taken earlier.
111
+ let cursor = vbJson<{ cursor: string }>(['read', channel, '--limit', '1']).cursor;
98
112
  const ready = vb(['tasks', channel, '--state', 'ready', ...labels]).trim();
99
113
  const me = whoami();
100
114
  // In the `.deictic/` whose board this is, or in each one near here where the board is the environment's.
@@ -130,6 +144,8 @@ export function run(args: string[]): void {
130
144
  );
131
145
  }
132
146
  const waiting = (ready ? ready.split('\n') : []).filter((line) => /^#\d+/.test(line));
147
+ // The tasks said, by ID: one made after the cursor above and listed as ready is said once.
148
+ const told = new Set(waiting.map((line) => /^#(\d+)/.exec(line)?.[1]));
133
149
  for (const line of waiting) say(`ready: ${line}`);
134
150
  if (values.once && waiting.length > 0) end(0);
135
151
 
@@ -154,8 +170,6 @@ export function run(args: string[]): void {
154
170
 
155
171
  // What the board says about each thread: its root's first line and where, to name it when a task is made.
156
172
  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
173
  const heardOf = (line: string) => {
160
174
  let e: Tailed;
161
175
  try {
@@ -163,6 +177,7 @@ export function run(args: string[]): void {
163
177
  } catch {
164
178
  return;
165
179
  }
180
+ // The last event heard, which a tail started again follows from: nothing left while the board was away is missed.
166
181
  if (e.cursor !== undefined) cursor = e.cursor;
167
182
  heard();
168
183
  const p = e.payload ?? {};
@@ -173,7 +188,8 @@ export function run(args: string[]): void {
173
188
  const project = label('deictic.project');
174
189
  roots.set(p.thread, `"${first(p.text ?? '')}"${at ? ` at ${at}` : ''}${page ? ` on ${page}` : ''}${project ? ` in ${project}` : ''}`);
175
190
  }
176
- if (e.type === 'task.created') event(`new task #${p.id}: ${roots.get(p.thread ?? -1) ?? ''}. Read it: npx deictic task ${p.id}`);
191
+ if (e.type === 'task.created' && !told.has(String(p.id)))
192
+ event(`new task #${p.id}: ${roots.get(p.thread ?? -1) ?? ''}. Read it: ${ME} task ${p.id}`);
177
193
  if (e.type === 'message.posted' && p.re !== null && p.re !== undefined) {
178
194
  if (me.profile !== null && p.by?.actor === me.actor) return;
179
195
  const by = e.message?.author?.handle ?? p.by?.actor ?? 'someone';
@@ -183,35 +199,48 @@ export function run(args: string[]): void {
183
199
  event(`task #${p.id} canceled: ${p.reason ?? ''}. Stop work on it, and put back what you changed for it.`);
184
200
  };
185
201
 
186
- const over = (code: number | null) => {
187
- say(`watch ended (vb tail exited ${code}): start it again`);
202
+ const over = (why: string) => {
203
+ say(`watch ended (${why}): start it again`);
188
204
  end(1);
189
205
  };
190
206
 
191
- /** Follows the channel, from `cursor` on where there is one, and again when the board comes back after going away. */
207
+ /** Follows the channel from `cursor`, and again when the board comes back after going away. */
192
208
  const follow = (again: boolean) => {
193
209
  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'] });
210
+ const [command, argv, options] = vbCommand(['tail', channel, ...labels, '--after', cursor, '--json']);
211
+ const child = spawn(command, argv, { env: options.env, shell: options.shell, stdio: ['ignore', 'pipe', 'pipe'] });
197
212
  tail = child;
198
213
  createInterface({ input: child.stdout }).on('line', heardOf);
214
+ // What it said as it ended goes in the watch's own line: a board started again refuses the old token, as expected,
215
+ // and the CLI's raw error isn't something for an agent to act on.
216
+ let said = '';
217
+ child.stderr.on('data', (chunk: Buffer) => (said += chunk.toString()));
218
+ // A dev server started again may start its board on another port: the tail would go on asking the old one for
219
+ // ever, so it's ended once the project's `.deictic/board.json` names another, and followed there.
220
+ const at = boardUrl();
221
+ let moved: string | undefined;
222
+ const elsewhere = setInterval(() => {
223
+ const now = boardUrl();
224
+ if (now === at || now === undefined) return;
225
+ moved = now;
226
+ child.kill();
227
+ }, 3000);
199
228
  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`);
229
+ clearInterval(elsewhere);
230
+ const reason = reasonOf(said);
231
+ const why = moved === undefined ? `vb tail exited ${code}${reason === undefined ? '' : `: ${reason}`}` : `started again on ${moved}`;
232
+ if (again && moved === undefined && Date.now() - started < SOON) return over(why);
233
+ say(`the board went away (${why}): waiting for it to come back`);
202
234
  const until = Date.now() + BACK;
203
235
  const tried = () => {
204
236
  // Asked anew each time: a board started again may be at another URL, and the CLI gets itself a new token for it.
205
237
  if (answers()) {
206
238
  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
- }
239
+ // A board started anew (its folder cleaned) has no channel again.
240
+ made();
212
241
  return follow(true);
213
242
  }
214
- if (Date.now() > until) return over(code);
243
+ if (Date.now() > until) return over(why);
215
244
  setTimeout(tried, 2000);
216
245
  };
217
246
  setTimeout(tried, 2000);