screenreader-speech-capture-client 0.0.1-preview.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,124 +1,59 @@
1
1
  #!/usr/bin/env node
2
- import { a as BridgeNotReadyError, c as SpeechTimeoutError, d as ClientConfigError, i as BridgeHttpError, n as createClientConfig, o as BridgeUnreachableError, p as URL_ENV, s as IncompatibleBridgeError, t as SpeechCaptureClient } from "./main-DH_3C5Dp.mjs";
2
+ import { _ as IncompatibleBridgeError, d as URL_ENV, g as ClientConfigError, h as BridgeUnreachableError, m as BridgeNotReadyError, n as createClientConfig, p as BridgeHttpError, t as SpeechCaptureClient, v as SpeechTimeoutError, y as SpeechTruncatedError } from "./main-GSQbmJHV.mjs";
3
+ import { hostname } from "node:os";
3
4
  import { parseArgs } from "node:util";
4
5
  // package.json
5
- var version = "0.0.1-preview.0";
6
- // src/adapters/in/cli/run.ts
7
- /** Exit codes (docs/client.md#cli-for-agents). */
6
+ var version = "0.1.0";
7
+ // src/adapters/in/cli/command.ts
8
+ /** Exit codes (docs/usage/client.md#cli-for-agents). */
8
9
  const EXIT = {
9
10
  ok: 0,
10
11
  timeout: 1,
11
12
  bridge: 2,
12
13
  usage: 3
13
14
  };
14
- var UsageError = class extends Error {};
15
- const NAME = "screenreader-speech-capture-client";
15
+ // src/adapters/in/cli/format.ts
16
16
  const SOURCE_LABEL = {
17
17
  explicit: "--url",
18
18
  env: URL_ENV,
19
19
  config: "config file",
20
20
  default: "default"
21
21
  };
