@raidiant/notifai 0.2.1 → 0.4.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 (94) hide show
  1. package/README.md +20 -4
  2. package/dist/atomic-file.d.ts +4 -0
  3. package/dist/atomic-file.js +60 -10
  4. package/dist/atomic-file.js.map +1 -1
  5. package/dist/client.d.ts +25 -2
  6. package/dist/client.js +45 -1
  7. package/dist/client.js.map +1 -1
  8. package/dist/commands.d.ts +85 -6
  9. package/dist/commands.js +1133 -322
  10. package/dist/commands.js.map +1 -1
  11. package/dist/config-schema.d.ts +62 -0
  12. package/dist/config-schema.js +312 -0
  13. package/dist/config-schema.js.map +1 -0
  14. package/dist/config.d.ts +38 -3
  15. package/dist/config.js +61 -14
  16. package/dist/config.js.map +1 -1
  17. package/dist/file-lock.d.ts +26 -0
  18. package/dist/file-lock.js +268 -0
  19. package/dist/file-lock.js.map +1 -0
  20. package/dist/harnesses.d.ts +28 -0
  21. package/dist/harnesses.js +40 -0
  22. package/dist/harnesses.js.map +1 -0
  23. package/dist/hook-adapter.d.ts +27 -0
  24. package/dist/hook-adapter.js +188 -0
  25. package/dist/hook-adapter.js.map +1 -0
  26. package/dist/hook-input.d.ts +10 -0
  27. package/dist/hook-input.js +64 -0
  28. package/dist/hook-input.js.map +1 -0
  29. package/dist/hooks.d.ts +66 -10
  30. package/dist/hooks.js +751 -276
  31. package/dist/hooks.js.map +1 -1
  32. package/dist/install-hooks.d.ts +40 -16
  33. package/dist/install-hooks.js +217 -73
  34. package/dist/install-hooks.js.map +1 -1
  35. package/dist/interactive.d.ts +4 -0
  36. package/dist/interactive.js +604 -0
  37. package/dist/interactive.js.map +1 -0
  38. package/dist/logging.d.ts +142 -0
  39. package/dist/logging.js +533 -0
  40. package/dist/logging.js.map +1 -0
  41. package/dist/main.js +201 -51
  42. package/dist/main.js.map +1 -1
  43. package/dist/opencode-plugin.d.ts +7 -7
  44. package/dist/opencode-plugin.js +12 -13
  45. package/dist/opencode-plugin.js.map +1 -1
  46. package/dist/ui/banner.d.ts +22 -0
  47. package/dist/ui/banner.js +87 -0
  48. package/dist/ui/banner.js.map +1 -0
  49. package/dist/ui/config-view.d.ts +32 -0
  50. package/dist/ui/config-view.js +108 -0
  51. package/dist/ui/config-view.js.map +1 -0
  52. package/dist/ui/help.d.ts +46 -0
  53. package/dist/ui/help.js +105 -0
  54. package/dist/ui/help.js.map +1 -0
  55. package/dist/ui/theme.d.ts +108 -0
  56. package/dist/ui/theme.js +261 -0
  57. package/dist/ui/theme.js.map +1 -0
  58. package/package.json +11 -9
  59. package/src/atomic-file.ts +86 -7
  60. package/src/client.test.ts +12 -0
  61. package/src/client.ts +72 -4
  62. package/src/commands.test.ts +971 -44
  63. package/src/commands.ts +1323 -337
  64. package/src/config-schema.test.ts +152 -0
  65. package/src/config-schema.ts +363 -0
  66. package/src/config.test.ts +6 -5
  67. package/src/config.ts +85 -16
  68. package/src/file-lock-process-worker.test.ts +64 -0
  69. package/src/file-lock.test.ts +279 -0
  70. package/src/file-lock.ts +318 -0
  71. package/src/harnesses.test.ts +48 -0
  72. package/src/harnesses.ts +59 -0
  73. package/src/hook-adapter.test.ts +187 -0
  74. package/src/hook-adapter.ts +212 -0
  75. package/src/hook-input.test.ts +39 -0
  76. package/src/hook-input.ts +72 -0
  77. package/src/hooks.test.ts +1318 -240
  78. package/src/hooks.ts +1046 -296
  79. package/src/install-hooks.test.ts +90 -41
  80. package/src/install-hooks.ts +259 -74
  81. package/src/interactive.ts +692 -0
  82. package/src/logging-process-worker.test.ts +39 -0
  83. package/src/logging.test.ts +453 -0
  84. package/src/logging.ts +639 -0
  85. package/src/main.ts +220 -48
  86. package/src/opencode-plugin.ts +15 -16
  87. package/src/session-end-log-lock-worker.test.ts +35 -0
  88. package/src/skill.test.ts +11 -0
  89. package/src/ui/banner.ts +95 -0
  90. package/src/ui/config-view.test.ts +88 -0
  91. package/src/ui/config-view.ts +138 -0
  92. package/src/ui/help.ts +124 -0
  93. package/src/ui/theme.test.ts +92 -0
  94. package/src/ui/theme.ts +279 -0
