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