@raidiant/notifai 10.1.1 → 10.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/commands-core.d.ts +1 -1
  3. package/dist/commands-init.js +9 -6
  4. package/dist/commands-init.js.map +1 -1
  5. package/dist/commands-send-support.js +3 -0
  6. package/dist/commands-send-support.js.map +1 -1
  7. package/dist/commands-skill.js +72 -54
  8. package/dist/commands-skill.js.map +1 -1
  9. package/dist/invocation-context.d.ts +1 -0
  10. package/dist/invocation-context.js +9 -1
  11. package/dist/invocation-context.js.map +1 -1
  12. package/dist/native-skills.d.ts +13 -3
  13. package/dist/native-skills.js +51 -12
  14. package/dist/native-skills.js.map +1 -1
  15. package/dist/node-floor.d.ts +2 -1
  16. package/dist/node-floor.js +9 -5
  17. package/dist/node-floor.js.map +1 -1
  18. package/dist/orca-session-title.d.ts +5 -4
  19. package/dist/orca-session-title.js +32 -19
  20. package/dist/orca-session-title.js.map +1 -1
  21. package/dist/platform.d.ts +11 -17
  22. package/dist/platform.js +20 -23
  23. package/dist/platform.js.map +1 -1
  24. package/dist/release.d.ts +5 -5
  25. package/dist/release.js +5 -5
  26. package/dist/setup-destinations.js +1 -1
  27. package/dist/setup-destinations.js.map +1 -1
  28. package/dist/skill-integrity.d.ts +49 -0
  29. package/dist/skill-integrity.js +154 -0
  30. package/dist/skill-integrity.js.map +1 -0
  31. package/dist/skill-source/manifest.json +16 -0
  32. package/dist/skill-source/notifai/SKILL.md +390 -0
  33. package/dist/skill-source/notifai/references/harness-setup.md +220 -0
  34. package/package.json +11 -14
  35. package/src/atomic-file.ts +0 -198
  36. package/src/claude-wake.test.ts +0 -321
  37. package/src/claude-wake.ts +0 -499
  38. package/src/cli-bin.test.ts +0 -176
  39. package/src/cli-bin.ts +0 -233
  40. package/src/cli-release.test.ts +0 -46
  41. package/src/cli-release.ts +0 -78
  42. package/src/cli-update-contract.ts +0 -9
  43. package/src/cli-update.test.ts +0 -125
  44. package/src/client.test.ts +0 -390
  45. package/src/client.ts +0 -352
  46. package/src/codex-wake.test.ts +0 -254
  47. package/src/codex-wake.ts +0 -301
  48. package/src/command-session.ts +0 -38
  49. package/src/commands-agent-sessions.ts +0 -72
  50. package/src/commands-auth.ts +0 -238
  51. package/src/commands-config.ts +0 -336
  52. package/src/commands-core.ts +0 -312
  53. package/src/commands-devices.ts +0 -180
  54. package/src/commands-doctor.ts +0 -1501
  55. package/src/commands-guidance.ts +0 -181
  56. package/src/commands-harness-context.ts +0 -207
  57. package/src/commands-hook-shape.ts +0 -69
  58. package/src/commands-hooks.ts +0 -2318
  59. package/src/commands-init.ts +0 -1055
  60. package/src/commands-io.ts +0 -108
  61. package/src/commands-logs.ts +0 -243
  62. package/src/commands-project.ts +0 -47
  63. package/src/commands-send-support.test.ts +0 -156
  64. package/src/commands-send-support.ts +0 -311
  65. package/src/commands-send.ts +0 -875
  66. package/src/commands-setup-proof.test.ts +0 -72
  67. package/src/commands-setup-proof.ts +0 -124
  68. package/src/commands-skill.test.ts +0 -44
  69. package/src/commands-skill.ts +0 -204
  70. package/src/commands-sounds.test.ts +0 -106
  71. package/src/commands-sounds.ts +0 -49
  72. package/src/commands-update.ts +0 -180
  73. package/src/commands.test.ts +0 -8297
  74. package/src/commands.ts +0 -77
  75. package/src/config-schema.test.ts +0 -153
  76. package/src/config-schema.ts +0 -349
  77. package/src/config.test.ts +0 -581
  78. package/src/config.ts +0 -475
  79. package/src/credentials.test.ts +0 -403
  80. package/src/credentials.ts +0 -403
  81. package/src/file-lock-process-worker.test.ts +0 -64
  82. package/src/file-lock.test.ts +0 -320
  83. package/src/file-lock.ts +0 -393
  84. package/src/fixtures/hermes-0.20.6-classic-cli-local.json +0 -50
  85. package/src/fixtures/openclaw-2026.7.1-2-agent-local.json +0 -57
  86. package/src/generated-session-label.ts +0 -155
  87. package/src/guidance-content.ts +0 -278
  88. package/src/guidance-render.ts +0 -56
  89. package/src/guidance.test.ts +0 -327
  90. package/src/guidance.ts +0 -233
  91. package/src/harness-integration.test.ts +0 -294
  92. package/src/harnesses.test.ts +0 -149
  93. package/src/harnesses.ts +0 -164
  94. package/src/hook-adapter.test.ts +0 -496
  95. package/src/hook-adapter.ts +0 -424
  96. package/src/hook-input.test.ts +0 -39
  97. package/src/hook-input.ts +0 -72
  98. package/src/hooks.test.ts +0 -5824
  99. package/src/hooks.ts +0 -4011
  100. package/src/install-hooks.test.ts +0 -1614
  101. package/src/install-hooks.ts +0 -1501
  102. package/src/interactive.test.ts +0 -387
  103. package/src/interactive.ts +0 -858
  104. package/src/invocation-context.test.ts +0 -352
  105. package/src/invocation-context.ts +0 -197
  106. package/src/logging-process-worker.test.ts +0 -45
  107. package/src/logging.test.ts +0 -544
  108. package/src/logging.ts +0 -698
  109. package/src/main-run.ts +0 -45
  110. package/src/main.ts +0 -12
  111. package/src/native-skills.test.ts +0 -115
  112. package/src/native-skills.ts +0 -162
  113. package/src/node-floor.test.ts +0 -27
  114. package/src/node-floor.ts +0 -37
  115. package/src/onboarding-docs.test.ts +0 -25
  116. package/src/openclaw-plugin.ts +0 -409
  117. package/src/opencode-plugin.ts +0 -298
  118. package/src/orca-session-title.test.ts +0 -54
  119. package/src/orca-session-title.ts +0 -103
  120. package/src/pack-feedback-slice.test.ts +0 -212
  121. package/src/pack-feedback-slice.ts +0 -187
  122. package/src/platform.test.ts +0 -152
  123. package/src/platform.ts +0 -173
  124. package/src/program.test.ts +0 -317
  125. package/src/program.ts +0 -842
  126. package/src/project-enablement.test.ts +0 -55
  127. package/src/project-enablement.ts +0 -99
  128. package/src/question-caps.test.ts +0 -49
  129. package/src/question-settlement-process.ts +0 -47
  130. package/src/question-timing.ts +0 -56
  131. package/src/readiness.test.ts +0 -25
  132. package/src/readiness.ts +0 -212
  133. package/src/release.ts +0 -51
  134. package/src/send-attempts.test.ts +0 -143
  135. package/src/send-attempts.ts +0 -188
  136. package/src/send.test.ts +0 -28
  137. package/src/send.ts +0 -436
  138. package/src/session-activation.ts +0 -61
  139. package/src/session-end-log-lock-worker.test.ts +0 -35
  140. package/src/session-labels.test.ts +0 -490
  141. package/src/session-labels.ts +0 -474
  142. package/src/setup-destinations.test.ts +0 -41
  143. package/src/setup-destinations.ts +0 -50
  144. package/src/skill.test.ts +0 -426
  145. package/src/sound-ref.test.ts +0 -31
  146. package/src/sound-ref.ts +0 -34
  147. package/src/trust-policy.test.ts +0 -701
  148. package/src/ui/banner.ts +0 -95
  149. package/src/ui/config-view.test.ts +0 -90
  150. package/src/ui/config-view.ts +0 -138
  151. package/src/ui/help.test.ts +0 -16
  152. package/src/ui/help.ts +0 -128
  153. package/src/ui/theme.test.ts +0 -92
  154. package/src/ui/theme.ts +0 -265
  155. package/src/url-policy.ts +0 -399
  156. package/tsconfig.json +0 -10
