@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,108 @@
1
+ import { openUrl } from './platform.js'
2
+ import type { CommandIo } from './commands-core.js'
3
+
4
+ // ---------------------------------------------------------------------------
5
+ // production IO
6
+ // ---------------------------------------------------------------------------
7
+
8
+ /**
9
+ * Whether a human is driving this terminal.
10
+ *
11
+ * A TTY alone is NOT that evidence: agent harnesses frequently allocate a PTY
12
+ * for the commands they run, and a prompt shown to an agent does not fail — it
13
+ * hangs, because every prompt library waits on stdin rather than erroring. So
14
+ * this also honours `CI` and an explicit `NOTIFAI_NO_INPUT=1` escape hatch,
15
+ * and every interactive affordance stays strictly optional: anything `init`
16
+ * can ask, a flag can answer.
17
+ */
18
+ function isHumanTerminal(env: NodeJS.ProcessEnv): boolean {
19
+ return (
20
+ process.stdin.isTTY === true &&
21
+ process.stdout.isTTY === true &&
22
+ (env['CI'] ?? '') === '' &&
23
+ (env['NOTIFAI_NO_INPUT'] ?? '') === ''
24
+ )
25
+ }
26
+
27
+ /**
28
+ * Lazy on purpose: the hook path runs in front of every prompt the user types,
29
+ * and must not pay for a prompt library it will never show.
30
+ */
31
+ async function clack() {
32
+ return await import('@clack/prompts')
33
+ }
34
+
35
+ export function realIo(env: NodeJS.ProcessEnv = process.env): CommandIo {
36
+ const interactive = () => isHumanTerminal(env)
37
+ return {
38
+ out: (line) => console.log(line),
39
+ err: (line) => console.error(line),
40
+ get interactive() {
41
+ return interactive()
42
+ },
43
+ confirm: async (question, fallback = false) => {
44
+ if (!interactive()) return fallback
45
+ const p = await clack()
46
+ const answer = await p.confirm({ message: question, initialValue: fallback })
47
+ // Ctrl-C mid-prompt arrives as a cancel symbol, not a SIGINT; treat it
48
+ // as the safe answer rather than letting a Symbol escape into logic.
49
+ return p.isCancel(answer) ? false : answer
50
+ },
51
+ select: async (message, options) => {
52
+ if (!interactive()) return null
53
+ const p = await clack()
54
+ const answer = await p.select({ message, options })
55
+ return p.isCancel(answer) ? null : (answer as string)
56
+ },
57
+ multiselect: async (message, options, initial) => {
58
+ if (!interactive()) return null
59
+ const p = await clack()
60
+ const answer = await p.multiselect({
61
+ message,
62
+ options,
63
+ required: true,
64
+ ...(initial !== undefined && initial.length > 0 ? { initialValues: initial } : {}),
65
+ })
66
+ return p.isCancel(answer) ? null : (answer as string[])
67
+ },
68
+ intro: async (title) => {
69
+ if (!interactive()) return
70
+ ;(await clack()).intro(title)
71
+ },
72
+ outro: async (message) => {
73
+ if (!interactive()) return
74
+ ;(await clack()).outro(message)
75
+ },
76
+ note: async (message, title) => {
77
+ if (!interactive()) return
78
+ ;(await clack()).note(message, title)
79
+ },
80
+ spinner: async (message) => {
81
+ if (!interactive()) return null
82
+ const progress = (await clack()).spinner()
83
+ progress.start(message)
84
+ return {
85
+ message: (next) => progress.message(next),
86
+ stop: (next) => progress.stop(next),
87
+ error: (next) => progress.error(next),
88
+ }
89
+ },
90
+ check: async (ok, message, tone) => {
91
+ if (!interactive()) return
92
+ const { log } = await clack()
93
+ switch (tone ?? (ok ? 'ok' : 'bad')) {
94
+ case 'ok':
95
+ return log.success(message)
96
+ case 'warn':
97
+ return log.warn(message)
98
+ case 'pending':
99
+ // Never checked. `log.info` reads as neutral, which is the honest
100
+ // rendering for a state no evidence was gathered about.
101
+ return log.info(message)
102
+ case 'bad':
103
+ return log.error(message)
104
+ }
105
+ },
106
+ openUrl,
107
+ }
108
+ }
@@ -0,0 +1,243 @@
1
+ import { unlinkSync } from 'node:fs'
2
+ import { type LogLevel } from './config.js'
3
+ import {
4
+ LOG_EVENTS,
5
+ RECORD_LEVELS,
6
+ activeLogPath,
7
+ archiveLogPaths,
8
+ logsDiskUsage,
9
+ readLogRecords,
10
+ renderRecord,
11
+ type LogQuery,
12
+ } from './logging.js'
13
+ import { EXIT, loadLoggedConfig, type CommandDeps } from './commands-core.js'
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // logs
17
+ // ---------------------------------------------------------------------------
18
+
19
+ export interface LogsFlags {
20
+ json?: boolean
21
+ limit?: number
22
+ all?: boolean
23
+ since?: string
24
+ level?: string
25
+ event?: string[]
26
+ run?: string
27
+ request?: string
28
+ session?: string
29
+ project?: string
30
+ allProjects?: boolean
31
+ grep?: string
32
+ path?: boolean
33
+ clear?: boolean
34
+ }
35
+
36
+ const LOG_RECORD_OPTIONS: readonly (readonly [keyof LogsFlags, string])[] = [
37
+ ['limit', '--limit'],
38
+ ['all', '--all'],
39
+ ['since', '--since'],
40
+ ['level', '--level'],
41
+ ['event', '--event'],
42
+ ['run', '--run'],
43
+ ['request', '--request'],
44
+ ['session', '--session'],
45
+ ['project', '--project'],
46
+ ['allProjects', '--all-projects'],
47
+ ['grep', '--grep'],
48
+ ]
49
+
50
+ /**
51
+ * Deliberately small. The reader is usually a model with a finite context, and
52
+ * a log command whose default answer is ten thousand lines gets used once.
53
+ * Everything beyond this is reachable by asking for it.
54
+ */
55
+ const DEFAULT_LOG_LIMIT = 30
56
+ /** Even `--all` stops somewhere; an unbounded dump is never the useful answer. */
57
+ const MAX_LOG_LIMIT = 2_000
58
+
59
+ /** `10m`, `2h`, `1d`, or an ISO 8601 instant. */
60
+ export function parseSince(raw: string, now: number): number | null {
61
+ const relative = /^(\d+)([smhd])$/.exec(raw.trim())
62
+ if (relative !== null) {
63
+ const amount = Number(relative[1])
64
+ const unit = relative[2] as 's' | 'm' | 'h' | 'd'
65
+ const seconds = { s: 1, m: 60, h: 3600, d: 86400 }[unit]
66
+ return now - amount * seconds * 1000
67
+ }
68
+ const absolute = Date.parse(raw)
69
+ return Number.isNaN(absolute) ? null : absolute
70
+ }
71
+
72
+ /**
73
+ * What this machine recorded about itself.
74
+ *
75
+ * The retrieval half of the local log, and the half that decides whether the
76
+ * log is worth having. Three things make it usable by an agent rather than
77
+ * merely available to one: the default is bounded and scoped to this project,
78
+ * the filters match the questions actually asked ("that run", "that
79
+ * notification", "just the failures"), and `--json` gives the machine the
80
+ * records untouched on stdout while every word of explanation goes to stderr.
81
+ */
82
+ export function logsCommand(deps: CommandDeps, flags: LogsFlags): number {
83
+ const selectedRetrievalOptions = LOG_RECORD_OPTIONS
84
+ .filter(([key]) => {
85
+ const value = flags[key]
86
+ return Array.isArray(value) ? value.length > 0 : value !== undefined && value !== false
87
+ })
88
+ .map(([, name]) => name)
89
+
90
+ if (flags.path === true && flags.clear === true) {
91
+ deps.io.err('Pass --path or --clear, not both.')
92
+ return EXIT.usage
93
+ }
94
+ if (flags.path === true && selectedRetrievalOptions.length > 0) {
95
+ deps.io.err(`--path cannot be combined with record options: ${selectedRetrievalOptions.join(', ')}.`)
96
+ return EXIT.usage
97
+ }
98
+ if (flags.clear === true && selectedRetrievalOptions.length > 0) {
99
+ deps.io.err(`--clear cannot be combined with record options: ${selectedRetrievalOptions.join(', ')}.`)
100
+ return EXIT.usage
101
+ }
102
+ if (flags.project !== undefined && flags.allProjects === true) {
103
+ deps.io.err('Pass --project or --all-projects, not both.')
104
+ return EXIT.usage
105
+ }
106
+ if (flags.limit !== undefined && flags.all === true) {
107
+ deps.io.err('Pass --limit or --all, not both.')
108
+ return EXIT.usage
109
+ }
110
+ if (flags.limit !== undefined && (!Number.isInteger(flags.limit) || flags.limit <= 0)) {
111
+ deps.io.err('--limit must be a positive integer.')
112
+ return EXIT.usage
113
+ }
114
+ if (flags.limit !== undefined && flags.limit > MAX_LOG_LIMIT) {
115
+ deps.io.err(`--limit cannot exceed ${MAX_LOG_LIMIT}; narrow the result with --since or filters.`)
116
+ return EXIT.usage
117
+ }
118
+
119
+ const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
120
+ const now = (deps.now ?? Date.now)()
121
+
122
+ if (flags.path === true) {
123
+ const usage = logsDiskUsage(deps.env)
124
+ const archives = archiveLogPaths(deps.env)
125
+ if (flags.json === true) {
126
+ deps.io.out(
127
+ JSON.stringify(
128
+ {
129
+ active: activeLogPath(deps.env),
130
+ archives,
131
+ files: usage.files,
132
+ bytes: usage.bytes,
133
+ level: config.log_level.value,
134
+ max_bytes: config.log_max_bytes.value,
135
+ max_files: config.log_max_files.value,
136
+ local_only: true,
137
+ },
138
+ null,
139
+ 2,
140
+ ),
141
+ )
142
+ return EXIT.ok
143
+ }
144
+ deps.io.out(activeLogPath(deps.env))
145
+ for (const archive of archives) deps.io.out(archive)
146
+ deps.io.err(
147
+ `${usage.files} file(s), ${Math.round(usage.bytes / 1024)} KB, level ${config.log_level.value}. These stay on this machine.`,
148
+ )
149
+ return EXIT.ok
150
+ }
151
+
152
+ if (flags.clear === true) {
153
+ let removed = 0
154
+ for (const file of [activeLogPath(deps.env), ...archiveLogPaths(deps.env)]) {
155
+ try {
156
+ unlinkSync(file)
157
+ removed += 1
158
+ } catch {
159
+ // Absent, or not ours to remove; either way there is nothing to report.
160
+ }
161
+ }
162
+ deps.io.out(
163
+ flags.json === true
164
+ ? JSON.stringify({ cleared_files: removed })
165
+ : `Cleared ${removed} log file${removed === 1 ? '' : 's'}.`,
166
+ )
167
+ return EXIT.ok
168
+ }
169
+
170
+ const query: LogQuery = {
171
+ limit: flags.limit ?? (flags.all === true ? MAX_LOG_LIMIT : DEFAULT_LOG_LIMIT),
172
+ }
173
+
174
+ if (flags.since !== undefined) {
175
+ const since = parseSince(flags.since, now)
176
+ if (since === null) {
177
+ deps.io.err(`Could not read "${flags.since}" as a time. Use 10m, 2h, 1d, or an ISO 8601 instant.`)
178
+ return EXIT.usage
179
+ }
180
+ query.since = since
181
+ }
182
+ if (flags.level !== undefined) {
183
+ if (!(RECORD_LEVELS as readonly string[]).includes(flags.level)) {
184
+ deps.io.err(`--level takes one of: ${RECORD_LEVELS.join(', ')} — not "${flags.level}".`)
185
+ return EXIT.usage
186
+ }
187
+ query.level = flags.level as LogLevel
188
+ }
189
+ if (flags.event !== undefined && flags.event.length > 0) {
190
+ const unknown = flags.event.filter((name) => !(LOG_EVENTS as readonly string[]).includes(name))
191
+ if (unknown.length > 0) {
192
+ deps.io.err(`Unknown event ${unknown.join(', ')}. Valid: ${LOG_EVENTS.join(', ')}`)
193
+ return EXIT.usage
194
+ }
195
+ query.event = flags.event
196
+ }
197
+ if (flags.run !== undefined) query.run = flags.run
198
+ if (flags.session !== undefined) query.session = flags.session
199
+ if (flags.request !== undefined) query.request = flags.request
200
+ if (flags.grep !== undefined) query.contains = flags.grep
201
+
202
+ // Scoped to this project by default. A machine commonly runs several agents
203
+ // in several worktrees at once, and the answer to "what just happened" is
204
+ // useless if three other projects are interleaved through it.
205
+ const scope =
206
+ flags.project ?? (flags.allProjects === true ? undefined : (config.project.value ?? undefined))
207
+ if (scope !== undefined) query.project = scope
208
+
209
+ const result = readLogRecords(deps.env, query)
210
+
211
+ if (flags.json === true) {
212
+ for (const record of result.records) deps.io.out(JSON.stringify(record))
213
+ } else {
214
+ for (const record of result.records) deps.io.out(renderRecord(record))
215
+ }
216
+
217
+ if (result.records.length === 0) {
218
+ if (config.log_level.value === 'off') {
219
+ deps.io.err('Nothing is being recorded: log_level is off.')
220
+ deps.io.err('Turn it on with `notifai config set log_level info --yes`.')
221
+ } else if (logsDiskUsage(deps.env).files === 0) {
222
+ deps.io.err('No log yet. It is written the next time a notifai command or harness hook runs.')
223
+ } else {
224
+ deps.io.err('No records matched. Widen it with --all-projects, --since 1d, or --all.')
225
+ }
226
+ return EXIT.ok
227
+ }
228
+
229
+ // Everything explanatory goes to stderr so `--json` leaves stdout as clean
230
+ // JSONL for whatever is parsing it.
231
+ const notes: string[] = []
232
+ if (scope !== undefined) notes.push(`project ${scope} (--all-projects for every project)`)
233
+ if (result.more) {
234
+ notes.push(
235
+ query.limit! < MAX_LOG_LIMIT
236
+ ? `more history behind this (-n ${Math.min(query.limit! * 4, MAX_LOG_LIMIT)} or --all)`
237
+ : `more history exists beyond the ${MAX_LOG_LIMIT}-record safety cap; narrow with --since or filters`,
238
+ )
239
+ }
240
+ if (config.log_level.value !== 'debug') notes.push('`log_level = debug` records request detail')
241
+ if (notes.length > 0) deps.io.err(`— ${result.records.length} records; ${notes.join('; ')}`)
242
+ return EXIT.ok
243
+ }
@@ -0,0 +1,227 @@
1
+ import { type ListRepliesResponse } from '@raidiant/notifai-protocol'
2
+ import { sha256Hex } from '@raidiant/notifai-protocol/node'
3
+ import { existsSync, readFileSync } from 'node:fs'
4
+ import path from 'node:path'
5
+ import { isRetryableReplyPollError, type ApiClient } from './client.js'
6
+ import { buildSourceContext, inferInvocationContext } from './invocation-context.js'
7
+ import { type DraftInvocation, type SendFlags } from './send.js'
8
+ import { EXIT, reportError, type CommandDeps } from './commands-core.js'
9
+ import type { ActiveHarnessSession } from './commands-harness-context.js'
10
+
11
+ export function resolveDraftInvocation(
12
+ deps: CommandDeps,
13
+ flags: Pick<SendFlags, 'sessionId' | 'sessionLabel'>,
14
+ active: ActiveHarnessSession | null,
15
+ ): { ok: true; invocation: DraftInvocation } | { ok: false; error: string } {
16
+ const inferred = inferInvocationContext(deps.cwd)
17
+ const source = buildSourceContext({
18
+ env: deps.env,
19
+ invocation: inferred,
20
+ ...(flags.sessionId !== undefined ? { sessionId: flags.sessionId } : {}),
21
+ ...(flags.sessionLabel !== undefined ? { sessionLabel: flags.sessionLabel } : {}),
22
+ ...(active === null
23
+ ? {}
24
+ : {
25
+ activeHarness: {
26
+ harness: active.harness,
27
+ ...(active.sessionId === undefined ? {} : { sessionId: active.sessionId }),
28
+ ...(active.sessionLabel === undefined ? {} : { sessionLabel: active.sessionLabel }),
29
+ ...(active.sessionLabelPending === true ? { sessionLabelPending: true } : {}),
30
+ },
31
+ }),
32
+ now: (deps.now ?? Date.now)(),
33
+ })
34
+ if (!source.ok) return source
35
+ return {
36
+ ok: true,
37
+ invocation: {
38
+ inferredProject: inferred.project,
39
+ ...(source.source === undefined ? {} : { source: source.source }),
40
+ },
41
+ }
42
+ }
43
+
44
+ interface ReplyWaitOptions {
45
+ timeoutSeconds: number
46
+ afterSeq: number
47
+ now?: (() => number) | undefined
48
+ sleep?: ((milliseconds: number) => Promise<void>) | undefined
49
+ }
50
+
51
+ interface ReplyWaitResult {
52
+ response: ListRepliesResponse
53
+ timedOut: boolean
54
+ /**
55
+ * The wait ended while polls were failing, so silence is unproven: the user
56
+ * may well have answered and we could not see it.
57
+ */
58
+ degraded: boolean
59
+ }
60
+
61
+ /** Loop over server-capped long polls until a reply arrives or the caller's deadline passes. */
62
+ export async function waitForReply(
63
+ client: ApiClient,
64
+ requestId: string,
65
+ options: ReplyWaitOptions,
66
+ ): Promise<ReplyWaitResult> {
67
+ const now = options.now ?? Date.now
68
+ const sleep = options.sleep ?? ((milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)))
69
+ const deadline = now() + options.timeoutSeconds * 1000
70
+ let lastResponse: ListRepliesResponse | null = null
71
+ let lastTransientError: Error | null = null
72
+ let consecutiveTransientErrors = 0
73
+ let firstPoll = true
74
+
75
+ while (firstPoll || now() < deadline) {
76
+ firstPoll = false
77
+ const remainingMs = Math.max(0, deadline - now())
78
+ const waitSeconds = Math.min(25, Math.floor(remainingMs / 1000))
79
+ try {
80
+ const response = await client.replies(requestId, {
81
+ waitSeconds,
82
+ afterSeq: options.afterSeq,
83
+ })
84
+ lastResponse = response
85
+ lastTransientError = null
86
+ consecutiveTransientErrors = 0
87
+ if (response.replies.length > 0) return { response, timedOut: false, degraded: false }
88
+
89
+ const pauseMs = Math.min(250, Math.max(0, deadline - now()))
90
+ if (pauseMs > 0) await sleep(pauseMs)
91
+ } catch (err) {
92
+ if (!isRetryableReplyPollError(err)) throw err
93
+ lastTransientError = err instanceof Error ? err : new Error(String(err))
94
+ consecutiveTransientErrors += 1
95
+ const remainingAfterError = Math.max(0, deadline - now())
96
+ if (remainingAfterError === 0) break
97
+ const backoffMs = Math.min(
98
+ 250 * 2 ** (consecutiveTransientErrors - 1),
99
+ 2_000,
100
+ remainingAfterError,
101
+ )
102
+ await sleep(backoffMs)
103
+ }
104
+ }
105
+
106
+ // Never saw a successful poll: surface the fault so callers get EXIT.network
107
+ // rather than a fake empty silence. The durable request is still on the
108
+ // server; the typed recovery is `notifai replies <id>`.
109
+ if (!lastResponse && lastTransientError) throw lastTransientError
110
+ return {
111
+ response:
112
+ lastResponse ??
113
+ ({
114
+ request_id: requestId,
115
+ reply_expires_at: null,
116
+ agent_acknowledgement_required: false,
117
+ agent_acknowledgement_text_required: false,
118
+ agent_acknowledgement: null,
119
+ replies: [],
120
+ } satisfies ListRepliesResponse),
121
+ timedOut: true,
122
+ // A poll succeeded at some point, so we do not throw — but the last thing
123
+ // we know is that we could not reach the server. Reporting that as a plain
124
+ // "no reply" would let an agent treat an unseen refusal as consent.
125
+ degraded: lastTransientError !== null,
126
+ }
127
+ }
128
+
129
+ function acknowledgeInvocation(requestId: string, textRequired: boolean): string {
130
+ return textRequired
131
+ ? `notifai acknowledge ${requestId} --text <text>`
132
+ : `notifai acknowledge ${requestId}`
133
+ }
134
+
135
+ export function acknowledgementCommand(
136
+ requestId: string,
137
+ required: boolean,
138
+ textRequired: boolean,
139
+ acknowledgement: ListRepliesResponse['agent_acknowledgement'],
140
+ hasReply = true,
141
+ ): string | null {
142
+ return required && acknowledgement === null && hasReply
143
+ ? acknowledgeInvocation(requestId, textRequired)
144
+ : null
145
+ }
146
+
147
+ export function printAcknowledgementStatus(deps: CommandDeps, response: ListRepliesResponse): void {
148
+ if (!response.agent_acknowledgement_required) {
149
+ deps.io.out('Agent Acknowledgement: not required for this request.')
150
+ return
151
+ }
152
+ const textRequired = response.agent_acknowledgement_text_required
153
+ if (response.agent_acknowledgement !== null) {
154
+ const recorded = `Agent Acknowledgement: recorded at ${response.agent_acknowledgement.created_at}`
155
+ deps.io.out(
156
+ response.agent_acknowledgement.text.length > 0
157
+ ? `${recorded}: ${response.agent_acknowledgement.text}`
158
+ : `${recorded}.`,
159
+ )
160
+ return
161
+ }
162
+ if (response.replies.length > 0) {
163
+ deps.io.out('Agent Acknowledgement required.')
164
+ deps.io.out(
165
+ textRequired
166
+ ? `next: Run \`${acknowledgeInvocation(response.request_id, true)}\` with concrete text saying what you will do because of the reply.`
167
+ : `next: Run \`${acknowledgeInvocation(response.request_id, false)}\` so the user sees you read the reply; this account turned acknowledgement text off.`,
168
+ )
169
+ return
170
+ }
171
+ deps.io.out('Agent Acknowledgement: required after a user reply; no reply is recorded yet.')
172
+ }
173
+
174
+ const MEDIA_TYPES: Record<string, 'image/jpeg' | 'image/png' | 'image/gif'> = {
175
+ '.jpg': 'image/jpeg',
176
+ '.jpeg': 'image/jpeg',
177
+ '.png': 'image/png',
178
+ '.gif': 'image/gif',
179
+ }
180
+
181
+ type UploadResult =
182
+ | { ok: true; mediaId: string }
183
+ /** `error: null` means `reportError` already said it; do not print it twice. */
184
+ | { ok: false; error: string | null; exit: number }
185
+
186
+ /** `--image` accepts a media id, a local file path, or an http(s) URL. */
187
+ export async function uploadImage(deps: CommandDeps, client: ApiClient, source: string): Promise<UploadResult> {
188
+ let bytes: Uint8Array
189
+ let mediaType: 'image/jpeg' | 'image/png' | 'image/gif' | undefined
190
+ if (/^https?:\/\//.test(source)) {
191
+ try {
192
+ const response = await fetch(source)
193
+ if (!response.ok) return { ok: false, error: `Could not fetch ${source} (${response.status}).`, exit: EXIT.usage }
194
+ const contentType = response.headers.get('content-type')?.split(';')[0]?.trim() ?? ''
195
+ mediaType = (['image/jpeg', 'image/png', 'image/gif'] as const).find((t) => t === contentType)
196
+ bytes = new Uint8Array(await response.arrayBuffer())
197
+ } catch (err) {
198
+ return { ok: false, error: `Could not fetch ${source}: ${String(err)}`, exit: EXIT.network }
199
+ }
200
+ } else {
201
+ if (!existsSync(source)) {
202
+ return { ok: false, error: `--image: "${source}" is not a media id, file, or URL.`, exit: EXIT.usage }
203
+ }
204
+ bytes = new Uint8Array(readFileSync(source))
205
+ mediaType = MEDIA_TYPES[path.extname(source).toLowerCase()]
206
+ }
207
+ if (!mediaType) {
208
+ return { ok: false, error: 'Images must be JPEG, PNG, or GIF.', exit: EXIT.usage }
209
+ }
210
+ try {
211
+ const grant = await client.createMediaUpload({
212
+ media_type: mediaType,
213
+ size_bytes: bytes.byteLength,
214
+ sha256: sha256Hex(bytes),
215
+ })
216
+ await client.uploadMedia(grant, bytes)
217
+ return { ok: true, mediaId: grant.media_id }
218
+ } catch (err) {
219
+ // Every other API failure in this file goes through `reportError`, which
220
+ // maps a revoked credential to the auth code, a server fault to the network
221
+ // one and everything else to plain failure, and records it in the local
222
+ // log with whatever next step the server named. This used to answer
223
+ // `network` to all of them, so an image too large for the account exited
224
+ // the same way an unreachable server did, and nothing about it was logged.
225
+ return { ok: false, error: null, exit: reportError(deps, err) }
226
+ }
227
+ }