@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
package/src/codex-wake.ts DELETED
@@ -1,301 +0,0 @@
1
- import { spawn } from 'node:child_process'
2
- import { closeSync, constants, existsSync, openSync } from 'node:fs'
3
- import path from 'node:path'
4
- import { configHome } from './install-hooks.js'
5
- import {
6
- hookContinuationRoute,
7
- type ContinuationEvent,
8
- type DeliveryOutcome,
9
- type EscalationDeliveryRoute,
10
- } from './hooks.js'
11
-
12
- /** Codex's per-thread writer lock directory, relative to `$CODEX_HOME`. */
13
- export const CODEX_THREAD_LOCK_DIR = 'thread-writer-locks'
14
-
15
- /**
16
- * BSD `open(2)` lock flags. Node does not surface them in `fs.constants`, and
17
- * they are the only way to take a non-blocking `flock` from Node without a
18
- * native addon: the kernel takes the lock at open and drops it at close.
19
- */
20
- const O_EXLOCK = 0x20
21
- const O_NONBLOCK = 0x4
22
-
23
- /** Platforms whose `open(2)` implements `O_EXLOCK`. Everything else fails closed. */
24
- const LOCK_PROBE_PLATFORMS: ReadonlySet<string> = new Set(['darwin', 'freebsd', 'openbsd'])
25
-
26
- /** Codex thread ids are UUIDs, and the lock file is named by the exact id. */
27
- const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
28
-
29
- export type CodexWakeObservation =
30
- /** A live writer owns this thread. Resuming it would create a divergent ghost. */
31
- | { state: 'live' }
32
- /** No process holds the thread's writer lock; a cold resume can own it. */
33
- | { state: 'stopped' }
34
- | { state: 'unknown'; reason: string }
35
-
36
- export interface CodexWakeAdapters {
37
- /** Non-blocking writer-lock probe. Never holds the lock beyond the probe. */
38
- probeThreadWriter(lockPath: string): CodexWakeObservation
39
- /** Is the harness process that will read this hook's stdout still running? */
40
- sourceAlive(pid: number): boolean
41
- resume(threadId: string, cwd: string, context: string): Promise<void>
42
- }
43
-
44
- /**
45
- * The one cross-process oracle for "who owns this Codex thread".
46
- *
47
- * Codex's thread store takes a non-blocking `flock(LOCK_EX)` on a zero-byte
48
- * file per thread and holds it for as long as that process owns the thread —
49
- * verified against both a hosted app-server thread sitting idle and an
50
- * in-process `codex exec` run (2026-08-12). Because the kernel holds it, a
51
- * crash, SIGKILL, or reboot releases it instantly, and the leftover file proves
52
- * nothing: only the lock does. Codex fails closed itself with `-32600` when a
53
- * second writer contends, but that is the backstop; this is the gate.
54
- */
55
- export function observeCodexThread(
56
- threadId: string,
57
- env: NodeJS.ProcessEnv,
58
- adapters: Pick<CodexWakeAdapters, 'probeThreadWriter'>,
59
- ): CodexWakeObservation {
60
- if (!THREAD_ID.test(threadId)) {
61
- return { state: 'unknown', reason: 'the Codex session id is not a thread id' }
62
- }
63
- try {
64
- return adapters.probeThreadWriter(codexThreadLockPath(threadId, env))
65
- } catch (err) {
66
- return {
67
- state: 'unknown',
68
- reason: `Codex thread-writer lock probe failed: ${err instanceof Error ? err.message : String(err)}`,
69
- }
70
- }
71
- }
72
-
73
- export function codexThreadLockPath(threadId: string, env: NodeJS.ProcessEnv): string {
74
- return path.join(codexThreadLockDirectory(env), `${threadId}.lock`)
75
- }
76
-
77
- export function codexThreadLockDirectory(env: NodeJS.ProcessEnv): string {
78
- return path.join(configHome(env, 'CODEX_HOME', '.codex'), CODEX_THREAD_LOCK_DIR)
79
- }
80
-
81
- export type CodexResumeReadiness =
82
- | { state: 'ready'; lockDirectory: string }
83
- | { state: 'unavailable'; reason: string }
84
-
85
- /**
86
- * Whether a Codex thread whose Stop hook has already returned could still be
87
- * cold-resumed, decided without taking any lock or spawning anything.
88
- *
89
- * Two things have to hold: this platform must implement the non-blocking
90
- * `flock` the probe is built on, and `$CODEX_HOME` must actually have a
91
- * thread-writer-lock directory — its absence is not evidence that a thread is
92
- * unowned, so the gate fails closed and the answer waits for the next turn.
93
- * Neither affects the ordinary path, where the hook's own stdout continues the
94
- * held turn.
95
- */
96
- export function inspectCodexResume(
97
- env: NodeJS.ProcessEnv,
98
- options: { platform: NodeJS.Platform; directoryExists: (directory: string) => boolean },
99
- ): CodexResumeReadiness {
100
- const lockDirectory = codexThreadLockDirectory(env)
101
- if (!LOCK_PROBE_PLATFORMS.has(options.platform)) {
102
- return {
103
- state: 'unavailable',
104
- reason: `no non-blocking thread-writer lock probe exists on ${options.platform}`,
105
- }
106
- }
107
- if (!options.directoryExists(lockDirectory)) {
108
- return {
109
- state: 'unavailable',
110
- reason: `no thread-writer-lock directory at ${lockDirectory}, so no thread can be proven unowned`,
111
- }
112
- }
113
- return { state: 'ready', lockDirectory }
114
- }
115
-
116
- /**
117
- * Codex's answer-delivery route: the blocking Stop hook, then nothing else.
118
- *
119
- * The default is the hook continuation itself. While the Codex process that
120
- * invoked this hook is alive it is reading this process's stdout, and
121
- * `{"decision":"block"}` there creates a real new user turn — no launch
122
- * ownership, no control plane, no probe required. That path must never depend
123
- * on the lock probe: printing to a dead pipe cannot ghost-write anything, so
124
- * an unreadable `$CODEX_HOME` is not a reason to withhold a continuation.
125
- *
126
- * Only when that process is gone does the answer need another last meter, and
127
- * then exactly one is safe: a cold `codex exec resume` of a thread no live
128
- * writer owns. Anything else — a live writer, an unprobeable platform, a thread
129
- * id we cannot name — is journaled and replayed at the session's next Stop.
130
- * That accepted gap is the honest floor of the Codex adapter: a session that
131
- * went idle after its Stop returned, which Notifai did not launch, cannot be
132
- * woken in place.
133
- */
134
- export function codexWakeRoute(options: {
135
- threadId: string
136
- cwd: string
137
- sourcePid: number
138
- env?: NodeJS.ProcessEnv
139
- adapters?: CodexWakeAdapters
140
- /** False for a detached recovery owner whose stdout no harness will read. */
141
- continuationActive?: boolean
142
- }): EscalationDeliveryRoute {
143
- const env = options.env ?? process.env
144
- const adapters = options.adapters ?? systemCodexWakeAdapters(env)
145
- const continuation = hookContinuationRoute()
146
- return {
147
- kind: 'hook-continuation',
148
- async deliver(event: ContinuationEvent): Promise<DeliveryOutcome> {
149
- if (options.continuationActive !== false && adapters.sourceAlive(options.sourcePid)) {
150
- return continuation.deliver(event)
151
- }
152
-
153
- // Probe immediately before the spawn, twice, and never trust the earlier
154
- // answer: ownership is a kernel fact that can change between two syscalls,
155
- // and resuming a thread someone else owns is the disqualifying failure.
156
- const observed = observeCodexThread(options.threadId, env, adapters)
157
- const held = holdForNextTurn(observed)
158
- if (held !== null) return held
159
- const confirmed = observeCodexThread(options.threadId, env, adapters)
160
- const raced = holdForNextTurn(confirmed)
161
- if (raced !== null) return raced
162
-
163
- if (!event.commitDelivery()) return cancelledDelivery()
164
- await adapters.resume(options.threadId, options.cwd, event.context)
165
- return {
166
- notes: ['cold-resumed the stopped Codex thread with its accepted answer'],
167
- log: { route: 'cold-resume', stage: 'delivered' },
168
- // The resume ran: the thread holds the answer, and no later hook of this
169
- // session will report on a turn that started elsewhere.
170
- acknowledgement: 'delivered',
171
- }
172
- },
173
- }
174
- }
175
-
176
- function cancelledDelivery(): DeliveryOutcome {
177
- return {
178
- notes: ['the Agent Session ended before answer delivery; stopping this observer'],
179
- log: { route: 'hold-for-next-turn', stage: 'queued', reason: 'session-ended' },
180
- acknowledgement: 'held',
181
- }
182
- }
183
-
184
- /** The journal, with the exact reason the thread could not be resumed. */
185
- function holdForNextTurn(observation: CodexWakeObservation): DeliveryOutcome | null {
186
- if (observation.state === 'stopped') return null
187
- const reason =
188
- observation.state === 'live'
189
- ? 'a live writer owns the Codex thread and this hook can no longer continue it'
190
- : observation.reason
191
- return {
192
- notes: [`holding the accepted answer for the next turn: ${reason}`],
193
- log: { route: 'hold-for-next-turn', stage: 'queued', reason },
194
- acknowledgement: 'held',
195
- }
196
- }
197
-
198
- /**
199
- * Take and release the writer lock in one open/close pair.
200
- *
201
- * The probe momentarily owns the lock when it is free, so it is held for
202
- * microseconds and never across a spawn — a probe racing a legitimate resume
203
- * must not be what makes that resume fail.
204
- */
205
- function probeThreadWriterLock(lockPath: string): CodexWakeObservation {
206
- if (!LOCK_PROBE_PLATFORMS.has(process.platform)) {
207
- return {
208
- state: 'unknown',
209
- reason: `no non-blocking thread-writer lock probe exists on ${process.platform}`,
210
- }
211
- }
212
- const directory = path.dirname(lockPath)
213
- if (!existsSync(directory)) {
214
- // No lock directory means this is not a Codex home that has ever opened a
215
- // thread, so its silence is not evidence that nothing owns this one.
216
- return { state: 'unknown', reason: `no Codex thread-writer lock directory at ${directory}` }
217
- }
218
- let handle: number
219
- try {
220
- handle = openSync(lockPath, constants.O_RDONLY | O_EXLOCK | O_NONBLOCK)
221
- } catch (err) {
222
- const code = (err as NodeJS.ErrnoException).code
223
- if (code === 'EAGAIN' || code === 'EWOULDBLOCK') return { state: 'live' }
224
- // Codex unlinks the lock file when its writer drops cleanly, so a missing
225
- // file inside a real lock directory means the thread has no owner.
226
- if (code === 'ENOENT') return { state: 'stopped' }
227
- return {
228
- state: 'unknown',
229
- reason: `Codex thread-writer lock probe failed: ${err instanceof Error ? err.message : String(err)}`,
230
- }
231
- }
232
- closeSync(handle)
233
- return { state: 'stopped' }
234
- }
235
-
236
- function runCodex(
237
- args: string[],
238
- options: { cwd: string; env: NodeJS.ProcessEnv },
239
- ): Promise<string> {
240
- return new Promise((resolve, reject) => {
241
- const child = spawn('codex', args, {
242
- cwd: options.cwd,
243
- env: options.env,
244
- stdio: ['ignore', 'pipe', 'pipe'],
245
- })
246
- const stdout: Buffer[] = []
247
- const stderr: Buffer[] = []
248
- child.stdout?.on('data', (chunk: Buffer | string) => stdout.push(Buffer.from(chunk)))
249
- child.stderr?.on('data', (chunk: Buffer | string) => stderr.push(Buffer.from(chunk)))
250
- child.once('error', reject)
251
- child.once('exit', (code, signal) => {
252
- if (code === 0) {
253
- resolve(Buffer.concat(stdout).toString())
254
- return
255
- }
256
- reject(
257
- new Error(
258
- `codex ${args[0] ?? ''} exited ${code === null ? `on ${String(signal)}` : String(code)}: ${Buffer.concat(stderr).toString().trim()}`,
259
- ),
260
- )
261
- })
262
- })
263
- }
264
-
265
- /**
266
- * The resumed process must not inherit the ended session's identity, or it
267
- * reports itself as that thread to every hook it fires. `CODEX_HOME` is the one
268
- * exception: it names the thread store the resume has to open.
269
- */
270
- function coldResumeEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
271
- const next = { ...env }
272
- for (const key of Object.keys(next)) {
273
- if (key.startsWith('CODEX_') && key !== 'CODEX_HOME') delete next[key]
274
- }
275
- return next
276
- }
277
-
278
- export function systemCodexWakeAdapters(
279
- env: NodeJS.ProcessEnv = process.env,
280
- ): CodexWakeAdapters {
281
- return {
282
- probeThreadWriter: probeThreadWriterLock,
283
- sourceAlive(pid) {
284
- if (!Number.isInteger(pid) || pid <= 1) return false
285
- try {
286
- process.kill(pid, 0)
287
- return true
288
- } catch (err) {
289
- // Signalling a process we may not touch still proves it exists.
290
- return (err as NodeJS.ErrnoException).code === 'EPERM'
291
- }
292
- },
293
- async resume(threadId, cwd, context) {
294
- if (!existsSync(cwd)) throw new Error(`Codex thread cwd no longer exists: ${cwd}`)
295
- await runCodex(['exec', 'resume', threadId, context], {
296
- cwd,
297
- env: coldResumeEnvironment(env),
298
- })
299
- },
300
- }
301
- }
@@ -1,38 +0,0 @@
1
- import type { CommandDeps } from './commands-core.js'
2
- import { resolveActiveHarness } from './commands-harness-context.js'
3
- import { findOwningSession, readProjectSession } from './hooks.js'
4
-
5
- export interface ResolvedCommandSession {
6
- sessionId: string
7
- source: 'exact-harness' | 'stable-id' | 'project-pointer'
8
- }
9
-
10
- /**
11
- * Resolve only Question Routing lifecycle ownership.
12
- *
13
- * Exact harness identity wins across checkouts. A stable question/request id
14
- * wins next. The cwd pointer remains a compatibility fallback for shells that
15
- * genuinely have no exact harness identity; it never owns Project or config
16
- * scope, which stay with the command's invocation directory.
17
- */
18
- export function resolveCommandSession(
19
- deps: CommandDeps,
20
- stableId?: string,
21
- ): ResolvedCommandSession | null {
22
- if (stableId !== undefined) {
23
- const owner = findOwningSession(stableId, deps.env)
24
- if (owner.ambiguous) return null
25
- if (owner.sessionId !== null) return { sessionId: owner.sessionId, source: 'stable-id' }
26
- }
27
- const now = (deps.now ?? Date.now)()
28
- const resolution = resolveActiveHarness(deps.env, deps.cwd, now)
29
- if (resolution.contested.length > 0) return null
30
- if (
31
- resolution.active?.sessionId !== undefined &&
32
- resolution.contested.length === 0
33
- ) {
34
- return { sessionId: resolution.active.sessionId, source: 'exact-harness' }
35
- }
36
- const pointer = readProjectSession(deps.cwd, deps.env, now)
37
- return pointer === null ? null : { sessionId: pointer, source: 'project-pointer' }
38
- }
@@ -1,72 +0,0 @@
1
- import { resolveActiveHarness } from './commands-harness-context.js'
2
- import {
3
- authedClient,
4
- EXIT,
5
- loadLoggedConfig,
6
- reportError,
7
- type CommandDeps,
8
- } from './commands-core.js'
9
- import {
10
- normalizeExplicitSessionLabel,
11
- renameStoredSessionLabel,
12
- } from './session-labels.js'
13
-
14
- export interface AgentSessionRenameFlags {
15
- json?: boolean
16
- }
17
-
18
- /** Rename only the exact harness-owned Agent Session running this command. */
19
- export async function agentSessionRenameCommand(
20
- deps: CommandDeps,
21
- label: string,
22
- flags: AgentSessionRenameFlags = {},
23
- ): Promise<number> {
24
- const now = deps.now?.() ?? Date.now()
25
- const resolution = resolveActiveHarness(deps.env, deps.cwd, now)
26
- const active = resolution.active
27
- if (resolution.contested.length > 0 || active?.sessionId === undefined) {
28
- deps.io.err(
29
- 'No exact active Agent Session can be proven here. Run this command inside the Agent Session you intend to rename.',
30
- )
31
- return EXIT.usage
32
- }
33
-
34
- const normalized = normalizeExplicitSessionLabel({
35
- env: deps.env,
36
- sessionId: active.sessionId,
37
- label,
38
- })
39
- if (!normalized.ok) {
40
- deps.io.err(normalized.error)
41
- return EXIT.usage
42
- }
43
-
44
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
45
- const auth = authedClient(deps, config)
46
- if (!auth) return EXIT.auth
47
- try {
48
- const renamed = await auth.client.putAgentSessionLabel({
49
- session_id: active.sessionId,
50
- label: normalized.label,
51
- })
52
- const local = renameStoredSessionLabel({
53
- env: deps.env,
54
- sessionId: active.sessionId,
55
- label: renamed.label,
56
- harness: active.harness,
57
- now,
58
- })
59
- if (!local.ok) {
60
- deps.io.err(local.error)
61
- return EXIT.failed
62
- }
63
- deps.io.out(
64
- flags.json
65
- ? JSON.stringify(renamed)
66
- : `Agent Session renamed to "${renamed.label}" across your Notifai account.`,
67
- )
68
- return EXIT.ok
69
- } catch (err) {
70
- return reportError(deps, err, { operation: 'agent_session_rename' })
71
- }
72
- }
@@ -1,238 +0,0 @@
1
- import { type AccountAccessResponse } from '@raidiant/notifai-protocol'
2
- import { sha256Hex } from '@raidiant/notifai-protocol/node'
3
- import { randomBytes } from 'node:crypto'
4
- import os from 'node:os'
5
- import { NetworkError } from './client.js'
6
- import { type FlagOverrides } from './config.js'
7
- import { checkApproveUrl } from './url-policy.js'
8
- import {
9
- EXIT,
10
- SETUP_COMMAND,
11
- authedClient,
12
- loadLoggedConfig,
13
- makeClient,
14
- reportError,
15
- type CommandDeps,
16
- } from './commands-core.js'
17
- import { setupAccessUrl } from './setup-destinations.js'
18
- import type { ReadinessState } from './readiness.js'
19
-
20
- // ---------------------------------------------------------------------------
21
- // login / logout / auth status
22
- // ---------------------------------------------------------------------------
23
-
24
- /**
25
- * Keep the one-time confirmation secret out of the HTTP request that opens
26
- * the dashboard. URL fragments are browser-local and are not sent by GET,
27
- * prefetchers, referrers, or link scanners.
28
- */
29
- export function pairingApprovalUrl(approveUrl: string, confirmationSecret: string): string {
30
- const url = new URL(approveUrl)
31
- url.hash = new URLSearchParams({ confirmation_secret: confirmationSecret }).toString()
32
- return url.toString()
33
- }
34
-
35
- /**
36
- * Why a sign-in stopped, in the shape the close line renders.
37
- *
38
- * Without it, `init` fell back to the state it had before the attempt — "this
39
- * machine is not paired … run `notifai init`" — so the last thing a User read
40
- * contradicted the correct line three lines above it and pointed back at the
41
- * command that had just failed, for a reason it never mentioned.
42
- *
43
- * Passing one also transfers the errand: whoever takes the blocker prints the
44
- * close, so this command stops after naming what stopped. A sign-in run on its
45
- * own has no such caller and states the errand itself.
46
- */
47
- export type LoginBlockedSink = (blocker: ReadinessState) => void
48
-
49
- export async function loginCommand(
50
- deps: CommandDeps,
51
- flags: { name?: string; baseUrl?: string; open?: boolean },
52
- onBlocked?: LoginBlockedSink,
53
- ): Promise<number> {
54
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env, flags: { base_url: flags.baseUrl } as FlagOverrides })
55
- const baseUrl = config.base_url.value
56
- const machineName = flags.name ?? os.hostname()
57
- const secret = randomBytes(32).toString('base64url')
58
- const pollVerifier = randomBytes(24).toString('base64url')
59
- const confirmationSecret = randomBytes(32).toString('base64url')
60
- const client = makeClient(deps, baseUrl, null)
61
-
62
- let begin
63
- try {
64
- begin = await client.beginPairing({
65
- machine_name: machineName,
66
- credential_hash: sha256Hex(secret),
67
- poll_verifier_hash: sha256Hex(pollVerifier),
68
- confirmation_hash: sha256Hex(confirmationSecret),
69
- })
70
- } catch (err) {
71
- return reportError(deps, err)
72
- }
73
- const approveUrl = pairingApprovalUrl(begin.approve_url, confirmationSecret)
74
-
75
- // The approval URL is the server's choice, and this machine is about to put
76
- // it in front of the user's browser. A compromised or misconfigured service
77
- // must not be able to aim that anywhere it likes, so the pairing stops here
78
- // rather than showing a link the user would reasonably trust.
79
- const approvable = checkApproveUrl(begin.approve_url, baseUrl, config.approve_origins.value)
80
- if (!approvable.ok) {
81
- deps.io.err(`Pairing stopped: ${approvable.reason}`)
82
- deps.io.err(
83
- 'next: If you self-host with the dashboard on its own origin, allow it with ' +
84
- '`notifai config set approve_origins <origin>` and run `notifai login` again.',
85
- )
86
- return EXIT.auth
87
- }
88
-
89
- const interactive = deps.io.interactive === true
90
- if (interactive) {
91
- await deps.io.intro?.('Notifai sign in')
92
- await deps.io.note?.(`Code: ${begin.code}\n${approveUrl}`, 'Approve this machine')
93
- } else {
94
- deps.io.out(`Pairing code: ${begin.code}`)
95
- deps.io.out(`Approve this machine at: ${approveUrl}`)
96
- deps.io.out('Waiting for approval…')
97
- }
98
- if (flags.open !== false) deps.io.openUrl(approveUrl)
99
-
100
- const expiresAt = new Date(begin.expires_at).getTime()
101
- const intervalMs = Math.max(begin.poll_interval_seconds, 1) * 1000
102
- const now = deps.now ?? Date.now
103
- const sleep = deps.sleep ?? ((milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds)))
104
- const approvalWaitMessage = (): string => {
105
- const remainingSec = Math.max(0, Math.ceil((expiresAt - now()) / 1000))
106
- const minutes = Math.floor(remainingSec / 60)
107
- const seconds = remainingSec % 60
108
- const remaining =
109
- minutes > 0 ? `${minutes}m ${seconds.toString().padStart(2, '0')}s` : `${seconds}s`
110
- return `Waiting for approval… code ${begin.code} · ${remaining} left`
111
- }
112
- const spinner = interactive ? await deps.io.spinner?.(approvalWaitMessage()) : null
113
- while (now() < expiresAt) {
114
- await sleep(intervalMs)
115
- let poll
116
- try {
117
- poll = await client.pollPairing(begin.pairing_id, pollVerifier)
118
- } catch (err) {
119
- if (err instanceof NetworkError) {
120
- spinner?.message(`Connection lost — retrying… code ${begin.code}`)
121
- continue
122
- }
123
- spinner?.error('Pairing failed')
124
- return reportError(deps, err)
125
- }
126
- if (poll.status === 'approved' && poll.machine_id) {
127
- deps.store.save({ machineId: poll.machine_id, secret, baseUrl, machineName })
128
- if (interactive) {
129
- spinner?.stop(`Machine "${machineName}" approved`)
130
- await deps.io.outro?.(`Credential stored in ${deps.store.describe()}`)
131
- } else {
132
- deps.io.out(`Machine "${machineName}" approved. Credential stored in ${deps.store.describe()}.`)
133
- }
134
- return EXIT.ok
135
- }
136
- if (poll.status === 'denied') {
137
- spinner?.error('Pairing denied')
138
- deps.io.err('Pairing was denied from the dashboard.')
139
- return EXIT.auth
140
- }
141
- // Proof-gated: the server never returns this from lookup. Stop now rather
142
- // than waiting out a TTL no approval can arrive within.
143
- if (poll.status === 'no_active_plan') {
144
- // The server owns which access errand is current — requesting it today,
145
- // choosing a plan after cutover — so its line wins whenever it sends one.
146
- const next = poll.next_action ?? `Open ${setupAccessUrl(baseUrl)} to set up access, then retry.`
147
- // Ends the wait, like its three siblings above and below; the wall
148
- // itself belongs to the line under it, which said the same sentence a
149
- // second time when this one tried to say it first.
150
- spinner?.error('Pairing stopped')
151
- // One wall, said once. When a caller takes the blocker it closes the
152
- // visit on this exact errand, so repeating the destination here — and
153
- // naming `init` as the way past a wall no command of theirs can open —
154
- // would leave the User three phrasings of one step to choose between.
155
- if (onBlocked === undefined) {
156
- deps.io.err('This account has no active plan or temporary Alpha access.')
157
- deps.io.err(`next: ${next}`)
158
- deps.io.err(`After access is granted, run \`${SETUP_COMMAND}\` again.`)
159
- }
160
- onBlocked?.({
161
- id: 'auth',
162
- title: 'Access',
163
- status: 'gap',
164
- detail: 'this account does not have access to Notifai yet',
165
- remedy: { by: 'user-elsewhere', summary: next },
166
- })
167
- return EXIT.auth
168
- }
169
- if (poll.status === 'expired') break
170
- spinner?.message(approvalWaitMessage())
171
- }
172
- spinner?.error('Pairing expired')
173
- deps.io.err(`Pairing expired before it was approved. Run \`${SETUP_COMMAND}\` again.`)
174
- return EXIT.auth
175
- }
176
-
177
- export function logoutCommand(deps: CommandDeps): number {
178
- deps.store.clear()
179
- deps.io.out('Machine credential removed. Revoke it in the dashboard too if the machine is untrusted.')
180
- return EXIT.ok
181
- }
182
-
183
- export function authStatusCommand(deps: CommandDeps, flags: { json?: boolean }): number {
184
- const credential = deps.store.load()
185
- if (flags.json) {
186
- deps.io.out(
187
- JSON.stringify(
188
- credential
189
- ? {
190
- signed_in: true,
191
- machine_id: credential.machineId,
192
- machine_name: credential.machineName,
193
- base_url: credential.baseUrl,
194
- store: deps.store.describe(),
195
- }
196
- : { signed_in: false },
197
- null,
198
- 2,
199
- ),
200
- )
201
- return credential ? EXIT.ok : EXIT.auth
202
- }
203
- if (!credential) {
204
- deps.io.err(`Not signed in. Run \`${SETUP_COMMAND}\`; it will coordinate machine login and device setup.`)
205
- return EXIT.auth
206
- }
207
- deps.io.out(`Signed in as machine "${credential.machineName}" (${credential.machineId})`)
208
- deps.io.out(`Server: ${credential.baseUrl}`)
209
- deps.io.out(`Credential store: ${deps.store.describe()}`)
210
- return EXIT.ok
211
- }
212
-
213
- /** Show the server's account access decision without attempting a product mutation. */
214
- export async function accessStatusCommand(
215
- deps: CommandDeps,
216
- flags: { json?: boolean },
217
- ): Promise<number> {
218
- const config = loadLoggedConfig(deps, { cwd: deps.cwd, env: deps.env })
219
- const authed = authedClient(deps, config)
220
- if (!authed) return EXIT.auth
221
- try {
222
- const access: AccountAccessResponse = await authed.client.accessStatus()
223
- if (flags.json) {
224
- deps.io.out(JSON.stringify(access, null, 2))
225
- return access.status === 'active' ? EXIT.ok : EXIT.failed
226
- }
227
- if (access.status === 'no_active_plan') {
228
- deps.io.out('This account does not have access to Notifai yet.')
229
- deps.io.out(`next: Open ${setupAccessUrl(authed.baseUrl)} to set up access, then retry.`)
230
- return EXIT.failed
231
- }
232
- const expiry = access.expires_at ? ` until ${access.expires_at}` : ''
233
- deps.io.out(`Access active (${access.reason})${expiry}`)
234
- return EXIT.ok
235
- } catch (err) {
236
- return reportError(deps, err)
237
- }
238
- }