@raidiant/notifai 7.0.1 → 8.0.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 (75) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/commands-devices.d.ts +2 -1
  3. package/dist/commands-devices.js +20 -8
  4. package/dist/commands-devices.js.map +1 -1
  5. package/dist/commands-doctor.js +14 -12
  6. package/dist/commands-doctor.js.map +1 -1
  7. package/dist/commands-guidance.d.ts +23 -0
  8. package/dist/commands-guidance.js +128 -0
  9. package/dist/commands-guidance.js.map +1 -0
  10. package/dist/commands-hooks.d.ts +7 -1
  11. package/dist/commands-hooks.js +3 -6
  12. package/dist/commands-hooks.js.map +1 -1
  13. package/dist/commands-init.js +25 -22
  14. package/dist/commands-init.js.map +1 -1
  15. package/dist/commands-send-support.js +5 -3
  16. package/dist/commands-send-support.js.map +1 -1
  17. package/dist/commands-send.d.ts +0 -1
  18. package/dist/commands-send.js +45 -28
  19. package/dist/commands-send.js.map +1 -1
  20. package/dist/commands.d.ts +1 -0
  21. package/dist/commands.js +1 -0
  22. package/dist/commands.js.map +1 -1
  23. package/dist/config-schema.js +6 -15
  24. package/dist/config-schema.js.map +1 -1
  25. package/dist/config.d.ts +1 -3
  26. package/dist/config.js +0 -3
  27. package/dist/config.js.map +1 -1
  28. package/dist/guidance-content.d.ts +30 -0
  29. package/dist/guidance-content.js +175 -0
  30. package/dist/guidance-content.js.map +1 -0
  31. package/dist/guidance.d.ts +48 -0
  32. package/dist/guidance.js +118 -0
  33. package/dist/guidance.js.map +1 -0
  34. package/dist/hooks.js +7 -7
  35. package/dist/hooks.js.map +1 -1
  36. package/dist/interactive.d.ts +1 -1
  37. package/dist/interactive.js +13 -8
  38. package/dist/interactive.js.map +1 -1
  39. package/dist/main.js +3 -474
  40. package/dist/main.js.map +1 -1
  41. package/dist/program.d.ts +49 -0
  42. package/dist/program.js +571 -0
  43. package/dist/program.js.map +1 -0
  44. package/dist/send.d.ts +4 -9
  45. package/dist/send.js +48 -28
  46. package/dist/send.js.map +1 -1
  47. package/dist/session-labels.d.ts +9 -3
  48. package/dist/session-labels.js +38 -7
  49. package/dist/session-labels.js.map +1 -1
  50. package/package.json +5 -3
  51. package/src/commands-devices.ts +28 -9
  52. package/src/commands-doctor.ts +17 -12
  53. package/src/commands-guidance.ts +170 -0
  54. package/src/commands-hooks.ts +10 -8
  55. package/src/commands-init.ts +31 -22
  56. package/src/commands-send-support.ts +5 -3
  57. package/src/commands-send.ts +50 -28
  58. package/src/commands.test.ts +374 -63
  59. package/src/commands.ts +5 -0
  60. package/src/config-schema.ts +6 -17
  61. package/src/config.test.ts +56 -1
  62. package/src/config.ts +0 -5
  63. package/src/guidance-content.ts +190 -0
  64. package/src/guidance.test.ts +268 -0
  65. package/src/guidance.ts +151 -0
  66. package/src/hooks.test.ts +37 -5
  67. package/src/hooks.ts +7 -7
  68. package/src/interactive.ts +13 -8
  69. package/src/main.ts +4 -600
  70. package/src/program.test.ts +202 -0
  71. package/src/program.ts +723 -0
  72. package/src/send.ts +53 -32
  73. package/src/session-labels.test.ts +120 -3
  74. package/src/session-labels.ts +38 -7
  75. package/src/skill.test.ts +45 -8
