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