@raidiant/notifai 5.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +2 -2
  3. package/dist/atomic-file.js +13 -0
  4. package/dist/atomic-file.js.map +1 -1
  5. package/dist/client.d.ts +8 -3
  6. package/dist/client.js +24 -3
  7. package/dist/client.js.map +1 -1
  8. package/dist/commands-auth.d.ts +14 -0
  9. package/dist/commands-auth.js +154 -0
  10. package/dist/commands-auth.js.map +1 -0
  11. package/dist/commands-config.d.ts +31 -0
  12. package/dist/commands-config.js +246 -0
  13. package/dist/commands-config.js.map +1 -0
  14. package/dist/commands-core.d.ts +102 -0
  15. package/dist/commands-core.js +135 -0
  16. package/dist/commands-core.js.map +1 -0
  17. package/dist/commands-devices.d.ts +31 -0
  18. package/dist/commands-devices.js +124 -0
  19. package/dist/commands-devices.js.map +1 -0
  20. package/dist/commands-doctor.d.ts +24 -0
  21. package/dist/commands-doctor.js +1011 -0
  22. package/dist/commands-doctor.js.map +1 -0
  23. package/dist/commands-harness-context.d.ts +65 -0
  24. package/dist/commands-harness-context.js +97 -0
  25. package/dist/commands-harness-context.js.map +1 -0
  26. package/dist/commands-hook-shape.d.ts +17 -0
  27. package/dist/commands-hook-shape.js +37 -0
  28. package/dist/commands-hook-shape.js.map +1 -0
  29. package/dist/commands-hooks.d.ts +115 -0
  30. package/dist/commands-hooks.js +1225 -0
  31. package/dist/commands-hooks.js.map +1 -0
  32. package/dist/commands-init.d.ts +35 -0
  33. package/dist/commands-init.js +580 -0
  34. package/dist/commands-init.js.map +1 -0
  35. package/dist/commands-io.d.ts +2 -0
  36. package/dist/commands-io.js +110 -0
  37. package/dist/commands-io.js.map +1 -0
  38. package/dist/commands-logs.d.ts +30 -0
  39. package/dist/commands-logs.js +201 -0
  40. package/dist/commands-logs.js.map +1 -0
  41. package/dist/commands-send-support.d.ts +44 -0
  42. package/dist/commands-send-support.js +183 -0
  43. package/dist/commands-send-support.js.map +1 -0
  44. package/dist/commands-send.d.ts +33 -0
  45. package/dist/commands-send.js +519 -0
  46. package/dist/commands-send.js.map +1 -0
  47. package/dist/commands-setup-proof.d.ts +15 -0
  48. package/dist/commands-setup-proof.js +53 -0
  49. package/dist/commands-setup-proof.js.map +1 -0
  50. package/dist/commands-skill.d.ts +10 -0
  51. package/dist/commands-skill.js +71 -0
  52. package/dist/commands-skill.js.map +1 -0
  53. package/dist/commands.d.ts +12 -387
  54. package/dist/commands.js +12 -4536
  55. package/dist/commands.js.map +1 -1
  56. package/dist/config-schema.js +1 -1
  57. package/dist/config-schema.js.map +1 -1
  58. package/dist/config.d.ts +4 -4
  59. package/dist/config.js +6 -4
  60. package/dist/config.js.map +1 -1
  61. package/dist/credentials.js +13 -3
  62. package/dist/credentials.js.map +1 -1
  63. package/dist/generated-session-label.d.ts +2 -0
  64. package/dist/generated-session-label.js +152 -0
  65. package/dist/generated-session-label.js.map +1 -0
  66. package/dist/hooks.d.ts +2 -2
  67. package/dist/hooks.js +127 -99
  68. package/dist/hooks.js.map +1 -1
  69. package/dist/interactive.js +4 -4
  70. package/dist/interactive.js.map +1 -1
  71. package/dist/invocation-context.d.ts +3 -0
  72. package/dist/invocation-context.js +23 -6
  73. package/dist/invocation-context.js.map +1 -1
  74. package/dist/logging.js +1 -0
  75. package/dist/logging.js.map +1 -1
  76. package/dist/main.js +3 -3
  77. package/dist/main.js.map +1 -1
  78. package/dist/opencode-plugin.js +18 -3
  79. package/dist/opencode-plugin.js.map +1 -1
  80. package/dist/readiness.d.ts +3 -1
  81. package/dist/readiness.js.map +1 -1
  82. package/dist/session-labels.d.ts +30 -0
  83. package/dist/session-labels.js +278 -0
  84. package/dist/session-labels.js.map +1 -0
  85. package/package.json +2 -2
  86. package/src/atomic-file.ts +12 -0
  87. package/src/client.test.ts +90 -1
  88. package/src/client.ts +35 -2
  89. package/src/commands-auth.ts +174 -0
  90. package/src/commands-config.ts +307 -0
  91. package/src/commands-core.ts +240 -0
  92. package/src/commands-devices.ts +150 -0
  93. package/src/commands-doctor.ts +1209 -0
  94. package/src/commands-harness-context.ts +134 -0
  95. package/src/commands-hook-shape.ts +53 -0
  96. package/src/commands-hooks.ts +1586 -0
  97. package/src/commands-init.ts +721 -0
  98. package/src/commands-io.ts +108 -0
  99. package/src/commands-logs.ts +243 -0
  100. package/src/commands-send-support.ts +227 -0
  101. package/src/commands-send.ts +623 -0
  102. package/src/commands-setup-proof.ts +71 -0
  103. package/src/commands-skill.ts +84 -0
  104. package/src/commands.test.ts +567 -42
  105. package/src/commands.ts +58 -5614
  106. package/src/config-schema.ts +1 -1
  107. package/src/config.test.ts +9 -0
  108. package/src/config.ts +10 -5
  109. package/src/credentials.test.ts +25 -1
  110. package/src/credentials.ts +13 -3
  111. package/src/generated-session-label.ts +155 -0
  112. package/src/hooks.test.ts +355 -16
  113. package/src/hooks.ts +145 -97
  114. package/src/install-hooks.test.ts +84 -1
  115. package/src/interactive.test.ts +19 -1
  116. package/src/interactive.ts +4 -4
  117. package/src/invocation-context.test.ts +115 -16
  118. package/src/invocation-context.ts +32 -11
  119. package/src/logging.test.ts +15 -2
  120. package/src/logging.ts +1 -0
  121. package/src/main.ts +9 -3
  122. package/src/opencode-plugin.ts +18 -3
  123. package/src/readiness.ts +3 -1
  124. package/src/session-labels.test.ts +303 -0
  125. package/src/session-labels.ts +360 -0
  126. package/src/skill.test.ts +13 -0