22
- function helpText() {
23
- return `Usage: ${NAME} <command> [options]
24
-
25
- Commands:
26
- status [--wait-ready] [--timeout <ms>]
27
- Bridge health and versions; --wait-ready waits until it is ready
28
- (default timeout 120000)
29
- clear Clear the speech buffer
30
- speech [--since <seq>] [--limit <n>] [--include-markers]
31
- Recorded speech entries, oldest first
32
- text [--since <seq>] [--separator <s>]
33
- All speech joined into one text (one line per entry)
34
- wait <text> [--regex] [--normalize] [--since <seq>] [--timeout <ms>]
35
- Wait until speech contains <text> (or matches the regex);
36
- also finds speech that arrived before the call (default timeout 5000)
37
- wait-silence [--quiet-for <ms>] [--timeout <ms>]
38
- Wait until nothing was spoken for --quiet-for ms (default 500, 10000)
39
- mark <label> Insert a marker and print its seq, for --since
40
-
41
- config set url <url> Store the bridge URL for this user
42
- config get url Show the bridge URL in use and where it comes from
43
- config unset url Remove the stored bridge URL
44
- config list Show all settings and where they come from
45
- config path Show the path of the config file
46
-
47
- Options:
48
- --url <url> Bridge URL (env ${URL_ENV}, then the config file, default http://localhost:5151)
49
- --json Machine-readable output
50
- -h, --help Show this help
51
- -v, --version Show the version
52
-
53
- --since <seq> takes a seq printed by mark (default 0: everything since the last clear).
54
-
55
- Exit codes: 0 success, 1 timeout / no match, 2 bridge not reachable, HTTP error or
56
- incompatible bridge, 3 invalid usage or config.
57
- `;
22
+ function formatEntry(entry) {
23
+ return entry.kind === "marker" ? `#${entry.seq} [marker] ${entry.text}` : `#${entry.seq} ${entry.text}`;
58
24
  }
59
- /** Runs one CLI invocation and returns its exit code. */
60
- async function runCli(argv, io) {
61
- try {
62
- return await dispatch(argv, io);
63
- } catch (error) {
64
- if (error instanceof UsageError) {
65
- io.stderr(`${NAME}: ${error.message}\nRun with --help to see the commands.\n`);
66
- return EXIT.usage;
67
- }
68
- if (error instanceof ClientConfigError) {
69
- io.stderr(`${NAME}: ${error.message}\n`);
70
- return EXIT.usage;
71
- }
72
- if (error instanceof BridgeNotReadyError) {
73
- io.stderr(`${NAME}: ${error.message}\n`);
74
- return EXIT.timeout;
75
- }
76
- if (error instanceof BridgeUnreachableError || error instanceof BridgeHttpError || error instanceof IncompatibleBridgeError) {
77
- io.stderr(`${NAME}: ${error.message}\n`);
78
- return EXIT.bridge;
79
- }
80
- throw error;
81
- }
25
+ function formatSession(session, current) {
26
+ const run = session.run === null ? "" : ` (run ${session.run})`;
27
+ const state = current ? "current" : "ended";
28
+ const count = `${session.entries} entr${session.entries === 1 ? "y" : "ies"}`;
29
+ const range = session.firstSeq === null ? "" : `, seq ${session.firstSeq}-${session.lastSeq ?? session.firstSeq}`;
30
+ return `#${session.id} ${session.name}${run}: ${state}, ${count}${range}`;
82
31
  }
83
- async function dispatch(argv, io) {
84
- let parsed;
85
- try {
86
- parsed = parseArgs({
87
- args: [...argv],
88
- allowPositionals: true,
89
- options: OPTIONS
90
- });
91
- } catch (error) {
92
- throw new UsageError(error.message);
93
- }
94
- const { values, positionals } = parsed;
95
- if (values.help) {
96
- io.stdout(helpText());
97
- return EXIT.ok;
98
- }
99
- if (values.version) {
100
- io.stdout(`${io.version}\n`);
101
- return EXIT.ok;
102
- }
103
- const [command, ...rest] = positionals;
104
- if (command === void 0) throw new UsageError("Missing command.");
105
- if (!isCommand(command)) throw new UsageError(`Unknown command "${command}".`);
106
- checkOptions(command, values);
107
- const globals = {
108
- url: values.url,
109
- json: values.json
110
- };
111
- if (command === "config") return config(rest, globals, io);
112
- const ctx = {
113
- ...globals,
114
- values,
115
- speech: io.speech(values.url),
116
- out: (json, text) => io.stdout(values.json ? `${JSON.stringify(json)}\n` : `${text}\n`),
117
- io
118
- };
119
- return SPEECH_COMMANDS[command](rest, ctx);
32
+ /** A session event in `tail`. */
33
+ function formatSessionEvent(session) {
34
+ return `--- session #${session.id} ${JSON.stringify(session.name)} ${session.endedAt === null ? "started" : "ended"} ---`;
120
35
  }
121
- /** Every option; {@link COMMAND_OPTIONS} says which command takes which. */
36
+ /** What a timed-out `wait` saw, appended to its error message. */
37
+ function seenText(entries) {
38
+ if (entries.length === 0) return " No speech arrived.";
39
+ return ` Speech seen:\n${entries.map((e) => ` ${formatEntry(e)}`).join("\n")}`;
40
+ }
41
+ function formatStatus(status) {
42
+ const { bridge, tcp, buffer, session } = status;
43
+ const connections = tcp.connections.length;
44
+ const range = buffer.firstSeq === null ? "empty" : `seq ${buffer.firstSeq}-${buffer.lastSeq ?? buffer.firstSeq}`;
45
+ return [
46
+ `bridge ${bridge.version} (API ${bridge.apiVersion}), ${bridge.state}`,
47
+ `tcp ${tcp.host}:${tcp.port} ${tcp.listening ? "listening" : "not listening"}, ${connections} voice connection${connections === 1 ? "" : "s"}, ${tcp.encoding}`,
48
+ `buffer ${buffer.size} of ${buffer.maxEntries} entries (${range})`,
49
+ `session ${session.current === null ? "none current" : `#${session.current.id} ${session.current.name}`}, ${session.count} in the buffer`
50
+ ].join("\n");
51
+ }
52
+ // src/adapters/in/cli/options.ts
53
+ const NAME = "screenreader-speech-capture-client";
54
+ /** Invalid usage: printed with a hint to `--help`, exit code 3. */
55
+ var UsageError = class extends Error {};
56
+ /** Every option; each command lists the ones it takes (`commands/`). */
122
57
  const OPTIONS = {
123
58
  url: { type: "string" },
124
59
  json: {
@@ -143,214 +78,621 @@ const OPTIONS = {
143
78
  separator: { type: "string" },
144
79
  regex: { type: "boolean" },
145
80
  normalize: { type: "boolean" },
146
- "wait-ready": { type: "boolean" }
81
+ "wait-ready": { type: "boolean" },
82
+ run: { type: "string" },
83
+ session: { type: "string" },
84
+ all: { type: "boolean" },
85
+ x: { type: "string" },
86
+ y: { type: "string" },
87
+ button: { type: "string" },
88
+ delay: { type: "string" }
147
89
  };
148
- /** Options every command takes. */
90
+ /** Options every command takes, with their help rows. */
149
91
  const GLOBAL_OPTIONS = [
150
- "url",
151
- "json",
152
- "help",
153
- "version"
92
+ {
93
+ option: "url",
94
+ flag: "--url <url>",
95
+ description: `Bridge URL (env ${URL_ENV}, then the config file, default http://localhost:5151)`
96
+ },
97
+ {
98
+ option: "json",
99
+ flag: "--json",
100
+ description: "Machine-readable output"
101
+ },
102
+ {
103
+ option: "help",
104
+ flag: "-h, --help",
105
+ description: "Show this help"
106
+ },
107
+ {
108
+ option: "version",
109
+ flag: "-v, --version",
110
+ description: "Show the version"
111
+ }
154
112
  ];
155
- const COMMAND_OPTIONS = {
156
- config: [],
157
- status: ["wait-ready", "timeout"],
158
- clear: [],
159
- speech: [
160
- "since",
161
- "limit",
162
- "include-markers"
113
+ /** Throws unless every given option is global or in `allowed`. */
114
+ function checkOptions(command, allowed, values) {
115
+ const all = /* @__PURE__ */ new Set([...GLOBAL_OPTIONS.map((g) => g.option), ...allowed]);
116
+ for (const [name, value] of Object.entries(values)) if (value !== void 0 && !all.has(name)) throw new UsageError(`"${command}" does not take --${name}.`);
117
+ }
118
+ /** An integer option >= `min`, `undefined` if not given. */
119
+ function optionalInt(values, name, min) {
120
+ const raw = values[name];
121
+ if (raw === void 0) return void 0;
122
+ const value = Number(raw);
123
+ if (typeof raw !== "string" || !/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < min) throw new UsageError(`--${name} must be an integer >= ${min}, got "${String(raw)}".`);
124
+ return value;
125
+ }
126
+ /** The positional arguments, if there are exactly `count`; otherwise a usage error. */
127
+ function expectArgs(args, count, usage) {
128
+ if (args.length !== count) throw new UsageError(`Usage: ${NAME} ${usage}`);
129
+ return args;
130
+ }
131
+ /**
132
+ * The session `speech`, `text` and `wait` read: `--session <id>`, nothing with `--all`, otherwise
133
+ * the current session. Its id, not `'current'`, so without a current session it reads the whole
134
+ * buffer instead of answering 404.
135
+ */
136
+ async function scope(values, speech) {
137
+ const id = optionalInt(values, "session", 1);
138
+ if (values.all && id !== void 0) throw new UsageError("Use either --session or --all.");
139
+ if (id !== void 0) return id;
140
+ if (values.all) return void 0;
141
+ return (await speech.status()).session.current?.id;
142
+ }
143
+ /** A required integer option, may be negative (a screen left of the primary one): `--x=-5`. */
144
+ function requiredSignedInt(values, name, usage) {
145
+ const raw = values[name];
146
+ if (typeof raw !== "string") throw new UsageError(`Usage: ${NAME} ${usage}`);
147
+ if (!/^-?\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new UsageError(`--${name} must be an integer, got "${raw}".`);
148
+ return Number(raw);
149
+ }
150
+ // src/adapters/in/cli/commands/config.ts
151
+ const SET = {
152
+ usage: "config set url <url>",
153
+ description: ["Store the bridge URL for this user"]
154
+ };
155
+ const GET = {
156
+ usage: "config get url",
157
+ description: ["Show the bridge URL in use and where it comes from"]
158
+ };
159
+ const UNSET = {
160
+ usage: "config unset url",
161
+ description: ["Remove the stored bridge URL"]
162
+ };
163
+ const LIST = {
164
+ usage: "config list",
165
+ description: ["Show all settings and where they come from"]
166
+ };
167
+ const PATH = {
168
+ usage: "config path",
169
+ description: ["Show the path of the config file"]
170
+ };
171
+ /** The per-user settings; works without a reachable bridge or a valid bridge URL. */
172
+ const config = {
173
+ options: [],
174
+ help: [
175
+ SET,
176
+ GET,
177
+ UNSET,
178
+ LIST,
179
+ PATH
163
180
  ],
164
- text: ["since", "separator"],
165
- wait: [
166
- "regex",
167
- "normalize",
168
- "since",
169
- "timeout"
181
+ async run(args, { values, io, out }) {
182
+ const { config } = io;
183
+ const file = config.location;
184
+ const explicit = { url: values.url };
185
+ const [action, ...rest] = args;
186
+ switch (action) {
187
+ case "set": {
188
+ const [key, value] = expectArgs(rest, 2, "config set <key> <value>");
189
+ const result = await config.set(key, value);
190
+ out("config set", {
191
+ ...result,
192
+ file
193
+ }, `Saved ${result.key} = ${result.value} to ${file}`);
194
+ if (result.shadowedBy === "env") io.stderr(`Note: ${URL_ENV} is set and takes precedence over the config file.\n`);
195
+ return EXIT.ok;
196
+ }
197
+ case "get": {
198
+ const [key] = expectArgs(rest, 1, "config get <key>");
199
+ const result = await config.get(key, explicit);
200
+ out("config get", result, `${result.value} (${SOURCE_LABEL[result.source]})`);
201
+ return EXIT.ok;
202
+ }
203
+ case "unset": {
204
+ const [key] = expectArgs(rest, 1, "config unset <key>");
205
+ const result = await config.unset(key);
206
+ out("config unset", {
207
+ ...result,
208
+ file
209
+ }, `Removed ${result.key} from ${file}`);
210
+ return EXIT.ok;
211
+ }
212
+ case "list": {
213
+ expectArgs(rest, 0, LIST.usage);
214
+ const entries = await config.list(explicit);
215
+ out("config list", {
216
+ file,
217
+ settings: entries
218
+ }, [`# ${file}`, ...entries.map((e) => `${e.key} = ${e.value} (${SOURCE_LABEL[e.source]})`)].join("\n"));
219
+ return EXIT.ok;
220
+ }
221
+ case "path":
222
+ expectArgs(rest, 0, PATH.usage);
223
+ out("config path", { file }, file);
224
+ return EXIT.ok;
225
+ case void 0: throw new UsageError("Missing config action: set, get, unset, list or path.");
226
+ default: throw new UsageError(`Unknown config action "${action}": use set, get, unset, list or path.`);
227
+ }
228
+ }
229
+ };
230
+ // src/adapters/in/cli/commands/input.ts
231
+ const FOCUS = {
232
+ usage: "click --x <px> --y <px> [--button left|right|middle]",
233
+ description: ["Native click at a screen point in physical pixels, for example to give", "a window the focus (negative values: --x=-5)"]
234
+ };
235
+ const click = {
236
+ options: [
237
+ "x",
238
+ "y",
239
+ "button"
170
240
  ],
171
- "wait-silence": ["quiet-for", "timeout"],
172
- mark: []
241
+ help: [FOCUS],
242
+ async run(args, { values, input, out }) {
243
+ if (args.length !== 0) throw new UsageError(`Usage: ${NAME} ${FOCUS.usage}`);
244
+ const x = requiredSignedInt(values, "x", FOCUS.usage);
245
+ const y = requiredSignedInt(values, "y", FOCUS.usage);
246
+ const { button } = values;
247
+ if (button !== void 0 && button !== "left" && button !== "right" && button !== "middle") throw new UsageError(`--button must be left, right or middle, got "${button}".`);
248
+ await input().click({
249
+ x,
250
+ y
251
+ }, { button });
252
+ out("click", { clicked: true }, `Clicked at ${x},${y}`);
253
+ return EXIT.ok;
254
+ }
173
255
  };
174
- const isCommand = (name) => Object.hasOwn(COMMAND_OPTIONS, name);
175
- function checkOptions(command, values) {
176
- const allowed = [...GLOBAL_OPTIONS, ...COMMAND_OPTIONS[command]];
177
- for (const [name, value] of Object.entries(values)) if (value !== void 0 && !allowed.includes(name)) throw new UsageError(`"${command}" does not take --${name}.`);
178
- }
179
- const SPEECH_COMMANDS = {
180
- async status(args, { values, speech, out }) {
181
- expectArgs(args, 0, "status [--wait-ready] [--timeout <ms>]");
256
+ const PRESS = {
257
+ usage: "press <keys...> [--delay <ms>]",
258
+ description: [
259
+ "Native key presses for screen reader commands: one chord (\"Insert+T\")",
260
+ "or several arguments as a sequence (h h Insert+Down); --delay pauses",
261
+ "between them"
262
+ ]
263
+ };
264
+ const press = {
265
+ options: ["delay"],
266
+ help: [PRESS],
267
+ async run(args, { values, input, out }) {
268
+ if (args.length === 0) throw new UsageError(`Usage: ${NAME} ${PRESS.usage}`);
269
+ const delayMs = optionalInt(values, "delay", 0);
270
+ await input().pressKeys(args.length === 1 ? args[0] : args, { delayMs });
271
+ out("press", { pressed: true }, `Pressed ${args.join(" ")}`);
272
+ return EXIT.ok;
273
+ }
274
+ };
275
+ // src/adapters/in/cli/commands/speech.ts
276
+ const STATUS = {
277
+ usage: "status [--wait-ready] [--timeout <ms>]",
278
+ description: ["Bridge health and versions; --wait-ready waits until it is ready", "(default timeout 120000)"]
279
+ };
280
+ const status = {
281
+ options: ["wait-ready", "timeout"],
282
+ help: [STATUS],
283
+ async run(args, { values, speech, out }) {
284
+ expectArgs(args, 0, STATUS.usage);
182
285
  const timeout = optionalInt(values, "timeout", 0);
183
286
  if (!values["wait-ready"] && timeout !== void 0) throw new UsageError("--timeout needs --wait-ready.");
184
- const status = values["wait-ready"] ? await speech.waitForReady({ timeout }) : await speech.status();
185
- out(status, formatStatus(status));
287
+ const result = values["wait-ready"] ? await speech().waitForReady({ timeout }) : await speech().status();
288
+ out("status", result, formatStatus(result));
186
289
  return EXIT.ok;
187
- },
188
- async clear(args, { speech, out }) {
189
- expectArgs(args, 0, "clear");
190
- await speech.clear();
191
- out({ cleared: true }, "Speech buffer cleared.");
290
+ }
291
+ };
292
+ const SESSION_START = {
293
+ usage: "session start <name> [--run <label>]",
294
+ description: ["Start a session (the previous one ends) and print its id"]
295
+ };
296
+ const SESSION_END = {
297
+ usage: "session end",
298
+ description: ["End the current session"]
299
+ };
300
+ const SESSION_LIST = {
301
+ usage: "session list",
302
+ description: ["The sessions in the buffer, newest first"]
303
+ };
304
+ const session = {
305
+ options: ["run"],
306
+ help: [
307
+ SESSION_START,
308
+ SESSION_END,
309
+ SESSION_LIST
310
+ ],
311
+ async run(args, { values, speech, out, io }) {
312
+ const [action, ...rest] = args;
313
+ if (action !== "start" && values.run !== void 0) throw new UsageError("--run only goes with \"session start\".");
314
+ switch (action) {
315
+ case "start": {
316
+ const [name] = expectArgs(rest, 1, SESSION_START.usage);
317
+ if (name.trim() === "") throw new UsageError("The session name must not be empty.");
318
+ if (values.run?.trim() === "") throw new UsageError("--run must not be empty.");
319
+ const started = await speech().startSession(name, { run: values.run });
320
+ const { replaced } = started;
321
+ if (replaced) io.stderr(`Warning: this ended session ${replaced.id} "${replaced.name}" of another client (${replaced.client ?? "unknown"}).\n`);
322
+ out("session start", started, String(started.id));
323
+ return EXIT.ok;
324
+ }
325
+ case "end":
326
+ expectArgs(rest, 0, SESSION_END.usage);
327
+ await speech().endSession();
328
+ out("session end", { ended: true }, "Session ended.");
329
+ return EXIT.ok;
330
+ case "list": {
331
+ expectArgs(rest, 0, SESSION_LIST.usage);
332
+ const list = await speech().sessions();
333
+ out("session list", list, list.sessions.length === 0 ? "No sessions." : list.sessions.map((s) => formatSession(s, s.id === list.currentId)).join("\n"));
334
+ return EXIT.ok;
335
+ }
336
+ case void 0: throw new UsageError("Missing session action: start, end or list.");
337
+ default: throw new UsageError(`Unknown session action "${action}": use start, end or list.`);
338
+ }
339
+ }
340
+ };
341
+ const CLEAR = {
342
+ usage: "clear",
343
+ description: ["Wipe the whole speech buffer, all sessions (for manual use)"]
344
+ };
345
+ const clear = {
346
+ options: [],
347
+ help: [CLEAR],
348
+ async run(args, { speech, out }) {
349
+ expectArgs(args, 0, CLEAR.usage);
350
+ await speech().clear();
351
+ out("clear", { cleared: true }, "Speech buffer cleared.");
192
352
  return EXIT.ok;
193
- },
194
- async speech(args, { values, speech, out }) {
195
- expectArgs(args, 0, "speech [--since <seq>] [--limit <n>] [--include-markers]");
196
- const entries = await speech.getSpeech({
353
+ }
354
+ };
355
+ const SPEECH = {
356
+ usage: "speech [--since <seq>] [--limit <n>] [--include-markers] [--session <id> | --all]",
357
+ description: ["Recorded speech entries, oldest first"]
358
+ };
359
+ const speech = {
360
+ options: [
361
+ "since",
362
+ "limit",
363
+ "include-markers",
364
+ "session",
365
+ "all"
366
+ ],
367
+ help: [SPEECH],
368
+ async run(args, { values, speech, out, io }) {
369
+ expectArgs(args, 0, SPEECH.usage);
370
+ const client = speech();
371
+ const options = {
197
372
  since: optionalInt(values, "since", 0) ?? 0,
198
373
  limit: optionalInt(values, "limit", 1),
199
- includeMarkers: values["include-markers"] ?? false
200
- });
201
- out({ entries }, entries.map(formatEntry).join("\n"));
374
+ includeMarkers: values["include-markers"] ?? false,
375
+ session: await scope(values, client)
376
+ };
377
+ const read = await readAll(io, () => client.getSpeech(options));
378
+ out("speech", read, read.entries.map(formatEntry).join("\n"));
202
379
  return EXIT.ok;
203
- },
204
- async text(args, { values, speech, out }) {
205
- expectArgs(args, 0, "text [--since <seq>] [--separator <s>]");
206
- const text = await speech.getText({
380
+ }
381
+ };
382
+ const TEXT = {
383
+ usage: "text [--since <seq>] [--separator <s>] [--session <id> | --all]",
384
+ description: ["All speech joined into one text (one line per entry)"]
385
+ };
386
+ const text = {
387
+ options: [
388
+ "since",
389
+ "separator",
390
+ "session",
391
+ "all"
392
+ ],
393
+ help: [TEXT],
394
+ async run(args, { values, speech, out, io }) {
395
+ expectArgs(args, 0, TEXT.usage);
396
+ const client = speech();
397
+ const options = {
207
398
  since: optionalInt(values, "since", 0) ?? 0,
208
- separator: values.separator
209
- });
210
- out({ text }, text);
399
+ session: await scope(values, client)
400
+ };
401
+ const { entries, truncated } = await readAll(io, () => client.getSpeech(options));
402
+ const joined = entries.map((e) => e.text).join(values.separator ?? "\n");
403
+ out("text", {
404
+ text: joined,
405
+ truncated
406
+ }, joined);
211
407
  return EXIT.ok;
212
- },
213
- async wait(args, { values, speech, out, io, json }) {
214
- const [text] = expectArgs(args, 1, "wait <text> [--regex] [--normalize] [--timeout <ms>]");
215
- if (text.trim() === "") throw new UsageError("The text to wait for must not be empty.");
216
- let match = text;
408
+ }
409
+ };
410
+ const WAIT = {
411
+ usage: "wait <text> [--regex] [--normalize] [--since <seq>] [--timeout <ms>] [--session <id> | --all]",
412
+ description: ["Wait until speech contains <text> (or matches the regex);", "also finds speech that arrived before the call (default timeout 5000)"]
413
+ };
414
+ const wait = {
415
+ options: [
416
+ "regex",
417
+ "normalize",
418
+ "since",
419
+ "timeout",
420
+ "session",
421
+ "all"
422
+ ],
423
+ help: [WAIT],
424
+ async run(args, { values, speech, out, io, json }) {
425
+ const [needle] = expectArgs(args, 1, WAIT.usage);
426
+ if (needle.trim() === "") throw new UsageError("The text to wait for must not be empty.");
427
+ let match = needle;
217
428
  if (values.regex) try {
218
- match = new RegExp(text, "u");
429
+ match = new RegExp(needle, "u");
219
430
  } catch (error) {
220
431
  throw new UsageError(`Invalid --regex: ${error.message}`);
221
432
  }
433
+ const client = speech();
434
+ const options = {
435
+ since: optionalInt(values, "since", 0) ?? 0,
436
+ timeout: optionalInt(values, "timeout", 0),
437
+ normalize: values.normalize ?? false,
438
+ session: await scope(values, client)
439
+ };
222
440
  try {
223
- const entry = await speech.waitForOutput(match, {
224
- since: optionalInt(values, "since", 0) ?? 0,
225
- timeout: optionalInt(values, "timeout", 0),
226
- normalize: values.normalize ?? false
227
- });
228
- out({
441
+ const entry = await client.waitForOutput(match, options);
442
+ out("wait", {
229
443
  matched: true,
230
444
  entry
231
445
  }, formatEntry(entry));
232
446
  return EXIT.ok;
233
447
  } catch (error) {
234
448
  if (!(error instanceof SpeechTimeoutError)) throw error;
235
- if (json) io.stdout(`${JSON.stringify({
449
+ if (json) out("wait", {
236
450
  matched: false,
237
- entries: error.entries
238
- })}\n`);
451
+ entries: error.entries,
452
+ truncated: error.truncated
453
+ }, "");
239
454
  io.stderr(`${NAME}: ${error.message}.${seenText(error.entries)}\n`);
240
455
  return EXIT.timeout;
241
456
  }
242
- },
243
- async "wait-silence"(args, { values, speech, out, io }) {
244
- expectArgs(args, 0, "wait-silence [--quiet-for <ms>] [--timeout <ms>]");
457
+ }
458
+ };
459
+ const WAIT_SILENCE = {
460
+ usage: "wait-silence [--quiet-for <ms>] [--timeout <ms>]",
461
+ description: ["Wait until nothing was spoken for --quiet-for ms (default 500, 10000)"]
462
+ };
463
+ const waitSilence = {
464
+ options: ["quiet-for", "timeout"],
465
+ help: [WAIT_SILENCE],
466
+ async run(args, { values, speech, out, io }) {
467
+ expectArgs(args, 0, WAIT_SILENCE.usage);
245
468
  const quietFor = optionalInt(values, "quiet-for", 1);
469
+ const timeout = optionalInt(values, "timeout", 0);
246
470
  try {
247
- await speech.waitForSilence({
471
+ await speech().waitForSilence({
248
472
  quietFor,
249
- timeout: optionalInt(values, "timeout", 0)
473
+ timeout
250
474
  });
251
- out({ silent: true }, "Silent.");
475
+ out("wait-silence", { silent: true }, "Silent.");
252
476
  return EXIT.ok;
253
477
  } catch (error) {
254
478
  if (!(error instanceof SpeechTimeoutError)) throw error;
255
479
  io.stderr(`${NAME}: ${error.message}.\n`);
256
480
  return EXIT.timeout;
257
481
  }
258
- },
259
- async mark(args, { speech, out }) {
260
- const [label] = expectArgs(args, 1, "mark <label>");
261
- const entry = await speech.mark(label);
262
- out(entry, String(entry.seq));
482
+ }
483
+ };
484
+ const MARK = {
485
+ usage: "mark <label>",
486
+ description: ["Insert a marker and print its seq, for --since"]
487
+ };
488
+ const mark = {
489
+ options: [],
490
+ help: [MARK],
491
+ async run(args, { speech, out }) {
492
+ const [label] = expectArgs(args, 1, MARK.usage);
493
+ const entry = await speech().mark(label);
494
+ out("mark", entry, String(entry.seq));
263
495
  return EXIT.ok;
264
496
  }
265
497
  };
266
- /** An integer option >= `min`, `undefined` if not given. */
267
- function optionalInt(values, name, min) {
268
- const raw = values[name];
269
- if (raw === void 0) return void 0;
270
- const value = Number(raw);
271
- if (typeof raw !== "string" || !/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < min) throw new UsageError(`--${name} must be an integer >= ${min}, got "${String(raw)}".`);
272
- return value;
498
+ const TAIL = {
499
+ usage: "tail [--since <seq>]",
500
+ description: ["Print speech live as it arrives, until Ctrl+C (one JSON event per", "line with --json); --since first prints the buffered entries after <seq>"]
501
+ };
502
+ const tail = {
503
+ options: ["since"],
504
+ help: [TAIL],
505
+ async run(args, { values, speech, out, io, json }) {
506
+ expectArgs(args, 0, TAIL.usage);
507
+ const since = optionalInt(values, "since", 0);
508
+ const client = speech();
509
+ await client.status();
510
+ const signal = io.interrupt();
511
+ return new Promise((resolve) => {
512
+ const finish = (code) => {
513
+ signal.removeEventListener("abort", interrupted);
514
+ stop();
515
+ resolve(code);
516
+ };
517
+ const interrupted = () => finish(EXIT.ok);
518
+ const stop = client.onSpeech((entry) => out("tail", {
519
+ type: "entry",
520
+ entry
521
+ }, formatEntry(entry)), {
522
+ since,
523
+ includeMarkers: true,
524
+ onSession: (s) => out("tail", {
525
+ type: "session",
526
+ session: s
527
+ }, formatSessionEvent(s)),
528
+ onClear: () => out("tail", { type: "clear" }, "--- buffer cleared ---"),
529
+ onTruncated: () => {
530
+ if (json) out("tail", { type: "truncated" }, "");
531
+ io.stderr(`${NAME}: some entries were dropped from the bridge's buffer before they could be shown.\n`);
532
+ },
533
+ onError: (error, { retrying }) => {
534
+ io.stderr(`${NAME}: ${error.message}${retrying ? ", reconnecting" : ""}\n`);
535
+ if (!retrying) finish(EXIT.bridge);
536
+ }
537
+ });
538
+ if (signal.aborted) finish(EXIT.ok);
539
+ else signal.addEventListener("abort", interrupted, { once: true });
540
+ });
541
+ }
542
+ };
543
+ /**
544
+ * A read that shows what is left when some of the speech was dropped from the bridge's full
545
+ * buffer, with a warning on stderr: a person or agent reading the CLI wants the rest, and
546
+ * `truncated` in the --json output says it is incomplete.
547
+ */
548
+ async function readAll(io, read) {
549
+ try {
550
+ return {
551
+ entries: await read(),
552
+ truncated: false
553
+ };
554
+ } catch (error) {
555
+ if (!(error instanceof SpeechTruncatedError)) throw error;
556
+ io.stderr(`${NAME}: some speech was dropped because the bridge's buffer was full (raise buffer.maxEntries); showing what is left.
557
+ `);
558
+ return {
559
+ entries: error.entries,
560
+ truncated: true
561
+ };
562
+ }
273
563
  }
274
- function formatEntry(entry) {
275
- return entry.kind === "marker" ? `#${entry.seq} [marker] ${entry.text}` : `#${entry.seq} ${entry.text}`;
564
+ // src/adapters/in/cli/commands/index.ts
565
+ /** The commands by name, grouped as `--help` lists them. */
566
+ const COMMAND_GROUPS = [
567
+ {
568
+ status,
569
+ session,
570
+ clear,
571
+ speech,
572
+ text,
573
+ wait,
574
+ "wait-silence": waitSilence,
575
+ mark,
576
+ tail
577
+ },
578
+ {
579
+ click,
580
+ press
581
+ },
582
+ { config }
583
+ ];
584
+ const COMMANDS = Object.fromEntries(COMMAND_GROUPS.flatMap((group) => Object.entries(group)));
585
+ // src/adapters/in/cli/help.ts
586
+ /** Column where command descriptions start; longer usages put theirs on the next line. */
587
+ const COLUMN = 25;
588
+ /** `--help`, built from the command table and the global options. */
589
+ function helpText() {
590
+ const commands = COMMAND_GROUPS.map((group) => Object.values(group).flatMap((command) => command.help).flatMap(({ usage, description }) => {
591
+ const [first = "", ...more] = description;
592
+ const lead = ` ${usage}`;
593
+ return [...lead.length + 2 <= COLUMN ? [lead.padEnd(COLUMN) + first] : [lead, " ".repeat(COLUMN) + first], ...more.map((line) => " ".repeat(COLUMN) + line)];
594
+ }).join("\n"));
595
+ const width = Math.max(...GLOBAL_OPTIONS.map((o) => o.flag.length)) + 1;
596
+ return `Usage: ${NAME} <command> [options]
597
+
598
+ Commands:
599
+ ${commands.join("\n\n")}
600
+
601
+ Options:
602
+ ${GLOBAL_OPTIONS.map((o) => ` ${o.flag.padEnd(width)}${o.description}`).join("\n")}
603
+
604
+ speech, text and wait read the current session (everything since "session start"), or the
605
+ whole buffer when no session is current. --session <id> reads another session, --all the
606
+ whole buffer. --since <seq> takes a seq printed by mark (for tail, default: only new speech).
607
+
608
+ Exit codes: 0 success, 1 timeout / no match, 2 bridge not reachable, HTTP error or
609
+ incompatible bridge, 3 invalid usage or config.
610
+ `;
276
611
  }
277
- function seenText(entries) {
278
- if (entries.length === 0) return " No speech arrived.";
279
- return ` Speech seen:\n${entries.map((e) => ` ${formatEntry(e)}`).join("\n")}`;
612
+ // src/adapters/in/cli/run.ts
613
+ /** Runs one CLI invocation and returns its exit code. */
614
+ async function runCli(argv, io) {
615
+ try {
616
+ return await dispatch(argv, io);
617
+ } catch (error) {
618
+ const code = exitCode(error);
619
+ if (code === void 0) throw error;
620
+ const hint = error instanceof UsageError ? "\nRun with --help to see the commands." : "";
621
+ io.stderr(`${NAME}: ${error.message}${hint}\n`);
622
+ return code;
623
+ }
280
624
  }
281
- function formatStatus(status) {
282
- const { bridge, tcp, buffer, input } = status;
283
- const connections = tcp.connections.length;
284
- const range = buffer.firstSeq === null ? "empty" : `seq ${buffer.firstSeq}-${buffer.lastSeq ?? buffer.firstSeq}`;
285
- return [
286
- `bridge ${bridge.version} (API ${bridge.apiVersion}), ${bridge.state}`,
287
- `tcp ${tcp.host}:${tcp.port} ${tcp.listening ? "listening" : "not listening"}, ${connections} voice connection${connections === 1 ? "" : "s"}, ${tcp.encoding}`,
288
- `buffer ${buffer.size} of ${buffer.maxEntries} entries (${range})`,
289
- `input ${input.enabled ? "enabled" : "disabled"}`
290
- ].join("\n");
625
+ /** The exit code for an expected error, `undefined` for a bug. */
626
+ function exitCode(error) {
627
+ if (error instanceof UsageError || error instanceof ClientConfigError) return EXIT.usage;
628
+ if (error instanceof BridgeNotReadyError) return EXIT.timeout;
629
+ if (error instanceof BridgeUnreachableError || error instanceof BridgeHttpError || error instanceof IncompatibleBridgeError) return EXIT.bridge;
291
630
  }
292
- async function config(args, globals, io) {
293
- const { config } = io;
294
- const file = config.location;
295
- const explicit = { url: globals.url };
296
- const out = (json, text) => io.stdout(globals.json ? `${JSON.stringify(json)}\n` : `${text}\n`);
297
- const [action, ...rest] = args;
298
- switch (action) {
299
- case "set": {
300
- const [key, value] = expectArgs(rest, 2, "config set <key> <value>");
301
- const result = await config.set(key, value);
302
- out({
303
- ...result,
304
- file
305
- }, `Saved ${result.key} = ${result.value} to ${file}`);
306
- if (result.shadowedBy === "env") io.stderr(`Note: ${URL_ENV} is set and takes precedence over the config file.\n`);
307
- return EXIT.ok;
308
- }
309
- case "get": {
310
- const [key] = expectArgs(rest, 1, "config get <key>");
311
- const result = await config.get(key, explicit);
312
- out(result, `${result.value} (${SOURCE_LABEL[result.source]})`);
313
- return EXIT.ok;
314
- }
315
- case "unset": {
316
- const [key] = expectArgs(rest, 1, "config unset <key>");
317
- const result = await config.unset(key);
318
- out({
319
- ...result,
320
- file
321
- }, `Removed ${result.key} from ${file}`);
322
- return EXIT.ok;
323
- }
324
- case "list": {
325
- expectArgs(rest, 0, "config list");
326
- const entries = await config.list(explicit);
327
- out({
328
- file,
329
- settings: entries
330
- }, [`# ${file}`, ...entries.map((e) => `${e.key} = ${e.value} (${SOURCE_LABEL[e.source]})`)].join("\n"));
331
- return EXIT.ok;
332
- }
333
- case "path":
334
- expectArgs(rest, 0, "config path");
335
- out({ file }, file);
336
- return EXIT.ok;
337
- case void 0: throw new UsageError("Missing config action: set, get, unset, list or path.");
338
- default: throw new UsageError(`Unknown config action "${action}": use set, get, unset, list or path.`);
631
+ async function dispatch(argv, io) {
632
+ let parsed;
633
+ try {
634
+ parsed = parseArgs({
635
+ args: [...argv],
636
+ allowPositionals: true,
637
+ options: OPTIONS
638
+ });
639
+ } catch (error) {
640
+ throw new UsageError(error.message);
339
641
  }
642
+ const { values, positionals } = parsed;
643
+ if (values.help) {
644
+ io.stdout(helpText());
645
+ return EXIT.ok;
646
+ }
647
+ if (values.version) {
648
+ io.stdout(`${io.version}\n`);
649
+ return EXIT.ok;
650
+ }
651
+ const [name, ...args] = positionals;
652
+ if (name === void 0) throw new UsageError("Missing command.");
653
+ const command = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : void 0;
654
+ if (command === void 0) throw new UsageError(`Unknown command "${name}".`);
655
+ checkOptions(name, command.options, values);
656
+ let client;
657
+ let input;
658
+ const ctx = {
659
+ values,
660
+ json: values.json,
661
+ io,
662
+ speech: () => client ??= io.speech(values.url),
663
+ input: () => input ??= io.input(values.url),
664
+ out: (_command, json, text) => io.stdout(values.json ? `${JSON.stringify(json)}\n` : `${text}\n`)
665
+ };
666
+ return command.run(args, ctx);
340
667
  }
341
- function expectArgs(args, count, usage) {
342
- if (args.length !== count) throw new UsageError(`Usage: ${NAME} ${usage}`);
343
- return args;
344
- }
345
- // src/adapters/in/cli/cli.ts
668
+ // src/bin/cli.ts
346
669
  process.exitCode = await runCli(process.argv.slice(2), {
347
670
  config: createClientConfig(process.env),
348
671
  speech: (url) => new SpeechCaptureClient({
349
672
  baseUrl: url,
350
- env: process.env
673
+ env: process.env,
674
+ clientName: `${hostname()} cli`
675
+ }),
676
+ input: (url) => new SpeechCaptureClient({
677
+ baseUrl: url,
678
+ env: process.env,
679
+ clientName: `${hostname()} cli`
351
680
  }),
352
681
  stdout: (text) => process.stdout.write(text),
353
682
  stderr: (text) => process.stderr.write(text),
354
- version
683
+ version,
684
+ interrupt
355
685
  });
686
+ /** Ctrl+C, a kill or a closed stdout (`tail --json | head -3`) end the command normally. */
687
+ function interrupt() {
688
+ const controller = new AbortController();
689
+ const stop = () => controller.abort();
690
+ process.once("SIGINT", stop);
691
+ process.once("SIGTERM", stop);
692
+ process.stdout.on("error", (error) => {
693
+ if (error.code !== "EPIPE") throw error;
694
+ stop();
695
+ });
696
+ return controller.signal;
697
+ }
356
698
  export {};