@raidiant/notifai 5.0.0 → 6.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.
- package/CHANGELOG.md +27 -0
- package/README.md +2 -2
- package/dist/client.d.ts +8 -3
- package/dist/client.js +24 -3
- package/dist/client.js.map +1 -1
- package/dist/commands-auth.d.ts +14 -0
- package/dist/commands-auth.js +154 -0
- package/dist/commands-auth.js.map +1 -0
- package/dist/commands-config.d.ts +31 -0
- package/dist/commands-config.js +246 -0
- package/dist/commands-config.js.map +1 -0
- package/dist/commands-core.d.ts +102 -0
- package/dist/commands-core.js +135 -0
- package/dist/commands-core.js.map +1 -0
- package/dist/commands-devices.d.ts +31 -0
- package/dist/commands-devices.js +124 -0
- package/dist/commands-devices.js.map +1 -0
- package/dist/commands-doctor.d.ts +24 -0
- package/dist/commands-doctor.js +1011 -0
- package/dist/commands-doctor.js.map +1 -0
- package/dist/commands-harness-context.d.ts +61 -0
- package/dist/commands-harness-context.js +93 -0
- package/dist/commands-harness-context.js.map +1 -0
- package/dist/commands-hook-shape.d.ts +17 -0
- package/dist/commands-hook-shape.js +37 -0
- package/dist/commands-hook-shape.js.map +1 -0
- package/dist/commands-hooks.d.ts +115 -0
- package/dist/commands-hooks.js +1225 -0
- package/dist/commands-hooks.js.map +1 -0
- package/dist/commands-init.d.ts +35 -0
- package/dist/commands-init.js +580 -0
- package/dist/commands-init.js.map +1 -0
- package/dist/commands-io.d.ts +2 -0
- package/dist/commands-io.js +110 -0
- package/dist/commands-io.js.map +1 -0
- package/dist/commands-logs.d.ts +30 -0
- package/dist/commands-logs.js +201 -0
- package/dist/commands-logs.js.map +1 -0
- package/dist/commands-send-support.d.ts +44 -0
- package/dist/commands-send-support.js +180 -0
- package/dist/commands-send-support.js.map +1 -0
- package/dist/commands-send.d.ts +33 -0
- package/dist/commands-send.js +519 -0
- package/dist/commands-send.js.map +1 -0
- package/dist/commands-setup-proof.d.ts +15 -0
- package/dist/commands-setup-proof.js +53 -0
- package/dist/commands-setup-proof.js.map +1 -0
- package/dist/commands-skill.d.ts +10 -0
- package/dist/commands-skill.js +71 -0
- package/dist/commands-skill.js.map +1 -0
- package/dist/commands.d.ts +12 -387
- package/dist/commands.js +12 -4536
- package/dist/commands.js.map +1 -1
- package/dist/config-schema.js +1 -1
- package/dist/config-schema.js.map +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/config.js +3 -1
- package/dist/config.js.map +1 -1
- package/dist/credentials.js +13 -3
- package/dist/credentials.js.map +1 -1
- package/dist/hooks.d.ts +2 -2
- package/dist/hooks.js +127 -99
- package/dist/hooks.js.map +1 -1
- package/dist/interactive.js +4 -4
- package/dist/interactive.js.map +1 -1
- package/dist/logging.js +1 -0
- package/dist/logging.js.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/readiness.d.ts +3 -1
- package/dist/readiness.js.map +1 -1
- package/package.json +2 -2
- package/src/client.test.ts +90 -1
- package/src/client.ts +35 -2
- package/src/commands-auth.ts +174 -0
- package/src/commands-config.ts +307 -0
- package/src/commands-core.ts +240 -0
- package/src/commands-devices.ts +150 -0
- package/src/commands-doctor.ts +1209 -0
- package/src/commands-harness-context.ts +126 -0
- package/src/commands-hook-shape.ts +53 -0
- package/src/commands-hooks.ts +1586 -0
- package/src/commands-init.ts +721 -0
- package/src/commands-io.ts +108 -0
- package/src/commands-logs.ts +243 -0
- package/src/commands-send-support.ts +224 -0
- package/src/commands-send.ts +623 -0
- package/src/commands-setup-proof.ts +71 -0
- package/src/commands-skill.ts +84 -0
- package/src/commands.test.ts +493 -39
- package/src/commands.ts +58 -5614
- package/src/config-schema.ts +1 -1
- package/src/config.test.ts +9 -0
- package/src/config.ts +7 -2
- package/src/credentials.test.ts +25 -1
- package/src/credentials.ts +13 -3
- package/src/hooks.test.ts +351 -11
- package/src/hooks.ts +145 -97
- package/src/interactive.test.ts +19 -1
- package/src/interactive.ts +4 -4
- package/src/logging.test.ts +15 -2
- package/src/logging.ts +1 -0
- package/src/main.ts +1 -1
- package/src/readiness.ts +3 -1
|
@@ -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,224 @@
|
|
|
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
|
+
},
|
|
29
|
+
}),
|
|
30
|
+
})
|
|
31
|
+
if (!source.ok) return source
|
|
32
|
+
return {
|
|
33
|
+
ok: true,
|
|
34
|
+
invocation: {
|
|
35
|
+
inferredProject: inferred.project,
|
|
36
|
+
...(source.source === undefined ? {} : { source: source.source }),
|
|
37
|
+
},
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface ReplyWaitOptions {
|
|
42
|
+
timeoutSeconds: number
|
|
43
|
+
afterSeq: number
|
|
44
|
+
now?: (() => number) | undefined
|
|
45
|
+
sleep?: ((milliseconds: number) => Promise<void>) | undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface ReplyWaitResult {
|
|
49
|
+
response: ListRepliesResponse
|
|
50
|
+
timedOut: boolean
|
|
51
|
+
/**
|
|
52
|
+
* The wait ended while polls were failing, so silence is unproven: the user
|
|
53
|
+
* may well have answered and we could not see it.
|
|
54
|
+
*/
|
|
55
|
+
degraded: boolean
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Loop over server-capped long polls until a reply arrives or the caller's deadline passes. */
|
|
59
|
+
export async function waitForReply(
|
|
60
|
+
client: ApiClient,
|
|
61
|
+
requestId: string,
|
|
62
|
+
options: ReplyWaitOptions,
|
|
63
|
+
): Promise<ReplyWaitResult> {
|
|
64
|
+
const now = options.now ?? Date.now
|
|
65
|
+
const sleep = options.sleep ?? ((milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds)))
|
|
66
|
+
const deadline = now() + options.timeoutSeconds * 1000
|
|
67
|
+
let lastResponse: ListRepliesResponse | null = null
|
|
68
|
+
let lastTransientError: Error | null = null
|
|
69
|
+
let consecutiveTransientErrors = 0
|
|
70
|
+
let firstPoll = true
|
|
71
|
+
|
|
72
|
+
while (firstPoll || now() < deadline) {
|
|
73
|
+
firstPoll = false
|
|
74
|
+
const remainingMs = Math.max(0, deadline - now())
|
|
75
|
+
const waitSeconds = Math.min(25, Math.floor(remainingMs / 1000))
|
|
76
|
+
try {
|
|
77
|
+
const response = await client.replies(requestId, {
|
|
78
|
+
waitSeconds,
|
|
79
|
+
afterSeq: options.afterSeq,
|
|
80
|
+
})
|
|
81
|
+
lastResponse = response
|
|
82
|
+
lastTransientError = null
|
|
83
|
+
consecutiveTransientErrors = 0
|
|
84
|
+
if (response.replies.length > 0) return { response, timedOut: false, degraded: false }
|
|
85
|
+
|
|
86
|
+
const pauseMs = Math.min(250, Math.max(0, deadline - now()))
|
|
87
|
+
if (pauseMs > 0) await sleep(pauseMs)
|
|
88
|
+
} catch (err) {
|
|
89
|
+
if (!isRetryableReplyPollError(err)) throw err
|
|
90
|
+
lastTransientError = err instanceof Error ? err : new Error(String(err))
|
|
91
|
+
consecutiveTransientErrors += 1
|
|
92
|
+
const remainingAfterError = Math.max(0, deadline - now())
|
|
93
|
+
if (remainingAfterError === 0) break
|
|
94
|
+
const backoffMs = Math.min(
|
|
95
|
+
250 * 2 ** (consecutiveTransientErrors - 1),
|
|
96
|
+
2_000,
|
|
97
|
+
remainingAfterError,
|
|
98
|
+
)
|
|
99
|
+
await sleep(backoffMs)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Never saw a successful poll: surface the fault so callers get EXIT.network
|
|
104
|
+
// rather than a fake empty silence. The durable request is still on the
|
|
105
|
+
// server; the typed recovery is `notifai replies <id>`.
|
|
106
|
+
if (!lastResponse && lastTransientError) throw lastTransientError
|
|
107
|
+
return {
|
|
108
|
+
response:
|
|
109
|
+
lastResponse ??
|
|
110
|
+
({
|
|
111
|
+
request_id: requestId,
|
|
112
|
+
reply_expires_at: null,
|
|
113
|
+
agent_acknowledgement_required: false,
|
|
114
|
+
agent_acknowledgement_text_required: false,
|
|
115
|
+
agent_acknowledgement: null,
|
|
116
|
+
replies: [],
|
|
117
|
+
} satisfies ListRepliesResponse),
|
|
118
|
+
timedOut: true,
|
|
119
|
+
// A poll succeeded at some point, so we do not throw — but the last thing
|
|
120
|
+
// we know is that we could not reach the server. Reporting that as a plain
|
|
121
|
+
// "no reply" would let an agent treat an unseen refusal as consent.
|
|
122
|
+
degraded: lastTransientError !== null,
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function acknowledgeInvocation(requestId: string, textRequired: boolean): string {
|
|
127
|
+
return textRequired
|
|
128
|
+
? `notifai acknowledge ${requestId} --text <text>`
|
|
129
|
+
: `notifai acknowledge ${requestId}`
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function acknowledgementCommand(
|
|
133
|
+
requestId: string,
|
|
134
|
+
required: boolean,
|
|
135
|
+
textRequired: boolean,
|
|
136
|
+
acknowledgement: ListRepliesResponse['agent_acknowledgement'],
|
|
137
|
+
hasReply = true,
|
|
138
|
+
): string | null {
|
|
139
|
+
return required && acknowledgement === null && hasReply
|
|
140
|
+
? acknowledgeInvocation(requestId, textRequired)
|
|
141
|
+
: null
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function printAcknowledgementStatus(deps: CommandDeps, response: ListRepliesResponse): void {
|
|
145
|
+
if (!response.agent_acknowledgement_required) {
|
|
146
|
+
deps.io.out('Agent Acknowledgement: not required for this request.')
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
const textRequired = response.agent_acknowledgement_text_required
|
|
150
|
+
if (response.agent_acknowledgement !== null) {
|
|
151
|
+
const recorded = `Agent Acknowledgement: recorded at ${response.agent_acknowledgement.created_at}`
|
|
152
|
+
deps.io.out(
|
|
153
|
+
response.agent_acknowledgement.text.length > 0
|
|
154
|
+
? `${recorded}: ${response.agent_acknowledgement.text}`
|
|
155
|
+
: `${recorded}.`,
|
|
156
|
+
)
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
if (response.replies.length > 0) {
|
|
160
|
+
deps.io.out('Agent Acknowledgement required.')
|
|
161
|
+
deps.io.out(
|
|
162
|
+
textRequired
|
|
163
|
+
? `next: Run \`${acknowledgeInvocation(response.request_id, true)}\` with concrete text saying what you will do because of the reply.`
|
|
164
|
+
: `next: Run \`${acknowledgeInvocation(response.request_id, false)}\` so the user sees you read the reply; this account turned acknowledgement text off.`,
|
|
165
|
+
)
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
deps.io.out('Agent Acknowledgement: required after a user reply; no reply is recorded yet.')
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const MEDIA_TYPES: Record<string, 'image/jpeg' | 'image/png' | 'image/gif'> = {
|
|
172
|
+
'.jpg': 'image/jpeg',
|
|
173
|
+
'.jpeg': 'image/jpeg',
|
|
174
|
+
'.png': 'image/png',
|
|
175
|
+
'.gif': 'image/gif',
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
type UploadResult =
|
|
179
|
+
| { ok: true; mediaId: string }
|
|
180
|
+
/** `error: null` means `reportError` already said it; do not print it twice. */
|
|
181
|
+
| { ok: false; error: string | null; exit: number }
|
|
182
|
+
|
|
183
|
+
/** `--image` accepts a media id, a local file path, or an http(s) URL. */
|
|
184
|
+
export async function uploadImage(deps: CommandDeps, client: ApiClient, source: string): Promise<UploadResult> {
|
|
185
|
+
let bytes: Uint8Array
|
|
186
|
+
let mediaType: 'image/jpeg' | 'image/png' | 'image/gif' | undefined
|
|
187
|
+
if (/^https?:\/\//.test(source)) {
|
|
188
|
+
try {
|
|
189
|
+
const response = await fetch(source)
|
|
190
|
+
if (!response.ok) return { ok: false, error: `Could not fetch ${source} (${response.status}).`, exit: EXIT.usage }
|
|
191
|
+
const contentType = response.headers.get('content-type')?.split(';')[0]?.trim() ?? ''
|
|
192
|
+
mediaType = (['image/jpeg', 'image/png', 'image/gif'] as const).find((t) => t === contentType)
|
|
193
|
+
bytes = new Uint8Array(await response.arrayBuffer())
|
|
194
|
+
} catch (err) {
|
|
195
|
+
return { ok: false, error: `Could not fetch ${source}: ${String(err)}`, exit: EXIT.network }
|
|
196
|
+
}
|
|
197
|
+
} else {
|
|
198
|
+
if (!existsSync(source)) {
|
|
199
|
+
return { ok: false, error: `--image: "${source}" is not a media id, file, or URL.`, exit: EXIT.usage }
|
|
200
|
+
}
|
|
201
|
+
bytes = new Uint8Array(readFileSync(source))
|
|
202
|
+
mediaType = MEDIA_TYPES[path.extname(source).toLowerCase()]
|
|
203
|
+
}
|
|
204
|
+
if (!mediaType) {
|
|
205
|
+
return { ok: false, error: 'Images must be JPEG, PNG, or GIF.', exit: EXIT.usage }
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
const grant = await client.createMediaUpload({
|
|
209
|
+
media_type: mediaType,
|
|
210
|
+
size_bytes: bytes.byteLength,
|
|
211
|
+
sha256: sha256Hex(bytes),
|
|
212
|
+
})
|
|
213
|
+
await client.uploadMedia(grant, bytes)
|
|
214
|
+
return { ok: true, mediaId: grant.media_id }
|
|
215
|
+
} catch (err) {
|
|
216
|
+
// Every other API failure in this file goes through `reportError`, which
|
|
217
|
+
// maps a revoked credential to the auth code, a server fault to the network
|
|
218
|
+
// one and everything else to plain failure, and records it in the local
|
|
219
|
+
// log with whatever next step the server named. This used to answer
|
|
220
|
+
// `network` to all of them, so an image too large for the account exited
|
|
221
|
+
// the same way an unreachable server did, and nothing about it was logged.
|
|
222
|
+
return { ok: false, error: null, exit: reportError(deps, err) }
|
|
223
|
+
}
|
|
224
|
+
}
|