@@ -1,875 +0,0 @@
1
- import {
2
- CAPABILITIES_V1,
3
- REPLY_MAX_WINDOW_SECONDS,
4
- validateDraft,
5
- type EvidenceSnapshot,
6
- type ListRepliesResponse,
7
- type ReplyView,
8
- type SubmissionReceipt,
9
- } from '@raidiant/notifai-protocol'
10
- import { ApiCallError, NetworkError } from './client.js'
11
- import type { FlagOverrides, loadConfig } from './config.js'
12
- import {
13
- MIN_REPLY_WINDOW_SECONDS,
14
- inspectQuestionState,
15
- readSessionState,
16
- type QuestionStateView,
17
- } from './hooks.js'
18
- import { enableProject, projectBinding } from './project-enablement.js'
19
- import {
20
- buildDraft,
21
- formatReceipt,
22
- receiptExitCode,
23
- rejectAccidentalEscapedNewlines,
24
- validateMediaInputs,
25
- type SendFlags,
26
- } from './send.js'
27
- import { recordObservedDeliveryProof, setupProofProject } from './commands-setup-proof.js'
28
- import {
29
- EXIT,
30
- authedClient,
31
- loadLoggedConfig,
32
- log,
33
- reportError,
34
- type CommandDeps,
35
- } from './commands-core.js'
36
- import { sourceContextHarnessSession } from './commands-harness-context.js'
37
- import { resolveCommandSession } from './command-session.js'
38
- import {
39
- beginSendAttempt,
40
- semanticMediaIds,
41
- sendDraftFingerprint,
42
- settleSendAttempt,
43
- } from './send-attempts.js'
44
- import {
45
- acknowledgementCommand,
46
- printAcknowledgementStatus,
47
- resolveDraftInvocation,
48
- uploadImage,
49
- waitForReply,
50
- } from './commands-send-support.js'
51
-
52
- // ---------------------------------------------------------------------------
53
- // send / status
54
- // ---------------------------------------------------------------------------
55
-
56
-
57
- export async function sendCommand(
58
- deps: CommandDeps,
59
- flags: SendFlags & {
60
- json?: boolean
61
- wait?: number
62
- noWait?: boolean
63
- replyTimeout?: number
64
- idempotencyKey?: string
65
- retry?: boolean
66
- baseUrl?: string
67
- },
68
- ): Promise<number> {
69
- if (flags.retry === true && flags.idempotencyKey !== undefined) {
70
- deps.io.err('Pass --retry or --idempotency-key, not both.')
71
- return EXIT.usage
72
- }
73
- const hasChoice = Array.isArray(flags.choice)
74
- ? flags.choice.length > 0
75
- : flags.choice !== undefined
76
- if (flags.reply && flags.kind !== undefined && flags.kind !== 'question') {
77
- deps.io.err(`--kind ${flags.kind} cannot be combined with --reply; a reply request is a question.`)
78
- return EXIT.usage
79
- }
80
- // Kind now decides the sound a notification arrives with, so it is asked for
81
- // at the boundary rather than defaulted silently: an unlabelled send would
82
- // reach the user as ordinary news whatever actually happened.
83
- if (!flags.reply && flags.kind === undefined) {
84
- deps.io.err(
85
- '--kind is required: say what this notification is. ' +
86
- 'update (news) · done (finished) · failed (terminal failure) · blocked (cannot proceed; no User reply would resume it). ' +
87
- '--reply makes it a question without --kind.',
88
- )
89
- return EXIT.usage
90
- }
91
- if (!flags.reply && flags.kind === 'question') {
92
- deps.io.err('--kind question requires --reply so the question can be answered.')
93
- return EXIT.usage
94
- }
95
- if (
96
- !flags.reply &&
97
- (flags.replyTimeout !== undefined || flags.replyWindow !== undefined || hasChoice)
98
- ) {
99
- deps.io.err('Use --reply with --reply-timeout, --reply-window, or --choice.')
100
- return EXIT.usage
101
- }
102
- const replyTimeout = flags.replyTimeout ?? 900
103
- if (flags.reply && !isNonNegativeInteger(replyTimeout)) {
104
- deps.io.err('--reply-timeout must be a non-negative integer number of seconds.')
105
- return EXIT.usage
106
- }
107
- // Asking while declaring that nothing will wait for the answer. The reply is
108
- // captured server-side and then unreachable: only a blocking send waits for
109
- // it, and the hook path drains questions registered by `ask`, never a send's
110
- // request id. So the user gets a real button, taps it, and nothing happens —
111
- // worse than a banner that never asked, because it spends their attention
112
- // and their trust in the channel.
113
- if (flags.reply && replyTimeout === 0) {
114
- deps.io.err(
115
- 'A question needs someone to hear the answer, so --reply cannot be combined ' +
116
- 'with --reply-timeout 0.\n' +
117
- 'To ask and end the turn, use `notifai ask` — the turn-end hook returns the answer.\n' +
118
- 'To announce finished work, drop --reply and its choices.',
119
- )
120
- return EXIT.usage
121
- }
122
- if (
123
- flags.reply &&
124
- flags.replyWindow !== undefined &&
125
- (!Number.isInteger(flags.replyWindow) ||
126
- flags.replyWindow < MIN_REPLY_WINDOW_SECONDS ||
127
- flags.replyWindow > REPLY_MAX_WINDOW_SECONDS)
128
- ) {
129
- deps.io.err(
130
- `--reply-window must be an integer from ${MIN_REPLY_WINDOW_SECONDS} to ${REPLY_MAX_WINDOW_SECONDS} seconds.`,
131
- )
132
- return EXIT.usage
133
- }
134
- const escapedBody = rejectAccidentalEscapedNewlines(flags.body, flags.literalBackslashN)
135
- if (escapedBody !== null) {
136
- deps.io.err(escapedBody)
137
- return EXIT.usage
138
- }
139
- const mediaInputError = validateMediaInputs(flags.image, flags.imageAlt)
140
- if (mediaInputError !== null) {
141
- deps.io.err(mediaInputError)
142
- return EXIT.usage
143
- }
144
- const config = loadLoggedConfig(deps, {
145
- cwd: deps.cwd,
146
- env: deps.env,
147
- flags: { base_url: flags.baseUrl, wait_seconds: flags.wait } as FlagOverrides,
148
- })
149
- const source = resolveDraftInvocation(
150
- deps,
151
- flags,
152
- sourceContextHarnessSession(deps.env, deps.cwd, (deps.now ?? Date.now)()),
153
- )
154
- if (!source.ok) {
155
- deps.io.err(source.error)
156
- return EXIT.usage
157
- }
158
- let semanticImages: string[]
159
- try {
160
- semanticImages = semanticMediaIds(flags.image ?? [], deps.cwd)
161
- } catch (err) {
162
- deps.io.err(`Could not fingerprint an image for safe retry: ${String(err)}`)
163
- return EXIT.usage
164
- }
165
- const semanticBuild = buildDraft(
166
- config,
167
- { ...flags, ...(semanticImages.length > 0 ? { image: semanticImages } : {}) },
168
- source.invocation,
169
- )
170
- if (!semanticBuild.ok) {
171
- deps.io.err(semanticBuild.error)
172
- return EXIT.usage
173
- }
174
- if (semanticBuild.draft.project !== undefined) {
175
- const binding = projectBinding(deps.cwd, deps.env, semanticBuild.draft.project)
176
- if (binding !== null) enableProject(binding)
177
- }
178
- const authed = authedClient(deps, config)
179
- if (!authed) return EXIT.auth
180
- const credential = deps.store.load()!
181
- const attempt = beginSendAttempt({
182
- env: deps.env,
183
- credential,
184
- fingerprint: sendDraftFingerprint(semanticBuild.draft, credential),
185
- retry: flags.retry === true,
186
- ...(flags.idempotencyKey === undefined ? {} : { idempotencyKey: flags.idempotencyKey }),
187
- now: (deps.now ?? Date.now)(),
188
- })
189
- if (!attempt.ok) {
190
- deps.io.err(`${attempt.code}: ${attempt.message}`)
191
- return EXIT.usage
192
- }
193
- const mediaIds: string[] = []
194
- for (const image of flags.image ?? []) {
195
- if (image.startsWith('med_')) {
196
- mediaIds.push(image)
197
- continue
198
- }
199
- const uploaded = await uploadImage(deps, authed.client, image, config.media_origins.value)
200
- if (!uploaded.ok) {
201
- settleSendAttempt(deps.env, attempt.attemptId)
202
- if (uploaded.error !== null) deps.io.err(uploaded.error)
203
- return uploaded.exit
204
- }
205
- mediaIds.push(uploaded.mediaId)
206
- }
207
- flags = { ...flags, image: mediaIds }
208
- const build = buildDraft(config, flags, source.invocation)
209
- if (!build.ok) {
210
- settleSendAttempt(deps.env, attempt.attemptId)
211
- deps.io.err(build.error)
212
- return EXIT.usage
213
- }
214
- const capabilities = CAPABILITIES_V1.describe(build.platform)
215
- if (!capabilities) {
216
- settleSendAttempt(deps.env, attempt.attemptId)
217
- deps.io.err(`No capability contract is available for ${build.platform}.`)
218
- return EXIT.usage
219
- }
220
- const validation = validateDraft(build.draft, capabilities)
221
- if (!validation.ok) {
222
- settleSendAttempt(deps.env, attempt.attemptId)
223
- for (const issue of validation.errors) deps.io.err(`${issue.path}: ${issue.message}`)
224
- return EXIT.usage
225
- }
226
- for (const warning of validation.warnings) {
227
- deps.io.err(`Heads up (${warning.path}): ${warning.message}`)
228
- }
229
- emitSendWarnings(deps, flags, config)
230
- if (
231
- !flags.reply &&
232
- (flags.title.trim().endsWith('?') || flags.body.trim().endsWith('?'))
233
- ) {
234
- deps.io.err(
235
- 'Heads up: this notification ends with a question but has no reply action. Add --reply (and optionally --choice) so it can be answered from the notification.',
236
- )
237
- }
238
- const waitSeconds = flags.noWait ? 0 : config.wait_seconds.value
239
- const idempotencyKey = attempt.idempotencyKey
240
- // Persist the retry identity before entering the ambiguous network boundary.
241
- // If the process is killed after the server accepts but before a response,
242
- // this is the only durable way to reconstruct the same Agent Event key.
243
- log(deps).info('send.attempt', {
244
- attempt_id: attempt.attemptId,
245
- idempotency_key: idempotencyKey,
246
- replay: attempt.replay,
247
- })
248
- let receipt: SubmissionReceipt
249
- try {
250
- receipt = await authed.client.submit(
251
- { idempotency_key: idempotencyKey, draft: build.draft },
252
- waitSeconds,
253
- )
254
- } catch (err) {
255
- const exit = reportError(deps, err)
256
- if (exit === EXIT.network) {
257
- deps.io.err(
258
- 'The server may have accepted this Notification Request before the connection failed. ' +
259
- 'Re-run the exact semantic send with `--retry`; the CLI will reuse its opaque attempt identity.',
260
- )
261
- }
262
- if (err instanceof ApiCallError && err.code === 'no_active_devices') {
263
- deps.io.err(
264
- 'After setup succeeds, repeat this exact original Notification Request with `--retry`; ' +
265
- 'the setup verification request does not replace this Agent Event.',
266
- )
267
- }
268
- if (!(exit === EXIT.network || (err instanceof ApiCallError && err.code === 'no_active_devices'))) {
269
- settleSendAttempt(deps.env, attempt.attemptId)
270
- } else {
271
- deps.io.err(`Opaque retry attempt: ${attempt.attemptId}. Re-run the exact semantic send with \`--retry\`; do not retry automatically.`)
272
- }
273
- return exit
274
- }
275
- settleSendAttempt(deps.env, attempt.attemptId)
276
- const receiptExit = receiptExitCode(receipt)
277
- // The single most useful line in the log: it ties the local invocation to
278
- // the server-side request id, which is what every later question about this
279
- // notification ("did it arrive?", "which device?") is asked in terms of.
280
- log(deps).info('send.submitted', {
281
- request_id: receipt.request_id,
282
- kind: flags.reply ? 'question' : (flags.kind ?? 'update'),
283
- title_chars: flags.title.length,
284
- overall: receipt.overall,
285
- replayed: receipt.replayed,
286
- agent_acknowledgement_required: receipt.agent_acknowledgement_required,
287
- deliveries: receipt.deliveries.length,
288
- wait_seconds: waitSeconds,
289
- exit: receiptExit,
290
- })
291
- log(deps).info('send.outcome', {
292
- request_id: receipt.request_id,
293
- overall: receipt.overall,
294
- // Per device, because "it said accepted but nothing arrived" is answered
295
- // by which device reached which state and why the provider said so.
296
- devices: receipt.deliveries.map((delivery) => ({
297
- device: delivery.device_name,
298
- state: delivery.state,
299
- attempts: delivery.attempts,
300
- provider_status: delivery.provider_status,
301
- provider_reason: delivery.provider_reason,
302
- })),
303
- ...(receipt.warnings.length > 0 ? { warnings: receipt.warnings } : {}),
304
- })
305
- if (!flags.json) {
306
- const quietOrdinarySuccess =
307
- !flags.reply &&
308
- receipt.overall === 'provider_accepted_all' &&
309
- receipt.warnings.length === 0
310
- if (!quietOrdinarySuccess) deps.io.out(formatReceipt(receipt))
311
- }
312
-
313
- // A zero wait can no longer reach here: --reply guarantees a positive one.
314
- if (!flags.reply || receiptExit !== EXIT.ok) {
315
- if (flags.json) {
316
- deps.io.out(
317
- flags.reply
318
- ? JSON.stringify(unansweredReplyResultJson(receipt, false))
319
- : JSON.stringify(receipt, null, 2),
320
- )
321
- }
322
- return receiptExit
323
- }
324
-
325
- try {
326
- const result = await waitForReply(authed.client, receipt.request_id, {
327
- timeoutSeconds: replyTimeout,
328
- afterSeq: 0,
329
- now: deps.now,
330
- sleep: deps.sleep,
331
- })
332
- recordReplies(deps, receipt.request_id, result.response.replies)
333
- if (flags.json) {
334
- deps.io.out(
335
- JSON.stringify(replyResultJson(result.response, result.degraded, receipt)),
336
- )
337
- } else if (result.response.replies.length > 0) {
338
- printReplies(deps, result.response.replies)
339
- printAcknowledgementStatus(deps, result.response)
340
- } else {
341
- printNoReply(deps, receipt.request_id, result.response.reply_expires_at)
342
- printAcknowledgementStatus(deps, result.response)
343
- }
344
- if (result.degraded) {
345
- log(deps).error('cli.error', {
346
- kind: 'network',
347
- operation: 'reply_wait',
348
- request_id: receipt.request_id,
349
- degraded: true,
350
- message: 'the reply wait ended while the server was unreachable or faulting',
351
- })
352
- deps.io.err(degradedWaitWarning(receipt.request_id))
353
- return EXIT.network
354
- }
355
- if (result.timedOut) {
356
- deps.io.err(
357
- `No reply yet. Retrieve it with \`notifai replies ${receipt.request_id}\` or retire the question with ` +
358
- `\`notifai close ${receipt.request_id}\`. ` +
359
- `This is a reply-wait timeout, not a Delivery or Companion Receipt failure — check with \`notifai status ${receipt.request_id}\`.`,
360
- )
361
- }
362
- return result.timedOut ? EXIT.noReply : EXIT.ok
363
- } catch (err) {
364
- // The send already succeeded durably; a wait fault must not read as "send
365
- // failed". Permanent poll errors (auth, closed window, not found) still
366
- // surface, but always name the durable request and point at recovery.
367
- if (err instanceof ApiCallError || err instanceof NetworkError) {
368
- log(deps).error('cli.error', {
369
- kind: err instanceof ApiCallError ? 'api' : 'network',
370
- operation: 'reply_wait',
371
- request_id: receipt.request_id,
372
- ...(err instanceof ApiCallError ? { status: err.status, code: err.code } : {}),
373
- message: err.message,
374
- })
375
- deps.io.err(
376
- `notifai: reply wait failed for ${receipt.request_id} (${err instanceof ApiCallError ? err.code : 'network'}: ${err.message}). ` +
377
- `Delivery and Companion Receipt are independent — check with \`notifai status ${receipt.request_id}\` and retry with \`notifai replies ${receipt.request_id}\`.`,
378
- )
379
- // JSON callers still get their one object: the durable receipt, no
380
- // replies, and `degraded: true` — "could not find out", not "no answer".
381
- if (flags.json) deps.io.out(JSON.stringify(unansweredReplyResultJson(receipt, true)))
382
- if (err instanceof ApiCallError) {
383
- if (err.code === 'auth_required' || err.code === 'machine_revoked') return EXIT.auth
384
- return err.status >= 500 || err.status === 429 || err.status === 408
385
- ? EXIT.network
386
- : EXIT.failed
387
- }
388
- return EXIT.network
389
- }
390
- return reportError(deps, err)
391
- }
392
- }
393
-
394
- function emitSendWarnings(
395
- deps: CommandDeps,
396
- flags: SendFlags,
397
- config: ReturnType<typeof loadConfig>,
398
- ): void {
399
- if (flags.title.length > 40) {
400
- deps.io.err(
401
- `Heads up: this title is ${flags.title.length} characters; notification titles work best around 40 characters or fewer.`,
402
- )
403
- }
404
- if (/^(?:update|done|question|failed|blocked)\s*(?:[·:—-]|$)/i.test(flags.title.trim())) {
405
- deps.io.err(
406
- 'Heads up: keep the title to the specific substance. Put notification type in --kind; Project identity is inferred separately.',
407
- )
408
- }
409
- if (
410
- flags.collapseKey === undefined &&
411
- config.collapse_key.value !== null &&
412
- config.collapse_key.source.startsWith('global:')
413
- ) {
414
- deps.io.err(
415
- 'Heads up: collapse_key comes from machine-global config, so unrelated notifications may replace each other. Prefer a project or command-specific --collapse-key.',
416
- )
417
- }
418
- if (flags.ttl !== undefined && flags.ttl > 259_200) {
419
- deps.io.err(
420
- 'Heads up: this explicit --ttl is longer than 72 hours; stale notifications may arrive after they are useful.',
421
- )
422
- }
423
- }
424
-
425
- export async function repliesCommand(
426
- deps: CommandDeps,
427
- requestedId: string | undefined,
428
- flags: { wait?: number; after?: number; json?: boolean; pending?: boolean },
429
- ): Promise<number> {
430
- const waitSeconds = flags.wait ?? 0
431
- const afterSeq = flags.after ?? 0
432
- if (!isNonNegativeInteger(waitSeconds)) {
433
- deps.io.err('--wait must be a non-negative integer number of seconds.')
434
- return EXIT.usage
435
- }
436
- if (!isNonNegativeInteger(afterSeq)) {
437
- deps.io.err('--after must be a non-negative integer sequence number.')
438
- return EXIT.usage
439
- }
440
-
441
- if (flags.pending === true && requestedId !== undefined) {
442
- deps.io.err('Pass a request id or --pending, not both.')
443
- return EXIT.usage
444
- }
445
- let requestIds = requestedId === undefined ? [] : [requestedId]
446
- let lifecycleSessionId: string | undefined
447
- if (flags.pending === true) {
448
- const session = resolveCommandSession(deps)
449
- if (session === null) {
450
- deps.io.err('No active session pointer is available in this directory.')
451
- return EXIT.noReply
452
- }
453
- const sessionId = session.sessionId
454
- lifecycleSessionId = sessionId
455
- // Every delivered question in the session's queue, in registration order —
456
- // an agent may have several outstanding at once.
457
- const state = readSessionState(sessionId, deps.env)
458
- const pending = Array.isArray(state.pending) ? state.pending : []
459
- requestIds = pending
460
- .map((entry) => entry.request_id)
461
- .filter((id): id is string => id !== undefined)
462
- const unsent = pending.filter((entry) => entry.request_id === undefined)
463
- if (requestIds.length === 0) {
464
- // `--json` is a promise about stdout, and an empty result is still a
465
- // result: a caller that asked for machine-readable output must not have
466
- // to parse an English sentence to learn there was nothing pending.
467
- if (flags.json === true) {
468
- deps.io.out(
469
- JSON.stringify(
470
- {
471
- session_id: sessionId,
472
- pending: unsent.map((entry) => ({
473
- question: entry.question,
474
- ...(entry.question_id === undefined ? {} : { question_id: entry.question_id }),
475
- })),
476
- replies: [],
477
- },
478
- null,
479
- 2,
480
- ),
481
- )
482
- } else if (unsent.length > 0) {
483
- for (const entry of unsent) {
484
- deps.io.out(
485
- entry.question_id === undefined
486
- ? `unpushed question: ${entry.question}`
487
- : `unpushed question ${entry.question_id}: ${entry.question}`,
488
- )
489
- }
490
- deps.io.out('Retire one with `notifai close <question_id>` so a later Stop will not send it.')
491
- } else {
492
- deps.io.err(`Session ${sessionId} has no pushed question pending.`)
493
- }
494
- return unsent.length > 0 ? EXIT.ok : EXIT.noReply
495
- }
496
- if (unsent.length > 0 && flags.json !== true) {
497
- for (const entry of unsent) {
498
- deps.io.out(
499
- entry.question_id === undefined
500
- ? `unpushed question: ${entry.question}`
501
- : `unpushed question ${entry.question_id}: ${entry.question}`,
502
- )
503
- }
504
- }
505
- }
506
- if (requestIds.length === 0) {
507
- deps.io.err('Pass a request id or --pending.')
508
- return EXIT.usage
509
- }
510
-
511
- const config = loadLoggedConfig(deps, {
512
- cwd: deps.cwd,
513
- env: deps.env,
514
- ...(lifecycleSessionId === undefined ? {} : { sessionId: lifecycleSessionId }),
515
- })
516
- const authed = authedClient(deps, config)
517
- if (!authed) return EXIT.auth
518
- try {
519
- let anyReplies = false
520
- const degradedRequestIds: string[] = []
521
- let allTimedOut = true
522
- const jsonBodies: object[] = []
523
- for (const requestId of requestIds) {
524
- try {
525
- const result = await waitForReply(authed.client, requestId, {
526
- timeoutSeconds: waitSeconds,
527
- afterSeq,
528
- now: deps.now,
529
- sleep: deps.sleep,
530
- })
531
- recordReplies(deps, requestId, result.response.replies)
532
- if (flags.json) {
533
- jsonBodies.push(replyResultJson(result.response, result.degraded))
534
- } else if (result.response.replies.length > 0) {
535
- if (flags.pending === true) deps.io.out(`pending request ${requestId}`)
536
- printReplies(deps, result.response.replies)
537
- printAcknowledgementStatus(deps, result.response)
538
- } else {
539
- printNoReply(deps, requestId, result.response.reply_expires_at)
540
- printAcknowledgementStatus(deps, result.response)
541
- }
542
- anyReplies ||= result.response.replies.length > 0
543
- if (result.degraded) degradedRequestIds.push(requestId)
544
- allTimedOut &&= result.timedOut
545
- } catch (err) {
546
- recordDegradedReplyWaits(deps, degradedRequestIds)
547
- return reportError(deps, err, { operation: 'reply_wait', request_id: requestId })
548
- }
549
- }
550
- if (flags.json) {
551
- // One request keeps the response shape agents already parse; several
552
- // (only possible via --pending) arrive as an array in queue order.
553
- deps.io.out(JSON.stringify(jsonBodies.length === 1 ? jsonBodies[0] : jsonBodies, null, 2))
554
- }
555
- if (degradedRequestIds.length > 0) {
556
- recordDegradedReplyWaits(deps, degradedRequestIds)
557
- // Name a request whose polls actually degraded, not merely the first item
558
- // in a multi-request queue that may have completed cleanly.
559
- deps.io.err(degradedWaitWarning(degradedRequestIds[0]!))
560
- return EXIT.network
561
- }
562
- if (anyReplies) return EXIT.ok
563
- return allTimedOut ? EXIT.noReply : EXIT.ok
564
- } catch (err) {
565
- return reportError(deps, err)
566
- }
567
- }
568
-
569
-
570
- function recordDegradedReplyWaits(deps: CommandDeps, requestIds: readonly string[]): void {
571
- if (requestIds.length === 0) return
572
- log(deps).error('cli.error', {
573
- kind: 'network',
574
- operation: 'reply_wait',
575
- request_ids: requestIds,
576
- degraded: true,
577
- message: 'the reply wait ended while the server was unreachable or faulting',
578
- })
579
- }
580
-
581
- /**
582
- * Shared by every surface that waits: "the user did not answer" and "I could
583
- * not find out" must not look the same, because agents branch on the exit code
584
- * and one of those two branches is safe to proceed from.
585
- *
586
- * Delivery / Companion Receipt / OS presentation are separate facts — a wait
587
- * fault is not evidence that the push failed.
588
- */
589
- function degradedWaitWarning(requestId: string): string {
590
- return (
591
- `notifai: the wait for ${requestId} ended while the server was unreachable or faulting, ` +
592
- `so this is "could not find out", not "no answer" — the request is still durable and the ` +
593
- `reply may already be waiting (Provider Acceptance and Companion Receipt are independent). ` +
594
- `Retry with \`notifai replies ${requestId}\`.`
595
- )
596
- }
597
- function isNonNegativeInteger(value: number): boolean {
598
- return Number.isInteger(value) && value >= 0
599
- }
600
-
601
-
602
- /**
603
- * The one JSON object `send --reply --json` prints, whatever happens after the
604
- * durable submit. Embedding the receipt keeps stdout a single parseable line;
605
- * `replies` (from a wait) omits it because there is no submission to report.
606
- */
607
- function replyResultJson(
608
- response: ListRepliesResponse,
609
- degraded: boolean,
610
- receipt?: SubmissionReceipt,
611
- ): object {
612
- return {
613
- type: 'reply_result',
614
- ...(receipt !== undefined ? { receipt } : {}),
615
- request_id: response.request_id,
616
- reply_expires_at: response.reply_expires_at,
617
- replies: response.replies,
618
- agent_acknowledgement_required: response.agent_acknowledgement_required,
619
- agent_acknowledgement: response.agent_acknowledgement,
620
- agent_acknowledgement_text_required: response.agent_acknowledgement_text_required,
621
- acknowledgement_command: acknowledgementCommand(
622
- response.request_id,
623
- response.agent_acknowledgement_required,
624
- response.agent_acknowledgement_text_required,
625
- response.agent_acknowledgement,
626
- response.replies.length > 0,
627
- ),
628
- degraded,
629
- }
630
- }
631
-
632
- /**
633
- * The reply_result for a reply send that has no answer to report — a receipt
634
- * failure, or a wait that faulted. Same shape, same single line; `degraded`
635
- * distinguishes "the wait could not find out" from "delivery already failed".
636
- */
637
- function unansweredReplyResultJson(receipt: SubmissionReceipt, degraded: boolean): object {
638
- return {
639
- type: 'reply_result',
640
- receipt,
641
- request_id: receipt.request_id,
642
- replies: [],
643
- agent_acknowledgement_required: receipt.agent_acknowledgement_required,
644
- agent_acknowledgement_text_required: receipt.agent_acknowledgement_text_required,
645
- agent_acknowledgement: null,
646
- acknowledgement_command: null,
647
- degraded,
648
- }
649
- }
650
-
651
-
652
- function recordReplies(deps: CommandDeps, requestId: string, replies: readonly ReplyView[]): void {
653
- const logger = log(deps)
654
- for (const reply of replies) {
655
- logger.info('reply.received', {
656
- request_id: requestId,
657
- sequence: reply.seq,
658
- device: reply.device_name,
659
- text_chars: reply.text.length,
660
- answers_count: reply.answers?.length ?? 0,
661
- source: reply.source,
662
- })
663
- }
664
- }
665
-
666
- function printReplies(deps: CommandDeps, replies: ReplyView[]): void {
667
- for (const reply of replies) deps.io.out(`reply from ${reply.device_name}: ${reply.text}`)
668
- const contradiction = contradictingAnswer(replies)
669
- if (contradiction !== null) deps.io.err(contradiction)
670
- }
671
-
672
- /**
673
- * The correction note for a wait that saw more than one answer.
674
- *
675
- * A later reply that conflicts with an earlier one is a correction, so the
676
- * latest answer is the one that counts. The server retires the question on
677
- * the other devices the moment one answers, which makes this rare; it is
678
- * still reachable, because a device can answer between the first reply
679
- * landing and its retirement arriving.
680
- *
681
- * Ordered by seq, so `replies.at(-1)` is the answer to act on.
682
- */
683
- export function contradictingAnswer(replies: ReplyView[]): string | null {
684
- const winner = replies.at(-1)
685
- if (winner === undefined || replies.length < 2) return null
686
- const key = (reply: ReplyView) =>
687
- reply.answers.length > 0 ? JSON.stringify(reply.answers) : reply.text
688
- const corrected = replies.slice(0, -1).filter((reply) => key(reply) !== key(winner))
689
- if (corrected.length === 0) return null
690
- const names = [...new Set(corrected.map((reply) => reply.device_name))].join(', ')
691
- return (
692
- `note: "${winner.text}" from ${winner.device_name} is the answer that counts — a later ` +
693
- `answer corrects an earlier one. Earlier differing answers from ${names} were superseded.`
694
- )
695
- }
696
-
697
- function printNoReply(deps: CommandDeps, requestId: string, expiresAt?: string | null): void {
698
- // A harness hook may have retired this question, in which case promising an
699
- // open window would send the caller back to wait for an answer the server
700
- // will now refuse.
701
- const closed = expiresAt != null && Date.parse(expiresAt) <= Date.now()
702
- deps.io.out(
703
- closed
704
- ? `no reply for request ${requestId}; the reply window has closed`
705
- : `no reply yet for request ${requestId}; the reply window remains open`,
706
- )
707
- }
708
-
709
- export async function statusCommand(
710
- deps: CommandDeps,
711
- id: string,
712
- flags: { json?: boolean },
713
- ): Promise<number> {
714
- const local = id.startsWith('q_') ? inspectQuestionState(id, deps.env) : null
715
- if (local?.found === true) {
716
- return questionStatusCommand(deps, local.session_id, local.question, flags)
717
- }
718
- if (local?.found === false) {
719
- deps.io.err(
720
- local.ambiguous
721
- ? `Question ${id} appears in more than one local Agent Session; refusing to guess.`
722
- : `No local registration state exists for ${id}. Inspect or close the original identity instead of registering a replacement.`,
723
- )
724
- return EXIT.failed
725
- }
726
-
727
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
728
- const authed = authedClient(deps, config)
729
- if (!authed) return EXIT.auth
730
- try {
731
- const snapshot = await authed.client.evidence(id)
732
- recordObservedDeliveryProof(deps, snapshot, setupProofProject(deps, config.project.value))
733
- if (flags.json) {
734
- deps.io.out(JSON.stringify(snapshot, null, 2))
735
- return EXIT.ok
736
- }
737
- printEvidenceSnapshot(deps, snapshot)
738
- return EXIT.ok
739
- } catch (err) {
740
- return reportError(deps, err)
741
- }
742
- }
743
-
744
- async function questionStatusCommand(
745
- deps: CommandDeps,
746
- sessionId: string,
747
- local: QuestionStateView,
748
- flags: { json?: boolean },
749
- ): Promise<number> {
750
- if (local.request_id === null) {
751
- const output = questionStatusOutput(local, null)
752
- if (flags.json) deps.io.out(JSON.stringify(output, null, 2))
753
- else printLocalQuestionStatus(deps, local)
754
- return EXIT.ok
755
- }
756
-
757
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env, sessionId })
758
- const authed = authedClient(deps, config)
759
- if (!authed) return EXIT.auth
760
- try {
761
- const snapshot = await authed.client.evidence(local.request_id)
762
- recordObservedDeliveryProof(deps, snapshot, setupProofProject(deps, config.project.value))
763
- const answered = snapshot.deliveries.some((delivery) =>
764
- delivery.events.some((event) => event.stage === 'reply_received'),
765
- )
766
- const question = answered && local.state === 'live'
767
- ? { ...local, state: 'answered' as const }
768
- : local
769
- if (flags.json) {
770
- deps.io.out(JSON.stringify(questionStatusOutput(question, snapshot), null, 2))
771
- return EXIT.ok
772
- }
773
- deps.io.out(`question ${question.question_id} — ${question.state} as ${question.request_id}`)
774
- printEvidenceSnapshot(deps, snapshot)
775
- deps.io.out(
776
- ` Recovery: inspect or close ${question.question_id}; do not register a replacement for the same question.`,
777
- )
778
- return EXIT.ok
779
- } catch (err) {
780
- return reportError(deps, err, { question_id: local.question_id, request_id: local.request_id })
781
- }
782
- }
783
-
784
- function questionStatusOutput(local: QuestionStateView, evidence: EvidenceSnapshot | null) {
785
- const receipt = evidence === null
786
- ? 'not_available'
787
- : evidence.deliveries.some((delivery) => delivery.companion_receipt.state === 'observed')
788
- ? 'observed'
789
- : 'unknown'
790
- return {
791
- question_id: local.question_id,
792
- state: local.state,
793
- submitted: local.submitted,
794
- request_id: local.request_id,
795
- frozen_request_id: local.frozen_request_id,
796
- provider_acceptance: evidence?.overall ?? 'not_available',
797
- companion_receipt: receipt,
798
- evidence,
799
- recovery: {
800
- inspect: `notifai status ${local.question_id}`,
801
- close: `notifai close ${local.question_id}`,
802
- register_replacement: false,
803
- },
804
- }
805
- }
806
-
807
- function printLocalQuestionStatus(deps: CommandDeps, local: QuestionStateView): void {
808
- deps.io.out(`question ${local.question_id} — ${local.state}`)
809
- if (local.state === 'local') {
810
- deps.io.out(' Submission: not submitted — this is only a local registration until question settlement runs')
811
- deps.io.out(' Provider Acceptance: not available — no Notification Request exists yet')
812
- } else if (local.state === 'frozen') {
813
- deps.io.out(
814
- ` Submission: frozen under reserved identity ${local.frozen_request_id}; service acceptance is not proven locally`,
815
- )
816
- deps.io.out(' Provider Acceptance: not available until the frozen identity is promoted locally')
817
- } else if (local.state === 'withdrawn') {
818
- deps.io.out(' Submission: not submitted — the local registration was withdrawn')
819
- deps.io.out(' Provider Acceptance: not available — no Notification Request was created')
820
- } else {
821
- deps.io.out(' Submission: retired before local promotion; service acceptance is not proven locally')
822
- deps.io.out(' Provider Acceptance: not available')
823
- }
824
- deps.io.out(
825
- ` Recovery: inspect or close ${local.question_id}; do not register a replacement for the same question.`,
826
- )
827
- }
828
-
829
- function printEvidenceSnapshot(deps: CommandDeps, snapshot: EvidenceSnapshot): void {
830
- deps.io.out(`request ${snapshot.request_id} — ${snapshot.overall}`)
831
- let anyReplyReceived = false
832
- for (const d of snapshot.deliveries) {
833
- deps.io.out(` ${d.device_name}:`)
834
- deps.io.out(` Delivery: ${d.state} after ${d.attempts} attempt(s)`)
835
- deps.io.out(
836
- ` Provider Acceptance: ${d.state === 'provider_accepted' ? 'accepted' : 'not recorded'}`,
837
- )
838
- if (d.companion_receipt.state === 'observed') {
839
- const latency = d.companion_receipt.latency_ms
840
- deps.io.out(
841
- ` Companion Receipt (the app's delivery confirmation): observed at ${d.companion_receipt.observed_at}` +
842
- (latency === null ? '' : ` (${formatElapsed(latency)} after Provider Acceptance)`),
843
- )
844
- } else {
845
- deps.io.out(
846
- " Companion Receipt (the app's delivery confirmation): unknown — not observed; this is not a failure or proof of non-receipt",
847
- )
848
- }
849
- deps.io.out(
850
- ' OS presentation: not observed by Notifai — Provider Acceptance and Companion Receipt do not prove a banner was shown',
851
- )
852
- const replyEvent = d.events.find((e) => e.stage === 'reply_received')
853
- if (replyEvent) {
854
- anyReplyReceived = true
855
- deps.io.out(` Reply received: yes (first at ${replyEvent.occurred_at})`)
856
- } else {
857
- deps.io.out(' Reply received: not yet recorded on this delivery')
858
- }
859
- for (const e of d.events) {
860
- deps.io.out(` ${e.occurred_at} ${e.stage}${e.reason ? ` (${e.reason})` : ''}`)
861
- }
862
- }
863
- deps.io.out(
864
- anyReplyReceived
865
- ? ` Reply wait: answers are on the server — collect with \`notifai replies ${snapshot.request_id}\` (a local wait fault does not erase them)`
866
- : ` Reply wait: no answer stored yet — a blocking wait failure is independent of Delivery above; retry with \`notifai replies ${snapshot.request_id}\``,
867
- )
868
- }
869
-
870
- function formatElapsed(milliseconds: number): string {
871
- const totalSeconds = Math.floor(milliseconds / 1_000)
872
- const minutes = Math.floor(totalSeconds / 60)
873
- const seconds = totalSeconds % 60
874
- return minutes === 0 ? `${seconds}s` : `${minutes}m ${seconds}s`
875
- }