@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,2318 +0,0 @@
1
- import {
2
- AGENT_ACKNOWLEDGEMENT_MAX_LENGTH,
3
- CAPABILITIES_V1,
4
- QUESTION_TEXT_MAX_LENGTH,
5
- REPLY_MAX_QUESTIONS,
6
- validateDraft,
7
- type NotificationDraftT,
8
- type QuestionT,
9
- } from '@raidiant/notifai-protocol'
10
- import {
11
- existsSync,
12
- lstatSync,
13
- mkdirSync,
14
- readFileSync,
15
- readdirSync,
16
- rmdirSync,
17
- rmSync,
18
- } from 'node:fs'
19
- import path from 'node:path'
20
- import { atomicWriteFileSync } from './atomic-file.js'
21
- import { claudeWakeRoute } from './claude-wake.js'
22
- import { ApiCallError } from './client.js'
23
- import { codexWakeRoute } from './codex-wake.js'
24
- import { loadConfig, type CliConfig } from './config.js'
25
- import { withTargetFileLock } from './file-lock.js'
26
- import {
27
- HARNESS_LABELS,
28
- HERMES_QUESTION_ROUTING_UNAVAILABLE,
29
- HOOK_INSTALLABLE_HARNESSES,
30
- isHookInstallableHarness,
31
- questionRoutingCapability,
32
- type HookInstallableHarness,
33
- } from './harnesses.js'
34
- import {
35
- inspectHookAdapter,
36
- installHookAdapter,
37
- isNpxAdapterTarget,
38
- type HookAdapterTarget,
39
- } from './hook-adapter.js'
40
- import {
41
- clearAcknowledgementObligation,
42
- claimCursorStopActivation,
43
- confirmCursorStopActivation,
44
- dropPendingQuestion,
45
- handleSessionEnd,
46
- handleStop,
47
- handleUserPromptSubmit,
48
- recordSessionStart,
49
- parkForRetirement,
50
- parseHookInput,
51
- pruneAbandonedSessions,
52
- readSessionState,
53
- resetCursorStopActivation,
54
- registerQuestion,
55
- withdrawUnpushedQuestions,
56
- type EscalationDeliveryRoute,
57
- type HookContext,
58
- type HookOutcome,
59
- type HookHarness,
60
- type PendingQuestion,
61
- } from './hooks.js'
62
- import {
63
- NON_ROUTING_BLOCKING_STOP_TIMEOUT_SECONDS,
64
- applyPlan,
65
- buildCursorHookConfig,
66
- buildHookConfig,
67
- cleanupEmptiedCodexLayer,
68
- codexCoexistenceNotes,
69
- codexHomeNote,
70
- codexLayerDir,
71
- codexLayerPaths,
72
- codexRepresentationProblems,
73
- codexTrustProblems,
74
- detectHarness,
75
- detectedHarnesses,
76
- findInstallations,
77
- handlerEvent,
78
- hookDefinitionFiles,
79
- loadCursorSettings,
80
- loadSettings,
81
- mergeCursorHooks,
82
- mergeHooks,
83
- removeCursorHooks,
84
- removeHooks,
85
- settingsFile,
86
- withCodexLayerTransaction,
87
- type Installation,
88
- } from './install-hooks.js'
89
- import { QUESTION_WAITER_CEILING_SECONDS } from './question-timing.js'
90
- import { inferInvocationContext } from './invocation-context.js'
91
- import { logConfigResolved, logSettingsFrom } from './logging.js'
92
- import { isOurOpencodePlugin, opencodePluginSource } from './opencode-plugin.js'
93
- import {
94
- OPENCLAW_PLUGIN_MANIFEST,
95
- OPENCLAW_PLUGIN_PACKAGE,
96
- isOurOpenclawPlugin,
97
- mergeOpenclawNotifaiEntry,
98
- openclawConfigPath,
99
- openclawPluginManifest,
100
- openclawPluginPackage,
101
- openclawPluginSource,
102
- parseOpenclawConfig,
103
- removeOpenclawNotifaiEntry,
104
- } from './openclaw-plugin.js'
105
- import { packageVersion } from './release.js'
106
- import { spawnQuestionSettlement } from './question-settlement-process.js'
107
- import { enableProject, projectBinding, projectEnabled } from './project-enablement.js'
108
- import { rejectAccidentalEscapedNewlines } from './send.js'
109
- import {
110
- cursorStopActivationOutput,
111
- sessionActivationOutput,
112
- } from './session-activation.js'
113
- import {
114
- CHOICE_USAGE,
115
- buildDraft,
116
- parseChoices,
117
- slugify,
118
- validateMediaInputs,
119
- type DraftInvocation,
120
- } from './send.js'
121
- import {
122
- EXIT,
123
- SETUP_COMMAND,
124
- authedClient,
125
- diagnoseIgnoredOriginOverride,
126
- loadLoggedConfig,
127
- log,
128
- makeClient,
129
- rejectedPaths,
130
- reportError,
131
- type CommandDeps,
132
- } from './commands-core.js'
133
- import {
134
- claudeSessionPid,
135
- resolveActiveHarness,
136
- type ActiveHarnessSession,
137
- } from './commands-harness-context.js'
138
- import { stopShapeProblems } from './commands-hook-shape.js'
139
- import {
140
- acknowledgementCommand,
141
- printAcknowledgementStatus,
142
- resolveDraftInvocation,
143
- uploadImage,
144
- waitForReply,
145
- } from './commands-send-support.js'
146
- import { resolveCommandSession } from './command-session.js'
147
-
148
- // ---------------------------------------------------------------------------
149
- // hook / ask / close — harness integration
150
- // ---------------------------------------------------------------------------
151
-
152
- export const HOOK_EVENTS = [
153
- 'session-start',
154
- 'subagent-start',
155
- 'activation-stop',
156
- 'user-prompt-submit',
157
- 'stop',
158
- 'session-end',
159
- ] as const
160
- export type HookEvent = (typeof HOOK_EVENTS)[number]
161
- const INTERNAL_HOOK_EVENTS = ['question-settlement'] as const
162
-
163
- /** Lifecycle handlers one installed harness must carry in this CLI build. */
164
- export function requiredHookEvents(harness: HookInstallableHarness): readonly HookEvent[] {
165
- if (harness === 'opencode' || harness === 'openclaw') return []
166
- return harness === 'cursor'
167
- ? ['session-start', 'activation-stop', 'user-prompt-submit', 'stop', 'session-end']
168
- : ['session-start', 'subagent-start', 'user-prompt-submit', 'stop', 'session-end']
169
- }
170
-
171
- /** SessionEnd cleanup must precede every diagnostic that can wait on a file lock. */
172
- export function hookDefersDiagnosticsUntilAfterCleanup(
173
- event: unknown,
174
- ): event is 'session-end' {
175
- return event === 'session-end'
176
- }
177
-
178
- /**
179
- * Runs one harness hook. Contract with every harness: hook JSON arrives on
180
- * stdin, harness output (if any) goes to stdout, diagnostics go to stderr, and
181
- * exit 0 with no stdout means "no decision or added context — carry on as normal".
182
- *
183
- * Every failure path in here must reach that no-decision state. A hook that
184
- * throws, or that blocks past the harness's timeout, degrades the agent for a
185
- * feature the user only asked to make it more convenient.
186
- */
187
- export async function hookRunCommand(
188
- deps: CommandDeps,
189
- event: string,
190
- readStdin: () => Promise<string>,
191
- harness?: HookHarness,
192
- ): Promise<number> {
193
- if (
194
- !(HOOK_EVENTS as readonly string[]).includes(event) &&
195
- !(INTERNAL_HOOK_EVENTS as readonly string[]).includes(event)
196
- ) {
197
- deps.io.err(`Unknown hook event "${event}". Valid: ${HOOK_EVENTS.join(', ')}`)
198
- return EXIT.usage
199
- }
200
-
201
- // One clock owns the complete Stop invocation, including stdin, config,
202
- // credentials, and client construction. Starting this inside `handleStop`
203
- // would grant slow setup a second budget and let the harness kill us before
204
- // an accepted answer is journaled or written to stdout.
205
- const now = deps.now ?? Date.now
206
- // One owner lifetime covers startup and the longest answer window. Claude
207
- // runs it detached; Codex holds the turn. The delivery mechanism does not
208
- // change how long the exact Agent Session remains reachable.
209
- const processDeadlineAt = now() + QUESTION_WAITER_CEILING_SECONDS * 1000
210
-
211
- const logger = log(deps)
212
- logger.bind({ cmd: `hook ${event}` })
213
- let started = false
214
- const start = (data: Record<string, unknown> = {}): void => {
215
- if (started) return
216
- started = true
217
- logger.info('hook.start', { hook: event, harness: harness ?? 'unknown', ...data })
218
- }
219
- const failureData = (err: unknown): Record<string, unknown> =>
220
- err instanceof ApiCallError
221
- ? { status: err.status, code: err.code, message: err.message, details: err.details }
222
- : { message: err instanceof Error ? err.message : String(err) }
223
-
224
- // Cursor may load ~/.claude/settings.json in addition to its own native
225
- // hooks. Cursor guarantees CURSOR_PROJECT_DIR to hook processes, so a Claude
226
- // compatibility copy becomes a no-op and the native Cursor definition is
227
- // the single owner. Real Claude hooks do not receive that hook-only marker.
228
- if (harness === 'claude-code' && deps.env['CURSOR_PROJECT_DIR']) {
229
- start({ outcome: 'cursor-compatibility-copy-skipped' })
230
- logger.info('hook.end', {
231
- hook: event,
232
- outcome: 'ignored',
233
- reason: 'cursor-native-handler-owns-event',
234
- decided: false,
235
- })
236
- return EXIT.ok
237
- }
238
-
239
- let raw: string
240
- try {
241
- raw = await readStdin()
242
- } catch (err) {
243
- start({ input: 'unavailable' })
244
- logger.error('hook.end', {
245
- hook: event,
246
- outcome: 'ignored',
247
- reason: 'input-read-failed',
248
- ...failureData(err),
249
- })
250
- return EXIT.ok
251
- }
252
-
253
- if (raw.trim() !== '') {
254
- try {
255
- const parsed: unknown = JSON.parse(raw)
256
- if (typeof parsed !== 'object' || parsed === null) throw new Error('not an object')
257
- } catch {
258
- start({ input: 'malformed' })
259
- logger.error('hook.end', { hook: event, outcome: 'ignored', reason: 'malformed-input' })
260
- deps.io.err('notifai: ignored malformed or truncated hook input; no routing action was taken')
261
- return EXIT.ok
262
- }
263
- }
264
-
265
- let envelope = parseHookInput(raw)
266
- if (harness === 'cursor') {
267
- const sessionId = envelope.session_id ?? envelope.conversation_id
268
- const cwd = envelope.cwd ?? envelope.workspace_roots?.[0]
269
- envelope = {
270
- ...envelope,
271
- ...(sessionId === undefined ? {} : { session_id: sessionId }),
272
- ...(cwd === undefined ? {} : { cwd }),
273
- stop_hook_active:
274
- envelope.stop_hook_active ??
275
- (typeof envelope.loop_count === 'number' && envelope.loop_count > 0),
276
- }
277
- }
278
-
279
- const cwd = envelope.cwd ?? deps.cwd
280
- const sessionEnd = hookDefersDiagnosticsUntilAfterCleanup(event)
281
- logger.bind({ session: envelope.session_id ?? null })
282
- const lifecycleEnabled = (): boolean => {
283
- try {
284
- const activationConfig = loadConfig({ cwd, env: deps.env, sessionId: envelope.session_id })
285
- return projectEnabled(projectBinding(cwd, deps.env, activationConfig.project.value))
286
- } catch (err) {
287
- logger.error('hook.end', { hook: event, outcome: 'enablement-unavailable', ...failureData(err) })
288
- return false
289
- }
290
- }
291
- // Installation only makes lifecycle hooks available. Model-visible
292
- // activation is a separate User-owned Project decision, checked anew on
293
- // every run so disabling takes effect without reinstalling anything.
294
- if (event === 'session-start' || event === 'subagent-start') {
295
- start({ cwd, source: envelope.source ?? null })
296
- if (!lifecycleEnabled()) {
297
- logger.info('hook.end', {
298
- hook: event,
299
- outcome: 'ignored',
300
- reason: 'project-disabled',
301
- decided: false,
302
- })
303
- return EXIT.ok
304
- }
305
- if (event === 'session-start' && harness === 'cursor' && envelope.session_id !== undefined) {
306
- try {
307
- resetCursorStopActivation(envelope.session_id, deps.env)
308
- } catch (err) {
309
- logger.error('hook.end', {
310
- hook: event,
311
- outcome: 'reset-failed',
312
- ...failureData(err),
313
- })
314
- }
315
- }
316
- const stdout = sessionActivationOutput(
317
- harness,
318
- event === 'session-start' ? 'SessionStart' : 'SubagentStart',
319
- cwd,
320
- deps.env,
321
- )
322
- if (stdout !== undefined) deps.io.out(stdout)
323
- if (event === 'session-start' && envelope.session_id !== undefined) {
324
- try {
325
- recordSessionStart(envelope.session_id, deps.env, harness, cwd)
326
- } catch (err) {
327
- logger.error('hook.end', {
328
- hook: event,
329
- outcome: 'record-failed',
330
- reason: 'session-state-failed',
331
- ...failureData(err),
332
- })
333
- }
334
- }
335
- logger.info('hook.end', {
336
- hook: event,
337
- outcome: stdout === undefined ? 'unsupported-harness' : 'context-added',
338
- decided: false,
339
- })
340
- return EXIT.ok
341
- }
342
-
343
- // Cursor has a confirmed host bug in which sessionStart.additional_context
344
- // is accepted but never reaches the model. A native Stop follow-up is the
345
- // host's guaranteed model-visible channel. Claim it once per conversation,
346
- // before config/auth/network, and leave the ordinary Stop handler separate
347
- // so question delivery is never displaced by activation.
348
- if (event === 'activation-stop') {
349
- start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null })
350
- if (harness !== 'cursor') {
351
- logger.info('hook.end', { hook: event, outcome: 'unsupported-harness', decided: false })
352
- return EXIT.ok
353
- }
354
- if (!lifecycleEnabled()) {
355
- logger.info('hook.end', {
356
- hook: event,
357
- outcome: 'ignored',
358
- reason: 'project-disabled',
359
- decided: false,
360
- })
361
- return EXIT.ok
362
- }
363
- if (envelope.status === 'aborted') {
364
- logger.info('hook.end', {
365
- hook: event,
366
- outcome: 'ignored',
367
- reason: `turn-${envelope.status}`,
368
- decided: false,
369
- })
370
- return EXIT.ok
371
- }
372
- if (envelope.session_id === undefined) {
373
- logger.info('hook.end', {
374
- hook: event,
375
- outcome: 'ignored',
376
- reason: 'missing-conversation-id',
377
- decided: false,
378
- })
379
- return EXIT.ok
380
- }
381
- if (
382
- envelope.session_id !== undefined &&
383
- typeof envelope.loop_count === 'number' &&
384
- envelope.loop_count > 0
385
- ) {
386
- let activationOwned = false
387
- try {
388
- activationOwned = confirmCursorStopActivation(envelope.session_id, deps.env, now())
389
- } catch (err) {
390
- logger.error('hook.end', {
391
- hook: event,
392
- outcome: 'confirm-failed',
393
- ...failureData(err),
394
- })
395
- }
396
- if (activationOwned) {
397
- logger.info('hook.end', { hook: event, outcome: 'confirmed', decided: false })
398
- return EXIT.ok
399
- }
400
- }
401
- const cursorState = readSessionState(envelope.session_id, deps.env)
402
- if (
403
- (cursorState.pending?.length ?? 0) > 0 ||
404
- cursorState.accepted !== undefined ||
405
- (cursorState.acknowledgement_due?.length ?? 0) > 0
406
- ) {
407
- logger.info('hook.end', {
408
- hook: event,
409
- outcome: 'deferred',
410
- reason: 'question-continuation-owns-stop',
411
- decided: false,
412
- })
413
- return EXIT.ok
414
- }
415
- let claimed = false
416
- try {
417
- claimed = claimCursorStopActivation(envelope.session_id, deps.env, now())
418
- } catch (err) {
419
- logger.error('hook.end', {
420
- hook: event,
421
- outcome: 'claim-failed',
422
- ...failureData(err),
423
- })
424
- }
425
- logger.info('hook.end', {
426
- hook: event,
427
- outcome: claimed ? 'followup-added' : 'already-activated',
428
- decided: claimed,
429
- })
430
- if (claimed) deps.io.out(cursorStopActivationOutput(cwd, deps.env))
431
- return EXIT.ok
432
- }
433
-
434
- let config: CliConfig | null = null
435
- let configFailure: unknown
436
- try {
437
- config = loadConfig({ cwd, env: deps.env, sessionId: envelope.session_id })
438
- // The hook's project is the session's, not this process's, and the log
439
- // settings that apply are that project's too. Keeping a mutable bootstrap
440
- // logger lets this more-specific layer turn logging back on.
441
- logger.adopt(logSettingsFrom(config))
442
- logger.bind({ project: config.project.value })
443
- if (!sessionEnd) {
444
- start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null })
445
- logConfigResolved(logger, config)
446
- }
447
- } catch (err) {
448
- configFailure = err
449
- if (!sessionEnd) {
450
- start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null })
451
- logger.error('hook.end', {
452
- hook: event,
453
- outcome: 'failed',
454
- reason: 'config-failed',
455
- ...failureData(err),
456
- })
457
- for (const line of describeHookFailure(err)) deps.io.err(`notifai: ${line}`)
458
- return EXIT.ok
459
- }
460
- }
461
-
462
- // Everything below is inside one fail-open boundary. Credential loading,
463
- // client construction and hook handling can all throw, and a hook that exits
464
- // non-zero makes the harness report a failure — strictly worse than skipping.
465
- try {
466
- if (sessionEnd) {
467
- // Codex gives SessionEnd one second total. Do every durable cleanup write
468
- // before lifecycle diagnostics: the log lock is deliberately allowed to
469
- // wait that long, and a busy log must never preserve ended-session state
470
- // or its inherited configuration. The resolved config above is retained
471
- // in memory so logging still uses the ending session's settings afterwards.
472
- const outcome = handleSessionEnd(deps.env, envelope, (deps.now ?? Date.now)())
473
- start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null })
474
- if (config !== null) logConfigResolved(logger, config)
475
- const data = { hook: event, decided: false, ...outcome.log }
476
- if (configFailure === undefined) logger.info('hook.end', data)
477
- else {
478
- logger.error('hook.end', {
479
- ...data,
480
- reason: 'config-failed',
481
- config_error: failureData(configFailure),
482
- })
483
- }
484
- for (const note of outcome.notes) deps.io.err(`notifai: ${note}`)
485
- return EXIT.ok
486
- }
487
-
488
- // Non-SessionEnd hooks cannot reach here without resolved configuration.
489
- const resolved = config!
490
- const credential = deps.store.load()
491
- if (!credential) {
492
- logger.error('hook.end', { hook: event, outcome: 'not-paired' })
493
- deps.io.err(`notifai: hook skipped: this machine is not paired; run \`${SETUP_COMMAND}\``)
494
- return EXIT.ok
495
- }
496
- // Pin authenticated traffic to the origin the credential was issued for. A
497
- // repository can commit `.notifai/config.toml`, and honouring a base_url
498
- // from it would hand this machine's bearer token to whatever host it names.
499
- const baseUrl = credential.baseUrl
500
- diagnoseIgnoredOriginOverride(deps.io, resolved, credential)
501
- // UserPromptSubmit runs in front of the user's own prompt under a 15s
502
- // harness ceiling and can make two calls, so each gets a small slice of it;
503
- // Stop is allowed to block and keeps the ordinary budget.
504
- const client = makeClient(
505
- deps,
506
- baseUrl,
507
- `Bearer nfm_${credential.machineId}.${credential.secret}`,
508
- {
509
- timeoutMs: event === 'user-prompt-submit' ? 4_000 : 20_000,
510
- ...(event === 'stop' || event === 'question-settlement'
511
- ? { deadlineAt: processDeadlineAt, now }
512
- : {}),
513
- },
514
- )
515
- const ctx: HookContext = {
516
- client,
517
- config: resolved,
518
- env: deps.env,
519
- now,
520
- sleep: deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
521
- waitForFirstReply: async (requestId, timeoutSeconds) => {
522
- const result = await waitForReply(client, requestId, {
523
- timeoutSeconds,
524
- afterSeq: 0,
525
- now: deps.now,
526
- sleep: deps.sleep,
527
- })
528
- return {
529
- replies: result.response.replies,
530
- timedOut: result.timedOut,
531
- degraded: result.degraded,
532
- }
533
- },
534
- log: logger,
535
- ...(harness === undefined ? {} : { harness }),
536
- }
537
-
538
- // Real clock, deliberately, not `deps.now`. This compares against file
539
- // mtimes, which are wall-clock facts — handing it a virtual or skewed clock
540
- // would have it delete live session state as "abandoned".
541
- // Daily state pruning is housekeeping, not part of the Stop delivery
542
- // contract. Its directory scan has no useful bound, so keep it on the
543
- // short prompt path and never spend the answer owner's finite budget on it.
544
- if (event !== 'stop' && event !== 'question-settlement') {
545
- pruneAbandonedSessions(deps.env)
546
- }
547
-
548
- let outcome: HookOutcome
549
- if (event === 'user-prompt-submit') {
550
- outcome = await handleUserPromptSubmit(ctx, envelope)
551
- if (
552
- outcome.settlementRequired === true &&
553
- envelope.session_id !== undefined &&
554
- harness !== undefined &&
555
- questionRoutingCapability(harness).stopContinuation !== 'unsupported'
556
- ) {
557
- try {
558
- const launchSettlement = deps.spawnQuestionSettlement ?? spawnQuestionSettlement
559
- launchSettlement({
560
- envelope: { session_id: envelope.session_id, cwd },
561
- harness,
562
- })
563
- outcome.log = { ...outcome.log, settlement: 'launched' }
564
- } catch (err) {
565
- outcome.log = {
566
- ...outcome.log,
567
- settlement: 'launch-failed',
568
- settlement_error: failureData(err),
569
- }
570
- }
571
- }
572
- } else {
573
- outcome = await handleStop(
574
- ctx,
575
- envelope,
576
- processDeadlineAt,
577
- stopWakeRoute(
578
- deps,
579
- harness,
580
- envelope.session_id,
581
- cwd,
582
- event === 'stop',
583
- ),
584
- event === 'stop',
585
- )
586
- }
587
- // Answer diagnostics are already persisted once as hook.answer. Keep every
588
- // other note in the lifecycle record without duplicating the user's text.
589
- const notes = outcome.notes.filter((note) => !/^(?:late )?answer from /.test(note))
590
- logger.info('hook.end', {
591
- hook: event,
592
- decided: outcome.decided ?? outcome.stdout !== undefined,
593
- ...(notes.length === 0 ? {} : { notes }),
594
- ...outcome.log,
595
- })
596
- for (const note of outcome.notes) deps.io.err(`notifai: ${note}`)
597
- if (outcome.stdout !== undefined) {
598
- // No work, await, or diagnostic may sit between this cross-process
599
- // SessionEnd fence and the irreversible harness stdout write.
600
- if (outcome.commitStdout === undefined || outcome.commitStdout()) {
601
- deps.io.out(outcome.stdout)
602
- } else {
603
- deps.io.err('notifai: the Agent Session ended before answer delivery; no continuation was written')
604
- }
605
- }
606
- return EXIT.ok
607
- } catch (err) {
608
- // SessionEnd defers its start record until after cleanup; if cleanup itself
609
- // fails, begin the after-the-fact lifecycle here before recording why.
610
- if (sessionEnd) start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null })
611
- // The hook still exits 0 — handing the terminal back is always right. What
612
- // this adds is that the reason survives, including the server's own words.
613
- logger.error('hook.end', {
614
- hook: event,
615
- outcome: 'failed',
616
- reason: 'execution-failed',
617
- ...failureData(err),
618
- })
619
- for (const line of describeHookFailure(err)) deps.io.err(`notifai: ${line}`)
620
- return EXIT.ok
621
- }
622
- }
623
-
624
- /**
625
- * The last meter for an answer this Stop hook accepted, chosen by harness.
626
- *
627
- * Both wake adapters need the harness process that invoked this hook: Claude's
628
- * to prove exact own-child session ownership before it posts to the inbox
629
- * socket, Codex's to know whether its own stdout is still a live continuation
630
- * channel. Without an exact session id neither can prove anything, so the
631
- * waiter falls back to the plain blocking Stop continuation.
632
- */
633
- function stopWakeRoute(
634
- deps: CommandDeps,
635
- harness: HookInstallableHarness | undefined,
636
- sessionId: string | undefined,
637
- cwd: string,
638
- continuationActive = true,
639
- ): EscalationDeliveryRoute | undefined {
640
- if (sessionId === undefined) return undefined
641
- const declaredSourcePid = declaredHookSourcePid(deps)
642
- if (harness === 'claude-code') {
643
- if ((deps.hookPlatform ?? process.platform) === 'win32') return undefined
644
- return claudeWakeRoute({
645
- sessionId,
646
- cwd,
647
- sourcePid: deps.claudeSourcePid ?? declaredSourcePid ?? claudeSessionPid(deps.env),
648
- ...(deps.claudeWake === undefined ? {} : { adapters: deps.claudeWake }),
649
- })
650
- }
651
- if (harness === 'codex') {
652
- return codexWakeRoute({
653
- threadId: sessionId,
654
- cwd,
655
- sourcePid: deps.codexSourcePid ?? declaredSourcePid ?? process.ppid,
656
- env: deps.env,
657
- ...(deps.codexWake === undefined ? {} : { adapters: deps.codexWake }),
658
- continuationActive,
659
- })
660
- }
661
- return undefined
662
- }
663
-
664
- /** Stable harness parent propagated by the managed adapter across child tools. */
665
- function declaredHookSourcePid(deps: CommandDeps): number | undefined {
666
- const value = Number(deps.env['NOTIFAI_HOOK_SOURCE_PID'])
667
- return Number.isInteger(value) && value > 0 ? value : undefined
668
- }
669
-
670
-
671
- /**
672
- * What went wrong, in terms of what to do about it.
673
- *
674
- * On 2026-08-03 a contract change shipped without the server deploy that goes
675
- * with it. The CLI stamped `lifecycle` on every question draft, the deployed
676
- * server rejected the unknown field, and escalation stopped working entirely —
677
- * announced as "hook failed, deferring to the terminal", which reads like a
678
- * flaky network. The information needed to diagnose it in one second was
679
- * already in hand: a 422 whose details name the offending path. It was being
680
- * thrown away by `String(err)`.
681
- *
682
- * A hook still exits 0 whatever this says. Handing the terminal back is always
683
- * right; the only question is whether the user is told anything they can use.
684
- */
685
- export function describeHookFailure(err: unknown): string[] {
686
- if (!(err instanceof ApiCallError)) {
687
- return [`hook failed, deferring to the terminal (${String(err)})`]
688
- }
689
- const lines = [`hook failed, deferring to the terminal (${err.code}: ${err.message})`]
690
- const paths = rejectedPaths(err.details)
691
- if (paths.length > 0) lines.push(`the server rejected: ${paths.join(', ')}`)
692
- // A 422 on a draft this CLI built is not a user error — this CLI's own
693
- // contract produced it. Either the server is behind, or the two disagree.
694
- if (err.status === 422) {
695
- lines.push(
696
- 'this build sent a field the server did not accept, which usually means the server ' +
697
- 'is older than this CLI — check with `notifai doctor`',
698
- )
699
- }
700
- return lines
701
- }
702
-
703
-
704
- export interface AskFlags {
705
- /** Emit the registration and its turn obligation as one JSON object. */
706
- json?: boolean
707
- choice?: string[]
708
- /** The single question is multi-select: several answers may be chosen. */
709
- multi?: boolean
710
- /** Optional Markdown context appended after the question block. */
711
- body?: string
712
- /** Allow visible backslash-n sequences in `--body`. */
713
- literalBackslashN?: boolean
714
- /** Raw JSON for a multi-question form; replaces the positional question. */
715
- form?: string
716
- image?: string[]
717
- imageAlt?: string[]
718
- project?: string
719
- sessionLabel?: string
720
- }
721
-
722
- export interface AskFailure {
723
- ok: false
724
- registered: false
725
- code: string
726
- check_id: string
727
- exit_code: number
728
- remedy: string
729
- message: string
730
- }
731
-
732
- /** One stable failure contract for every machine-readable ask refusal. */
733
- export function reportAskFailure(
734
- deps: CommandDeps,
735
- flags: Pick<AskFlags, 'json'>,
736
- failure: Omit<AskFailure, 'ok' | 'registered'>,
737
- ): number {
738
- if (flags.json === true) {
739
- deps.io.out(JSON.stringify({ ok: false, registered: false, ...failure }, null, 2))
740
- } else {
741
- deps.io.err(failure.message)
742
- deps.io.err(`next: ${failure.remedy}`)
743
- }
744
- return failure.exit_code
745
- }
746
-
747
- function askFailure(
748
- deps: CommandDeps,
749
- flags: AskFlags,
750
- code: string,
751
- checkId: string,
752
- message: string,
753
- remedy: string,
754
- exitCode: number = EXIT.usage,
755
- ): number {
756
- return reportAskFailure(deps, flags, {
757
- code,
758
- check_id: checkId,
759
- exit_code: exitCode,
760
- remedy,
761
- message,
762
- })
763
- }
764
-
765
- /** The `--form` document: what an agent writes to ask several things at once. */
766
- interface AskFormQuestion {
767
- text: string
768
- choices?: string[]
769
- multi?: boolean
770
- }
771
-
772
- export interface BuiltQuestions {
773
- questions: QuestionT[]
774
- /**
775
- * Canonical Markdown body. The question already travels as the notification
776
- * title and as structured questions, so the body carries only the context —
777
- * repeating the question there put it on the lock screen and the reply
778
- * screen twice. Only when there is no context does the question text stand
779
- * in, because the wire requires a body.
780
- */
781
- body: string
782
- }
783
-
784
- /**
785
- * Turn ask input into questions plus their canonical body. Everything is
786
- * validated at registration because a later hook failure is easy to miss.
787
- */
788
- export function buildQuestions(
789
- flags: AskFlags,
790
- question: string | undefined,
791
- ): { ok: true; questions: QuestionT[]; body: string } | { ok: false; error: string } {
792
- if (flags.form !== undefined) {
793
- if (question !== undefined || flags.choice?.length || flags.multi) {
794
- return { ok: false, error: '--form replaces the positional question, --choice, and --multi.' }
795
- }
796
- let parsed: unknown
797
- try {
798
- parsed = JSON.parse(flags.form)
799
- } catch {
800
- return {
801
- ok: false,
802
- error: '--form must be JSON: {"questions": [{"text", "choices"?, "multi"?}], "body"?}.',
803
- }
804
- }
805
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
806
- return { ok: false, error: `--form needs a "questions" array (1-${REPLY_MAX_QUESTIONS} entries).` }
807
- }
808
- const record = parsed as Record<string, unknown>
809
- const unknownKeys = Object.keys(record).filter((key) => key !== 'questions' && key !== 'body')
810
- if (unknownKeys.length > 0) {
811
- return {
812
- ok: false,
813
- error: `Unknown --form ${unknownKeys.length === 1 ? 'key' : 'keys'}: ${unknownKeys.join(', ')}. Use "body" for Markdown context.`,
814
- }
815
- }
816
- if (!Array.isArray(record['questions'])) {
817
- return { ok: false, error: `--form needs a "questions" array (1-${REPLY_MAX_QUESTIONS} entries).` }
818
- }
819
- const formQuestions = record['questions']
820
- if (formQuestions.length < 1 || formQuestions.length > REPLY_MAX_QUESTIONS) {
821
- return {
822
- ok: false,
823
- error: `A form asks 1-${REPLY_MAX_QUESTIONS} questions; this one has ${formQuestions.length}.`,
824
- }
825
- }
826
- if (record['body'] !== undefined && typeof record['body'] !== 'string') {
827
- return { ok: false, error: '"body" must be a Markdown string.' }
828
- }
829
- if (flags.body !== undefined && record['body'] !== undefined) {
830
- return { ok: false, error: 'Pass form context in either --body or the form "body" key, not both.' }
831
- }
832
- const questions: QuestionT[] = []
833
- const usedIds = new Set<string>()
834
- for (const [index, entry] of formQuestions.entries()) {
835
- if (typeof entry !== 'object' || entry === null || typeof (entry as AskFormQuestion).text !== 'string') {
836
- return { ok: false, error: `Question ${index + 1} needs a "text" string.` }
837
- }
838
- const spec = entry as AskFormQuestion
839
- const built = buildOneQuestion(spec.text, spec.choices, spec.multi === true, index, usedIds)
840
- if ('error' in built) return { ok: false, error: `Question ${index + 1}: ${built.error}` }
841
- questions.push(built.question)
842
- }
843
- const context = flags.body ?? (record['body'] as string | undefined)
844
- return {
845
- ok: true,
846
- questions,
847
- body:
848
- context !== undefined && context.trim() !== ''
849
- ? context
850
- : questions.map((entry, index) => `${index + 1}. ${entry.text}`).join('\n'),
851
- }
852
- }
853
-
854
- if (question === undefined || question.trim() === '') {
855
- return { ok: false, error: 'The question cannot be empty.' }
856
- }
857
- const built = buildOneQuestion(question, flags.choice, flags.multi === true, 0, new Set())
858
- if ('error' in built) return { ok: false, error: built.error }
859
- const context = flags.body
860
- return {
861
- ok: true,
862
- questions: [built.question],
863
- body: context !== undefined && context.trim() !== '' ? context : built.question.text,
864
- }
865
- }
866
-
867
- function buildOneQuestion(
868
- text: string,
869
- choiceLabels: string[] | undefined,
870
- multi: boolean,
871
- index: number,
872
- usedIds: Set<string>,
873
- ): { question: QuestionT } | { error: string } {
874
- const trimmed = text.trim()
875
- if (trimmed === '') return { error: 'the question text cannot be empty.' }
876
- if (trimmed.length > QUESTION_TEXT_MAX_LENGTH) {
877
- return {
878
- error:
879
- `a question must be readable where it is answered: keep it within ` +
880
- `${QUESTION_TEXT_MAX_LENGTH} characters and put the longer context in --body.`,
881
- }
882
- }
883
- const choices = parseChoices(choiceLabels)
884
- if (choices === 'invalid') return { error: CHOICE_USAGE }
885
- if (multi && choices === null) {
886
- return { error: '--multi needs answers to select between; add --choice.' }
887
- }
888
- let id = slugify(trimmed)
889
- if (id === '' || usedIds.has(id)) id = `q${index + 1}`
890
- usedIds.add(id)
891
- return {
892
- question: {
893
- id,
894
- text: trimmed,
895
- ...(choices !== null ? { choices } : {}),
896
- ...(multi ? { multi: true } : {}),
897
- },
898
- }
899
- }
900
-
901
- function buildAskDraft(
902
- config: CliConfig,
903
- built: BuiltQuestions,
904
- flags: AskFlags,
905
- invocation: DraftInvocation,
906
- mediaIds: string[],
907
- ): { ok: true; draft: NotificationDraftT } | { ok: false; error: string } {
908
- const result = buildDraft(
909
- config,
910
- {
911
- title: built.questions[0]!.text,
912
- body: built.body,
913
- ...(flags.project !== undefined ? { project: flags.project } : {}),
914
- ...(mediaIds.length > 0 ? { image: mediaIds } : {}),
915
- ...(flags.imageAlt !== undefined ? { imageAlt: flags.imageAlt } : {}),
916
- reply: true,
917
- questions: built.questions,
918
- },
919
- invocation,
920
- )
921
- if (!result.ok) return result
922
- const capabilities = CAPABILITIES_V1.describe(result.platform)
923
- if (capabilities === null) return { ok: false, error: 'No iOS capability contract is available.' }
924
- const validation = validateDraft(result.draft, capabilities)
925
- if (!validation.ok) {
926
- return {
927
- ok: false,
928
- error: validation.errors.map((issue) => `${issue.path}: ${issue.message}`).join('\n'),
929
- }
930
- }
931
- return { ok: true, draft: result.draft }
932
- }
933
-
934
- function recordRegisteredQuestion(
935
- deps: CommandDeps,
936
- sessionId: string,
937
- built: BuiltQuestions,
938
- draft: NotificationDraftT,
939
- json = false,
940
- ): number {
941
- let questionId: string
942
- try {
943
- questionId = registerQuestion(
944
- sessionId,
945
- deps.env,
946
- {
947
- question: built.questions[0]!.text,
948
- questions: built.questions,
949
- body: draft.presentation.body,
950
- ...(draft.project !== undefined ? { project: draft.project } : {}),
951
- ...(draft.source !== undefined ? { source: draft.source } : {}),
952
- ...(draft.presentation.media !== undefined ? { media: draft.presentation.media } : {}),
953
- },
954
- (deps.now ?? Date.now)(),
955
- )
956
- } catch (err) {
957
- log(deps).error('ask.registered', { ok: false, session: sessionId, message: String(err) })
958
- return askFailure(
959
- deps,
960
- { json },
961
- 'registration_failed',
962
- 'question_registration',
963
- `Could not register the question: ${err instanceof Error ? err.message : String(err)}`,
964
- 'retire an older pending question if the limit was reached, then retry the same ask',
965
- EXIT.failed,
966
- )
967
- }
968
- log(deps).info('ask.registered', {
969
- ok: true,
970
- session: sessionId,
971
- question_id: questionId,
972
- questions: built.questions.length,
973
- text_chars: built.questions[0]!.text.length,
974
- choices: built.questions[0]!.choices?.length ?? 0,
975
- media: draft.presentation.media?.length ?? 0,
976
- })
977
- // The block below is the densest guidance this CLI prints, and until now it
978
- // was prose only: an agent could not read back the choice ids it must branch
979
- // on without asking the server for them. The JSON form carries the same
980
- // obligation as data.
981
- if (json) {
982
- deps.io.out(
983
- JSON.stringify(
984
- {
985
- registered: true,
986
- question_id: questionId,
987
- state: 'local',
988
- submitted: false,
989
- request_id: null,
990
- provider_acceptance: 'not_available',
991
- questions: built.questions.map((entry) => ({
992
- id: entry.id,
993
- text: entry.text,
994
- ...(entry.choices === undefined ? {} : { choices: entry.choices }),
995
- ...(entry.multi === true ? { multi: true } : {}),
996
- })),
997
- status: `notifai status ${questionId}`,
998
- close: `notifai close ${questionId}`,
999
- next: {
1000
- end_turn: true,
1001
- in_this_turn:
1002
- 'Ask the question in the conversation and say what concrete work each possible answer will make you resume, then end the turn.',
1003
- route_neutral:
1004
- 'Never say where the answer must arrive; it returns by whatever route the harness supports.',
1005
- on_answer:
1006
- 'Acknowledge it, then resume the committed work without asking the user to confirm again.',
1007
- answered_outside_notifai: `If they answer in the conversation instead, run \`notifai close ${questionId}\` before ending the turn so a later Stop will not send this question.`,
1008
- },
1009
- },
1010
- null,
1011
- 2,
1012
- ),
1013
- )
1014
- return EXIT.ok
1015
- }
1016
- for (const [index, entry] of built.questions.entries()) {
1017
- const prefix = built.questions.length > 1 ? `${index + 1}. ` : ''
1018
- if (entry.choices !== undefined) {
1019
- const kind = entry.multi === true ? 'answers offered (several may be chosen)' : 'answers offered'
1020
- deps.io.out(`${prefix}${entry.text} — ${kind}: ${entry.choices.map((choice) => choice.label).join(' / ')}`)
1021
- } else if (built.questions.length > 1) {
1022
- deps.io.out(`${prefix}${entry.text} — free text`)
1023
- }
1024
- }
1025
- deps.io.out(
1026
- built.questions.length > 1
1027
- ? `${built.questions.length} questions registered locally as one form (${questionId}); they have not been submitted as a Notification Request and have no Provider Acceptance yet. Ask them in the conversation, state the concrete work you will resume for their answers, then end your turn.`
1028
- : `Question registered locally (${questionId}); it has not been submitted as a Notification Request and has no Provider Acceptance yet. Ask it in the conversation, state the concrete work you will resume when the answer arrives, then end your turn.`,
1029
- )
1030
- deps.io.out(
1031
- `Question settlement runs after registration. Inspect the original identity with \`notifai status ${questionId}\`; never register a replacement to check whether this one was sent.`,
1032
- )
1033
- deps.io.out('Before ending this turn, pre-commit in your own words to the work you will resume:')
1034
- for (const [index, entry] of built.questions.entries()) {
1035
- const questionPrefix = built.questions.length > 1 ? `Question ${index + 1}, ` : ''
1036
- if (entry.choices !== undefined) {
1037
- for (const choice of entry.choices) {
1038
- deps.io.out(
1039
- `- ${questionPrefix}If the answer is ${JSON.stringify(choice.label)}: state the concrete work you will resume.`,
1040
- )
1041
- }
1042
- deps.io.out(
1043
- `- ${questionPrefix}For an unexpected typed answer: state how it will determine the concrete work you resume.`,
1044
- )
1045
- } else {
1046
- deps.io.out(
1047
- `- ${questionPrefix}For the free-text answer: state how its content will determine the concrete work you resume.`,
1048
- )
1049
- }
1050
- }
1051
- deps.io.out(
1052
- 'When the answer arrives, resume the matching work without asking the user to confirm again. Frame this as work you will resume, not as approval you receive.',
1053
- )
1054
- deps.io.out(
1055
- 'A Notifai answer cannot answer a harness permission prompt or interactive picker; leave those to the harness and user.',
1056
- )
1057
- deps.io.out(
1058
- `If they answer in this conversation instead, retire it with \`notifai close ${questionId}\` so a later Stop will not send it.`,
1059
- )
1060
- return EXIT.ok
1061
- }
1062
-
1063
- async function uploadAskMedia(
1064
- deps: CommandDeps,
1065
- config: CliConfig,
1066
- sessionId: string,
1067
- built: BuiltQuestions,
1068
- flags: AskFlags,
1069
- invocation: DraftInvocation,
1070
- ): Promise<number> {
1071
- const authed = authedClient(deps, config)
1072
- if (!authed) {
1073
- return askFailure(
1074
- deps,
1075
- flags,
1076
- 'auth_required',
1077
- 'credential',
1078
- 'Question routing is not paired on this machine.',
1079
- 'run `notifai init --json`',
1080
- EXIT.auth,
1081
- )
1082
- }
1083
- const mediaIds: string[] = []
1084
- for (const image of flags.image ?? []) {
1085
- if (image.startsWith('med_')) {
1086
- mediaIds.push(image)
1087
- continue
1088
- }
1089
- const uploaded = await uploadImage(deps, authed.client, image, config.media_origins.value)
1090
- if (!uploaded.ok) {
1091
- if (uploaded.error !== null) deps.io.err(uploaded.error)
1092
- return askFailure(
1093
- deps,
1094
- flags,
1095
- 'media_upload_failed',
1096
- 'media',
1097
- uploaded.error ?? 'The image upload failed.',
1098
- 'fix the reported image or network problem, then retry the same ask',
1099
- uploaded.exit,
1100
- )
1101
- }
1102
- mediaIds.push(uploaded.mediaId)
1103
- }
1104
- const ready = buildAskDraft(config, built, flags, invocation, mediaIds)
1105
- if (!ready.ok) {
1106
- return askFailure(deps, flags, 'invalid_draft', 'draft', ready.error, 'fix the reported field and retry')
1107
- }
1108
- return recordRegisteredQuestion(deps, sessionId, built, ready.draft, flags.json === true)
1109
- }
1110
-
1111
- /**
1112
- * Registers a question for turn-end routing. Returns immediately so the agent
1113
- * can ask in prose and end its turn; the terminal keeps the question to itself
1114
- * for `ask_grace_seconds` before it reaches any device.
1115
- */
1116
- export function askCommand(
1117
- deps: CommandDeps,
1118
- question: string | undefined,
1119
- flags: AskFlags,
1120
- ): number | Promise<number> {
1121
- // Validate before route discovery. A malformed question belongs to the
1122
- // caller and should not be hidden behind whichever harness setup issue
1123
- // happens to exist on this machine.
1124
- const escapedBody = rejectAccidentalEscapedNewlines(flags.body, flags.literalBackslashN)
1125
- if (escapedBody !== null) {
1126
- return askFailure(deps, flags, 'invalid_input', 'body', escapedBody, 'fix the body and retry')
1127
- }
1128
- const built = buildQuestions(flags, question)
1129
- if (!built.ok) {
1130
- return askFailure(deps, flags, 'invalid_input', 'questions', built.error, 'fix the question input and retry')
1131
- }
1132
- const mediaInputError = validateMediaInputs(flags.image, flags.imageAlt)
1133
- if (mediaInputError !== null) {
1134
- return askFailure(deps, flags, 'invalid_input', 'media', mediaInputError, 'fix the media flags and retry')
1135
- }
1136
- let explicitUseConfig: CliConfig
1137
- try {
1138
- explicitUseConfig = loadConfig({ cwd: deps.cwd, env: deps.env })
1139
- } catch (err) {
1140
- return askFailure(deps, flags, 'config_invalid', 'configuration', `Question routing configuration is invalid: ${String(err)}`, 'fix the reported Notifai configuration and retry')
1141
- }
1142
- const explicitProject = flags.project ?? explicitUseConfig.project.value ?? inferInvocationContext(deps.cwd).project
1143
- if (explicitProject !== null) {
1144
- const binding = projectBinding(deps.cwd, deps.env, explicitProject)
1145
- if (binding !== null) enableProject(binding)
1146
- }
1147
- if (deps.store.load() === null) {
1148
- return askFailure(
1149
- deps,
1150
- flags,
1151
- 'auth_required',
1152
- 'credential',
1153
- 'Question routing is not paired on this machine.',
1154
- 'run `notifai init --json`',
1155
- EXIT.auth,
1156
- )
1157
- }
1158
- // An agent calling this gets no hook payload. Harness-native environment
1159
- // markers identify the active owner, while UserPromptSubmit adds the hook's
1160
- // canonical id to the directory's concurrent-session index.
1161
- const now = (deps.now ?? Date.now)()
1162
- const { active, contested } = resolveActiveHarness(deps.env, deps.cwd, now)
1163
- let sessionId: string | undefined
1164
- if (active !== null) {
1165
- if (contested.length > 1) {
1166
- return askFailure(
1167
- deps,
1168
- flags,
1169
- 'session_identity_ambiguous',
1170
- 'exact_session',
1171
- `Several harness sessions could own this shell (${contested.map((candidate) => candidate.label).join(', ')}).`,
1172
- 'run the ask from a shell with one exact active harness session',
1173
- )
1174
- }
1175
- if (!isHookInstallableHarness(active.harness)) {
1176
- const capability = HERMES_QUESTION_ROUTING_UNAVAILABLE
1177
- return askFailure(
1178
- deps,
1179
- flags,
1180
- 'question_routing_unavailable',
1181
- 'hook_contract',
1182
- `${active.label}: ${capability.deliveryContract}`,
1183
- 'use a blocking `notifai send --reply` question',
1184
- )
1185
- }
1186
- const exactState = active.sessionId === undefined
1187
- ? null
1188
- : readSessionState(active.sessionId, deps.env)
1189
- const installationCwd = exactState?.activation_cwd ?? deps.cwd
1190
- const installationDeps = installationCwd === deps.cwd ? deps : { ...deps, cwd: installationCwd }
1191
- const installations = findInstallations(installationCwd, deps.env, deps.hookAdapterHome, deps.hookPlatform)
1192
- const activeInstalled = installations.some(
1193
- (installation) => installation.harness === active.harness,
1194
- )
1195
- if (!activeInstalled) {
1196
- return askFailure(
1197
- deps,
1198
- flags,
1199
- 'hooks_not_installed',
1200
- 'hook_installation',
1201
- `Notifai ${active.label} hooks are not installed for this project.`,
1202
- `run \`notifai init --json\` from this ${active.label} session`,
1203
- )
1204
- }
1205
- if (active.sessionId === undefined) {
1206
- return askFailure(
1207
- deps,
1208
- flags,
1209
- 'session_identity_missing',
1210
- 'exact_session',
1211
- `The active ${active.label} shell does not expose an exact session id.`,
1212
- 'use a blocking `notifai send --reply` question',
1213
- )
1214
- }
1215
- const routeProblems = activeQuestionRouteProblems(installationDeps, active, installations)
1216
- if (routeProblems.length > 0) {
1217
- return askFailure(
1218
- deps,
1219
- flags,
1220
- 'question_routing_unavailable',
1221
- 'hook_contract',
1222
- `Question routing is not ready: ${routeProblems.join('; ')}`,
1223
- 'run `notifai init --json` and follow its question-routing remedy',
1224
- )
1225
- }
1226
- const state = exactState ?? readSessionState(active.sessionId, deps.env)
1227
- if (state.harness !== active.harness || state.last_prompt_at === undefined) {
1228
- return askFailure(
1229
- deps,
1230
- flags,
1231
- 'session_not_activated',
1232
- 'user_prompt_submit',
1233
- `This exact ${active.label} session has not fired UserPromptSubmit.`,
1234
- `send one prompt in this ${active.label} session, then retry \`notifai ask --json\``,
1235
- )
1236
- }
1237
- if (state.last_stop_at === undefined) {
1238
- return askFailure(
1239
- deps,
1240
- flags,
1241
- 'stop_not_observed',
1242
- 'stop_hook',
1243
- `This exact ${active.label} session has fired UserPromptSubmit, but its Stop hook has not been observed.`,
1244
- `end one harmless turn, send a new prompt, then retry \`notifai ask --json\``,
1245
- )
1246
- }
1247
- sessionId = active.sessionId
1248
- } else {
1249
- return askFailure(
1250
- deps,
1251
- flags,
1252
- 'session_identity_missing',
1253
- 'exact_session',
1254
- 'Could not prove which live Agent Session owns this command.',
1255
- 'run it from a supported harness with exact Agent Session identity, or use a blocking `notifai send --reply` question',
1256
- )
1257
- }
1258
- if (!sessionId) {
1259
- return askFailure(deps, flags, 'session_identity_missing', 'exact_session', 'No exact active Agent Session is available.', 'use a blocking `notifai send --reply` question')
1260
- }
1261
- let routingConfig: CliConfig
1262
- try {
1263
- routingConfig = loadConfig({ cwd: deps.cwd, env: deps.env, sessionId })
1264
- } catch (err) {
1265
- return askFailure(
1266
- deps,
1267
- flags,
1268
- 'config_invalid',
1269
- 'configuration',
1270
- `Question routing configuration is invalid: ${String(err)}`,
1271
- 'fix the reported Notifai configuration and retry',
1272
- )
1273
- }
1274
- if (!routingConfig.ask_notifications.value) {
1275
- return askFailure(
1276
- deps,
1277
- flags,
1278
- 'question_routing_disabled',
1279
- 'ask_notifications',
1280
- 'Question routing is disabled by ask_notifications=false.',
1281
- 'enable question routing or use a blocking `notifai send --reply` question',
1282
- )
1283
- }
1284
- const source = resolveDraftInvocation(deps, flags, active)
1285
- if (!source.ok) {
1286
- return askFailure(deps, flags, 'invalid_source', 'source_context', source.error, 'remove the conflicting source override and retry')
1287
- }
1288
- if (source.invocation.source?.session_id !== sessionId) {
1289
- return askFailure(
1290
- deps,
1291
- flags,
1292
- 'session_identity_mismatch',
1293
- 'exact_session',
1294
- `The inferred session does not match the exact active ${active.label} session.`,
1295
- 'remove NOTIFAI_SESSION_ID and retry from the exact active session',
1296
- )
1297
- }
1298
-
1299
- // Placeholders let every body, source, project, media, and payload limit fail
1300
- // before an upload starts. The real ids replace them only after this passes.
1301
- const placeholders = (flags.image ?? []).map((_, index) => `med_pending_${index + 1}`)
1302
- const preflight = buildAskDraft(routingConfig, built, flags, source.invocation, placeholders)
1303
- if (!preflight.ok) {
1304
- return askFailure(deps, flags, 'invalid_draft', 'draft', preflight.error, 'fix the reported field and retry')
1305
- }
1306
- if ((flags.image?.length ?? 0) > 0) {
1307
- return uploadAskMedia(
1308
- deps,
1309
- routingConfig,
1310
- sessionId,
1311
- built,
1312
- flags,
1313
- source.invocation,
1314
- )
1315
- }
1316
- return recordRegisteredQuestion(deps, sessionId, built, preflight.draft, flags.json === true)
1317
- }
1318
-
1319
-
1320
- /**
1321
- * One fail-closed admission gate shared by every active harness route.
1322
- * Finding a file is not readiness: the exact session, one current definition,
1323
- * the stable adapter, a long enough Stop owner, and (for Codex) trust must all
1324
- * be true before `ask` is allowed to create an answerable notification.
1325
- */
1326
- export function activeQuestionRouteProblems(
1327
- deps: CommandDeps,
1328
- active: ActiveHarnessSession,
1329
- installations: Installation[],
1330
- ): string[] {
1331
- const problems: string[] = []
1332
- if (active.sessionId === undefined) {
1333
- problems.push(
1334
- `the active ${active.label} shell does not expose an exact session id; a project-level last-writer pointer can cross-wire two sessions. Use a blocking \`notifai send --reply\` question`,
1335
- )
1336
- }
1337
- const capability = isHookInstallableHarness(active.harness)
1338
- ? questionRoutingCapability(active.harness)
1339
- : HERMES_QUESTION_ROUTING_UNAVAILABLE
1340
- if (capability.stopContinuation === 'unsupported') {
1341
- problems.push(`${active.label}: ${capability.deliveryContract}`)
1342
- }
1343
- const matching = installations.filter(
1344
- (installation) => installation.harness === active.harness,
1345
- )
1346
- if (matching.length > 1) {
1347
- problems.push(
1348
- `${matching.length} ${active.label} definitions are active (${matching.map((entry) => entry.file).join(', ')}); keep either project or global routing`,
1349
- )
1350
- }
1351
- for (const installation of matching) {
1352
- for (const problem of installation.problems ?? []) {
1353
- problems.push(`${installation.file}: ${problem}`)
1354
- }
1355
- for (const handler of installation.handlers) {
1356
- const event = handlerEvent(handler.command)
1357
- if (event !== null && !(HOOK_EVENTS as readonly string[]).includes(event)) {
1358
- problems.push(
1359
- `${handler.event} in ${installation.file} names the unsupported event ${event}; reinstall the ${active.label} hooks`,
1360
- )
1361
- }
1362
- }
1363
- }
1364
- for (const problem of inspectHookAdapter(deps.hookAdapterHome, deps.hookPlatform).problems) {
1365
- problems.push(problem)
1366
- }
1367
- for (const installation of matching) problems.push(...stopShapeProblems(installation, deps.hookPlatform))
1368
- problems.push(...codexTrustProblems(matching, deps.env))
1369
- return [...new Set(problems)]
1370
- }
1371
-
1372
- /** The least disruptive verified way to make each installed adapter run once. */
1373
- export function hookActivationAdvice(installations: Installation[]): string {
1374
- const harnesses = new Set(installations.map((installation) => installation.harness))
1375
- const advice: string[] = []
1376
- if (
1377
- installations.some(
1378
- (installation) => installation.harness === 'claude-code' && !installation.global,
1379
- )
1380
- ) {
1381
- advice.push('Claude Code: start one fresh session, send one prompt, then run `notifai doctor`')
1382
- }
1383
- if (
1384
- installations.some(
1385
- (installation) => installation.harness === 'claude-code' && installation.global,
1386
- )
1387
- ) {
1388
- advice.push('Claude Code global hooks: start one fresh session, send one prompt, then run `notifai doctor`')
1389
- }
1390
- if (
1391
- installations.some(
1392
- (installation) => installation.harness === 'cursor' && !installation.global,
1393
- )
1394
- ) {
1395
- advice.push(
1396
- 'Cursor: start one fresh conversation, send one prompt, finish its first turn, then run `notifai doctor`',
1397
- )
1398
- }
1399
- if (
1400
- installations.some(
1401
- (installation) => installation.harness === 'cursor' && installation.global,
1402
- )
1403
- ) {
1404
- advice.push('Cursor global hooks: start one fresh conversation, send one prompt, finish its first turn, then run `notifai doctor`')
1405
- }
1406
- if (harnesses.has('codex')) {
1407
- advice.push(
1408
- 'Codex: approve the Notifai handlers in `/hooks` if asked, start one fresh session, send one prompt, then run `notifai doctor`',
1409
- )
1410
- }
1411
- if (harnesses.has('opencode')) {
1412
- advice.push(
1413
- 'OpenCode: restart it, then send one prompt; plugins load at startup, but non-blocking question continuation is intentionally unsupported',
1414
- )
1415
- }
1416
- if (harnesses.has('openclaw')) {
1417
- advice.push(
1418
- 'OpenClaw: restart the Gateway, then send one prompt; plugins load at startup, but non-blocking question continuation is intentionally unsupported',
1419
- )
1420
- }
1421
- return `${advice.join('. ')}.`
1422
- }
1423
-
1424
- /**
1425
- * Record the one Agent Acknowledgement associated with a replied-to request.
1426
- *
1427
- * `--text` is optional here because the acknowledgement is not: an account may
1428
- * turn the agent's written reply off, and the receipt must still be recorded so
1429
- * the user sees that an agent read the answer. The service holds the account's
1430
- * snapshot, so it — not this process — decides whether text was owed.
1431
- */
1432
- export async function acknowledgeCommand(
1433
- deps: CommandDeps,
1434
- requestId: string,
1435
- flags: { text?: string; json?: boolean },
1436
- ): Promise<number> {
1437
- const text = flags.text?.trim() ?? ''
1438
- if (flags.text !== undefined && text.length === 0) {
1439
- deps.io.err('--text must contain non-whitespace text. Drop it to acknowledge without text.')
1440
- return EXIT.usage
1441
- }
1442
- if (text.length > AGENT_ACKNOWLEDGEMENT_MAX_LENGTH) {
1443
- deps.io.err(
1444
- `--text must be at most ${AGENT_ACKNOWLEDGEMENT_MAX_LENGTH} characters after trimming. Shorten it: an acknowledgement is a receipt, not a report.`,
1445
- )
1446
- return EXIT.usage
1447
- }
1448
-
1449
- const logger = log(deps)
1450
- const lifecycleSession = resolveCommandSession(deps, requestId)
1451
- const config = loadLoggedConfig(deps, {
1452
- cwd: deps.cwd,
1453
- env: deps.env,
1454
- ...(lifecycleSession === null ? {} : { sessionId: lifecycleSession.sessionId }),
1455
- })
1456
- logger.info('acknowledgement.attempted', {
1457
- request_id: requestId,
1458
- characters: text.length,
1459
- })
1460
- const authed = authedClient(deps, config)
1461
- if (!authed) return EXIT.auth
1462
- try {
1463
- const result = await authed.client.putAgentAcknowledgement(
1464
- requestId,
1465
- text.length > 0 ? { text } : {},
1466
- )
1467
- const output = {
1468
- request_id: requestId,
1469
- outcome: result.status,
1470
- acknowledgement: result.agent_acknowledgement,
1471
- agent_acknowledgement_required: true,
1472
- }
1473
- logger.info('acknowledgement.outcome', {
1474
- request_id: requestId,
1475
- outcome: result.status,
1476
- text_chars: result.agent_acknowledgement.text.length,
1477
- created_at: result.agent_acknowledgement.created_at,
1478
- agent_acknowledgement_required: true,
1479
- })
1480
- if (lifecycleSession !== null) {
1481
- clearAcknowledgementObligation(lifecycleSession.sessionId, deps.env, requestId)
1482
- }
1483
- if (flags.json) deps.io.out(JSON.stringify(output, null, 2))
1484
- else {
1485
- deps.io.out(
1486
- `Agent Acknowledgement ${result.status} for ${requestId} at ${result.agent_acknowledgement.created_at}.`,
1487
- )
1488
- }
1489
- return EXIT.ok
1490
- } catch (err) {
1491
- return reportError(deps, err, { operation: 'agent_acknowledgement', request_id: requestId })
1492
- }
1493
- }
1494
-
1495
- /** Retire a question so a late answer is rejected rather than silently lost. */
1496
- export async function closeCommand(
1497
- deps: CommandDeps,
1498
- requestId: string | undefined,
1499
- flags: { json?: boolean; pending?: boolean } = {},
1500
- ): Promise<number> {
1501
- if (flags.pending === true && requestId !== undefined) {
1502
- deps.io.err('Pass a request id or --pending, not both.')
1503
- return EXIT.usage
1504
- }
1505
- if (flags.pending !== true && requestId === undefined) {
1506
- deps.io.err('Pass a request id or --pending.')
1507
- return EXIT.usage
1508
- }
1509
-
1510
- if (flags.pending === true) {
1511
- return closePendingQuestions(deps, flags.json === true)
1512
- }
1513
-
1514
- const local = await closeLocalQuestion(deps, requestId!, flags.json === true)
1515
- if (local !== null) return local
1516
-
1517
- const lifecycleSession = resolveCommandSession(deps, requestId!)
1518
- const config = loadLoggedConfig(deps, {
1519
- cwd: deps.cwd,
1520
- env: deps.env,
1521
- ...(lifecycleSession === null ? {} : { sessionId: lifecycleSession.sessionId }),
1522
- })
1523
- const authed = authedClient(deps, config)
1524
- if (!authed) return EXIT.auth
1525
- try {
1526
- const response = await authed.client.closeReplies(requestId!)
1527
- forgetClosedQuestion(deps, requestId!)
1528
- if (flags.json) {
1529
- deps.io.out(
1530
- JSON.stringify(
1531
- {
1532
- ...response,
1533
- acknowledgement_command: acknowledgementCommand(
1534
- response.request_id,
1535
- response.agent_acknowledgement_required,
1536
- response.agent_acknowledgement_text_required,
1537
- response.agent_acknowledgement,
1538
- response.replies.length > 0,
1539
- ),
1540
- },
1541
- null,
1542
- 2,
1543
- ),
1544
- )
1545
- } else {
1546
- deps.io.out(`Closed the reply window for ${requestId}.`)
1547
- if (response.replies.length > 0) printAcknowledgementStatus(deps, response)
1548
- }
1549
- return EXIT.ok
1550
- } catch (err) {
1551
- return reportError(deps, err)
1552
- }
1553
- }
1554
-
1555
- /**
1556
- * Retire this session's outstanding questions, including registrations the
1557
- * Stop hook has not pushed yet. Unpushed entries only exist locally: dropping
1558
- * them is the whole retirement. Live ones still need their reply window closed.
1559
- */
1560
- async function closePendingQuestions(deps: CommandDeps, json: boolean): Promise<number> {
1561
- const lifecycleSession = resolveCommandSession(deps)
1562
- if (lifecycleSession === null) {
1563
- deps.io.err('No active session pointer is available in this directory.')
1564
- return EXIT.noReply
1565
- }
1566
- const sessionId = lifecycleSession.sessionId
1567
- const pending = readSessionState(sessionId, deps.env).pending ?? []
1568
- if (pending.length === 0) {
1569
- if (json) {
1570
- deps.io.out(
1571
- JSON.stringify({ session_id: sessionId, withdrawn: [], closed: [] }, null, 2),
1572
- )
1573
- } else {
1574
- deps.io.err(`Session ${sessionId} has no registered question pending.`)
1575
- }
1576
- return EXIT.noReply
1577
- }
1578
-
1579
- const withdrawn = withdrawUnpushedQuestions(sessionId, deps.env)
1580
- const live = (readSessionState(sessionId, deps.env).pending ?? []).filter(
1581
- (entry): entry is PendingQuestion & { request_id: string } =>
1582
- entry.request_id !== undefined,
1583
- )
1584
-
1585
- const closed: string[] = []
1586
- if (live.length > 0) {
1587
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env, sessionId })
1588
- const authed = authedClient(deps, config)
1589
- if (!authed) return EXIT.auth
1590
- for (const entry of live) {
1591
- try {
1592
- await authed.client.closeReplies(entry.request_id)
1593
- parkClosedQuestion(sessionId, deps.env, entry)
1594
- dropPendingQuestion(sessionId, deps.env, entry)
1595
- closed.push(entry.request_id)
1596
- } catch (err) {
1597
- return reportError(deps, err, { operation: 'close', request_id: entry.request_id })
1598
- }
1599
- }
1600
- }
1601
-
1602
- const output = {
1603
- session_id: sessionId,
1604
- withdrawn: withdrawn.map((entry) => ({
1605
- question: entry.question,
1606
- ...(entry.question_id === undefined ? {} : { question_id: entry.question_id }),
1607
- })),
1608
- closed,
1609
- }
1610
- if (json) deps.io.out(JSON.stringify(output, null, 2))
1611
- else {
1612
- if (withdrawn.length > 0) {
1613
- deps.io.out(
1614
- withdrawn.length === 1
1615
- ? 'Withdrew 1 unpushed question so a later Stop will not send it.'
1616
- : `Withdrew ${withdrawn.length} unpushed questions so a later Stop will not send them.`,
1617
- )
1618
- }
1619
- for (const requestId of closed) {
1620
- deps.io.out(`Closed the reply window for ${requestId}.`)
1621
- }
1622
- }
1623
- return EXIT.ok
1624
- }
1625
-
1626
- /**
1627
- * Close one outstanding question by the stable id `notifai ask` returned, or
1628
- * by a request id already on a device. Unpushed entries only exist locally.
1629
- * Returns null when this directory's session has no matching registration, so
1630
- * the caller can still close a live request id against the service.
1631
- */
1632
- async function closeLocalQuestion(
1633
- deps: CommandDeps,
1634
- id: string,
1635
- json: boolean,
1636
- ): Promise<number | null> {
1637
- const lifecycleSession = resolveCommandSession(deps, id)
1638
- if (lifecycleSession === null) return null
1639
- const sessionId = lifecycleSession.sessionId
1640
- const entry = (readSessionState(sessionId, deps.env).pending ?? []).find(
1641
- (candidate) => candidate.question_id === id || candidate.request_id === id,
1642
- )
1643
- if (entry === undefined) return null
1644
-
1645
- if (entry.request_id === undefined) {
1646
- dropPendingQuestion(sessionId, deps.env, entry, 'withdrawn')
1647
- const output = {
1648
- session_id: sessionId,
1649
- withdrawn: [
1650
- {
1651
- question: entry.question,
1652
- ...(entry.question_id === undefined ? {} : { question_id: entry.question_id }),
1653
- },
1654
- ],
1655
- closed: [] as string[],
1656
- }
1657
- if (json) deps.io.out(JSON.stringify(output, null, 2))
1658
- else {
1659
- deps.io.out(
1660
- `Withdrew unpushed question ${entry.question_id ?? id} so a later Stop will not send it.`,
1661
- )
1662
- }
1663
- return EXIT.ok
1664
- }
1665
-
1666
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env, sessionId })
1667
- const authed = authedClient(deps, config)
1668
- if (!authed) return EXIT.auth
1669
- try {
1670
- const response = await authed.client.closeReplies(entry.request_id)
1671
- parkClosedQuestion(sessionId, deps.env, entry)
1672
- dropPendingQuestion(sessionId, deps.env, entry)
1673
- if (json) {
1674
- deps.io.out(
1675
- JSON.stringify(
1676
- {
1677
- ...response,
1678
- question_id: entry.question_id,
1679
- acknowledgement_command: acknowledgementCommand(
1680
- response.request_id,
1681
- response.agent_acknowledgement_required,
1682
- response.agent_acknowledgement_text_required,
1683
- response.agent_acknowledgement,
1684
- response.replies.length > 0,
1685
- ),
1686
- },
1687
- null,
1688
- 2,
1689
- ),
1690
- )
1691
- } else {
1692
- deps.io.out(`Closed the reply window for ${entry.request_id}.`)
1693
- if (response.replies.length > 0) printAcknowledgementStatus(deps, response)
1694
- }
1695
- return EXIT.ok
1696
- } catch (err) {
1697
- return reportError(deps, err, { operation: 'close', request_id: entry.request_id })
1698
- }
1699
- }
1700
-
1701
- function forgetClosedQuestion(deps: CommandDeps, requestId: string): void {
1702
- const lifecycleSession = resolveCommandSession(deps, requestId)
1703
- if (lifecycleSession === null) return
1704
- const sessionId = lifecycleSession.sessionId
1705
- const entry = (readSessionState(sessionId, deps.env).pending ?? []).find(
1706
- (candidate) => candidate.request_id === requestId,
1707
- )
1708
- if (entry === undefined) return
1709
- parkClosedQuestion(sessionId, deps.env, entry)
1710
- dropPendingQuestion(sessionId, deps.env, entry)
1711
- }
1712
-
1713
- function parkClosedQuestion(
1714
- sessionId: string,
1715
- env: NodeJS.ProcessEnv,
1716
- entry: PendingQuestion,
1717
- ): void {
1718
- try {
1719
- parkForRetirement(sessionId, env, entry, 'expired')
1720
- } catch {
1721
- // Incomplete identifiers cannot be retired on a device; dropping the
1722
- // local record is still the right way to stop a later Stop from waiting.
1723
- }
1724
- }
1725
-
1726
- export interface HooksInstallFlags {
1727
- harness?: string
1728
- global?: boolean
1729
- /** Init owns the final setup result and suppresses per-harness close narration. */
1730
- narrate?: boolean
1731
- /** Test seam; production resolves the running CLI. */
1732
- execPath?: string
1733
- scriptPath?: string
1734
- }
1735
-
1736
- /** True when this process is `npx` / `npm exec`, not a global or linked install. */
1737
- export function runningViaNpx(env: NodeJS.ProcessEnv, scriptPath: string): boolean {
1738
- if (env['npm_command'] === 'exec') return true
1739
- return scriptPath.includes(`${path.sep}_npx${path.sep}`)
1740
- }
1741
-
1742
- function fileHookInstallTarget(
1743
- target: HookAdapterTarget | undefined,
1744
- ): { execPath: string; scriptPath: string } | undefined {
1745
- if (target === undefined || isNpxAdapterTarget(target)) return undefined
1746
- return target
1747
- }
1748
-
1749
- function resolveHookAdapterTarget(deps: CommandDeps, flags: HooksInstallFlags): HookAdapterTarget {
1750
- if (deps.hookInstallTarget !== undefined && isNpxAdapterTarget(deps.hookInstallTarget)) {
1751
- return deps.hookInstallTarget
1752
- }
1753
- const fileTarget = fileHookInstallTarget(deps.hookInstallTarget)
1754
- const execPath = flags.execPath ?? fileTarget?.execPath ?? process.execPath
1755
- const scriptPath = flags.scriptPath ?? fileTarget?.scriptPath ?? process.argv[1] ?? 'notifai'
1756
- if (runningViaNpx(deps.env, scriptPath)) {
1757
- const version = packageVersion()
1758
- const npmCli = deps.env['npm_execpath']
1759
- if (version === null) {
1760
- throw new Error(
1761
- 'Could not read this CLI version, so an npx hook target cannot be pinned. Install `@raidiant/notifai` globally and rerun `notifai hooks install`.',
1762
- )
1763
- }
1764
- if (typeof npmCli !== 'string' || npmCli === '') {
1765
- throw new Error(
1766
- 'This process looks like npx but npm_execpath is missing. Install `@raidiant/notifai` globally and rerun `notifai hooks install`.',
1767
- )
1768
- }
1769
- return { kind: 'npx', execPath, npmCli, spec: `@raidiant/notifai@${version}` }
1770
- }
1771
- return { execPath, scriptPath }
1772
- }
1773
-
1774
- function printHooksInstallClose(deps: CommandDeps, harness: HookInstallableHarness, file: string): void {
1775
- const label = HARNESS_LABELS[harness]
1776
- const activation =
1777
- harness === 'codex'
1778
- ? 'Approve the Notifai handlers in `/hooks` if Codex asks, then start one fresh Codex session, send one prompt, and run `notifai doctor`.'
1779
- : harness === 'cursor'
1780
- ? 'Start one fresh Cursor conversation, send one prompt, finish its first turn, then run `notifai doctor`.'
1781
- : harness === 'opencode'
1782
- ? 'Restart OpenCode, start one fresh session, send one prompt, then run `notifai doctor`.'
1783
- : harness === 'openclaw'
1784
- ? 'Restart the OpenClaw Gateway, start one fresh Agent Session, send one prompt, then run `notifai doctor`.'
1785
- : `Start one fresh ${label} session, send one prompt, then run \`notifai doctor\`.`
1786
- if (deps.io.interactive === true && deps.io.note) {
1787
- void deps.io.note(`${file}\n${activation}`, `${label} hooks installed`)
1788
- return
1789
- }
1790
- deps.io.out(`Installed ${harness} hooks in ${file}`)
1791
- deps.io.out(activation)
1792
- }
1793
-
1794
- export function hooksInstallCommand(deps: CommandDeps, flags: HooksInstallFlags): number {
1795
- if (flags.harness === undefined) {
1796
- const detected = detectedHarnesses(deps.cwd, deps.env)
1797
- if (detected.length === 0) {
1798
- deps.io.err(`Could not tell which harness you mean — pass --harness <${HOOK_INSTALLABLE_HARNESSES.join('|')}>.`)
1799
- return EXIT.usage
1800
- }
1801
- let ok = true
1802
- for (const harness of detected) {
1803
- if (hooksInstallCommand(deps, { ...flags, harness }) !== EXIT.ok) ok = false
1804
- }
1805
- return ok ? EXIT.ok : EXIT.failed
1806
- }
1807
- const harness = resolveHarness(deps, flags.harness)
1808
- if (!harness) return EXIT.usage
1809
- const adapterTarget = resolveHookAdapterTarget(deps, flags)
1810
- const scriptPath =
1811
- flags.scriptPath ?? fileHookInstallTarget(adapterTarget)?.scriptPath ?? process.argv[1] ?? 'notifai'
1812
- const hookPlatform = deps.hookPlatform ?? process.platform
1813
- const nodePath = adapterTarget.execPath
1814
- let adapterPath: string
1815
- try {
1816
- adapterPath = installHookAdapter(adapterTarget, deps.hookAdapterHome, hookPlatform).path
1817
- } catch (err) {
1818
- deps.io.err(`Could not prepare the stable hook adapter: ${String(err)}`)
1819
- return EXIT.failed
1820
- }
1821
- const wantGlobal = flags.global === true
1822
- const existing = findInstallations(deps.cwd, deps.env, deps.hookAdapterHome, deps.hookPlatform).filter(
1823
- (installation) => installation.harness === harness,
1824
- )
1825
- const otherScope = existing.filter((installation) => installation.global !== wantGlobal)
1826
- if (!wantGlobal && otherScope.some((installation) => installation.global)) {
1827
- const globalInstallations = otherScope.filter((installation) => installation.global)
1828
- const globalInstallation = globalInstallations[0]
1829
- const installedEvents = new Set(
1830
- globalInstallation?.handlers
1831
- .map((handler) => handlerEvent(handler.command))
1832
- .filter((event): event is HookEvent =>
1833
- event !== null && (HOOK_EVENTS as readonly string[]).includes(event),
1834
- ) ?? [],
1835
- )
1836
- if (
1837
- globalInstallations.length !== 1 ||
1838
- globalInstallations.some((installation) => (installation.problems?.length ?? 0) > 0) ||
1839
- globalInstallations.some(
1840
- (installation) => stopShapeProblems(installation, deps.hookPlatform).length > 0,
1841
- ) ||
1842
- !requiredHookEvents(harness).every((event) => installedEvents.has(event))
1843
- ) {
1844
- return hooksInstallCommand(deps, { ...flags, global: true, harness })
1845
- }
1846
- const globalFile = globalInstallation?.file
1847
- if (flags.narrate !== false) {
1848
- deps.io.out(
1849
- `${HARNESS_LABELS[harness]} hooks already cover this machine (${globalFile}). This project does not need its own copy. To wire only this project: notifai hooks uninstall --harness ${harness} --global && notifai hooks install --harness ${harness}`,
1850
- )
1851
- }
1852
- return EXIT.ok
1853
- }
1854
- if (wantGlobal && otherScope.some((installation) => !installation.global)) {
1855
- if (hooksUninstallCommand(deps, { ...flags, global: false, harness }) !== EXIT.ok) {
1856
- return EXIT.failed
1857
- }
1858
- }
1859
- const codexPaths =
1860
- harness === 'codex'
1861
- ? codexLayerPaths(wantGlobal, deps.cwd, deps.env, hookPlatform)
1862
- : null
1863
- const settingsTarget =
1864
- codexPaths?.configToml ?? settingsFile(harness, wantGlobal, deps.cwd, deps.env, hookPlatform)
1865
-
1866
- // OpenCode's adapter is a generated plugin module rather than a handler
1867
- // merged into a settings document, so it owns the whole file.
1868
- if (harness === 'opencode') {
1869
- return installOpencodePlugin(deps, settingsTarget, {
1870
- adapterPath,
1871
- timeoutSeconds: NON_ROUTING_BLOCKING_STOP_TIMEOUT_SECONDS,
1872
- platform: hookPlatform,
1873
- nodePath,
1874
- ...(flags.narrate === undefined ? {} : { narrate: flags.narrate }),
1875
- })
1876
- }
1877
- if (harness === 'openclaw') {
1878
- return installOpenclawPlugin(deps, settingsTarget, {
1879
- adapterPath,
1880
- timeoutSeconds: NON_ROUTING_BLOCKING_STOP_TIMEOUT_SECONDS,
1881
- platform: hookPlatform,
1882
- nodePath,
1883
- global: wantGlobal,
1884
- ...(flags.narrate === undefined ? {} : { narrate: flags.narrate }),
1885
- })
1886
- }
1887
-
1888
- if (harness === 'cursor') {
1889
- try {
1890
- withTargetFileLock(settingsTarget, () => {
1891
- const document = loadCursorSettings(settingsTarget)
1892
- const result = mergeCursorHooks(
1893
- document,
1894
- buildCursorHookConfig({
1895
- adapterPath,
1896
- harness: 'cursor',
1897
- platform: hookPlatform,
1898
- nodePath,
1899
- }),
1900
- scriptPath,
1901
- )
1902
- applyPlan(settingsTarget, result.document)
1903
- return result
1904
- })
1905
- } catch (err) {
1906
- deps.io.err(String(err))
1907
- return EXIT.failed
1908
- }
1909
- if (flags.narrate !== false) printHooksInstallClose(deps, harness, settingsTarget)
1910
- return EXIT.ok
1911
- }
1912
-
1913
- const installInto = (file: string): { file: string; foreignStopCount: number } => {
1914
- const document = loadSettings(file)
1915
- const foreignStopCount = foreignStopHandlers(document).length
1916
- const result = mergeHooks(
1917
- document,
1918
- buildHookConfig({
1919
- adapterPath,
1920
- harness,
1921
- platform: hookPlatform,
1922
- nodePath,
1923
- }),
1924
- scriptPath,
1925
- )
1926
- applyPlan(file, result.document)
1927
- return { file, foreignStopCount }
1928
- }
1929
-
1930
- let installed: { file: string; foreignStopCount: number }
1931
- try {
1932
- installed =
1933
- codexPaths === null
1934
- ? withTargetFileLock(settingsTarget, () => installInto(settingsTarget))
1935
- : withCodexLayerTransaction(codexPaths, (inspection) => {
1936
- const staleTarget =
1937
- inspection.writeTarget === inspection.paths.hooksJson
1938
- ? inspection.paths.configToml
1939
- : inspection.paths.hooksJson
1940
- const staleEvents =
1941
- staleTarget === inspection.paths.hooksJson
1942
- ? inspection.ourJsonEvents
1943
- : inspection.ourTomlEvents
1944
- if (staleEvents.length > 0) {
1945
- const staleDocument = loadSettings(staleTarget)
1946
- const stripped = removeHooks(staleDocument, scriptPath)
1947
- if (stripped.replaced.length > 0) applyPlan(staleTarget, stripped.document)
1948
- }
1949
- return installInto(inspection.writeTarget)
1950
- })
1951
- } catch (err) {
1952
- deps.io.err(String(err))
1953
- return EXIT.failed
1954
- }
1955
-
1956
- if (harness === 'codex') {
1957
- const layer = flags.global ? null : codexLayerDir(deps.cwd)
1958
- if (layer !== null) mkdirSync(layer, { recursive: true })
1959
- }
1960
- if (flags.narrate !== false) printHooksInstallClose(deps, harness, installed.file)
1961
- if (installed.foreignStopCount > 0) {
1962
- deps.io.out(
1963
- "This layer already has a Stop handler. Codex runs every matching handler, so Notifai's Stop and the existing one will both fire.",
1964
- )
1965
- }
1966
- if (harness === 'codex') {
1967
- for (const problem of codexRepresentationProblems(deps.cwd, deps.env, hookPlatform)) {
1968
- deps.io.out(problem)
1969
- }
1970
- for (const note of codexCoexistenceNotes(deps.cwd, deps.env, hookPlatform)) {
1971
- deps.io.out(note)
1972
- }
1973
- if (flags.global) {
1974
- const home = codexHomeNote(deps.env, hookPlatform)
1975
- if (home !== null) deps.io.out(home)
1976
- }
1977
- }
1978
- return EXIT.ok
1979
- }
1980
-
1981
- function foreignStopHandlers(document: { hooks?: Record<string, { hooks?: { command: string }[] }[]> }): { command: string }[] {
1982
- const groups = document.hooks?.['Stop']
1983
- if (!Array.isArray(groups)) return []
1984
- return groups
1985
- .flatMap((group) => group.hooks ?? [])
1986
- .filter(
1987
- (handler) =>
1988
- !/ hook (session-start|subagent-start|activation-stop|user-prompt-submit|stop|session-end)\b/.test(
1989
- handler.command,
1990
- ),
1991
- )
1992
- }
1993
-
1994
- /**
1995
- * Writes the OpenCode plugin, replacing any Notifai plugin already there —
1996
- * including one a different checkout wrote, matched on the managed marker for
1997
- * the same reason command hooks are.
1998
- */
1999
- function installOpencodePlugin(
2000
- deps: CommandDeps,
2001
- file: string,
2002
- options: {
2003
- adapterPath: string
2004
- timeoutSeconds: number
2005
- platform?: NodeJS.Platform
2006
- nodePath?: string
2007
- narrate?: boolean
2008
- },
2009
- ): number {
2010
- try {
2011
- withTargetFileLock(file, () => {
2012
- if (existsSync(file)) {
2013
- assertOwnedRegularFile(file)
2014
- const existing = readFileSync(file, 'utf8')
2015
- if (!isOurOpencodePlugin(existing)) {
2016
- throw new Error(`${file} exists and was not written by Notifai; move it aside first.`)
2017
- }
2018
- }
2019
- atomicWriteFileSync(file, opencodePluginSource(options), {
2020
- mode: 0o600,
2021
- preserveMode: false,
2022
- requireCurrentUserOwner: true,
2023
- })
2024
- })
2025
- } catch (err) {
2026
- deps.io.err(String(err))
2027
- return EXIT.failed
2028
- }
2029
- if (options.narrate !== false) printHooksInstallClose(deps, 'opencode', file)
2030
- return EXIT.ok
2031
- }
2032
-
2033
- function installOpenclawPlugin(
2034
- deps: CommandDeps,
2035
- file: string,
2036
- options: {
2037
- adapterPath: string
2038
- timeoutSeconds: number
2039
- platform?: NodeJS.Platform
2040
- nodePath?: string
2041
- global: boolean
2042
- narrate?: boolean
2043
- },
2044
- ): number {
2045
- const pluginDir = path.dirname(file)
2046
- try {
2047
- withTargetFileLock(file, () => {
2048
- if (existsSync(file)) {
2049
- assertOwnedRegularFile(file)
2050
- const existing = readFileSync(file, 'utf8')
2051
- if (!isOurOpenclawPlugin(existing)) {
2052
- throw new Error(`${file} exists and was not written by Notifai; move it aside first.`)
2053
- }
2054
- }
2055
- atomicWriteFileSync(file, openclawPluginSource(options), {
2056
- mode: 0o600,
2057
- preserveMode: false,
2058
- requireCurrentUserOwner: true,
2059
- })
2060
- atomicWriteFileSync(path.join(pluginDir, OPENCLAW_PLUGIN_MANIFEST), openclawPluginManifest(), {
2061
- mode: 0o600,
2062
- preserveMode: false,
2063
- requireCurrentUserOwner: true,
2064
- })
2065
- atomicWriteFileSync(path.join(pluginDir, OPENCLAW_PLUGIN_PACKAGE), openclawPluginPackage(), {
2066
- mode: 0o600,
2067
- preserveMode: false,
2068
- requireCurrentUserOwner: true,
2069
- })
2070
- })
2071
- writeOpenclawEnablement(deps, pluginDir, options.global)
2072
- } catch (err) {
2073
- deps.io.err(String(err))
2074
- return EXIT.failed
2075
- }
2076
- if (options.narrate !== false) printHooksInstallClose(deps, 'openclaw', file)
2077
- return EXIT.ok
2078
- }
2079
-
2080
- function writeOpenclawEnablement(deps: CommandDeps, pluginDir: string, global: boolean): void {
2081
- const configFile = openclawConfigPath(deps.env, deps.hookPlatform)
2082
- withTargetFileLock(configFile, () => {
2083
- let config: Record<string, unknown> = {}
2084
- if (existsSync(configFile)) {
2085
- assertOwnedRegularFile(configFile)
2086
- config = parseOpenclawConfig(readFileSync(configFile, 'utf8'))
2087
- }
2088
- const merged = mergeOpenclawNotifaiEntry(config, pluginDir, global)
2089
- atomicWriteFileSync(configFile, `${JSON.stringify(merged, null, 2)}\n`, {
2090
- mode: 0o600,
2091
- preserveMode: true,
2092
- requireCurrentUserOwner: true,
2093
- })
2094
- })
2095
- }
2096
-
2097
- function uninstallOpenclawPlugin(deps: CommandDeps, file: string): number {
2098
- const pluginDir = path.dirname(file)
2099
- try {
2100
- const removed = withTargetFileLock(file, () => {
2101
- if (!existsSync(file)) return false
2102
- assertOwnedRegularFile(file)
2103
- if (!isOurOpenclawPlugin(readFileSync(file, 'utf8'))) {
2104
- deps.io.out(`Left ${file} alone: Notifai did not write it.`)
2105
- return false
2106
- }
2107
- rmSync(file, { force: true })
2108
- rmSync(path.join(pluginDir, OPENCLAW_PLUGIN_MANIFEST), { force: true })
2109
- rmSync(path.join(pluginDir, OPENCLAW_PLUGIN_PACKAGE), { force: true })
2110
- if (existsSync(pluginDir) && readdirSync(pluginDir).length === 0) {
2111
- rmdirSync(pluginDir)
2112
- }
2113
- return true
2114
- })
2115
- if (removed) {
2116
- const configFile = openclawConfigPath(deps.env, deps.hookPlatform)
2117
- if (existsSync(configFile)) {
2118
- withTargetFileLock(configFile, () => {
2119
- assertOwnedRegularFile(configFile)
2120
- const config = parseOpenclawConfig(readFileSync(configFile, 'utf8'))
2121
- const next = removeOpenclawNotifaiEntry(config, pluginDir)
2122
- atomicWriteFileSync(configFile, `${JSON.stringify(next, null, 2)}\n`, {
2123
- mode: 0o600,
2124
- preserveMode: true,
2125
- requireCurrentUserOwner: true,
2126
- })
2127
- })
2128
- }
2129
- deps.io.out(`Removed the Notifai OpenClaw plugin at ${file}`)
2130
- } else if (!existsSync(file)) {
2131
- deps.io.out(`Nothing to remove: ${file} does not exist.`)
2132
- }
2133
- return EXIT.ok
2134
- } catch (err) {
2135
- deps.io.err(String(err))
2136
- return EXIT.failed
2137
- }
2138
- }
2139
-
2140
- export function hooksUninstallCommand(deps: CommandDeps, flags: HooksInstallFlags): number {
2141
- const harness = resolveHarness(deps, flags.harness)
2142
- if (!harness) return EXIT.usage
2143
- const scriptPath = flags.scriptPath ?? process.argv[1] ?? 'notifai'
2144
- const global = flags.global ?? false
2145
- const codexPaths =
2146
- harness === 'codex'
2147
- ? codexLayerPaths(global, deps.cwd, deps.env, deps.hookPlatform)
2148
- : null
2149
- const file =
2150
- codexPaths?.configToml ?? settingsFile(harness, global, deps.cwd, deps.env, deps.hookPlatform)
2151
- if (harness === 'opencode') {
2152
- try {
2153
- return withTargetFileLock(file, () => {
2154
- if (!existsSync(file)) {
2155
- deps.io.out(`Nothing to remove: ${file} does not exist.`)
2156
- return EXIT.ok
2157
- }
2158
- assertOwnedRegularFile(file)
2159
- // We own the whole file, but only if we wrote it.
2160
- if (!isOurOpencodePlugin(readFileSync(file, 'utf8'))) {
2161
- deps.io.out(`Left ${file} alone: Notifai did not write it.`)
2162
- return EXIT.ok
2163
- }
2164
- rmSync(file, { force: true })
2165
- deps.io.out(`Removed the Notifai OpenCode plugin at ${file}`)
2166
- return EXIT.ok
2167
- })
2168
- } catch (err) {
2169
- deps.io.err(String(err))
2170
- return EXIT.failed
2171
- }
2172
- }
2173
- if (harness === 'openclaw') {
2174
- return uninstallOpenclawPlugin(deps, file)
2175
- }
2176
- if (harness === 'cursor') {
2177
- let stripped: ReturnType<typeof removeCursorHooks> | null
2178
- try {
2179
- stripped = withTargetFileLock(file, () => {
2180
- if (!existsSync(file)) return null
2181
- const document = loadCursorSettings(file)
2182
- const result = removeCursorHooks(document, scriptPath)
2183
- applyPlan(file, result.document)
2184
- return result
2185
- })
2186
- } catch (err) {
2187
- deps.io.err(String(err))
2188
- return EXIT.failed
2189
- }
2190
- if (stripped === null) {
2191
- deps.io.out(`Nothing to remove: ${file} does not exist.`)
2192
- return EXIT.ok
2193
- }
2194
- deps.io.out(
2195
- stripped.replaced.length > 0
2196
- ? `Removed Notifai hooks (${stripped.replaced.join(', ')}) from ${file}`
2197
- : `No Notifai hooks found in ${file}`,
2198
- )
2199
- return EXIT.ok
2200
- }
2201
- const removeInstalledHooks = (): { existing: string[]; removedAny: boolean } => {
2202
- const files =
2203
- codexPaths === null
2204
- ? hookDefinitionFiles(harness, global, deps.cwd, deps.env, deps.hookPlatform)
2205
- : [codexPaths.hooksJson, codexPaths.configToml]
2206
- const existing = files.filter((candidate) => existsSync(candidate))
2207
- let removedAny = false
2208
- for (const candidate of existing) {
2209
- const removeFromCandidate = () => {
2210
- const document = loadSettings(candidate)
2211
- const result = removeHooks(document, scriptPath)
2212
- if (result.replaced.length > 0) applyPlan(candidate, result.document)
2213
- return result
2214
- }
2215
- const stripped =
2216
- codexPaths === null
2217
- ? withTargetFileLock(candidate, removeFromCandidate)
2218
- : removeFromCandidate()
2219
- if (stripped.replaced.length > 0) {
2220
- removedAny = true
2221
- deps.io.out(`Removed Notifai hooks (${stripped.replaced.join(', ')}) from ${candidate}`)
2222
- }
2223
- }
2224
- return { existing, removedAny }
2225
- }
2226
-
2227
- let result: { existing: string[]; removedAny: boolean }
2228
- try {
2229
- result =
2230
- codexPaths === null
2231
- ? removeInstalledHooks()
2232
- : withCodexLayerTransaction(codexPaths, (inspection) => {
2233
- const stripped = removeInstalledHooks()
2234
- cleanupEmptiedCodexLayer(inspection.paths)
2235
- return stripped
2236
- })
2237
- } catch (err) {
2238
- deps.io.err(String(err))
2239
- return EXIT.failed
2240
- }
2241
- if (result.existing.length === 0) {
2242
- deps.io.out(`Nothing to remove: ${file} does not exist.`)
2243
- return EXIT.ok
2244
- }
2245
- if (!result.removedAny) {
2246
- deps.io.out(`No Notifai hooks found in ${result.existing.join(', ')}`)
2247
- }
2248
- return EXIT.ok
2249
- }
2250
-
2251
- function assertOwnedRegularFile(file: string): void {
2252
- const stat = lstatSync(file)
2253
- if (stat.isSymbolicLink() || !stat.isFile()) {
2254
- throw new Error(`${file} is not a regular file; refusing to read or replace it.`)
2255
- }
2256
- const uid = typeof process.getuid === 'function' ? process.getuid() : undefined
2257
- if (uid !== undefined && stat.uid !== uid) {
2258
- throw new Error(`${file} is owned by uid ${stat.uid}, not the current user.`)
2259
- }
2260
- }
2261
-
2262
- function resolveHarness(deps: CommandDeps, requested: string | undefined): HookInstallableHarness | null {
2263
- if (requested !== undefined) {
2264
- if ((HOOK_INSTALLABLE_HARNESSES as readonly string[]).includes(requested)) return requested as HookInstallableHarness
2265
- deps.io.err(
2266
- `Unknown harness "${requested}". Supported: ${HOOK_INSTALLABLE_HARNESSES.join(', ')}.`,
2267
- )
2268
- return null
2269
- }
2270
- const detected = detectHarness(deps.cwd, deps.env)
2271
- if (!detected) {
2272
- deps.io.err(`Could not tell which harness to install for — pass --harness <${HOOK_INSTALLABLE_HARNESSES.join('|')}>.`)
2273
- return null
2274
- }
2275
- return detected
2276
- }
2277
-
2278
- /**
2279
- * Which harnesses to wire. An explicit `--harness` still wins as a singleton.
2280
- * Otherwise: every detected harness, or a human picker when detection is empty
2281
- * or names more than one.
2282
- */
2283
- export async function pickHarnessesToInstall(
2284
- deps: CommandDeps,
2285
- requested?: string,
2286
- ): Promise<HookInstallableHarness[] | null> {
2287
- if (requested !== undefined) {
2288
- const harness = resolveHarness(deps, requested)
2289
- return harness === null ? null : [harness]
2290
- }
2291
- const detected = detectedHarnesses(deps.cwd, deps.env)
2292
- if (detected.length === 1) return detected
2293
- if (deps.io.interactive === true && deps.io.multiselect) {
2294
- const picked = await deps.io.multiselect(
2295
- 'Which agent harnesses should Notifai wire here?',
2296
- HOOK_INSTALLABLE_HARNESSES.map((name) => ({
2297
- value: name,
2298
- label: HARNESS_LABELS[name],
2299
- ...(detected.includes(name) ? { hint: 'detected on this machine' } : {}),
2300
- })),
2301
- detected,
2302
- )
2303
- if (picked === null) return null
2304
- const unknown = picked.filter((name) => !(HOOK_INSTALLABLE_HARNESSES as readonly string[]).includes(name))
2305
- if (unknown.length > 0) {
2306
- deps.io.err(`Unknown harness "${unknown[0]}". Supported: ${HOOK_INSTALLABLE_HARNESSES.join(', ')}.`)
2307
- return null
2308
- }
2309
- return picked as HookInstallableHarness[]
2310
- }
2311
- if (detected.length === 0) {
2312
- deps.io.err(
2313
- `Could not tell which harness to wire. Run: notifai hooks install --harness <${HOOK_INSTALLABLE_HARNESSES.join('|')}>`,
2314
- )
2315
- return null
2316
- }
2317
- return detected
2318
- }