@raidiant/notifai 10.1.1 → 10.1.2

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 (156) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/commands-core.d.ts +1 -1
  3. package/dist/commands-init.js +9 -6
  4. package/dist/commands-init.js.map +1 -1
  5. package/dist/commands-send-support.js +3 -0
  6. package/dist/commands-send-support.js.map +1 -1
  7. package/dist/commands-skill.js +72 -54
  8. package/dist/commands-skill.js.map +1 -1
  9. package/dist/invocation-context.d.ts +1 -0
  10. package/dist/invocation-context.js +9 -1
  11. package/dist/invocation-context.js.map +1 -1
  12. package/dist/native-skills.d.ts +13 -3
  13. package/dist/native-skills.js +51 -12
  14. package/dist/native-skills.js.map +1 -1
  15. package/dist/node-floor.d.ts +2 -1
  16. package/dist/node-floor.js +9 -5
  17. package/dist/node-floor.js.map +1 -1
  18. package/dist/orca-session-title.d.ts +5 -4
  19. package/dist/orca-session-title.js +32 -19
  20. package/dist/orca-session-title.js.map +1 -1
  21. package/dist/platform.d.ts +11 -17
  22. package/dist/platform.js +20 -23
  23. package/dist/platform.js.map +1 -1
  24. package/dist/release.d.ts +5 -5
  25. package/dist/release.js +5 -5
  26. package/dist/setup-destinations.js +1 -1
  27. package/dist/setup-destinations.js.map +1 -1
  28. package/dist/skill-integrity.d.ts +49 -0
  29. package/dist/skill-integrity.js +154 -0
  30. package/dist/skill-integrity.js.map +1 -0
  31. package/dist/skill-source/manifest.json +16 -0
  32. package/dist/skill-source/notifai/SKILL.md +390 -0
  33. package/dist/skill-source/notifai/references/harness-setup.md +220 -0
  34. package/package.json +11 -14
  35. package/src/atomic-file.ts +0 -198
  36. package/src/claude-wake.test.ts +0 -321
  37. package/src/claude-wake.ts +0 -499
  38. package/src/cli-bin.test.ts +0 -176
  39. package/src/cli-bin.ts +0 -233
  40. package/src/cli-release.test.ts +0 -46
  41. package/src/cli-release.ts +0 -78
  42. package/src/cli-update-contract.ts +0 -9
  43. package/src/cli-update.test.ts +0 -125
  44. package/src/client.test.ts +0 -390
  45. package/src/client.ts +0 -352
  46. package/src/codex-wake.test.ts +0 -254
  47. package/src/codex-wake.ts +0 -301
  48. package/src/command-session.ts +0 -38
  49. package/src/commands-agent-sessions.ts +0 -72
  50. package/src/commands-auth.ts +0 -238
  51. package/src/commands-config.ts +0 -336
  52. package/src/commands-core.ts +0 -312
  53. package/src/commands-devices.ts +0 -180
  54. package/src/commands-doctor.ts +0 -1501
  55. package/src/commands-guidance.ts +0 -181
  56. package/src/commands-harness-context.ts +0 -207
  57. package/src/commands-hook-shape.ts +0 -69
  58. package/src/commands-hooks.ts +0 -2318
  59. package/src/commands-init.ts +0 -1055
  60. package/src/commands-io.ts +0 -108
  61. package/src/commands-logs.ts +0 -243
  62. package/src/commands-project.ts +0 -47
  63. package/src/commands-send-support.test.ts +0 -156
  64. package/src/commands-send-support.ts +0 -311
  65. package/src/commands-send.ts +0 -875
  66. package/src/commands-setup-proof.test.ts +0 -72
  67. package/src/commands-setup-proof.ts +0 -124
  68. package/src/commands-skill.test.ts +0 -44
  69. package/src/commands-skill.ts +0 -204
  70. package/src/commands-sounds.test.ts +0 -106
  71. package/src/commands-sounds.ts +0 -49
  72. package/src/commands-update.ts +0 -180
  73. package/src/commands.test.ts +0 -8297
  74. package/src/commands.ts +0 -77
  75. package/src/config-schema.test.ts +0 -153
  76. package/src/config-schema.ts +0 -349
  77. package/src/config.test.ts +0 -581
  78. package/src/config.ts +0 -475
  79. package/src/credentials.test.ts +0 -403
  80. package/src/credentials.ts +0 -403
  81. package/src/file-lock-process-worker.test.ts +0 -64
  82. package/src/file-lock.test.ts +0 -320
  83. package/src/file-lock.ts +0 -393
  84. package/src/fixtures/hermes-0.20.6-classic-cli-local.json +0 -50
  85. package/src/fixtures/openclaw-2026.7.1-2-agent-local.json +0 -57
  86. package/src/generated-session-label.ts +0 -155
  87. package/src/guidance-content.ts +0 -278
  88. package/src/guidance-render.ts +0 -56
  89. package/src/guidance.test.ts +0 -327
  90. package/src/guidance.ts +0 -233
  91. package/src/harness-integration.test.ts +0 -294
  92. package/src/harnesses.test.ts +0 -149
  93. package/src/harnesses.ts +0 -164
  94. package/src/hook-adapter.test.ts +0 -496
  95. package/src/hook-adapter.ts +0 -424
  96. package/src/hook-input.test.ts +0 -39
  97. package/src/hook-input.ts +0 -72
  98. package/src/hooks.test.ts +0 -5824
  99. package/src/hooks.ts +0 -4011
  100. package/src/install-hooks.test.ts +0 -1614
  101. package/src/install-hooks.ts +0 -1501
  102. package/src/interactive.test.ts +0 -387
  103. package/src/interactive.ts +0 -858
  104. package/src/invocation-context.test.ts +0 -352
  105. package/src/invocation-context.ts +0 -197
  106. package/src/logging-process-worker.test.ts +0 -45
  107. package/src/logging.test.ts +0 -544
  108. package/src/logging.ts +0 -698
  109. package/src/main-run.ts +0 -45
  110. package/src/main.ts +0 -12
  111. package/src/native-skills.test.ts +0 -115
  112. package/src/native-skills.ts +0 -162
  113. package/src/node-floor.test.ts +0 -27
  114. package/src/node-floor.ts +0 -37
  115. package/src/onboarding-docs.test.ts +0 -25
  116. package/src/openclaw-plugin.ts +0 -409
  117. package/src/opencode-plugin.ts +0 -298
  118. package/src/orca-session-title.test.ts +0 -54
  119. package/src/orca-session-title.ts +0 -103
  120. package/src/pack-feedback-slice.test.ts +0 -212
  121. package/src/pack-feedback-slice.ts +0 -187
  122. package/src/platform.test.ts +0 -152
  123. package/src/platform.ts +0 -173
  124. package/src/program.test.ts +0 -317
  125. package/src/program.ts +0 -842
  126. package/src/project-enablement.test.ts +0 -55
  127. package/src/project-enablement.ts +0 -99
  128. package/src/question-caps.test.ts +0 -49
  129. package/src/question-settlement-process.ts +0 -47
  130. package/src/question-timing.ts +0 -56
  131. package/src/readiness.test.ts +0 -25
  132. package/src/readiness.ts +0 -212
  133. package/src/release.ts +0 -51
  134. package/src/send-attempts.test.ts +0 -143
  135. package/src/send-attempts.ts +0 -188
  136. package/src/send.test.ts +0 -28
  137. package/src/send.ts +0 -436
  138. package/src/session-activation.ts +0 -61
  139. package/src/session-end-log-lock-worker.test.ts +0 -35
  140. package/src/session-labels.test.ts +0 -490
  141. package/src/session-labels.ts +0 -474
  142. package/src/setup-destinations.test.ts +0 -41
  143. package/src/setup-destinations.ts +0 -50
  144. package/src/skill.test.ts +0 -426
  145. package/src/sound-ref.test.ts +0 -31
  146. package/src/sound-ref.ts +0 -34
  147. package/src/trust-policy.test.ts +0 -701
  148. package/src/ui/banner.ts +0 -95
  149. package/src/ui/config-view.test.ts +0 -90
  150. package/src/ui/config-view.ts +0 -138
  151. package/src/ui/help.test.ts +0 -16
  152. package/src/ui/help.ts +0 -128
  153. package/src/ui/theme.test.ts +0 -92
  154. package/src/ui/theme.ts +0 -265
  155. package/src/url-policy.ts +0 -399
  156. package/tsconfig.json +0 -10