@@ -0,0 +1,212 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ statSync,
8
+ } from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+ import { atomicWriteFileSync } from './atomic-file.js'
12
+ import { withTargetFileLock } from './file-lock.js'
13
+
14
+ const ADAPTER_MARKER = '# notifai managed hook adapter'
15
+ const ADAPTER_VERSION = 1
16
+
17
+ export interface HookAdapterTarget {
18
+ execPath: string
19
+ scriptPath: string
20
+ }
21
+
22
+ export interface HookAdapterInspection {
23
+ path: string
24
+ target: HookAdapterTarget | null
25
+ problems: string[]
26
+ }
27
+
28
+ /**
29
+ * One user-level identity for every harness and every project/global install.
30
+ *
31
+ * The pathname is deliberately outside XDG configuration/state routing. XDG
32
+ * overrides routinely differ between shells, package managers, and harness
33
+ * processes; allowing one to select this path would put mutable environment
34
+ * back into every trusted definition. Only the user's home boundary selects
35
+ * it; CLI, Node, package-manager, checkout, and preference paths stay behind
36
+ * it and may change without changing hook identity.
37
+ */
38
+ export function hookAdapterPath(homeDir: string = os.userInfo().homedir): string {
39
+ return path.join(homeDir, '.notifai', 'bin', 'hook-adapter')
40
+ }
41
+
42
+ /** Install or repair the stable adapter and atomically retarget its implementation. */
43
+ export function installHookAdapter(
44
+ target: HookAdapterTarget,
45
+ homeDir?: string,
46
+ ): { path: string; changed: boolean } {
47
+ assertUsableTarget(target)
48
+ const file = hookAdapterPath(homeDir)
49
+ ensureManagedDirectories(homeDir ?? os.userInfo().homedir)
50
+ const source = hookAdapterSource(target)
51
+ return withTargetFileLock(file, () => {
52
+ const existing = existsSync(file) ? readSafeManagedFile(file) : null
53
+ const changed =
54
+ existing === null || existing.contents !== source || (existing.mode & 0o777) !== 0o700
55
+ if (changed) {
56
+ atomicWriteFileSync(file, source, {
57
+ mode: 0o700,
58
+ preserveMode: false,
59
+ requireCurrentUserOwner: true,
60
+ })
61
+ }
62
+ return { path: file, changed }
63
+ })
64
+ }
65
+
66
+ function assertUsableTarget(target: HookAdapterTarget): void {
67
+ let exec
68
+ try {
69
+ exec = statSync(target.execPath)
70
+ } catch {
71
+ throw new Error(`Hook adapter runtime ${target.execPath} does not exist.`)
72
+ }
73
+ if (!exec.isFile() || (exec.mode & 0o111) === 0) {
74
+ throw new Error(`Hook adapter runtime ${target.execPath} is not executable.`)
75
+ }
76
+ try {
77
+ if (!statSync(target.scriptPath).isFile()) {
78
+ throw new Error(`Hook adapter CLI ${target.scriptPath} is not a regular file.`)
79
+ }
80
+ } catch (err) {
81
+ if (err instanceof Error && err.message.startsWith('Hook adapter CLI ')) throw err
82
+ throw new Error(`Hook adapter CLI ${target.scriptPath} does not exist.`)
83
+ }
84
+ }
85
+
86
+ /** Inspect the shared adapter without executing either it or its registered CLI. */
87
+ export function inspectHookAdapter(
88
+ homeDir?: string,
89
+ ): HookAdapterInspection {
90
+ const file = hookAdapterPath(homeDir)
91
+ if (!existsSync(file)) {
92
+ return { path: file, target: null, problems: [`${file} is missing; rerun \`notifai hooks install\``] }
93
+ }
94
+
95
+ let stat
96
+ try {
97
+ stat = lstatSync(file)
98
+ } catch (err) {
99
+ return { path: file, target: null, problems: [String(err)] }
100
+ }
101
+ if (stat.isSymbolicLink() || !stat.isFile()) {
102
+ return {
103
+ path: file,
104
+ target: null,
105
+ problems: [`${file} is not a regular file; refusing the adapter`],
106
+ }
107
+ }
108
+
109
+ const problems: string[] = []
110
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined
111
+ if (uid !== undefined && stat.uid !== uid) {
112
+ problems.push(`${file} is owned by uid ${stat.uid}, not the current user`)
113
+ }
114
+ if ((stat.mode & 0o077) !== 0 || (stat.mode & 0o700) !== 0o700) {
115
+ problems.push(`${file} permissions are ${(stat.mode & 0o777).toString(8)}, expected 700`)
116
+ }
117
+
118
+ const contents = readFileSync(file, 'utf8')
119
+ if (!contents.startsWith(`#!/bin/sh\n${ADAPTER_MARKER}\n`)) {
120
+ problems.push(`${file} has no managed adapter marker`)
121
+ }
122
+ const version = Number(/^# adapter-version: (\d+)$/m.exec(contents)?.[1] ?? Number.NaN)
123
+ if (version !== ADAPTER_VERSION) problems.push(`${file} uses obsolete adapter version ${version}`)
124
+ const target = parseTarget(contents)
125
+ if (target === null) {
126
+ problems.push(`${file} has malformed target metadata`)
127
+ } else {
128
+ try {
129
+ const exec = statSync(target.execPath)
130
+ if (!exec.isFile() || (exec.mode & 0o111) === 0) {
131
+ problems.push(`registered runtime ${target.execPath} is not executable`)
132
+ }
133
+ } catch {
134
+ problems.push(`registered runtime ${target.execPath} is missing`)
135
+ }
136
+ try {
137
+ if (!statSync(target.scriptPath).isFile()) {
138
+ problems.push(`registered CLI ${target.scriptPath} is not a regular file`)
139
+ }
140
+ } catch {
141
+ problems.push(`registered CLI ${target.scriptPath} is missing`)
142
+ }
143
+ }
144
+ return { path: file, target, problems }
145
+ }
146
+
147
+ function hookAdapterSource(target: HookAdapterTarget): string {
148
+ return `#!/bin/sh
149
+ ${ADAPTER_MARKER}
150
+ # adapter-version: ${ADAPTER_VERSION}
151
+ # target-exec-json: ${JSON.stringify(target.execPath)}
152
+ # target-script-json: ${JSON.stringify(target.scriptPath)}
153
+ set -eu
154
+
155
+ registered_exec=${quote(target.execPath)}
156
+ registered_script=${quote(target.scriptPath)}
157
+
158
+ if [ -x "$registered_exec" ] && [ -f "$registered_script" ]; then
159
+ exec "$registered_exec" "$registered_script" "$@"
160
+ fi
161
+
162
+ printf '%s\n' 'Notifai hook adapter target is stale; run notifai hooks install.' >&2
163
+ exit 127
164
+ `
165
+ }
166
+
167
+ function parseTarget(contents: string): HookAdapterTarget | null {
168
+ const exec = /^# target-exec-json: (.+)$/m.exec(contents)?.[1]
169
+ const script = /^# target-script-json: (.+)$/m.exec(contents)?.[1]
170
+ if (exec === undefined || script === undefined) return null
171
+ try {
172
+ const execPath: unknown = JSON.parse(exec)
173
+ const scriptPath: unknown = JSON.parse(script)
174
+ return typeof execPath === 'string' && typeof scriptPath === 'string'
175
+ ? { execPath, scriptPath }
176
+ : null
177
+ } catch {
178
+ return null
179
+ }
180
+ }
181
+
182
+ function quote(value: string): string {
183
+ return `'${value.replaceAll("'", `'\\''`)}'`
184
+ }
185
+
186
+ function ensureManagedDirectories(homeDir: string): void {
187
+ if (!existsSync(homeDir)) mkdirSync(homeDir, { recursive: true, mode: 0o700 })
188
+ for (const dir of [path.join(homeDir, '.notifai'), path.join(homeDir, '.notifai', 'bin')]) {
189
+ if (!existsSync(dir)) mkdirSync(dir, { mode: 0o700 })
190
+ const stat = lstatSync(dir)
191
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
192
+ throw new Error(`${dir} is not a regular directory; refusing to install the hook adapter.`)
193
+ }
194
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined
195
+ if (uid !== undefined && stat.uid !== uid) {
196
+ throw new Error(`${dir} is owned by uid ${stat.uid}, not the current user.`)
197
+ }
198
+ chmodSync(dir, 0o700)
199
+ }
200
+ }
201
+
202
+ function readSafeManagedFile(file: string): { contents: string; mode: number } {
203
+ const stat = lstatSync(file)
204
+ if (stat.isSymbolicLink() || !stat.isFile()) {
205
+ throw new Error(`${file} is not a regular file; refusing to replace it.`)
206
+ }
207
+ const uid = typeof process.getuid === 'function' ? process.getuid() : undefined
208
+ if (uid !== undefined && stat.uid !== uid) {
209
+ throw new Error(`${file} is owned by uid ${stat.uid}, not the current user.`)
210
+ }
211
+ return { contents: readFileSync(file, 'utf8'), mode: stat.mode }
212
+ }
@@ -0,0 +1,39 @@
1
+ import { PassThrough } from 'node:stream'
2
+ import { describe, expect, it } from 'vitest'
3
+ import { readStdinWithTimeout } from './hook-input.js'
4
+
5
+ describe('hook input reader', () => {
6
+ it('rejects a timeout when the harness pipe delivered no bytes', async () => {
7
+ const input = new PassThrough()
8
+ await expect(readStdinWithTimeout(input, 5)).rejects.toThrow(/timed out waiting 5ms/)
9
+ })
10
+
11
+ it('rejects a stream failure when no useful input exists', async () => {
12
+ const input = new PassThrough()
13
+ const reading = readStdinWithTimeout(input, 1_000)
14
+ input.destroy(new Error('stdin disappeared'))
15
+ await expect(reading).rejects.toThrow('stdin disappeared')
16
+ })
17
+
18
+ it('returns partial bytes on timeout so the hook can diagnose truncation', async () => {
19
+ const input = new PassThrough()
20
+ const reading = readStdinWithTimeout(input, 5)
21
+ input.write('{"session_id":')
22
+ await expect(reading).resolves.toBe('{"session_id":')
23
+ })
24
+
25
+ it('preserves complete buffered JSON when the stream fails after delivering it', async () => {
26
+ const input = new PassThrough()
27
+ const reading = readStdinWithTimeout(input, 1_000)
28
+ input.write('{"session_id":"kept"}')
29
+ input.destroy(new Error('late pipe failure'))
30
+ await expect(reading).resolves.toBe('{"session_id":"kept"}')
31
+ })
32
+
33
+ it('marks an oversized payload as truncated instead of treating it as empty', async () => {
34
+ const input = new PassThrough()
35
+ const reading = readStdinWithTimeout(input, 1_000, 12)
36
+ input.end('{"session_id":"far-too-long"}')
37
+ await expect(reading).resolves.toMatch(/hook input truncated/)
38
+ })
39
+ })
@@ -0,0 +1,72 @@
1
+ import type { Readable } from 'node:stream'
2
+
3
+ const TRUNCATED_INPUT_SUFFIX = '\n[notifai: hook input truncated]\n'
4
+
5
+ /**
6
+ * Read one harness-hook envelope without letting a stuck pipe hold the prompt.
7
+ *
8
+ * A timeout or stream error before any bytes arrive rejects, so the hook can
9
+ * record that its input was unavailable. Once bytes exist they are more useful
10
+ * than the transport failure: complete JSON can still run, while partial or
11
+ * capped JSON reaches the hook's malformed/truncated diagnostic.
12
+ */
13
+ export function readStdinWithTimeout(
14
+ input: Readable = process.stdin,
15
+ timeoutMs = 2_000,
16
+ maxBytes = 1_000_000,
17
+ ): Promise<string> {
18
+ if ((input as Readable & { isTTY?: boolean }).isTTY === true) return Promise.resolve('')
19
+
20
+ return new Promise<string>((resolve, reject) => {
21
+ const chunks: Buffer[] = []
22
+ let total = 0
23
+ let settled = false
24
+
25
+ const cleanup = (): void => {
26
+ clearTimeout(timer)
27
+ input.off('data', onData)
28
+ input.off('end', onEnd)
29
+ input.off('error', onError)
30
+ input.destroy()
31
+ }
32
+ const finishBuffered = (): void => {
33
+ if (settled) return
34
+ settled = true
35
+ cleanup()
36
+ resolve(Buffer.concat(chunks).toString('utf8'))
37
+ }
38
+ const failEmpty = (err: Error): void => {
39
+ if (settled) return
40
+ if (chunks.length > 0) return finishBuffered()
41
+ settled = true
42
+ cleanup()
43
+ reject(err)
44
+ }
45
+ const onData = (chunk: Buffer | string): void => {
46
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
47
+ const remaining = Math.max(0, maxBytes - total)
48
+ if (bytes.length <= remaining) {
49
+ chunks.push(bytes)
50
+ total += bytes.length
51
+ return
52
+ }
53
+ if (remaining > 0) {
54
+ chunks.push(bytes.subarray(0, remaining))
55
+ total += remaining
56
+ }
57
+ chunks.push(Buffer.from(TRUNCATED_INPUT_SUFFIX))
58
+ finishBuffered()
59
+ }
60
+ const onEnd = (): void => finishBuffered()
61
+ const onError = (err: Error): void => failEmpty(err)
62
+
63
+ const timer = setTimeout(
64
+ () => failEmpty(new Error(`timed out waiting ${timeoutMs}ms for hook input`)),
65
+ timeoutMs,
66
+ )
67
+ timer.unref?.()
68
+ input.on('data', onData)
69
+ input.once('end', onEnd)
70
+ input.once('error', onError)
71
+ })
72
+ }