@@ -0,0 +1,1225 @@
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, 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_CAPABILITIES, HARNESS_LABELS } from './harnesses.js';
11
+ import { inspectHookAdapter, installHookAdapter, isNpxAdapterTarget, } from './hook-adapter.js';
12
+ import { clearAcknowledgementObligation, handleSessionEnd, handleStop, handleUserPromptSubmit, parseHookInput, pruneAbandonedSessions, readMatchingProjectSessionPointer, readProjectSession, readSessionState, registerQuestion, waiterCeilingSeconds, } from './hooks.js';
13
+ import { BLOCKING_STOP_TIMEOUT_SECONDS, HARNESSES, applyPlan, buildCursorHookConfig, buildHookConfig, codexCoexistenceNotes, codexHomeNote, codexLayerDir, codexLayerPaths, codexRepresentationProblems, codexTrustProblems, detectHarness, detectedHarnesses, findInstallations, handlerEvent, hookDefinitionFiles, loadCursorSettings, loadSettings, mergeCursorHooks, mergeHooks, removeCursorHooks, removeHooks, settingsFile, stopHandlerIsDetached, withCodexLayerTransaction, } from './install-hooks.js';
14
+ import { logConfigResolved, logSettingsFrom } from './logging.js';
15
+ import { isOurOpencodePlugin, opencodePluginSource } from './opencode-plugin.js';
16
+ import { packageVersion } from './release.js';
17
+ import { CHOICE_USAGE, buildDraft, parseChoices, slugify, validateMediaInputs, } from './send.js';
18
+ import { EXIT, authedClient, loadLoggedConfig, log, makeClient, rejectedPaths, reportError, } from './commands-core.js';
19
+ import { claudeSessionPid, resolveActiveHarness, } from './commands-harness-context.js';
20
+ import { stopShapeProblems } from './commands-hook-shape.js';
21
+ import { acknowledgementCommand, printAcknowledgementStatus, resolveDraftInvocation, uploadImage, waitForReply, } from './commands-send-support.js';
22
+ // ---------------------------------------------------------------------------
23
+ // hook / ask / close — harness integration
24
+ // ---------------------------------------------------------------------------
25
+ export const HOOK_EVENTS = ['user-prompt-submit', 'stop', 'session-end'];
26
+ /** SessionEnd cleanup must precede every diagnostic that can wait on a file lock. */
27
+ export function hookDefersDiagnosticsUntilAfterCleanup(event) {
28
+ return event === 'session-end';
29
+ }
30
+ /**
31
+ * Runs one harness hook. Contract with every harness: hook JSON arrives on
32
+ * stdin, the decision (if any) goes to stdout, diagnostics go to stderr, and
33
+ * exit 0 with no stdout means "no decision — carry on as normal".
34
+ *
35
+ * Every failure path in here must reach that no-decision state. A hook that
36
+ * throws, or that blocks past the harness's timeout, degrades the agent for a
37
+ * feature the user only asked to make it more convenient.
38
+ */
39
+ export async function hookRunCommand(deps, event, readStdin, harness) {
40
+ if (!HOOK_EVENTS.includes(event)) {
41
+ deps.io.err(`Unknown hook event "${event}". Valid: ${HOOK_EVENTS.join(', ')}`);
42
+ return EXIT.usage;
43
+ }
44
+ // One clock owns the complete Stop invocation, including stdin, config,
45
+ // credentials, and client construction. Starting this inside `handleStop`
46
+ // would grant slow setup a second budget and let the harness kill us before
47
+ // an accepted answer is journaled or written to stdout.
48
+ const now = deps.now ?? Date.now;
49
+ // The waiter may spend a long wall clock exactly when no turn is held open
50
+ // for it, which is the same condition the installer used to declare
51
+ // `async: true`. One predicate decides it for both.
52
+ const detachedWaiter = stopHandlerIsDetached(harness, deps.hookPlatform ?? process.platform);
53
+ const processDeadlineAt = now() + waiterCeilingSeconds(detachedWaiter) * 1000;
54
+ const logger = log(deps);
55
+ logger.bind({ cmd: `hook ${event}` });
56
+ let started = false;
57
+ const start = (data = {}) => {
58
+ if (started)
59
+ return;
60
+ started = true;
61
+ logger.info('hook.start', { hook: event, harness: harness ?? 'unknown', ...data });
62
+ };
63
+ const failureData = (err) => err instanceof ApiCallError
64
+ ? { status: err.status, code: err.code, message: err.message, details: err.details }
65
+ : { message: err instanceof Error ? err.message : String(err) };
66
+ let raw;
67
+ try {
68
+ raw = await readStdin();
69
+ }
70
+ catch (err) {
71
+ start({ input: 'unavailable' });
72
+ logger.error('hook.end', {
73
+ hook: event,
74
+ outcome: 'ignored',
75
+ reason: 'input-read-failed',
76
+ ...failureData(err),
77
+ });
78
+ return EXIT.ok;
79
+ }
80
+ if (raw.trim() !== '') {
81
+ try {
82
+ const parsed = JSON.parse(raw);
83
+ if (typeof parsed !== 'object' || parsed === null)
84
+ throw new Error('not an object');
85
+ }
86
+ catch {
87
+ start({ input: 'malformed' });
88
+ logger.error('hook.end', { hook: event, outcome: 'ignored', reason: 'malformed-input' });
89
+ deps.io.err('notifai: ignored malformed or truncated hook input; no routing action was taken');
90
+ return EXIT.ok;
91
+ }
92
+ }
93
+ let envelope = parseHookInput(raw);
94
+ if (harness === 'cursor') {
95
+ const sessionId = envelope.session_id ?? envelope.conversation_id;
96
+ const cwd = envelope.cwd ?? envelope.workspace_roots?.[0];
97
+ envelope = {
98
+ ...envelope,
99
+ ...(sessionId === undefined ? {} : { session_id: sessionId }),
100
+ ...(cwd === undefined ? {} : { cwd }),
101
+ stop_hook_active: envelope.stop_hook_active ??
102
+ (typeof envelope.loop_count === 'number' && envelope.loop_count > 0),
103
+ };
104
+ }
105
+ const cwd = envelope.cwd ?? deps.cwd;
106
+ const sessionEnd = hookDefersDiagnosticsUntilAfterCleanup(event);
107
+ logger.bind({ session: envelope.session_id ?? null });
108
+ let config = null;
109
+ let configFailure;
110
+ try {
111
+ config = loadConfig({ cwd, env: deps.env, sessionId: envelope.session_id });
112
+ // The hook's project is the session's, not this process's, and the log
113
+ // settings that apply are that project's too. Keeping a mutable bootstrap
114
+ // logger lets this more-specific layer turn logging back on.
115
+ logger.adopt(logSettingsFrom(config));
116
+ logger.bind({ project: config.project.value });
117
+ if (!sessionEnd) {
118
+ start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null });
119
+ logConfigResolved(logger, config);
120
+ }
121
+ }
122
+ catch (err) {
123
+ configFailure = err;
124
+ if (!sessionEnd) {
125
+ start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null });
126
+ logger.error('hook.end', {
127
+ hook: event,
128
+ outcome: 'failed',
129
+ reason: 'config-failed',
130
+ ...failureData(err),
131
+ });
132
+ for (const line of describeHookFailure(err))
133
+ deps.io.err(`notifai: ${line}`);
134
+ return EXIT.ok;
135
+ }
136
+ }
137
+ // Everything below is inside one fail-open boundary. Credential loading,
138
+ // client construction and hook handling can all throw, and a hook that exits
139
+ // non-zero makes the harness report a failure — strictly worse than skipping.
140
+ try {
141
+ if (sessionEnd) {
142
+ // Codex gives SessionEnd one second total. Do every durable cleanup write
143
+ // before lifecycle diagnostics: the log lock is deliberately allowed to
144
+ // wait that long, and a busy log must never preserve ended-session state
145
+ // or its inherited configuration. The resolved config above is retained
146
+ // in memory so logging still uses the ending session's settings afterwards.
147
+ const outcome = handleSessionEnd(deps.env, envelope, (deps.now ?? Date.now)());
148
+ start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null });
149
+ if (config !== null)
150
+ logConfigResolved(logger, config);
151
+ const data = { hook: event, decided: false, ...outcome.log };
152
+ if (configFailure === undefined)
153
+ logger.info('hook.end', data);
154
+ else {
155
+ logger.error('hook.end', {
156
+ ...data,
157
+ reason: 'config-failed',
158
+ config_error: failureData(configFailure),
159
+ });
160
+ }
161
+ for (const note of outcome.notes)
162
+ deps.io.err(`notifai: ${note}`);
163
+ return EXIT.ok;
164
+ }
165
+ // Non-SessionEnd hooks cannot reach here without resolved configuration.
166
+ const resolved = config;
167
+ const credential = deps.store.load();
168
+ if (!credential) {
169
+ logger.error('hook.end', { hook: event, outcome: 'not-paired' });
170
+ deps.io.err('notifai: hook skipped: this machine is not paired; run `notifai login`');
171
+ return EXIT.ok;
172
+ }
173
+ // Pin authenticated traffic to the origin the credential was issued for. A
174
+ // repository can commit `.notifai/config.toml`, and honouring a base_url
175
+ // from it would hand this machine's bearer token to whatever host it names.
176
+ const baseUrl = credential.baseUrl;
177
+ if (resolved.base_url.source !== 'default' && resolved.base_url.value !== baseUrl) {
178
+ deps.io.err(`notifai: ignoring base_url from ${resolved.base_url.source}; hooks only talk to ${baseUrl}`);
179
+ }
180
+ // UserPromptSubmit runs in front of the user's own prompt under a 15s
181
+ // harness ceiling and can make two calls, so each gets a small slice of it;
182
+ // Stop is allowed to block and keeps the ordinary budget.
183
+ const client = makeClient(deps, baseUrl, `Bearer nfm_${credential.machineId}.${credential.secret}`, {
184
+ timeoutMs: event === 'user-prompt-submit' ? 4_000 : 20_000,
185
+ ...(event === 'stop' ? { deadlineAt: processDeadlineAt, now } : {}),
186
+ });
187
+ const ctx = {
188
+ client,
189
+ config: resolved,
190
+ env: deps.env,
191
+ now,
192
+ sleep: deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
193
+ waitForFirstReply: async (requestId, timeoutSeconds) => {
194
+ const result = await waitForReply(client, requestId, {
195
+ timeoutSeconds,
196
+ afterSeq: 0,
197
+ now: deps.now,
198
+ sleep: deps.sleep,
199
+ });
200
+ return {
201
+ replies: result.response.replies,
202
+ timedOut: result.timedOut,
203
+ degraded: result.degraded,
204
+ };
205
+ },
206
+ log: logger,
207
+ ...(harness === undefined ? {} : { harness }),
208
+ };
209
+ // Real clock, deliberately, not `deps.now`. This compares against file
210
+ // mtimes, which are wall-clock facts — handing it a virtual or skewed clock
211
+ // would have it delete live session state as "abandoned".
212
+ // Daily state pruning is housekeeping, not part of the Stop delivery
213
+ // contract. Its directory scan has no useful bound, so keep it on the
214
+ // short prompt path and never spend the answer owner's finite budget on it.
215
+ if (event !== 'stop')
216
+ pruneAbandonedSessions(deps.env);
217
+ const outcome = event === 'user-prompt-submit'
218
+ ? await handleUserPromptSubmit(ctx, envelope)
219
+ : await handleStop(ctx, envelope, processDeadlineAt, stopWakeRoute(deps, harness, envelope.session_id, cwd));
220
+ // Answer diagnostics are already persisted once as hook.answer. Keep every
221
+ // other note in the lifecycle record without duplicating the user's text.
222
+ const notes = outcome.notes.filter((note) => !/^(?:late )?answer from /.test(note));
223
+ logger.info('hook.end', {
224
+ hook: event,
225
+ // A hook that returns stdout has taken over the turn; one that does not
226
+ // has handed the terminal back. That distinction is the whole contract.
227
+ decided: outcome.stdout !== undefined,
228
+ ...(notes.length === 0 ? {} : { notes }),
229
+ ...outcome.log,
230
+ });
231
+ for (const note of outcome.notes)
232
+ deps.io.err(`notifai: ${note}`);
233
+ if (outcome.stdout !== undefined)
234
+ deps.io.out(outcome.stdout);
235
+ return EXIT.ok;
236
+ }
237
+ catch (err) {
238
+ // SessionEnd defers its start record until after cleanup; if cleanup itself
239
+ // fails, begin the after-the-fact lifecycle here before recording why.
240
+ if (sessionEnd)
241
+ start({ cwd, stop_hook_active: envelope.stop_hook_active ?? null });
242
+ // The hook still exits 0 — handing the terminal back is always right. What
243
+ // this adds is that the reason survives, including the server's own words.
244
+ logger.error('hook.end', {
245
+ hook: event,
246
+ outcome: 'failed',
247
+ reason: 'execution-failed',
248
+ ...failureData(err),
249
+ });
250
+ for (const line of describeHookFailure(err))
251
+ deps.io.err(`notifai: ${line}`);
252
+ return EXIT.ok;
253
+ }
254
+ }
255
+ /**
256
+ * The last meter for an answer this Stop hook accepted, chosen by harness.
257
+ *
258
+ * Both wake adapters need the harness process that invoked this hook: Claude's
259
+ * to prove exact own-child session ownership before it posts to the inbox
260
+ * socket, Codex's to know whether its own stdout is still a live continuation
261
+ * channel. Without an exact session id neither can prove anything, so the
262
+ * waiter falls back to the plain blocking Stop continuation.
263
+ */
264
+ function stopWakeRoute(deps, harness, sessionId, cwd) {
265
+ if (sessionId === undefined)
266
+ return undefined;
267
+ if (harness === 'claude-code') {
268
+ if ((deps.hookPlatform ?? process.platform) === 'win32')
269
+ return undefined;
270
+ return claudeWakeRoute({
271
+ sessionId,
272
+ cwd,
273
+ sourcePid: deps.claudeSourcePid ?? claudeSessionPid(deps.env),
274
+ ...(deps.claudeWake === undefined ? {} : { adapters: deps.claudeWake }),
275
+ });
276
+ }
277
+ if (harness === 'codex') {
278
+ return codexWakeRoute({
279
+ threadId: sessionId,
280
+ cwd,
281
+ sourcePid: deps.codexSourcePid ?? process.ppid,
282
+ env: deps.env,
283
+ ...(deps.codexWake === undefined ? {} : { adapters: deps.codexWake }),
284
+ });
285
+ }
286
+ return undefined;
287
+ }
288
+ /**
289
+ * What went wrong, in terms of what to do about it.
290
+ *
291
+ * On 2026-08-03 a contract change shipped without the server deploy that goes
292
+ * with it. The CLI stamped `lifecycle` on every question draft, the deployed
293
+ * server rejected the unknown field, and escalation stopped working entirely —
294
+ * announced as "hook failed, deferring to the terminal", which reads like a
295
+ * flaky network. The information needed to diagnose it in one second was
296
+ * already in hand: a 422 whose details name the offending path. It was being
297
+ * thrown away by `String(err)`.
298
+ *
299
+ * A hook still exits 0 whatever this says. Handing the terminal back is always
300
+ * right; the only question is whether the user is told anything they can use.
301
+ */
302
+ export function describeHookFailure(err) {
303
+ if (!(err instanceof ApiCallError)) {
304
+ return [`hook failed, deferring to the terminal (${String(err)})`];
305
+ }
306
+ const lines = [`hook failed, deferring to the terminal (${err.code}: ${err.message})`];
307
+ const paths = rejectedPaths(err.details);
308
+ if (paths.length > 0)
309
+ lines.push(`the server rejected: ${paths.join(', ')}`);
310
+ // A 422 on a draft this CLI built is not a user error — this CLI's own
311
+ // contract produced it. Either the server is behind, or the two disagree.
312
+ if (err.status === 422) {
313
+ lines.push('this build sent a field the server did not accept, which usually means the server ' +
314
+ 'is older than this CLI — check with `notifai doctor`');
315
+ }
316
+ return lines;
317
+ }
318
+ /**
319
+ * Turn ask input into questions plus their canonical body. Everything is
320
+ * validated at registration because a later hook failure is easy to miss.
321
+ */
322
+ export function buildQuestions(flags, question) {
323
+ if (flags.form !== undefined) {
324
+ if (question !== undefined || flags.choice?.length || flags.multi) {
325
+ return { ok: false, error: '--form replaces the positional question, --choice, and --multi.' };
326
+ }
327
+ let parsed;
328
+ try {
329
+ parsed = JSON.parse(flags.form);
330
+ }
331
+ catch {
332
+ return {
333
+ ok: false,
334
+ error: '--form must be JSON: {"questions": [{"text", "choices"?, "multi"?}], "body"?}.',
335
+ };
336
+ }
337
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
338
+ return { ok: false, error: `--form needs a "questions" array (1-${REPLY_MAX_QUESTIONS} entries).` };
339
+ }
340
+ const record = parsed;
341
+ const unknownKeys = Object.keys(record).filter((key) => key !== 'questions' && key !== 'body');
342
+ if (unknownKeys.length > 0) {
343
+ return {
344
+ ok: false,
345
+ error: `Unknown --form ${unknownKeys.length === 1 ? 'key' : 'keys'}: ${unknownKeys.join(', ')}. Use "body" for Markdown context.`,
346
+ };
347
+ }
348
+ if (!Array.isArray(record['questions'])) {
349
+ return { ok: false, error: `--form needs a "questions" array (1-${REPLY_MAX_QUESTIONS} entries).` };
350
+ }
351
+ const formQuestions = record['questions'];
352
+ if (formQuestions.length < 1 || formQuestions.length > REPLY_MAX_QUESTIONS) {
353
+ return {
354
+ ok: false,
355
+ error: `A form asks 1-${REPLY_MAX_QUESTIONS} questions; this one has ${formQuestions.length}.`,
356
+ };
357
+ }
358
+ if (record['body'] !== undefined && typeof record['body'] !== 'string') {
359
+ return { ok: false, error: '"body" must be a Markdown string.' };
360
+ }
361
+ if (flags.body !== undefined && record['body'] !== undefined) {
362
+ return { ok: false, error: 'Pass form context in either --body or the form "body" key, not both.' };
363
+ }
364
+ const questions = [];
365
+ const usedIds = new Set();
366
+ for (const [index, entry] of formQuestions.entries()) {
367
+ if (typeof entry !== 'object' || entry === null || typeof entry.text !== 'string') {
368
+ return { ok: false, error: `Question ${index + 1} needs a "text" string.` };
369
+ }
370
+ const spec = entry;
371
+ const built = buildOneQuestion(spec.text, spec.choices, spec.multi === true, index, usedIds);
372
+ if ('error' in built)
373
+ return { ok: false, error: `Question ${index + 1}: ${built.error}` };
374
+ questions.push(built.question);
375
+ }
376
+ const context = flags.body ?? record['body'];
377
+ const questionBlock = questions.map((entry, index) => `${index + 1}. ${entry.text}`).join('\n');
378
+ return {
379
+ ok: true,
380
+ questions,
381
+ body: context !== undefined && context.trim() !== ''
382
+ ? `${questionBlock}\n\n${context}`
383
+ : questionBlock,
384
+ };
385
+ }
386
+ if (question === undefined || question.trim() === '') {
387
+ return { ok: false, error: 'The question cannot be empty.' };
388
+ }
389
+ const built = buildOneQuestion(question, flags.choice, flags.multi === true, 0, new Set());
390
+ if ('error' in built)
391
+ return { ok: false, error: built.error };
392
+ const context = flags.body;
393
+ return {
394
+ ok: true,
395
+ questions: [built.question],
396
+ body: context !== undefined && context.trim() !== ''
397
+ ? `${built.question.text}\n\n${context}`
398
+ : built.question.text,
399
+ };
400
+ }
401
+ function buildOneQuestion(text, choiceLabels, multi, index, usedIds) {
402
+ const trimmed = text.trim();
403
+ if (trimmed === '')
404
+ return { error: 'the question text cannot be empty.' };
405
+ if (trimmed.length > QUESTION_TEXT_MAX_LENGTH) {
406
+ return {
407
+ error: `a question must be readable where it is answered: keep it within ` +
408
+ `${QUESTION_TEXT_MAX_LENGTH} characters and put the longer context in --body.`,
409
+ };
410
+ }
411
+ const choices = parseChoices(choiceLabels);
412
+ if (choices === 'invalid')
413
+ return { error: CHOICE_USAGE };
414
+ if (multi && choices === null) {
415
+ return { error: '--multi needs answers to select between; add --choice.' };
416
+ }
417
+ let id = slugify(trimmed);
418
+ if (id === '' || usedIds.has(id))
419
+ id = `q${index + 1}`;
420
+ usedIds.add(id);
421
+ return {
422
+ question: {
423
+ id,
424
+ text: trimmed,
425
+ ...(choices !== null ? { choices } : {}),
426
+ ...(multi ? { multi: true } : {}),
427
+ },
428
+ };
429
+ }
430
+ function buildAskDraft(config, built, flags, invocation, mediaIds) {
431
+ const result = buildDraft(config, {
432
+ title: built.questions[0].text,
433
+ body: built.body,
434
+ ...(flags.project !== undefined ? { project: flags.project } : {}),
435
+ ...(mediaIds.length > 0 ? { image: mediaIds } : {}),
436
+ ...(flags.imageAlt !== undefined ? { imageAlt: flags.imageAlt } : {}),
437
+ reply: true,
438
+ questions: built.questions,
439
+ }, invocation);
440
+ if (!result.ok)
441
+ return result;
442
+ const capabilities = CAPABILITIES_V1.describe(result.platform);
443
+ if (capabilities === null)
444
+ return { ok: false, error: 'No iOS capability contract is available.' };
445
+ const validation = validateDraft(result.draft, capabilities);
446
+ if (!validation.ok) {
447
+ return {
448
+ ok: false,
449
+ error: validation.errors.map((issue) => `${issue.path}: ${issue.message}`).join('\n'),
450
+ };
451
+ }
452
+ return { ok: true, draft: result.draft };
453
+ }
454
+ function recordRegisteredQuestion(deps, sessionId, built, draft, json = false) {
455
+ try {
456
+ registerQuestion(sessionId, deps.env, {
457
+ question: built.questions[0].text,
458
+ questions: built.questions,
459
+ body: draft.presentation.body,
460
+ ...(draft.project !== undefined ? { project: draft.project } : {}),
461
+ ...(draft.source !== undefined ? { source: draft.source } : {}),
462
+ ...(draft.presentation.media !== undefined ? { media: draft.presentation.media } : {}),
463
+ }, (deps.now ?? Date.now)());
464
+ }
465
+ catch (err) {
466
+ log(deps).error('ask.registered', { ok: false, session: sessionId, message: String(err) });
467
+ deps.io.err(`Could not register the question: ${err instanceof Error ? err.message : String(err)}`);
468
+ return EXIT.failed;
469
+ }
470
+ log(deps).info('ask.registered', {
471
+ ok: true,
472
+ session: sessionId,
473
+ questions: built.questions.length,
474
+ text: built.questions[0].text,
475
+ choices: built.questions[0].choices?.length ?? 0,
476
+ media: draft.presentation.media?.length ?? 0,
477
+ });
478
+ // The block below is the densest guidance this CLI prints, and until now it
479
+ // was prose only: an agent could not read back the choice ids it must branch
480
+ // on without asking the server for them. The JSON form carries the same
481
+ // obligation as data.
482
+ if (json) {
483
+ deps.io.out(JSON.stringify({
484
+ registered: true,
485
+ questions: built.questions.map((entry) => ({
486
+ id: entry.id,
487
+ text: entry.text,
488
+ ...(entry.choices === undefined ? {} : { choices: entry.choices }),
489
+ ...(entry.multi === true ? { multi: true } : {}),
490
+ })),
491
+ next: {
492
+ end_turn: true,
493
+ 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.',
494
+ route_neutral: 'Never say where the answer must arrive; it returns by whatever route the harness supports.',
495
+ on_answer: 'Acknowledge it, then resume the committed work without asking the user to confirm again.',
496
+ },
497
+ }, null, 2));
498
+ return EXIT.ok;
499
+ }
500
+ for (const [index, entry] of built.questions.entries()) {
501
+ const prefix = built.questions.length > 1 ? `${index + 1}. ` : '';
502
+ if (entry.choices !== undefined) {
503
+ const kind = entry.multi === true ? 'answers offered (several may be chosen)' : 'answers offered';
504
+ deps.io.out(`${prefix}${entry.text} — ${kind}: ${entry.choices.map((choice) => choice.label).join(' / ')}`);
505
+ }
506
+ else if (built.questions.length > 1) {
507
+ deps.io.out(`${prefix}${entry.text} — free text`);
508
+ }
509
+ }
510
+ deps.io.out(built.questions.length > 1
511
+ ? `${built.questions.length} questions registered as one form. Ask them in the conversation, state the concrete work you will resume for their answers, then end your turn.`
512
+ : 'Question registered. Ask it in the conversation, state the concrete work you will resume when the answer arrives, then end your turn.');
513
+ deps.io.out('Before ending this turn, pre-commit in your own words to the work you will resume:');
514
+ for (const [index, entry] of built.questions.entries()) {
515
+ const questionPrefix = built.questions.length > 1 ? `Question ${index + 1}, ` : '';
516
+ if (entry.choices !== undefined) {
517
+ for (const choice of entry.choices) {
518
+ deps.io.out(`- ${questionPrefix}If the answer is ${JSON.stringify(choice.label)}: state the concrete work you will resume.`);
519
+ }
520
+ deps.io.out(`- ${questionPrefix}For an unexpected typed answer: state how it will determine the concrete work you resume.`);
521
+ }
522
+ else {
523
+ deps.io.out(`- ${questionPrefix}For the free-text answer: state how its content will determine the concrete work you resume.`);
524
+ }
525
+ }
526
+ 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.');
527
+ deps.io.out('A Notifai answer cannot answer a harness permission prompt or interactive picker; leave those to the harness and user.');
528
+ return EXIT.ok;
529
+ }
530
+ async function uploadAskMedia(deps, config, sessionId, built, flags, invocation) {
531
+ const authed = authedClient(deps, config);
532
+ if (!authed)
533
+ return EXIT.auth;
534
+ const mediaIds = [];
535
+ for (const image of flags.image ?? []) {
536
+ if (image.startsWith('med_')) {
537
+ mediaIds.push(image);
538
+ continue;
539
+ }
540
+ const uploaded = await uploadImage(deps, authed.client, image);
541
+ if (!uploaded.ok) {
542
+ if (uploaded.error !== null)
543
+ deps.io.err(uploaded.error);
544
+ return uploaded.exit;
545
+ }
546
+ mediaIds.push(uploaded.mediaId);
547
+ }
548
+ const ready = buildAskDraft(config, built, flags, invocation, mediaIds);
549
+ if (!ready.ok) {
550
+ deps.io.err(ready.error);
551
+ return EXIT.usage;
552
+ }
553
+ return recordRegisteredQuestion(deps, sessionId, built, ready.draft, flags.json === true);
554
+ }
555
+ /**
556
+ * Registers a question for turn-end routing. Returns immediately so the agent
557
+ * can ask in prose and end its turn; the terminal keeps the question to itself
558
+ * for `ask_grace_seconds` before it reaches any device.
559
+ */
560
+ export function askCommand(deps, question, flags) {
561
+ // Validate before route discovery. A malformed question belongs to the
562
+ // caller and should not be hidden behind whichever harness setup issue
563
+ // happens to exist on this machine.
564
+ const built = buildQuestions(flags, question);
565
+ if (!built.ok) {
566
+ deps.io.err(built.error);
567
+ return EXIT.usage;
568
+ }
569
+ const mediaInputError = validateMediaInputs(flags.image, flags.imageAlt);
570
+ if (mediaInputError !== null) {
571
+ deps.io.err(mediaInputError);
572
+ return EXIT.usage;
573
+ }
574
+ const routingConfig = loadConfig({ cwd: deps.cwd, env: deps.env });
575
+ if (!routingConfig.ask_notifications.value) {
576
+ deps.io.err('Question routing is disabled by ask_notifications=false; enable it or use a blocking `notifai send --reply` question.');
577
+ return EXIT.usage;
578
+ }
579
+ if (deps.store.load() === null) {
580
+ deps.io.err('Question routing is not paired on this machine; run `notifai login` before registering an asynchronous question.');
581
+ return EXIT.usage;
582
+ }
583
+ // An agent calling this gets no hook payload. Harness-native environment
584
+ // markers identify the active owner, while UserPromptSubmit adds the hook's
585
+ // canonical id to the directory's concurrent-session index.
586
+ const now = (deps.now ?? Date.now)();
587
+ const { active, contested } = resolveActiveHarness(deps.env, deps.cwd, now);
588
+ let sessionId;
589
+ if (active !== null) {
590
+ const installations = findInstallations(deps.cwd, deps.env, deps.hookAdapterHome, deps.hookPlatform);
591
+ const activeInstalled = installations.some((installation) => installation.harness === active.harness);
592
+ if (!activeInstalled) {
593
+ for (const line of diagnoseActiveHarnessSession(active, 'not-installed', installations, contested)) {
594
+ deps.io.err(line);
595
+ }
596
+ return EXIT.usage;
597
+ }
598
+ if (active.sessionId === undefined) {
599
+ for (const problem of activeQuestionRouteProblems(deps, active, installations)) {
600
+ deps.io.err(`Question routing is not ready: ${problem}`);
601
+ }
602
+ return EXIT.usage;
603
+ }
604
+ const projectPointer = readMatchingProjectSessionPointer(deps.cwd, deps.env, now, active.sessionId, active.harness);
605
+ if (projectPointer === null) {
606
+ for (const line of diagnoseActiveHarnessSession(active, 'not-fired', installations, contested)) {
607
+ deps.io.err(line);
608
+ }
609
+ return EXIT.usage;
610
+ }
611
+ const routeProblems = activeQuestionRouteProblems(deps, active, installations);
612
+ if (routeProblems.length > 0) {
613
+ for (const problem of routeProblems)
614
+ deps.io.err(`Question routing is not ready: ${problem}`);
615
+ return EXIT.usage;
616
+ }
617
+ if (readSessionState(projectPointer.sessionId, deps.env).last_stop_at === undefined) {
618
+ deps.io.err(`Question routing is not ready: this ${active.label} session has fired UserPromptSubmit, but its Stop hook has not been observed. End one harmless turn, send a new prompt, then run \`notifai doctor\`.`);
619
+ return EXIT.usage;
620
+ }
621
+ sessionId = projectPointer.sessionId;
622
+ }
623
+ else {
624
+ for (const line of diagnoseMissingSession(deps))
625
+ deps.io.err(line);
626
+ deps.io.err('Could not prove which live harness session owns this command, so Notifai will not register a question that could be delivered to the wrong or already-ended agent. Run it from a supported harness with exact session identity, or use a blocking `notifai send --reply` question.');
627
+ return EXIT.usage;
628
+ }
629
+ if (!sessionId) {
630
+ for (const line of diagnoseMissingSession(deps))
631
+ deps.io.err(line);
632
+ return EXIT.usage;
633
+ }
634
+ const source = resolveDraftInvocation(deps, flags, active);
635
+ if (!source.ok) {
636
+ deps.io.err(source.error);
637
+ return EXIT.usage;
638
+ }
639
+ if (source.invocation.source?.session_id !== sessionId) {
640
+ deps.io.err(`Question routing is not ready: --session-id or NOTIFAI_SESSION_ID does not match the exact active ${active.label} session; refusing cross-session routing.`);
641
+ return EXIT.usage;
642
+ }
643
+ // Placeholders let every body, source, project, media, and payload limit fail
644
+ // before an upload starts. The real ids replace them only after this passes.
645
+ const placeholders = (flags.image ?? []).map((_, index) => `med_pending_${index + 1}`);
646
+ const preflight = buildAskDraft(routingConfig, built, flags, source.invocation, placeholders);
647
+ if (!preflight.ok) {
648
+ deps.io.err(preflight.error);
649
+ return EXIT.usage;
650
+ }
651
+ if ((flags.image?.length ?? 0) > 0) {
652
+ return uploadAskMedia(deps, routingConfig, sessionId, built, flags, source.invocation);
653
+ }
654
+ return recordRegisteredQuestion(deps, sessionId, built, preflight.draft, flags.json === true);
655
+ }
656
+ /**
657
+ * One fail-closed admission gate shared by every active harness route.
658
+ * Finding a file is not readiness: the exact session, one current definition,
659
+ * the stable adapter, a long enough Stop owner, and (for Codex) trust must all
660
+ * be true before `ask` is allowed to create an answerable notification.
661
+ */
662
+ export function activeQuestionRouteProblems(deps, active, installations) {
663
+ const problems = [];
664
+ if (active.sessionId === undefined) {
665
+ 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`);
666
+ }
667
+ const capability = HARNESS_CAPABILITIES[active.harness];
668
+ if (capability.stopContinuation === 'unsupported') {
669
+ problems.push(`${active.label}: ${capability.deliveryContract}`);
670
+ }
671
+ const matching = installations.filter((installation) => installation.harness === active.harness);
672
+ if (matching.length > 1) {
673
+ problems.push(`${matching.length} ${active.label} definitions are active (${matching.map((entry) => entry.file).join(', ')}); keep either project or global routing`);
674
+ }
675
+ for (const installation of matching) {
676
+ for (const problem of installation.problems ?? []) {
677
+ problems.push(`${installation.file}: ${problem}`);
678
+ }
679
+ for (const handler of installation.handlers) {
680
+ const event = handlerEvent(handler.command);
681
+ if (event !== null && !HOOK_EVENTS.includes(event)) {
682
+ problems.push(`${handler.event} in ${installation.file} names the unsupported event ${event}; reinstall the ${active.label} hooks`);
683
+ }
684
+ }
685
+ }
686
+ for (const problem of inspectHookAdapter(deps.hookAdapterHome, deps.hookPlatform).problems) {
687
+ problems.push(problem);
688
+ }
689
+ for (const installation of matching)
690
+ problems.push(...stopShapeProblems(installation, deps.hookPlatform));
691
+ problems.push(...codexTrustProblems(matching, deps.env));
692
+ return [...new Set(problems)];
693
+ }
694
+ function diagnoseActiveHarnessSession(active, problem, installations, contested = []) {
695
+ // Naming one harness confidently is wrong when the environment carries the
696
+ // markers of several and none of them has fired here: whichever one the
697
+ // agent is told to prompt may not be the one it is running in.
698
+ const ambiguity = contested.length > 1
699
+ ? [
700
+ `Several harness markers are present here (${contested.map((candidate) => candidate.label).join(', ')}) and none names a session that has fired in this directory, so ${active.label} is a guess from the environment. Send the prompt in the harness you are actually running.`,
701
+ ]
702
+ : [];
703
+ if (problem === 'not-installed') {
704
+ const others = installations.map((installation) => installation.harness);
705
+ return [
706
+ `Could not register the question for the active ${active.label} session: Notifai ${active.label} hooks are not installed for this project.`,
707
+ ...ambiguity,
708
+ ...(others.length === 0
709
+ ? []
710
+ : [
711
+ `Hooks installed for ${[...new Set(others)].join(', ')} do not route an active ${active.label} session.`,
712
+ ]),
713
+ `Run \`notifai hooks install --harness ${active.harness}\`, then send one ${active.label} prompt and run \`notifai doctor\`.`,
714
+ `Retry \`notifai ask\` only after doctor reports that the ${active.label} hooks fired.`,
715
+ ];
716
+ }
717
+ if (problem === 'different-session') {
718
+ return [
719
+ `Could not register the question for the active ${active.label} session: the project pointer belongs to another ${active.label} session or harness.`,
720
+ ...ambiguity,
721
+ `Refusing to guess or cross-wire the question. Send one prompt in this ${active.label} session, then run \`notifai doctor\`.`,
722
+ `Retry \`notifai ask\` only after doctor reports that this active ${active.label} session fired the hooks.`,
723
+ ];
724
+ }
725
+ return [
726
+ `Could not register the question for the active ${active.label} session: Notifai hooks are installed, but this session has not published its pointer.`,
727
+ ...ambiguity,
728
+ `Send one ${active.label} prompt, then run \`notifai doctor\`.`,
729
+ `Retry \`notifai ask\` only after doctor reports that the active ${active.label} session fired the hooks.`,
730
+ ];
731
+ }
732
+ /**
733
+ * Why `ask` cannot see a session, in terms of what to do about it.
734
+ *
735
+ * Only a UserPromptSubmit hook firing produces the pointer this reads, and the
736
+ * old message answered every cause with "run `notifai hooks install` and send
737
+ * one prompt". The useful next action depends on the harness: some reload
738
+ * project hook files, OpenCode loads its plugin at startup, and Codex should be
739
+ * checked after a prompt before assuming that a new session is required.
740
+ */
741
+ function diagnoseMissingSession(deps) {
742
+ const installations = findInstallations(deps.cwd, deps.env, deps.hookAdapterHome, deps.hookPlatform);
743
+ if (installations.length === 0) {
744
+ return [
745
+ 'Could not tell which harness session this is: no Notifai hooks are installed for this project.',
746
+ 'Run `notifai hooks install`, then follow the activation instruction it prints.',
747
+ ];
748
+ }
749
+ const where = installations.map((i) => `${i.harness} in ${i.file}`).join(', ');
750
+ return [
751
+ `Could not tell which harness session this is. Notifai hooks are installed (${where}),`,
752
+ 'but no usable session pointer from the last 24 hours exists here.',
753
+ hookActivationAdvice(installations),
754
+ 'Do not bypass this with a guessed session id; run from the exact active harness session or use a blocking `notifai send --reply` question.',
755
+ ];
756
+ }
757
+ /** The least disruptive verified way to make each installed adapter run once. */
758
+ export function hookActivationAdvice(installations) {
759
+ const harnesses = new Set(installations.map((installation) => installation.harness));
760
+ const advice = [];
761
+ if (installations.some((installation) => installation.harness === 'claude-code' && !installation.global)) {
762
+ advice.push('Claude Code: send one new prompt; project hook files reload without a restart');
763
+ }
764
+ if (installations.some((installation) => installation.harness === 'claude-code' && installation.global)) {
765
+ advice.push('Claude Code global hooks: send one prompt; start a new session only if it does not fire');
766
+ }
767
+ if (installations.some((installation) => installation.harness === 'cursor' && !installation.global)) {
768
+ advice.push('Cursor: send one prompt, then run `notifai doctor`; start a new session only if it still has not fired');
769
+ }
770
+ if (installations.some((installation) => installation.harness === 'cursor' && installation.global)) {
771
+ advice.push('Cursor global hooks: send one prompt; start a new session only if it does not fire');
772
+ }
773
+ if (harnesses.has('codex')) {
774
+ advice.push('Codex: send one prompt, then run `notifai doctor`; start a new session only if it still has not fired');
775
+ }
776
+ if (harnesses.has('opencode')) {
777
+ advice.push('OpenCode: restart it, then send one prompt; plugins load at startup, but non-blocking question continuation is intentionally unsupported');
778
+ }
779
+ return `${advice.join('. ')}.`;
780
+ }
781
+ /**
782
+ * Record the one Agent Acknowledgement associated with a replied-to request.
783
+ *
784
+ * `--text` is optional here because the acknowledgement is not: an account may
785
+ * turn the agent's written reply off, and the receipt must still be recorded so
786
+ * the user sees that an agent read the answer. The service holds the account's
787
+ * snapshot, so it — not this process — decides whether text was owed.
788
+ */
789
+ export async function acknowledgeCommand(deps, requestId, flags) {
790
+ const text = flags.text?.trim() ?? '';
791
+ if (flags.text !== undefined && text.length === 0) {
792
+ deps.io.err('--text must contain non-whitespace text. Drop it to acknowledge without text.');
793
+ return EXIT.usage;
794
+ }
795
+ if (text.length > AGENT_ACKNOWLEDGEMENT_MAX_LENGTH) {
796
+ 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.`);
797
+ return EXIT.usage;
798
+ }
799
+ const logger = log(deps);
800
+ const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env });
801
+ logger.info('acknowledgement.attempted', {
802
+ request_id: requestId,
803
+ text,
804
+ characters: text.length,
805
+ });
806
+ const authed = authedClient(deps, config);
807
+ if (!authed)
808
+ return EXIT.auth;
809
+ try {
810
+ const result = await authed.client.putAgentAcknowledgement(requestId, text.length > 0 ? { text } : {});
811
+ const output = {
812
+ request_id: requestId,
813
+ outcome: result.status,
814
+ acknowledgement: result.agent_acknowledgement,
815
+ agent_acknowledgement_required: true,
816
+ };
817
+ logger.info('acknowledgement.outcome', {
818
+ request_id: requestId,
819
+ outcome: result.status,
820
+ text: result.agent_acknowledgement.text,
821
+ created_at: result.agent_acknowledgement.created_at,
822
+ agent_acknowledgement_required: true,
823
+ });
824
+ const sessionId = readProjectSession(deps.cwd, deps.env, (deps.now ?? Date.now)());
825
+ if (sessionId !== null) {
826
+ clearAcknowledgementObligation(sessionId, deps.env, requestId);
827
+ }
828
+ if (flags.json)
829
+ deps.io.out(JSON.stringify(output, null, 2));
830
+ else {
831
+ deps.io.out(`Agent Acknowledgement ${result.status} for ${requestId} at ${result.agent_acknowledgement.created_at}.`);
832
+ }
833
+ return EXIT.ok;
834
+ }
835
+ catch (err) {
836
+ return reportError(deps, err, { operation: 'agent_acknowledgement', request_id: requestId });
837
+ }
838
+ }
839
+ /** Retire a question so a late answer is rejected rather than silently lost. */
840
+ export async function closeCommand(deps, requestId, flags = {}) {
841
+ const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env });
842
+ const authed = authedClient(deps, config);
843
+ if (!authed)
844
+ return EXIT.auth;
845
+ try {
846
+ const response = await authed.client.closeReplies(requestId);
847
+ if (flags.json) {
848
+ deps.io.out(JSON.stringify({
849
+ ...response,
850
+ acknowledgement_command: acknowledgementCommand(response.request_id, response.agent_acknowledgement_required, response.agent_acknowledgement_text_required, response.agent_acknowledgement, response.replies.length > 0),
851
+ }, null, 2));
852
+ }
853
+ else {
854
+ deps.io.out(`Closed the reply window for ${requestId}.`);
855
+ if (response.replies.length > 0)
856
+ printAcknowledgementStatus(deps, response);
857
+ }
858
+ return EXIT.ok;
859
+ }
860
+ catch (err) {
861
+ return reportError(deps, err);
862
+ }
863
+ }
864
+ /** True when this process is `npx` / `npm exec`, not a global or linked install. */
865
+ export function runningViaNpx(env, scriptPath) {
866
+ if (env['npm_command'] === 'exec')
867
+ return true;
868
+ return scriptPath.includes(`${path.sep}_npx${path.sep}`);
869
+ }
870
+ function fileHookInstallTarget(target) {
871
+ if (target === undefined || isNpxAdapterTarget(target))
872
+ return undefined;
873
+ return target;
874
+ }
875
+ function resolveHookAdapterTarget(deps, flags) {
876
+ if (deps.hookInstallTarget !== undefined && isNpxAdapterTarget(deps.hookInstallTarget)) {
877
+ return deps.hookInstallTarget;
878
+ }
879
+ const fileTarget = fileHookInstallTarget(deps.hookInstallTarget);
880
+ const execPath = flags.execPath ?? fileTarget?.execPath ?? process.execPath;
881
+ const scriptPath = flags.scriptPath ?? fileTarget?.scriptPath ?? process.argv[1] ?? 'notifai';
882
+ if (runningViaNpx(deps.env, scriptPath)) {
883
+ const version = packageVersion();
884
+ const npmCli = deps.env['npm_execpath'];
885
+ if (version === null) {
886
+ 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`.');
887
+ }
888
+ if (typeof npmCli !== 'string' || npmCli === '') {
889
+ throw new Error('This process looks like npx but npm_execpath is missing. Install `@raidiant/notifai` globally and rerun `notifai hooks install`.');
890
+ }
891
+ return { kind: 'npx', execPath, npmCli, spec: `@raidiant/notifai@${version}` };
892
+ }
893
+ return { execPath, scriptPath };
894
+ }
895
+ function printHooksInstallClose(deps, harness, file) {
896
+ const label = HARNESS_LABELS[harness];
897
+ if (deps.io.interactive === true && deps.io.note) {
898
+ void deps.io.note(`${file}\nSend one ${label} prompt, then run \`notifai doctor\`.`, `${label} hooks installed`);
899
+ return;
900
+ }
901
+ deps.io.out(`Installed ${harness} hooks in ${file}`);
902
+ deps.io.out(`Send one ${label} prompt, then check \`notifai doctor\`.`);
903
+ }
904
+ export function hooksInstallCommand(deps, flags) {
905
+ if (flags.harness === undefined) {
906
+ const detected = detectedHarnesses(deps.cwd, deps.env);
907
+ if (detected.length === 0) {
908
+ deps.io.err(`Could not tell which harness you mean — pass --harness <${HARNESSES.join('|')}>.`);
909
+ return EXIT.usage;
910
+ }
911
+ let ok = true;
912
+ for (const harness of detected) {
913
+ if (hooksInstallCommand(deps, { ...flags, harness }) !== EXIT.ok)
914
+ ok = false;
915
+ }
916
+ return ok ? EXIT.ok : EXIT.failed;
917
+ }
918
+ const harness = resolveHarness(deps, flags.harness);
919
+ if (!harness)
920
+ return EXIT.usage;
921
+ const adapterTarget = resolveHookAdapterTarget(deps, flags);
922
+ const scriptPath = flags.scriptPath ?? fileHookInstallTarget(adapterTarget)?.scriptPath ?? process.argv[1] ?? 'notifai';
923
+ const hookPlatform = deps.hookPlatform ?? process.platform;
924
+ const nodePath = adapterTarget.execPath;
925
+ let adapterPath;
926
+ try {
927
+ adapterPath = installHookAdapter(adapterTarget, deps.hookAdapterHome, hookPlatform).path;
928
+ }
929
+ catch (err) {
930
+ deps.io.err(`Could not prepare the stable hook adapter: ${String(err)}`);
931
+ return EXIT.failed;
932
+ }
933
+ const wantGlobal = flags.global === true;
934
+ const existing = findInstallations(deps.cwd, deps.env, deps.hookAdapterHome, deps.hookPlatform).filter((installation) => installation.harness === harness);
935
+ const otherScope = existing.filter((installation) => installation.global !== wantGlobal);
936
+ if (!wantGlobal && otherScope.some((installation) => installation.global)) {
937
+ const globalFile = otherScope.find((installation) => installation.global)?.file;
938
+ 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}`);
939
+ return EXIT.ok;
940
+ }
941
+ if (wantGlobal && otherScope.some((installation) => !installation.global)) {
942
+ if (hooksUninstallCommand(deps, { ...flags, global: false, harness }) !== EXIT.ok) {
943
+ return EXIT.failed;
944
+ }
945
+ }
946
+ const codexPaths = harness === 'codex'
947
+ ? codexLayerPaths(wantGlobal, deps.cwd, deps.env, hookPlatform)
948
+ : null;
949
+ const settingsTarget = codexPaths?.configToml ?? settingsFile(harness, wantGlobal, deps.cwd, deps.env, hookPlatform);
950
+ // OpenCode's adapter is a generated plugin module rather than a handler
951
+ // merged into a settings document, so it owns the whole file.
952
+ if (harness === 'opencode') {
953
+ return installOpencodePlugin(deps, settingsTarget, {
954
+ adapterPath,
955
+ timeoutSeconds: BLOCKING_STOP_TIMEOUT_SECONDS,
956
+ platform: hookPlatform,
957
+ nodePath,
958
+ });
959
+ }
960
+ if (harness === 'cursor') {
961
+ try {
962
+ withTargetFileLock(settingsTarget, () => {
963
+ const document = loadCursorSettings(settingsTarget);
964
+ const result = mergeCursorHooks(document, buildCursorHookConfig({
965
+ adapterPath,
966
+ harness: 'cursor',
967
+ platform: hookPlatform,
968
+ nodePath,
969
+ }), scriptPath);
970
+ applyPlan(settingsTarget, result.document);
971
+ return result;
972
+ });
973
+ }
974
+ catch (err) {
975
+ deps.io.err(String(err));
976
+ return EXIT.failed;
977
+ }
978
+ printHooksInstallClose(deps, harness, settingsTarget);
979
+ return EXIT.ok;
980
+ }
981
+ const installInto = (file) => {
982
+ const document = loadSettings(file);
983
+ const foreignStopCount = foreignStopHandlers(document).length;
984
+ const result = mergeHooks(document, buildHookConfig({
985
+ adapterPath,
986
+ harness,
987
+ platform: hookPlatform,
988
+ nodePath,
989
+ }), scriptPath);
990
+ applyPlan(file, result.document);
991
+ return { file, foreignStopCount };
992
+ };
993
+ let installed;
994
+ try {
995
+ installed =
996
+ codexPaths === null
997
+ ? withTargetFileLock(settingsTarget, () => installInto(settingsTarget))
998
+ : withCodexLayerTransaction(codexPaths, (inspection) => installInto(inspection.writeTarget));
999
+ }
1000
+ catch (err) {
1001
+ deps.io.err(String(err));
1002
+ return EXIT.failed;
1003
+ }
1004
+ if (harness === 'codex') {
1005
+ const layer = flags.global ? null : codexLayerDir(deps.cwd);
1006
+ if (layer !== null)
1007
+ mkdirSync(layer, { recursive: true });
1008
+ }
1009
+ printHooksInstallClose(deps, harness, installed.file);
1010
+ if (installed.foreignStopCount > 0) {
1011
+ deps.io.out("This layer already has a Stop handler. Codex runs every matching handler, so Notifai's Stop and the existing one will both fire.");
1012
+ }
1013
+ if (harness === 'codex') {
1014
+ for (const problem of codexRepresentationProblems(deps.cwd, deps.env, hookPlatform)) {
1015
+ deps.io.out(problem);
1016
+ }
1017
+ for (const note of codexCoexistenceNotes(deps.cwd, deps.env, hookPlatform)) {
1018
+ deps.io.out(note);
1019
+ }
1020
+ if (flags.global) {
1021
+ const home = codexHomeNote(deps.env, hookPlatform);
1022
+ if (home !== null)
1023
+ deps.io.out(home);
1024
+ }
1025
+ }
1026
+ return EXIT.ok;
1027
+ }
1028
+ function foreignStopHandlers(document) {
1029
+ const groups = document.hooks?.['Stop'];
1030
+ if (!Array.isArray(groups))
1031
+ return [];
1032
+ return groups
1033
+ .flatMap((group) => group.hooks ?? [])
1034
+ .filter((handler) => !/ hook (user-prompt-submit|stop|session-end)\b/.test(handler.command));
1035
+ }
1036
+ /**
1037
+ * Writes the OpenCode plugin, replacing any Notifai plugin already there —
1038
+ * including one a different checkout wrote, matched on the managed marker for
1039
+ * the same reason command hooks are.
1040
+ */
1041
+ function installOpencodePlugin(deps, file, options) {
1042
+ try {
1043
+ withTargetFileLock(file, () => {
1044
+ if (existsSync(file)) {
1045
+ assertOwnedRegularFile(file);
1046
+ const existing = readFileSync(file, 'utf8');
1047
+ if (!isOurOpencodePlugin(existing)) {
1048
+ throw new Error(`${file} exists and was not written by Notifai; move it aside first.`);
1049
+ }
1050
+ }
1051
+ atomicWriteFileSync(file, opencodePluginSource(options), {
1052
+ mode: 0o600,
1053
+ preserveMode: false,
1054
+ requireCurrentUserOwner: true,
1055
+ });
1056
+ });
1057
+ }
1058
+ catch (err) {
1059
+ deps.io.err(String(err));
1060
+ return EXIT.failed;
1061
+ }
1062
+ printHooksInstallClose(deps, 'opencode', file);
1063
+ return EXIT.ok;
1064
+ }
1065
+ export function hooksUninstallCommand(deps, flags) {
1066
+ const harness = resolveHarness(deps, flags.harness);
1067
+ if (!harness)
1068
+ return EXIT.usage;
1069
+ const scriptPath = flags.scriptPath ?? process.argv[1] ?? 'notifai';
1070
+ const global = flags.global ?? false;
1071
+ const codexPaths = harness === 'codex'
1072
+ ? codexLayerPaths(global, deps.cwd, deps.env, deps.hookPlatform)
1073
+ : null;
1074
+ const file = codexPaths?.configToml ?? settingsFile(harness, global, deps.cwd, deps.env, deps.hookPlatform);
1075
+ if (harness === 'opencode') {
1076
+ try {
1077
+ return withTargetFileLock(file, () => {
1078
+ if (!existsSync(file)) {
1079
+ deps.io.out(`Nothing to remove: ${file} does not exist.`);
1080
+ return EXIT.ok;
1081
+ }
1082
+ assertOwnedRegularFile(file);
1083
+ // We own the whole file, but only if we wrote it.
1084
+ if (!isOurOpencodePlugin(readFileSync(file, 'utf8'))) {
1085
+ deps.io.out(`Left ${file} alone: Notifai did not write it.`);
1086
+ return EXIT.ok;
1087
+ }
1088
+ rmSync(file, { force: true });
1089
+ deps.io.out(`Removed the Notifai OpenCode plugin at ${file}`);
1090
+ return EXIT.ok;
1091
+ });
1092
+ }
1093
+ catch (err) {
1094
+ deps.io.err(String(err));
1095
+ return EXIT.failed;
1096
+ }
1097
+ }
1098
+ if (harness === 'cursor') {
1099
+ let stripped;
1100
+ try {
1101
+ stripped = withTargetFileLock(file, () => {
1102
+ if (!existsSync(file))
1103
+ return null;
1104
+ const document = loadCursorSettings(file);
1105
+ const result = removeCursorHooks(document, scriptPath);
1106
+ applyPlan(file, result.document);
1107
+ return result;
1108
+ });
1109
+ }
1110
+ catch (err) {
1111
+ deps.io.err(String(err));
1112
+ return EXIT.failed;
1113
+ }
1114
+ if (stripped === null) {
1115
+ deps.io.out(`Nothing to remove: ${file} does not exist.`);
1116
+ return EXIT.ok;
1117
+ }
1118
+ deps.io.out(stripped.replaced.length > 0
1119
+ ? `Removed Notifai hooks (${stripped.replaced.join(', ')}) from ${file}`
1120
+ : `No Notifai hooks found in ${file}`);
1121
+ return EXIT.ok;
1122
+ }
1123
+ const removeInstalledHooks = () => {
1124
+ const files = codexPaths === null
1125
+ ? hookDefinitionFiles(harness, global, deps.cwd, deps.env, deps.hookPlatform)
1126
+ : [codexPaths.hooksJson, codexPaths.configToml];
1127
+ const existing = files.filter((candidate) => existsSync(candidate));
1128
+ let removedAny = false;
1129
+ for (const candidate of existing) {
1130
+ const removeFromCandidate = () => {
1131
+ const document = loadSettings(candidate);
1132
+ const result = removeHooks(document, scriptPath);
1133
+ if (result.replaced.length > 0)
1134
+ applyPlan(candidate, result.document);
1135
+ return result;
1136
+ };
1137
+ const stripped = codexPaths === null
1138
+ ? withTargetFileLock(candidate, removeFromCandidate)
1139
+ : removeFromCandidate();
1140
+ if (stripped.replaced.length > 0) {
1141
+ removedAny = true;
1142
+ deps.io.out(`Removed Notifai hooks (${stripped.replaced.join(', ')}) from ${candidate}`);
1143
+ }
1144
+ }
1145
+ return { existing, removedAny };
1146
+ };
1147
+ let result;
1148
+ try {
1149
+ result =
1150
+ codexPaths === null
1151
+ ? removeInstalledHooks()
1152
+ : withCodexLayerTransaction(codexPaths, removeInstalledHooks);
1153
+ }
1154
+ catch (err) {
1155
+ deps.io.err(String(err));
1156
+ return EXIT.failed;
1157
+ }
1158
+ if (result.existing.length === 0) {
1159
+ deps.io.out(`Nothing to remove: ${file} does not exist.`);
1160
+ return EXIT.ok;
1161
+ }
1162
+ if (!result.removedAny) {
1163
+ deps.io.out(`No Notifai hooks found in ${result.existing.join(', ')}`);
1164
+ }
1165
+ return EXIT.ok;
1166
+ }
1167
+ function assertOwnedRegularFile(file) {
1168
+ const stat = lstatSync(file);
1169
+ if (stat.isSymbolicLink() || !stat.isFile()) {
1170
+ throw new Error(`${file} is not a regular file; refusing to read or replace it.`);
1171
+ }
1172
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined;
1173
+ if (uid !== undefined && stat.uid !== uid) {
1174
+ throw new Error(`${file} is owned by uid ${stat.uid}, not the current user.`);
1175
+ }
1176
+ }
1177
+ function resolveHarness(deps, requested) {
1178
+ if (requested !== undefined) {
1179
+ if (HARNESSES.includes(requested))
1180
+ return requested;
1181
+ deps.io.err(`Unknown harness "${requested}". Supported: ${HARNESSES.join(', ')}.`);
1182
+ return null;
1183
+ }
1184
+ const detected = detectHarness(deps.cwd, deps.env);
1185
+ if (!detected) {
1186
+ deps.io.err(`Could not tell which harness to install for — pass --harness <${HARNESSES.join('|')}>.`);
1187
+ return null;
1188
+ }
1189
+ return detected;
1190
+ }
1191
+ /**
1192
+ * Which harnesses to wire. An explicit `--harness` still wins as a singleton.
1193
+ * Otherwise: every detected harness, or a human picker when detection is empty
1194
+ * or names more than one.
1195
+ */
1196
+ export async function pickHarnessesToInstall(deps, requested) {
1197
+ if (requested !== undefined) {
1198
+ const harness = resolveHarness(deps, requested);
1199
+ return harness === null ? null : [harness];
1200
+ }
1201
+ const detected = detectedHarnesses(deps.cwd, deps.env);
1202
+ if (detected.length === 1)
1203
+ return detected;
1204
+ if (deps.io.interactive === true && deps.io.multiselect) {
1205
+ const picked = await deps.io.multiselect('Which agent harnesses should Notifai wire here?', HARNESSES.map((name) => ({
1206
+ value: name,
1207
+ label: HARNESS_LABELS[name],
1208
+ ...(detected.includes(name) ? { hint: 'detected on this machine' } : {}),
1209
+ })), detected);
1210
+ if (picked === null)
1211
+ return null;
1212
+ const unknown = picked.filter((name) => !HARNESSES.includes(name));
1213
+ if (unknown.length > 0) {
1214
+ deps.io.err(`Unknown harness "${unknown[0]}". Supported: ${HARNESSES.join(', ')}.`);
1215
+ return null;
1216
+ }
1217
+ return picked;
1218
+ }
1219
+ if (detected.length === 0) {
1220
+ deps.io.err(`Could not tell which harness to wire. Run: notifai hooks install --harness <${HARNESSES.join('|')}>`);
1221
+ return null;
1222
+ }
1223
+ return detected;
1224
+ }
1225
+ //# sourceMappingURL=commands-hooks.js.map