@@ -1,336 +0,0 @@
1
- import {
2
- existsSync,
3
- mkdirSync,
4
- readFileSync,
5
- rmSync,
6
- writeFileSync,
7
- } from 'node:fs'
8
- import path from 'node:path'
9
- import { parse as parseToml, stringify as stringifyToml } from 'smol-toml'
10
- import { ensurePrivateDirectory } from './atomic-file.js'
11
- import { acceptedValues, configInfo } from './config-schema.js'
12
- import {
13
- BOOLEAN_CONFIG_KEYS,
14
- CONFIG_KEYS,
15
- NUMERIC_CONFIG_KEYS,
16
- ORIGIN_LIST_CONFIG_KEYS,
17
- USER_OWNED_CONFIG_KEYS,
18
- configBounds,
19
- configDefaultValue,
20
- findProjectConfigPath,
21
- globalConfigPath,
22
- personalProjectConfigPath,
23
- sessionConfigPath,
24
- type ConfigKey,
25
- } from './config.js'
26
- import { normalizeOrigin } from './url-policy.js'
27
- import { renderConfigExplain, renderConfigList, renderConfigPlain } from './ui/config-view.js'
28
- import { EXIT, loadLoggedConfig, type CommandDeps } from './commands-core.js'
29
- import { isCliSoundRef } from './sound-ref.js'
30
-
31
- // ---------------------------------------------------------------------------
32
- // config show / set / unset
33
- // ---------------------------------------------------------------------------
34
-
35
- export function configShowCommand(
36
- deps: CommandDeps,
37
- flags: { json?: boolean; explain?: boolean; plain?: boolean },
38
- ): number {
39
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
40
- if (flags.json) {
41
- const output = Object.fromEntries(
42
- CONFIG_KEYS.map((key) => [
43
- key,
44
- {
45
- value: config[key].value,
46
- source: config[key].source,
47
- summary: configInfo(key).summary,
48
- },
49
- ]),
50
- )
51
- deps.io.out(JSON.stringify(output, null, 2))
52
- return EXIT.ok
53
- }
54
- // Anything that is not a person at a terminal keeps the flat `key = value`
55
- // form it has always had. Scripts parse this, and a prettier layout for an
56
- // audience that cannot see it would only be a breaking change.
57
- if (deps.io.interactive !== true || flags.plain === true) {
58
- for (const line of renderConfigPlain(config, flags.explain === true)) deps.io.out(line)
59
- return EXIT.ok
60
- }
61
- for (const line of renderConfigList(config, { showAdvanced: flags.explain === true })) {
62
- deps.io.out(line)
63
- }
64
- return EXIT.ok
65
- }
66
-
67
- /**
68
- * One setting, explained in full.
69
- *
70
- * The gap this closes: `config show` prints a value and provenance but that is
71
- * not enough to explain the setting's consequences. Every key already had a
72
- * careful explanation — in a TypeScript comment, read by everyone except the
73
- * person who needed it.
74
- */
75
- export function configExplainCommand(
76
- deps: CommandDeps,
77
- key: string,
78
- flags: { json?: boolean } = {},
79
- ): number {
80
- if (!(CONFIG_KEYS as readonly string[]).includes(key)) {
81
- deps.io.err(`Unknown setting "${key}".`)
82
- deps.io.err(`Valid settings: ${CONFIG_KEYS.join(', ')}`)
83
- return EXIT.usage
84
- }
85
- const configKey = key as ConfigKey
86
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
87
- const info = configInfo(configKey)
88
- const entry = config[configKey]
89
-
90
- if (flags.json) {
91
- deps.io.out(
92
- JSON.stringify(
93
- {
94
- key: configKey,
95
- label: info.label,
96
- group: info.group,
97
- kind: info.kind,
98
- summary: info.summary,
99
- detail: info.detail,
100
- accepts: acceptedValues(configKey),
101
- ...(info.choices !== undefined ? { choices: info.choices } : {}),
102
- value: entry.value,
103
- source: entry.source,
104
- },
105
- null,
106
- 2,
107
- ),
108
- )
109
- return EXIT.ok
110
- }
111
-
112
- if (deps.io.interactive !== true) {
113
- deps.io.out(`${configKey} = ${JSON.stringify(entry.value)} [${entry.source}]`)
114
- deps.io.out(info.detail.replace(/\n\n/g, '\n'))
115
- deps.io.out(`accepts: ${acceptedValues(configKey)}`)
116
- return EXIT.ok
117
- }
118
- for (const line of renderConfigExplain(configKey, config)) deps.io.out(line)
119
- return EXIT.ok
120
- }
121
-
122
- /**
123
- * Closest config key by edit distance, or null when nothing is close.
124
- *
125
- * The threshold matters more than the algorithm: suggesting a key that shares
126
- * three letters with the typo sends the reader to the wrong setting with
127
- * confidence, which is worse than listing all fourteen and letting them look.
128
- */
129
- function nearestKey(input: string): string | null {
130
- let best: string | null = null
131
- let bestDistance = Number.POSITIVE_INFINITY
132
- for (const candidate of CONFIG_KEYS) {
133
- const distance = editDistance(input.toLowerCase(), candidate)
134
- if (distance < bestDistance) {
135
- bestDistance = distance
136
- best = candidate
137
- }
138
- }
139
- return best !== null && bestDistance <= Math.max(2, Math.floor(best.length / 3)) ? best : null
140
- }
141
-
142
- function editDistance(a: string, b: string): number {
143
- const previous = Array.from({ length: b.length + 1 }, (_, i) => i)
144
- for (let i = 1; i <= a.length; i += 1) {
145
- let diagonal = previous[0]!
146
- previous[0] = i
147
- for (let j = 1; j <= b.length; j += 1) {
148
- const above = previous[j]!
149
- previous[j] = Math.min(
150
- previous[j]! + 1,
151
- previous[j - 1]! + 1,
152
- diagonal + (a[i - 1] === b[j - 1] ? 0 : 1),
153
- )
154
- diagonal = above
155
- }
156
- }
157
- return previous[b.length]!
158
- }
159
-
160
- export async function configSetCommand(
161
- deps: CommandDeps,
162
- key: string,
163
- rawValue: string,
164
- flags: { project?: boolean; local?: boolean; session?: string; yes?: boolean },
165
- ): Promise<number> {
166
- const configKey = configMutationKey(deps, key)
167
- if (configKey === null) return EXIT.usage
168
- const info = configInfo(configKey)
169
- let value: unknown = rawValue
170
- if (NUMERIC_CONFIG_KEYS.includes(configKey)) {
171
- const numeric = Number(rawValue)
172
- if (!Number.isInteger(numeric)) {
173
- deps.io.err(`${key} takes ${acceptedValues(configKey)}, not "${rawValue}".`)
174
- return EXIT.usage
175
- }
176
- const bounds = configBounds(configKey)
177
- if (bounds !== undefined && (numeric < bounds.min || numeric > bounds.max)) {
178
- deps.io.err(`${key} must be between ${bounds.min} and ${bounds.max}.`)
179
- return EXIT.usage
180
- }
181
- value = numeric
182
- }
183
- if (BOOLEAN_CONFIG_KEYS.includes(configKey)) {
184
- if (rawValue !== 'true' && rawValue !== 'false') {
185
- deps.io.err(`${key} is a toggle — pass "true" or "false", not "${rawValue}".`)
186
- return EXIT.usage
187
- }
188
- value = rawValue === 'true'
189
- }
190
- // Sound is listed as an enum of shipped names so the interactive picker has
191
- // choices, but it also accepts an Account custom name or id. Other enum keys
192
- // stay closed: an unrecognised value used to be written and only fail at send.
193
- if (configKey === 'sound') {
194
- if (!isCliSoundRef(rawValue)) {
195
- deps.io.err(`${key} takes ${acceptedValues(configKey)} — not "${rawValue}".`)
196
- return EXIT.usage
197
- }
198
- } else if (info.kind === 'enum' && info.choices !== undefined && !info.choices.includes(rawValue)) {
199
- deps.io.err(`${key} takes one of: ${info.choices.join(', ')} — not "${rawValue}".`)
200
- return EXIT.usage
201
- }
202
- if (info.kind === 'list') value = rawValue.split(',').map((s) => s.trim()).filter(Boolean)
203
- if (ORIGIN_LIST_CONFIG_KEYS.includes(configKey)) {
204
- const origins = (value as string[]).map((entry) => normalizeOrigin(entry))
205
- const rejected = (value as string[]).filter((_, index) => origins[index] === null)
206
- if (rejected.length > 0) {
207
- deps.io.err(
208
- `${key} entries must be bare http(s) origins like "https://host" or "http://host:8080" — not ${rejected.map((entry) => `"${entry}"`).join(', ')}.`,
209
- )
210
- return EXIT.usage
211
- }
212
- value = origins
213
- }
214
-
215
- const target = await configMutationTarget(deps, flags)
216
- if (target === null) return EXIT.usage
217
- if (target.layer === 'project' && USER_OWNED_CONFIG_KEYS.includes(configKey)) {
218
- deps.io.err(
219
- `${key} widens which origins this machine trusts, so it is never read from the repository's shared config — a cloned repository must not be able to set it.`,
220
- )
221
- deps.io.err('Store it on this machine (no flag) or for this project personally (--local).')
222
- return EXIT.usage
223
- }
224
- if (target.layer === 'global' && Object.is(value, configDefaultValue(configKey))) {
225
- deps.io.err(`${key} is already the shipped default (${JSON.stringify(value)}).`)
226
- deps.io.err(
227
- `Run \`notifai config unset ${key} --yes\` to remove a redundant override instead of creating one.`,
228
- )
229
- return EXIT.usage
230
- }
231
-
232
- if (!flags.yes) {
233
- const confirmed = await deps.io.confirm(`Set ${key} = ${JSON.stringify(value)} in ${target.path}?`)
234
- if (!confirmed) {
235
- deps.io.err('Not confirmed. Pass --yes to skip the confirmation gate.')
236
- return EXIT.usage
237
- }
238
- }
239
-
240
- const existing = existsSync(target.path)
241
- ? (parseToml(readFileSync(target.path, 'utf8')) as Record<string, unknown>)
242
- : {}
243
- existing[key] = value
244
- if (target.layer === 'project') mkdirSync(path.dirname(target.path), { recursive: true })
245
- else ensurePrivateDirectory(path.dirname(target.path))
246
- writeFileSync(target.path, `${stringifyToml(existing)}\n`)
247
- deps.io.out(`Wrote ${key} to ${target.path}`)
248
- return EXIT.ok
249
- }
250
-
251
- function configMutationKey(deps: CommandDeps, key: string): ConfigKey | null {
252
- if (!(CONFIG_KEYS as readonly string[]).includes(key)) {
253
- deps.io.err(`Unknown setting "${key}".`)
254
- const near = nearestKey(key)
255
- if (near !== null) deps.io.err(`Did you mean "${near}"?`)
256
- deps.io.err(`Valid settings: ${CONFIG_KEYS.join(', ')}`)
257
- deps.io.err('Run `notifai config explain <key>` to see what one of them does.')
258
- return null
259
- }
260
- return key as ConfigKey
261
- }
262
-
263
- type ConfigMutationFlags = { project?: boolean; local?: boolean; session?: string; yes?: boolean }
264
- type ConfigMutationLayer = 'global' | 'project' | 'local' | 'session'
265
-
266
- async function configMutationTarget(
267
- deps: CommandDeps,
268
- flags: ConfigMutationFlags,
269
- ): Promise<{ path: string; layer: ConfigMutationLayer } | null> {
270
- let layer = flags.local ? 'local' : flags.project ? 'project' : 'global'
271
- if (
272
- flags.session === undefined &&
273
- flags.local !== true &&
274
- flags.project !== true &&
275
- flags.yes !== true &&
276
- deps.io.interactive === true &&
277
- deps.io.select
278
- ) {
279
- const selected = await deps.io.select('Where should this setting live?', [
280
- { value: 'global', label: 'This machine', hint: 'applies across projects' },
281
- { value: 'project', label: 'This project (shared)', hint: '.notifai/config.toml' },
282
- { value: 'local', label: 'This project (personal)', hint: 'stored on this machine, not in the repo' },
283
- ])
284
- if (selected === null) {
285
- deps.io.err('No configuration layer selected.')
286
- return null
287
- }
288
- layer = selected
289
- }
290
-
291
- const targetPath = flags.session
292
- ? sessionConfigPath(flags.session, deps.env)
293
- : layer === 'local'
294
- ? personalProjectConfigPath(deps.cwd, deps.env)
295
- : layer === 'project'
296
- ? (findProjectConfigPath(deps.cwd) ?? path.join(deps.cwd, '.notifai', 'config.toml'))
297
- : globalConfigPath(deps.env)
298
- return {
299
- path: targetPath,
300
- layer: flags.session ? 'session' : (layer as Exclude<ConfigMutationLayer, 'session'>),
301
- }
302
- }
303
-
304
- export async function configUnsetCommand(
305
- deps: CommandDeps,
306
- key: string,
307
- flags: ConfigMutationFlags,
308
- ): Promise<number> {
309
- const configKey = configMutationKey(deps, key)
310
- if (configKey === null) return EXIT.usage
311
- const target = await configMutationTarget(deps, flags)
312
- if (target === null) return EXIT.usage
313
- const existing = existsSync(target.path)
314
- ? (parseToml(readFileSync(target.path, 'utf8')) as Record<string, unknown>)
315
- : {}
316
- if (!Object.prototype.hasOwnProperty.call(existing, configKey)) {
317
- deps.io.out(`${configKey} is not set in ${target.path}`)
318
- return EXIT.ok
319
- }
320
- if (!flags.yes) {
321
- const confirmed = await deps.io.confirm(`Remove ${configKey} from ${target.path}?`)
322
- if (!confirmed) {
323
- deps.io.err('Not confirmed. Pass --yes to skip the confirmation gate.')
324
- return EXIT.usage
325
- }
326
- }
327
-
328
- delete existing[configKey]
329
- if (Object.keys(existing).length === 0) {
330
- rmSync(target.path, { force: true })
331
- } else {
332
- writeFileSync(target.path, `${stringifyToml(existing)}\n`)
333
- }
334
- deps.io.out(`Removed ${configKey} from ${target.path}; the inherited value now applies.`)
335
- return EXIT.ok
336
- }
@@ -1,312 +0,0 @@
1
- import { SHIPPED_CLI_CAPABILITIES, type RecoveryAction } from '@raidiant/notifai-protocol'
2
- import { type ClaudeWakeAdapters } from './claude-wake.js'
3
- import {
4
- ApiCallError,
5
- NetworkError,
6
- createClient,
7
- type ApiClient,
8
- type ClientOptions,
9
- } from './client.js'
10
- import { type CodexWakeAdapters } from './codex-wake.js'
11
- import { loadConfig, type CliConfig } from './config.js'
12
- import type { CredentialStore, MachineCredential } from './credentials.js'
13
- import { type HookAdapterTarget } from './hook-adapter.js'
14
- import { logConfigResolved, logSettingsFrom, nullLogger, type Logger } from './logging.js'
15
- import type { NativeSkills } from './native-skills.js'
16
- import type { OrcaSessionTitleLookup } from './orca-session-title.js'
17
- import type { QuestionSettlementLaunch } from './question-settlement-process.js'
18
- import { packageVersion } from './release.js'
19
- import type { Tone } from './ui/theme.js'
20
- import { cliUpdateRecoveryCommand } from './cli-update-contract.js'
21
-
22
- export interface CommandIo {
23
- out(line: string): void
24
- err(line: string): void
25
- /** Interactive confirmation; resolves `fallback` (default false) when not interactive. */
26
- confirm(question: string, fallback?: boolean): Promise<boolean>
27
- openUrl(url: string): void
28
- /**
29
- * True only when a human is demonstrably driving a terminal. Everything below
30
- * is optional sugar that MUST only be called behind this flag: an agent that
31
- * reaches an interactive prompt does not error, it hangs — the prompt
32
- * libraries wait on stdin for ever — so the gate is bypass, not handling.
33
- * Test fakes leave all of this undefined and exercise the plain paths.
34
- */
35
- interactive?: boolean
36
- select?(message: string, options: { value: string; label: string; hint?: string }[]): Promise<string | null>
37
- /** Interactive multi-select. `initial` are pre-selected values. */
38
- multiselect?(
39
- message: string,
40
- options: { value: string; label: string; hint?: string }[],
41
- initial?: string[],
42
- ): Promise<string[] | null>
43
- intro?(title: string): Promise<void>
44
- outro?(message: string): Promise<void>
45
- note?(message: string, title?: string): Promise<void>
46
- spinner?(message: string): Promise<CommandSpinner | null>
47
- /**
48
- * A report line. `tone` distinguishes the two states that are neither pass
49
- * nor fail — something optional the user declined, and something that was
50
- * never evaluated — which a boolean has to round to one or the other.
51
- * Optional so existing implementations keep type-checking.
52
- */
53
- check?(ok: boolean, message: string, tone?: Tone): Promise<void>
54
- }
55
-
56
- export interface CommandSpinner {
57
- message(message: string): void
58
- stop(message: string): void
59
- error(message: string): void
60
- }
61
-
62
- export interface CommandDeps {
63
- io: CommandIo
64
- store: CredentialStore
65
- env: NodeJS.ProcessEnv
66
- cwd: string
67
- /** Test seam; production fixes the hook adapter under os.homedir(). */
68
- hookAdapterHome?: string
69
- /** Test seam; production uses this process's Node and CLI paths. */
70
- hookInstallTarget?: HookAdapterTarget
71
- /** Test seam; production uses process.platform for adapter format and quoting. */
72
- hookPlatform?: NodeJS.Platform
73
- /** Test seam; production uses fetch against base_url. */
74
- clientFactory?: (baseUrl: string, bearer: string | null, options?: ClientOptions) => ApiClient
75
- /** Test seam for bounded polling without wall-clock sleeps. */
76
- now?: () => number
77
- /** Test seam for retry/backoff timing. */
78
- sleep?: (milliseconds: number) => Promise<void>
79
- /** Test seams for Claude liveness, socket delivery, and cold resume. */
80
- claudeWake?: ClaudeWakeAdapters
81
- claudeSourcePid?: number
82
- /** Test seams for the Codex thread-writer probe and cold resume. */
83
- codexWake?: CodexWakeAdapters
84
- codexSourcePid?: number
85
- /** Test seam for the detached owner recovered from a pre-Stop User prompt. */
86
- spawnQuestionSettlement?: (launch: QuestionSettlementLaunch) => void
87
- /** Test seam and production adapter for the external native skills installer. */
88
- nativeSkills?: NativeSkills
89
- /** Test seam for Orca's exact-worktree task/session title lookup. */
90
- orcaSessionTitle?: OrcaSessionTitleLookup
91
- /** Test seam for registry reads; production uses fetch. */
92
- fetchImpl?: typeof fetch
93
- /**
94
- * The local record of what this invocation did. Optional so a test fake need
95
- * not carry one; `log(deps)` supplies a logger that records nothing.
96
- */
97
- logger?: Logger
98
- }
99
-
100
- /** The invocation's logger, or one that discards everything. */
101
- export function log(deps: CommandDeps): Logger {
102
- return deps.logger ?? nullLogger()
103
- }
104
-
105
- export function loadLoggedConfig(
106
- deps: CommandDeps,
107
- options: Parameters<typeof loadConfig>[0],
108
- ): CliConfig {
109
- const config = loadConfig(options)
110
- const logger = log(deps)
111
- logger.adopt(logSettingsFrom(config))
112
- logger.bind({ project: config.project.value })
113
- logConfigResolved(logger, config)
114
- return config
115
- }
116
-
117
- export const EXIT = {
118
- ok: 0,
119
- failed: 1,
120
- usage: 2,
121
- noReply: 3,
122
- auth: 4,
123
- network: 5,
124
- } as const
125
-
126
- export function makeClient(
127
- deps: CommandDeps,
128
- baseUrl: string,
129
- bearer: string | null,
130
- options?: ClientOptions,
131
- ): ApiClient {
132
- return (deps.clientFactory ?? createClient)(baseUrl, bearer, {
133
- ...options,
134
- logger: log(deps),
135
- cliVersion: packageVersion(),
136
- capabilities: SHIPPED_CLI_CAPABILITIES,
137
- })
138
- }
139
-
140
- export function resolvedBaseUrl(config: CliConfig, credential: MachineCredential | null): string {
141
- return credential ? credential.baseUrl : config.base_url.value
142
- }
143
-
144
- /**
145
- * Whether a flag or env origin would send signed-in traffic somewhere other
146
- * than the origin stored with this machine's credential.
147
- *
148
- * Login still honours those overrides: pairing has no credential to pin to.
149
- * Returning the source (not the override URL, and never the bearer) is what
150
- * lets callers diagnose the ignore without leaking either.
151
- */
152
- export function ignoredOriginOverride(
153
- config: CliConfig,
154
- credential: MachineCredential,
155
- ): CliConfig['base_url']['source'] | null {
156
- if (config.base_url.source === 'default') return null
157
- if (config.base_url.value === credential.baseUrl) return null
158
- return config.base_url.source
159
- }
160
-
161
- export function diagnoseIgnoredOriginOverride(
162
- io: Pick<CommandIo, 'err'>,
163
- config: CliConfig,
164
- credential: MachineCredential,
165
- ): void {
166
- const source = ignoredOriginOverride(config, credential)
167
- if (source === null) return
168
- io.err(
169
- `Ignoring base_url from ${source}; authenticated traffic uses the origin stored with this machine's credential. Run \`notifai login\` to pair with a different origin.`,
170
- )
171
- }
172
-
173
- export function authedClient(deps: CommandDeps, config: CliConfig): { client: ApiClient; baseUrl: string } | null {
174
- const credential = deps.store.load()
175
- if (!credential) {
176
- // The commonest reason a command does nothing, and one that leaves no other
177
- // trace: it returns before any request is made, so without this the log
178
- // shows an exit code and no cause.
179
- log(deps).error('cli.error', { kind: 'auth', message: 'not signed in', store: deps.store.describe() })
180
- deps.io.err('Not signed in. Run `notifai init`; it will coordinate machine login and device setup.')
181
- return null
182
- }
183
- diagnoseIgnoredOriginOverride(deps.io, config, credential)
184
- const baseUrl = resolvedBaseUrl(config, credential)
185
- return {
186
- client: makeClient(deps, baseUrl, `Bearer nfm_${credential.machineId}.${credential.secret}`),
187
- baseUrl,
188
- }
189
- }
190
-
191
- /**
192
- * Resolve a current CLI independently of PATH. A bare `notifai update` would
193
- * be captured by the stale winner this action is meant to repair.
194
- */
195
- export function updateCliCommand(_deps: Pick<CommandDeps, 'hookInstallTarget' | 'hookPlatform'>): string {
196
- return cliUpdateRecoveryCommand()
197
- }
198
-
199
- /** The one first-run command an unsigned machine is told to run. */
200
- export const SETUP_COMMAND = 'notifai init'
201
-
202
- function affectedDeviceNames(details: unknown): string[] {
203
- if (typeof details !== 'object' || details === null || !('device_names' in details)) return []
204
- const names = (details as { device_names?: unknown }).device_names
205
- if (!Array.isArray(names)) return []
206
- return [...new Set(names.filter((name): name is string => typeof name === 'string' && name.trim() !== ''))]
207
- }
208
-
209
- function naturalList(values: readonly string[]): string {
210
- if (values.length <= 1) return values[0] ?? ''
211
- if (values.length === 2) return `${values[0]} and ${values[1]}`
212
- return `${values.slice(0, -1).join(', ')}, and ${values.at(-1)}`
213
- }
214
-
215
- function localRecovery(
216
- deps: Pick<CommandDeps, 'hookInstallTarget' | 'hookPlatform'>,
217
- action: RecoveryAction | null,
218
- details: unknown,
219
- ): string | null {
220
- switch (action) {
221
- case 'update_cli':
222
- return `next: ${updateCliCommand(deps)}`
223
- case 'update_companion': {
224
- const names = affectedDeviceNames(details)
225
- return names.length > 0
226
- ? `next: Update Notifai on ${naturalList(names)}.`
227
- : 'next: Update Notifai on the affected devices.'
228
- }
229
- case 'wait_for_service':
230
- return 'next: The service is being updated; try again later.'
231
- default:
232
- return null
233
- }
234
- }
235
-
236
- export function reportError(
237
- deps: CommandDeps,
238
- err: unknown,
239
- context: Record<string, unknown> = {},
240
- ): number {
241
- // Recorded before it is printed: stderr from an agent's shell call is often
242
- // the one thing that does not survive into the next turn, and this is exactly
243
- // the line someone comes back looking for.
244
- log(deps).error('cli.error', {
245
- ...context,
246
- ...(err instanceof ApiCallError
247
- ? {
248
- kind: 'api',
249
- status: err.status,
250
- code: err.code,
251
- message: err.message,
252
- next_action: err.nextAction,
253
- recovery_action: err.recoveryAction,
254
- details: err.details,
255
- }
256
- : err instanceof NetworkError
257
- ? { kind: 'network', message: err.message }
258
- : { kind: 'unknown', message: String(err) }),
259
- })
260
- if (err instanceof ApiCallError) {
261
- deps.io.err(
262
- deps.io.interactive === true && err.recoveryAction !== null
263
- ? err.message
264
- : `${err.code}: ${err.message}`,
265
- )
266
- // The server's field-level details were already being logged above, but
267
- // stderr is the one surface an agent's next turn actually reads — so the
268
- // diagnosis has to be on it, the same way the hook path prints it.
269
- const paths = rejectedPaths(err.details)
270
- if (paths.length > 0) deps.io.err(`the server rejected: ${paths.join(', ')}`)
271
- // A 422 on a request this CLI built is not a user error: the two sides
272
- // disagree about the contract, in whichever direction. `doctor` says which.
273
- // Codes that name a policy the account chose are the exception — the
274
- // contract held, the body simply did not satisfy that account.
275
- if (
276
- err.status === 422 &&
277
- err.code !== 'acknowledgement_text_required' &&
278
- err.code !== 'feature_unavailable'
279
- ) {
280
- deps.io.err(
281
- 'this build sent a field the server did not accept — the CLI and server ' +
282
- 'disagree about the contract; check with `notifai doctor`',
283
- )
284
- }
285
- const recovery =
286
- err.code === 'no_active_devices'
287
- ? 'next: Run `notifai init` to connect an active Companion App; it will complete machine setup and identify any human-only device step.'
288
- : localRecovery(deps, err.recoveryAction, err.details)
289
- if (recovery !== null) deps.io.err(recovery)
290
- else if (err.recoveryAction === null && err.nextAction) deps.io.err(`next: ${err.nextAction}`)
291
- if (err.code === 'auth_required' || err.code === 'machine_revoked') return EXIT.auth
292
- return err.status >= 500 ? EXIT.network : EXIT.failed
293
- }
294
- if (err instanceof NetworkError) {
295
- deps.io.err(err.message)
296
- return EXIT.network
297
- }
298
- deps.io.err(String(err))
299
- return EXIT.failed
300
- }
301
-
302
- export function rejectedPaths(details: unknown): string[] {
303
- if (!Array.isArray(details)) return []
304
- return details
305
- .map((issue) =>
306
- typeof issue === 'object' && issue !== null && typeof (issue as { path?: unknown }).path === 'string'
307
- ? (issue as { path: string }).path
308
- : null,
309
- )
310
- .filter((path): path is string => path !== null && path !== '')
311
- .slice(0, 5)
312
- }