package/src/program.ts ADDED
@@ -0,0 +1,723 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { Command } from 'commander'
3
+ import {
4
+ acknowledgeCommand,
5
+ askCommand,
6
+ accessStatusCommand,
7
+ authStatusCommand,
8
+ capabilitiesCommand,
9
+ closeCommand,
10
+ configExplainCommand,
11
+ configSetCommand,
12
+ configShowCommand,
13
+ configUnsetCommand,
14
+ devicesCommand,
15
+ doctorCommand,
16
+ guidanceSetCommand,
17
+ guidanceShowCommand,
18
+ guidanceUnsetCommand,
19
+ hookDefersDiagnosticsUntilAfterCleanup,
20
+ hookRunCommand,
21
+ hooksInstallCommand,
22
+ hooksUninstallCommand,
23
+ initCommand,
24
+ loginCommand,
25
+ logoutCommand,
26
+ logsCommand,
27
+ repliesCommand,
28
+ sendCommand,
29
+ statusCommand,
30
+ type CommandDeps,
31
+ } from './commands.js'
32
+ import { packageVersion } from './release.js'
33
+ import { HARNESSES } from './install-hooks.js'
34
+ import type { Platform } from '@raidiant/notifai-protocol'
35
+ import type { SkillScope } from './native-skills.js'
36
+ import { GROUP, SEND_GROUP, helpConfiguration, rootHelpFooter } from './ui/help.js'
37
+ import { readStdinWithTimeout } from './hook-input.js'
38
+
39
+ /**
40
+ * One source of truth for the version: the manifest npm actually published.
41
+ *
42
+ * It was hardcoded here as well, and the first patch release proved why that
43
+ * does not hold — `package.json` moved and `notifai --version` kept reporting
44
+ * the old number, which is exactly the string someone pastes into a bug report
45
+ * to say what they are running.
46
+ *
47
+ * `unknown` is the display form of "this build cannot tell"; the skill pin
48
+ * derived from the same source refuses instead, because a wrong ref installs
49
+ * the wrong thing while a wrong version string only misinforms.
50
+ */
51
+ function version(): string {
52
+ return packageVersion() ?? 'unknown'
53
+ }
54
+
55
+ /**
56
+ * The full command path, e.g. `config set`, so a filter on `cmd` distinguishes
57
+ * subcommands that share a leaf name.
58
+ */
59
+ function commandPath(command: Command): string {
60
+ const parts: string[] = []
61
+ for (let node: Command | null = command; node?.parent != null; node = node.parent) {
62
+ parts.unshift(node.name())
63
+ }
64
+ return parts.join(' ') || 'notifai'
65
+ }
66
+
67
+ /**
68
+ * Every command implementation the tree dispatches to, injectable so a test
69
+ * can parse real argv and assert the exact flags a command would receive —
70
+ * the layer where `--no-wait` disentangling and collector defaults live, which
71
+ * unit tests on the commands themselves can never see.
72
+ */
73
+ const defaultRunners = {
74
+ init: initCommand,
75
+ doctor: doctorCommand,
76
+ login: loginCommand,
77
+ logout: logoutCommand,
78
+ authStatus: authStatusCommand,
79
+ accessStatus: accessStatusCommand,
80
+ devices: devicesCommand,
81
+ capabilities: capabilitiesCommand,
82
+ send: sendCommand,
83
+ replies: repliesCommand,
84
+ acknowledge: acknowledgeCommand,
85
+ status: statusCommand,
86
+ ask: askCommand,
87
+ close: closeCommand,
88
+ hookRun: hookRunCommand,
89
+ hooksInstall: hooksInstallCommand,
90
+ hooksUninstall: hooksUninstallCommand,
91
+ logs: logsCommand,
92
+ configShow: configShowCommand,
93
+ configExplain: configExplainCommand,
94
+ configSet: configSetCommand,
95
+ configUnset: configUnsetCommand,
96
+ guidanceShow: guidanceShowCommand,
97
+ guidanceSet: guidanceSetCommand,
98
+ guidanceUnset: guidanceUnsetCommand,
99
+ /**
100
+ * Dynamic so that the prompt library, the banner and the whole interactive
101
+ * tree cost nothing to the paths that never draw them — `send`, `ask`, and
102
+ * the hook that runs in front of every prompt the user types.
103
+ */
104
+ interactive: async (deps: CommandDeps, versionString: string): Promise<number> => {
105
+ const { interactiveCommand } = await import('./interactive.js')
106
+ return interactiveCommand(deps, versionString)
107
+ },
108
+ }
109
+
110
+ export type ProgramRunners = typeof defaultRunners
111
+
112
+ export interface BuildProgramOptions {
113
+ /** Test seam; production ends the process with the command's exit code. */
114
+ exit?: (code: number) => void
115
+ runners?: Partial<ProgramRunners>
116
+ }
117
+
118
+ export function buildProgram(deps: CommandDeps, options: BuildProgramOptions = {}): Command {
119
+ const exit = options.exit ?? ((code: number) => process.exit(code))
120
+ const runners: ProgramRunners = { ...defaultRunners, ...options.runners }
121
+ const logger = deps.logger
122
+
123
+ const program = new Command('notifai')
124
+ .description('Send native device notifications from agents and local programs')
125
+ .version(version())
126
+ .configureHelp(helpConfiguration)
127
+ // Lazy on purpose. `addHelpText` also takes a string, but that builds the
128
+ // footer on every invocation — including the hook that runs in front of
129
+ // every prompt the user types, which never renders help at all.
130
+ .addHelpText('after', () => rootHelpFooter())
131
+ // Commander's default is to print the full help and exit 0 for an unknown
132
+ // `help` topic, so `notifai help nonsense` looked like it had worked. A
133
+ // reader who mistyped a command deserves to be told, and a script deserves
134
+ // a nonzero code.
135
+ .showSuggestionAfterError(true)
136
+ // Commander drops the implicit `help [command]` as soon as the program
137
+ // itself has an action handler — which the interactive default below gives
138
+ // it. Without this, adding that default would silently break
139
+ // `notifai help send` for everyone who reaches for it before `--help`.
140
+ .helpCommand(true)
141
+ .hook('preAction', (_program, actionCommand) => {
142
+ logger?.bind({ cmd: commandPath(actionCommand) })
143
+ // SessionEnd uses the hook policy shared with commands.ts: local cleanup
144
+ // precedes every diagnostic that can wait on the shared log lock.
145
+ const deferDiagnostics =
146
+ actionCommand.name() === 'hook' &&
147
+ hookDefersDiagnosticsUntilAfterCleanup(actionCommand.processedArgs[0])
148
+ // Values only at `debug`; `cli.end` carries the flag names at every level.
149
+ if (!deferDiagnostics) {
150
+ logger?.debug('cli.start', {
151
+ version: version(),
152
+ argv: process.argv.slice(2),
153
+ cwd: process.cwd(),
154
+ })
155
+ }
156
+ })
157
+
158
+ /**
159
+ * Commander exits 1 for every usage error it detects itself, which contradicts
160
+ * the exit vocabulary this CLI documents and every hand-written usage error it
161
+ * returns. A caller branching on exit codes should not have to know which layer
162
+ * rejected it. Help and version stay successful.
163
+ */
164
+ program.exitOverride((err) => {
165
+ exit(err.exitCode === 0 ? 0 : 2)
166
+ })
167
+
168
+ /**
169
+ * Bare `notifai`.
170
+ *
171
+ * At a human terminal this opens the interactive app; anywhere else it prints
172
+ * help exactly as before. The check is the same one every other prompt in this
173
+ * CLI is gated on — stdin and stdout both TTYs, not CI, `NOTIFAI_NO_INPUT`
174
+ * unset — because an agent that reaches a prompt does not fail, it hangs
175
+ * for ever waiting on a stdin nobody is typing into.
176
+ */
177
+ /**
178
+ * An unrecognised subcommand reaches the root as an excess argument, and
179
+ * "expected 0 arguments but got 1" tells a caller nothing about what it typed
180
+ * or what exists. Naming it — with the nearest real command when there is one —
181
+ * turns a dead end into one more try.
182
+ */
183
+ program.usage('[options] [command]')
184
+ program.argument('[command]').action(async (command?: string) => {
185
+ if (command !== undefined) {
186
+ const names = program.commands.map((cmd) => cmd.name())
187
+ const near = names.filter(
188
+ (name) =>
189
+ name.startsWith(command.slice(0, 2)) ||
190
+ command.startsWith(name.slice(0, 2)) ||
191
+ name.includes(command) ||
192
+ command.includes(name),
193
+ )
194
+ deps.io.err(
195
+ `Unknown command "${command}".` +
196
+ (near.length > 0 ? ` Did you mean: ${near.slice(0, 3).join(', ')}?` : '') +
197
+ ' Run notifai --help for the full list.',
198
+ )
199
+ return exit(2)
200
+ }
201
+ if (deps.io.interactive !== true) {
202
+ program.outputHelp()
203
+ return
204
+ }
205
+ exit(await runners.interactive(deps, version()))
206
+ })
207
+
208
+ // Setup leads: `init` is the single entry command for first-run friendliness.
209
+ program
210
+ .command('init')
211
+ .helpGroup(GROUP.start)
212
+ .summary('Set this project up, step by step')
213
+ .description(
214
+ 'Set up Notifai here, idempotently: sign-in, project id, hooks, device readiness, live receipt proof. ' +
215
+ 'Interactive at a human terminal; never prompts otherwise (agents: pass flags)',
216
+ )
217
+ .option('--project-id <id>', 'project identifier slug (default: derived from the directory name)')
218
+ .option('--skills', 'install/update the agent skill from its pinned public release')
219
+ .option('--no-skills', 'suppress the optional agent-skill status line')
220
+ .option('--skills-scope <scope>', 'unattended skill scope: project or global')
221
+ .option('--hooks', 'install harness hooks for registered-question routing')
222
+ .option('--no-hooks', 'skip the hooks without being asked')
223
+ .action(async (opts: { projectId?: string; skills?: boolean; skillsScope?: SkillScope; hooks?: boolean }) => {
224
+ exit(await runners.init(deps, opts))
225
+ })
226
+
227
+ program
228
+ .command('doctor')
229
+ .helpGroup(GROUP.daily)
230
+ .summary('Check every part of the setup')
231
+ .description('Audit config, credential, server, contract, device, hook, and saved receipt proof; exits nonzero when any line is FAIL (no live send)')
232
+ .option('--json', 'machine-readable output')
233
+ .action(async (opts: { json?: boolean }) => {
234
+ exit(await runners.doctor(deps, opts))
235
+ })
236
+
237
+ program
238
+ .command('login')
239
+ .helpGroup(GROUP.start)
240
+ .summary('Sign in and pair this machine')
241
+ .description('Pair this machine with your Notifai account via browser approval')
242
+ .option('--name <name>', 'machine name shown in the dashboard (default: hostname)')
243
+ .option('--base-url <url>', 'developer override for the service origin (also NOTIFAI_BASE_URL)')
244
+ .option('--no-open', 'do not open the approval page in a browser')
245
+ .action(async (opts: { name?: string; baseUrl?: string; open?: boolean }) => {
246
+ exit(await runners.login(deps, opts))
247
+ })
248
+
249
+ program
250
+ .command('logout')
251
+ .helpGroup(GROUP.advanced)
252
+ .summary('Remove the stored machine credential')
253
+ .description('Remove the stored machine credential')
254
+ .action(() => {
255
+ exit(runners.logout(deps))
256
+ })
257
+
258
+ const auth = program
259
+ .command('auth')
260
+ .description('Authentication helpers')
261
+ .summary('Machine identity and account plan')
262
+ .helpGroup(GROUP.advanced)
263
+ auth
264
+ .command('status')
265
+ .description('Show the stored machine identity')
266
+ .option('--json', 'machine-readable output')
267
+ .action((opts: { json?: boolean }) => {
268
+ exit(runners.authStatus(deps, opts))
269
+ })
270
+ auth
271
+ .command('access')
272
+ .description('Show the account plan and access decision')
273
+ .option('--json', 'machine-readable output')
274
+ .action(async (opts: { json?: boolean }) => {
275
+ exit(await runners.accessStatus(deps, opts))
276
+ })
277
+
278
+ program
279
+ .command('devices')
280
+ .helpGroup(GROUP.daily)
281
+ .summary('List your devices and whether they can receive')
282
+ .description('List registered devices and their delivery readiness')
283
+ .option('--platform <platform>', 'show only devices on one supported platform')
284
+ .option('--json', 'machine-readable output')
285
+ .action(async (opts: { json?: boolean; platform?: string }) => {
286
+ exit(await runners.devices(deps, opts))
287
+ })
288
+
289
+ program
290
+ .command('capabilities')
291
+ .helpGroup(GROUP.advanced)
292
+ .summary('Show what a platform can render')
293
+ .description('Show a platform capability contract')
294
+ .option('--platform <platform>', 'platform to describe (default: ios)')
295
+ .option('--json', 'machine-readable output')
296
+ .action(async (opts: { json?: boolean; platform?: Platform }) => {
297
+ exit(await runners.capabilities(deps, opts))
298
+ })
299
+
300
+ const send = program
301
+ .command('send')
302
+ .helpGroup(GROUP.agent)
303
+ .summary('Send a notification')
304
+ .description('Send a notification')
305
+ .optionsGroup(SEND_GROUP.content)
306
+ .requiredOption('--title <title>', 'brief title whose substance is immediately understandable')
307
+ .option('--body <markdown>', 'canonical Markdown body')
308
+ .option('--body-file <path>', 'read the canonical Markdown body from a file (use - for stdin)')
309
+ .option('--subtitle <subtitle>', 'a plain-text line between the title and body')
310
+ .option(
311
+ '--image <path|url|media_id>',
312
+ 'upload or attach an image in collection order (repeatable, maximum 8)',
313
+ (v: string, all: string[] = []) => [...all, v],
314
+ )
315
+ .option(
316
+ '--image-alt <text>',
317
+ 'alt text paired with --image occurrences by position (repeatable)',
318
+ (v: string, all: string[] = []) => [...all, v],
319
+ )
320
+ .optionsGroup(SEND_GROUP.routing)
321
+ .option('--kind <kind>', 'what this is (required): update | done | failed | blocked — question is set by --reply')
322
+ .option('--project <id>', 'project identifier override (otherwise configured or inferred)')
323
+ .option('--device <id>', 'target a device id (repeatable)', (v: string, all: string[] = []) => [...all, v])
324
+ .option('--all', 'target all routable devices (overrides configured devices)')
325
+ .option('--session-id <id>', 'opaque exact-session override (env: NOTIFAI_SESSION_ID)')
326
+ .option(
327
+ '--session-label <text>',
328
+ 'first human session name, frozen locally (env: NOTIFAI_SESSION_LABEL)',
329
+ )
330
+ .option('--event <event>', 'agent event name, e.g. tests_passed')
331
+ .optionsGroup(SEND_GROUP.presentation)
332
+ .option('--collapse-key <key>', 'replace earlier notifications with the same key')
333
+ .option('--thread-id <id>', 'group related notifications')
334
+ .option('--ttl <seconds>', 'delivery window in seconds', (v: string) => Number(v))
335
+ .option('--platform <platform>', 'limit optional fields to one supported platform')
336
+ .optionsGroup(SEND_GROUP.reply)
337
+ .option('--reply', 'enable the inline reply action and block for the answer')
338
+ .option('--reply-timeout <seconds>', 'how long to wait for a reply (default: 900)', (v: string) => Number(v))
339
+ .option(
340
+ '--reply-window <seconds>',
341
+ 'how long an answer is still accepted, 60-259200 (default: reply_window_seconds, a day)',
342
+ (v: string) => Number(v),
343
+ )
344
+ .option(
345
+ '--choice <label>',
346
+ 'with --reply, ask a closed question; repeat the flag once per answer (2-6)',
347
+ (v: string, all: string[] = []) => [...all, v],
348
+ )
349
+ .option('--multi', 'with --choice, several answers may be selected')
350
+ .optionsGroup(SEND_GROUP.advanced)
351
+ .option('--sound <sound>', 'override saved sound: default | done | attention | alert | none')
352
+ .option(
353
+ '--level <level>',
354
+ 'Apple-only interruption level: passive | active | time_sensitive (unsupported with --platform android)',
355
+ )
356
+ .option('--wait <seconds>', 'how long to wait for provider outcomes', (v: string) => Number(v))
357
+ .option('--no-wait', 'return immediately after acceptance')
358
+ .option('--data <key=value>', 'custom data (repeatable)', (v: string, all: string[] = []) => [...all, v])
359
+ .option('--idempotency-key <key>', 'safe-retry key (default: random)')
360
+ .option('--base-url <url>', 'developer override for the service origin (also NOTIFAI_BASE_URL)')
361
+ .option('--json', 'print the full submission receipt as JSON')
362
+ .action(async (opts: Record<string, unknown>) => {
363
+ // commander maps --no-wait onto the same "wait" flag; disentangle.
364
+ const noWait = opts['wait'] === false
365
+ const wait = typeof opts['wait'] === 'number' ? opts['wait'] : undefined
366
+ const sendOpts = { ...opts }
367
+ // Commander collectors default to []; an empty list means "not passed".
368
+ for (const key of ['choice', 'image', 'imageAlt']) {
369
+ if (Array.isArray(sendOpts[key]) && sendOpts[key].length === 0) delete sendOpts[key]
370
+ }
371
+ const bodyFile = sendOpts['bodyFile']
372
+ delete sendOpts['bodyFile']
373
+ if (typeof bodyFile === 'string') {
374
+ if (sendOpts['body'] !== undefined) {
375
+ deps.io.err('Pass either --body or --body-file, not both.')
376
+ return exit(2)
377
+ }
378
+ try {
379
+ sendOpts['body'] = readFileSync(bodyFile === '-' ? 0 : bodyFile, 'utf8')
380
+ } catch (err) {
381
+ deps.io.err(`Could not read ${bodyFile}: ${String(err)}`)
382
+ return exit(2)
383
+ }
384
+ }
385
+ const flags = { ...sendOpts, noWait } as Parameters<typeof sendCommand>[1]
386
+ if (wait === undefined) delete (flags as { wait?: number }).wait
387
+ else flags.wait = wait
388
+ exit(await runners.send(deps, flags))
389
+ })
390
+
391
+ send.addHelpText(
392
+ 'after',
393
+ `\nKind is required, and it selects the sound the notification arrives with: done rings the completion chime, failed the most insistent tone, blocked and question a distinct attention tone, update the standard one.\nAn explicit --sound or saved sound preference outranks that default. --level is Apple-only; Android attention is owned by kind, product channels, and device settings.\n`,
394
+ )
395
+
396
+ program
397
+ .command('replies [request_id]')
398
+ .helpGroup(GROUP.agent)
399
+ .summary('Retrieve replies to a question')
400
+ .description('Retrieve replies for a notification request')
401
+ .option('--pending', 'use the pushed question pending for this project session')
402
+ .option('--wait <seconds>', 'how long to wait for a reply', (v: string) => Number(v))
403
+ .option('--after <seq>', 'return replies after this sequence number', (v: string) => Number(v))
404
+ .option('--json', 'machine-readable output')
405
+ .action(async (requestId: string | undefined, opts: { wait?: number; after?: number; json?: boolean; pending?: boolean }) => {
406
+ exit(await runners.replies(deps, requestId, opts))
407
+ })
408
+
409
+ program
410
+ .command('acknowledge <request_id>')
411
+ .helpGroup(GROUP.agent)
412
+ .summary("Tell the user what you'll do because of their reply")
413
+ .description(
414
+ 'Record the required Agent Acknowledgement for a replied-to notification request; never prompts',
415
+ )
416
+ .option('--text <text>', 'concrete work you will do because of the reply')
417
+ .option('--json', 'machine-readable output')
418
+ .action(async (requestId: string, opts: { text?: string; json?: boolean }) => {
419
+ exit(await runners.acknowledge(deps, requestId, opts))
420
+ })
421
+
422
+ program
423
+ .command('status <request_id>')
424
+ .helpGroup(GROUP.agent)
425
+ .summary('Show the evidence trail for a request')
426
+ .description('Show the evidence trail for a notification request')
427
+ .option('--json', 'machine-readable output')
428
+ .action(async (requestId: string, opts: { json?: boolean }) => {
429
+ exit(await runners.status(deps, requestId, opts))
430
+ })
431
+
432
+ program
433
+ .command('ask [question]')
434
+ .helpGroup(GROUP.agent)
435
+ .summary('Register a question, then end the turn')
436
+ .description('Register a question for the turn-end hook to route to your devices, subject to your question-routing settings')
437
+ .option(
438
+ '--choice <label>',
439
+ 'answers to offer instead of free text; repeat the flag once per answer (2-6)',
440
+ (v: string, all: string[] = []) => [...all, v],
441
+ )
442
+ .option('--multi', 'with --choice, several answers may be selected')
443
+ .option('--json', 'machine-readable output')
444
+ .option('--body <markdown>', 'optional Markdown context appended after the question block')
445
+ .option('--body-file <path>', 'read optional Markdown context from a file (use - for stdin)')
446
+ .option('--form <path>', 'ask several questions as one form; JSON file (use - for stdin)')
447
+ .option(
448
+ '--image <path|url|media_id>',
449
+ 'upload or attach an image in collection order (repeatable, maximum 8)',
450
+ (v: string, all: string[] = []) => [...all, v],
451
+ )
452
+ .option(
453
+ '--image-alt <text>',
454
+ 'alt text paired with --image occurrences by position (repeatable)',
455
+ (v: string, all: string[] = []) => [...all, v],
456
+ )
457
+ .option('--project <id>', 'project identifier override (otherwise configured or inferred)')
458
+ .option('--session-id <id>', 'opaque exact-session override (env: NOTIFAI_SESSION_ID)')
459
+ .option(
460
+ '--session-label <text>',
461
+ 'first human session name, frozen locally (env: NOTIFAI_SESSION_LABEL)',
462
+ )
463
+ .action(async (question: string | undefined, opts: {
464
+ choice?: string[]
465
+ multi?: boolean
466
+ json?: boolean
467
+ body?: string
468
+ bodyFile?: string
469
+ form?: string
470
+ image?: string[]
471
+ imageAlt?: string[]
472
+ project?: string
473
+ sessionId?: string
474
+ sessionLabel?: string
475
+ }) => {
476
+ let body = opts.body
477
+ if (typeof opts.bodyFile === 'string') {
478
+ if (body !== undefined) {
479
+ deps.io.err('Pass either --body or --body-file, not both.')
480
+ return exit(2)
481
+ }
482
+ try {
483
+ body = readFileSync(opts.bodyFile === '-' ? 0 : opts.bodyFile, 'utf8')
484
+ } catch (err) {
485
+ deps.io.err(`Could not read ${opts.bodyFile}: ${String(err)}`)
486
+ return exit(2)
487
+ }
488
+ }
489
+ let form: string | undefined
490
+ if (typeof opts.form === 'string') {
491
+ try {
492
+ form = readFileSync(opts.form === '-' ? 0 : opts.form, 'utf8')
493
+ } catch (err) {
494
+ deps.io.err(`Could not read ${opts.form}: ${String(err)}`)
495
+ return exit(2)
496
+ }
497
+ }
498
+ // Commander collectors default to []; an empty list means "not passed".
499
+ const flags: Parameters<typeof askCommand>[2] = {
500
+ ...(opts.choice?.length ? { choice: opts.choice } : {}),
501
+ ...(opts.multi ? { multi: true } : {}),
502
+ ...(body !== undefined ? { body } : {}),
503
+ ...(form !== undefined ? { form } : {}),
504
+ ...(opts.image?.length ? { image: opts.image } : {}),
505
+ ...(opts.imageAlt?.length ? { imageAlt: opts.imageAlt } : {}),
506
+ ...(opts.project !== undefined ? { project: opts.project } : {}),
507
+ ...(opts.sessionId !== undefined ? { sessionId: opts.sessionId } : {}),
508
+ ...(opts.sessionLabel !== undefined ? { sessionLabel: opts.sessionLabel } : {}),
509
+ ...(opts.json === true ? { json: true } : {}),
510
+ }
511
+ exit(await runners.ask(deps, question, flags))
512
+ })
513
+
514
+ program
515
+ .command('close <request_id>')
516
+ .helpGroup(GROUP.agent)
517
+ .summary('Retire a question so late answers are rejected')
518
+ .description('Retire a question so late answers are rejected rather than lost')
519
+ .option('--json', 'machine-readable output')
520
+ .action(async (requestId: string, opts: { json?: boolean }) => {
521
+ exit(await runners.close(deps, requestId, opts))
522
+ })
523
+
524
+ // Hidden, not removed. It is an entry point the hook installer writes into a
525
+ // harness config file, never something a person types — and listing it beside
526
+ // `send` invited exactly one reading, which is that you were supposed to.
527
+ program
528
+ .command('hook <event>', { hidden: true })
529
+ .description('Internal: run a harness hook (reads hook JSON on stdin)')
530
+ // Inert, and the point of it is that it is inert: the installed command line
531
+ // carries a marker that says "Notifai wrote this" independently of which
532
+ // checkout wrote it.
533
+ .option('--owner <name>', 'internal ownership marker')
534
+ .option('--harness <name>', 'internal harness output adapter')
535
+ .action(async (event: string, opts: { harness?: string }) => {
536
+ const harness = HARNESSES.find((candidate) => candidate === opts.harness)
537
+ exit(await runners.hookRun(deps, event, () => readStdinWithTimeout(), harness))
538
+ })
539
+
540
+ const hooks = program
541
+ .command('hooks')
542
+ .description('Install harness hooks for registered-question routing')
543
+ .summary('Wire a harness to route questions to your devices')
544
+ .helpGroup(GROUP.advanced)
545
+ hooks
546
+ .command('install')
547
+ .description('Wire this harness to route registered questions to your devices')
548
+ .option(
549
+ '--harness <name>',
550
+ 'claude-code | codex | cursor | opencode (default: every detected harness)',
551
+ )
552
+ .option('--global', 'install for every project instead of just this one')
553
+ .action((opts: { harness?: string; global?: boolean }) => {
554
+ exit(runners.hooksInstall(deps, opts))
555
+ })
556
+ hooks
557
+ .command('uninstall')
558
+ .description('Remove the hooks this CLI installed')
559
+ .option('--harness <name>', 'claude-code | codex | cursor | opencode (default: detected)')
560
+ .option('--global', 'remove the machine-wide install')
561
+ .action((opts: { harness?: string; global?: boolean }) => {
562
+ exit(runners.hooksUninstall(deps, opts))
563
+ })
564
+
565
+ program
566
+ .command('logs')
567
+ .helpGroup(GROUP.daily)
568
+ .summary('Show what this machine recorded about what it did')
569
+ .description(
570
+ 'Read the local record of commands, notifications, and the question decisions harness hooks made. ' +
571
+ 'Bounded and scoped to this project by default; never leaves this machine',
572
+ )
573
+ .option('-n, --limit <count>', 'how many records to show (default: 30)', (v: string) => Number(v))
574
+ .option('--all', 'lift the default limit, up to a hard cap')
575
+ .option('--since <when>', 'only records newer than this: 10m, 2h, 1d, or an ISO 8601 instant')
576
+ .option('--level <level>', 'minimum severity: error | info | debug (error shows only failures)')
577
+ .option('--event <name>', 'only this event; repeatable', (v: string, all: string[] = []) => [...all, v])
578
+ .option('--run <id>', 'everything one command invocation did')
579
+ .option('--request <id>', 'everything about one notification request')
580
+ .option('--session <id>', 'only this harness session')
581
+ .option('--project <id>', 'only this project')
582
+ .option('--all-projects', 'do not scope to the project in this directory')
583
+ .option('--grep <text>', 'only records containing this text')
584
+ .option('--json', 'one JSON record per line on stdout')
585
+ .option('--path', 'print the log file paths instead of the records')
586
+ .option('--clear', 'delete the log files')
587
+ .action((opts: Record<string, unknown>) => {
588
+ const flags = { ...opts } as Parameters<typeof logsCommand>[1]
589
+ if (Array.isArray(flags.event) && flags.event.length === 0) delete flags.event
590
+ exit(runners.logs(deps, flags))
591
+ })
592
+
593
+ const config = program
594
+ .command('config')
595
+ .description('Show or change settings')
596
+ .summary('Show or change settings')
597
+ .helpGroup(GROUP.daily)
598
+ config
599
+ .command('show')
600
+ .description('Show every setting, what it does, and where its value came from')
601
+ .option('--explain', 'include advanced settings and the file each value came from')
602
+ .option('--plain', 'the flat key = value form, even at a terminal')
603
+ .option('--json', 'machine-readable output')
604
+ .action((opts: { json?: boolean; explain?: boolean; plain?: boolean }) => {
605
+ exit(runners.configShow(deps, opts))
606
+ })
607
+ config
608
+ .command('explain <key>')
609
+ .description('Explain one setting in full: what it does, what it accepts, what it is now')
610
+ .option('--json', 'machine-readable output')
611
+ .action((key: string, opts: { json?: boolean }) => {
612
+ exit(runners.configExplain(deps, key, opts))
613
+ })
614
+ config
615
+ .command('set <key> <value>')
616
+ .description(
617
+ 'Set a configuration value (choose a layer interactively; unattended defaults machine-global and requires --yes)',
618
+ )
619
+ .option('--project', 'write to the shared .notifai/config.toml instead')
620
+ .option('--local', 'write a personal project preference on this machine (not in the repo)')
621
+ .option('--session <id>', 'apply only to one session')
622
+ .option('--yes', 'skip the confirmation gate')
623
+ .action(
624
+ async (
625
+ key: string,
626
+ value: string,
627
+ opts: { project?: boolean; local?: boolean; session?: string; yes?: boolean },
628
+ ) => {
629
+ exit(await runners.configSet(deps, key, value, opts))
630
+ },
631
+ )
632
+ config
633
+ .command('unset <key>')
634
+ .description(
635
+ 'Remove a configuration value so the next layer or shipped default applies (choose a layer interactively; unattended defaults machine-global and requires --yes)',
636
+ )
637
+ .option('--project', 'remove from the shared .notifai/config.toml instead')
638
+ .option('--local', 'remove a personal project preference stored on this machine')
639
+ .option('--session <id>', 'remove from one session')
640
+ .option('--yes', 'skip the confirmation gate')
641
+ .action(
642
+ async (
643
+ key: string,
644
+ opts: { project?: boolean; local?: boolean; session?: string; yes?: boolean },
645
+ ) => {
646
+ exit(await runners.configUnset(deps, key, opts))
647
+ },
648
+ )
649
+
650
+ const guidance = program
651
+ .command('guidance')
652
+ .description('How notifications are written: the shipped guidance and your overrides, per topic')
653
+ .summary('Show or change how notifications are written')
654
+ .helpGroup(GROUP.daily)
655
+ guidance
656
+ .command('show', { isDefault: true })
657
+ .description('Print the effective guidance, every topic under the layer that supplied it')
658
+ .option('--json', 'machine-readable output')
659
+ .action((opts: { json?: boolean }) => {
660
+ exit(runners.guidanceShow(deps, opts))
661
+ })
662
+ guidance
663
+ .command('set <topic> [text]')
664
+ .description(
665
+ 'Write one guidance topic in your words; it replaces the shipped topic of the same name for that scope ' +
666
+ '(choose a layer interactively; unattended defaults machine-global and requires --yes)',
667
+ )
668
+ .option('--file <path>', 'read the guidance text from a file (use - for stdin)')
669
+ .option('--project', 'write to the shared .notifai/guidance/ instead')
670
+ .option('--local', 'write a personal project preference on this machine (not in the repo)')
671
+ .option('--yes', 'skip the confirmation gate')
672
+ .action(
673
+ async (
674
+ topic: string,
675
+ text: string | undefined,
676
+ opts: { file?: string; project?: boolean; local?: boolean; yes?: boolean },
677
+ ) => {
678
+ let content = text
679
+ if (typeof opts.file === 'string') {
680
+ if (content !== undefined) {
681
+ deps.io.err('Pass either the text or --file, not both.')
682
+ exit(2)
683
+ return
684
+ }
685
+ try {
686
+ content = readFileSync(opts.file === '-' ? 0 : opts.file, 'utf8')
687
+ } catch (err) {
688
+ deps.io.err(`Could not read ${opts.file}: ${String(err)}`)
689
+ exit(2)
690
+ return
691
+ }
692
+ }
693
+ if (content === undefined) {
694
+ deps.io.err('Pass the guidance text, or --file <path|-> to read it.')
695
+ exit(2)
696
+ return
697
+ }
698
+ exit(
699
+ await runners.guidanceSet(deps, topic, content, {
700
+ project: opts.project,
701
+ local: opts.local,
702
+ yes: opts.yes,
703
+ }),
704
+ )
705
+ },
706
+ )
707
+ guidance
708
+ .command('unset <topic>')
709
+ .description(
710
+ 'Remove a guidance override so the next layer or the shipped topic applies ' +
711
+ '(choose a layer interactively; unattended defaults machine-global and requires --yes)',
712
+ )
713
+ .option('--project', 'remove from the shared .notifai/guidance/ instead')
714
+ .option('--local', 'remove a personal project preference stored on this machine')
715
+ .option('--yes', 'skip the confirmation gate')
716
+ .action(
717
+ async (topic: string, opts: { project?: boolean; local?: boolean; yes?: boolean }) => {
718
+ exit(await runners.guidanceUnset(deps, topic, opts))
719
+ },
720
+ )
721
+
722
+ return program
723
+ }