@namzu/sdk 69.2.0 → 69.3.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 +14 -0
- package/dist/constants/plugin/index.d.ts +8 -0
- package/dist/constants/plugin/index.d.ts.map +1 -1
- package/dist/constants/plugin/index.js +8 -0
- package/dist/constants/plugin/index.js.map +1 -1
- package/dist/plugin/common-layout/index.d.ts +5 -0
- package/dist/plugin/common-layout/index.d.ts.map +1 -0
- package/dist/plugin/common-layout/index.js +3 -0
- package/dist/plugin/common-layout/index.js.map +1 -0
- package/dist/plugin/common-layout/mcp.d.ts +21 -0
- package/dist/plugin/common-layout/mcp.d.ts.map +1 -0
- package/dist/plugin/common-layout/mcp.js +305 -0
- package/dist/plugin/common-layout/mcp.js.map +1 -0
- package/dist/plugin/common-layout/paths.d.ts +27 -0
- package/dist/plugin/common-layout/paths.d.ts.map +1 -0
- package/dist/plugin/common-layout/paths.js +48 -0
- package/dist/plugin/common-layout/paths.js.map +1 -0
- package/dist/plugin/common-layout/read.d.ts +25 -0
- package/dist/plugin/common-layout/read.d.ts.map +1 -0
- package/dist/plugin/common-layout/read.js +1155 -0
- package/dist/plugin/common-layout/read.js.map +1 -0
- package/dist/plugin/common-layout/types.d.ts +66 -0
- package/dist/plugin/common-layout/types.d.ts.map +1 -0
- package/dist/plugin/common-layout/types.js +2 -0
- package/dist/plugin/common-layout/types.js.map +1 -0
- package/dist/plugin/common-layout-names.d.ts +65 -0
- package/dist/plugin/common-layout-names.d.ts.map +1 -0
- package/dist/plugin/common-layout-names.js +94 -0
- package/dist/plugin/common-layout-names.js.map +1 -0
- package/dist/plugin/hook-module/capabilities.d.ts +41 -0
- package/dist/plugin/hook-module/capabilities.d.ts.map +1 -0
- package/dist/plugin/hook-module/capabilities.js +438 -0
- package/dist/plugin/hook-module/capabilities.js.map +1 -0
- package/dist/plugin/hook-module/consent.d.ts +39 -0
- package/dist/plugin/hook-module/consent.d.ts.map +1 -0
- package/dist/plugin/hook-module/consent.js +59 -0
- package/dist/plugin/hook-module/consent.js.map +1 -0
- package/dist/plugin/hook-module/events.d.ts +33 -0
- package/dist/plugin/hook-module/events.d.ts.map +1 -0
- package/dist/plugin/hook-module/events.js +149 -0
- package/dist/plugin/hook-module/events.js.map +1 -0
- package/dist/plugin/hook-module/host.d.ts +79 -0
- package/dist/plugin/hook-module/host.d.ts.map +1 -0
- package/dist/plugin/hook-module/host.js +546 -0
- package/dist/plugin/hook-module/host.js.map +1 -0
- package/dist/plugin/hook-module/index.d.ts +11 -0
- package/dist/plugin/hook-module/index.d.ts.map +1 -0
- package/dist/plugin/hook-module/index.js +6 -0
- package/dist/plugin/hook-module/index.js.map +1 -0
- package/dist/plugin/hook-module/scan.d.ts +99 -0
- package/dist/plugin/hook-module/scan.d.ts.map +1 -0
- package/dist/plugin/hook-module/scan.js +789 -0
- package/dist/plugin/hook-module/scan.js.map +1 -0
- package/dist/plugin/hook-module/worker-source.d.ts +31 -0
- package/dist/plugin/hook-module/worker-source.d.ts.map +1 -0
- package/dist/plugin/hook-module/worker-source.js +498 -0
- package/dist/plugin/hook-module/worker-source.js.map +1 -0
- package/dist/plugin/index.d.ts +5 -2
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +4 -1
- package/dist/plugin/index.js.map +1 -1
- package/dist/plugin/lifecycle.d.ts +57 -0
- package/dist/plugin/lifecycle.d.ts.map +1 -1
- package/dist/plugin/lifecycle.js +92 -11
- package/dist/plugin/lifecycle.js.map +1 -1
- package/dist/plugin/loader.d.ts +30 -0
- package/dist/plugin/loader.d.ts.map +1 -1
- package/dist/plugin/loader.js +76 -19
- package/dist/plugin/loader.js.map +1 -1
- package/dist/plugin/shell-hook-env.d.ts +7 -0
- package/dist/plugin/shell-hook-env.d.ts.map +1 -1
- package/dist/plugin/shell-hook-env.js.map +1 -1
- package/dist/plugin/shell-hook.d.ts +10 -1
- package/dist/plugin/shell-hook.d.ts.map +1 -1
- package/dist/plugin/shell-hook.js +81 -70
- package/dist/plugin/shell-hook.js.map +1 -1
- package/dist/public-runtime.d.ts +3 -2
- package/dist/public-runtime.d.ts.map +1 -1
- package/dist/public-runtime.js +2 -2
- package/dist/public-runtime.js.map +1 -1
- package/dist/skills/loader.d.ts +8 -2
- package/dist/skills/loader.d.ts.map +1 -1
- package/dist/skills/loader.js +22 -11
- package/dist/skills/loader.js.map +1 -1
- package/dist/skills/registry.d.ts.map +1 -1
- package/dist/skills/registry.js +9 -1
- package/dist/skills/registry.js.map +1 -1
- package/dist/types/plugin/index.d.ts +73 -0
- package/dist/types/plugin/index.d.ts.map +1 -1
- package/dist/types/plugin/index.js +28 -6
- package/dist/types/plugin/index.js.map +1 -1
- package/dist/types/skills/index.d.ts +6 -0
- package/dist/types/skills/index.d.ts.map +1 -1
- package/package.json +2 -1
- package/src/constants/plugin/index.ts +9 -0
- package/src/plugin/common-layout/index.ts +19 -0
- package/src/plugin/common-layout/mcp.ts +362 -0
- package/src/plugin/common-layout/paths.ts +70 -0
- package/src/plugin/common-layout/read.ts +1282 -0
- package/src/plugin/common-layout/types.ts +77 -0
- package/src/plugin/common-layout-names.ts +108 -0
- package/src/plugin/hook-module/capabilities.ts +500 -0
- package/src/plugin/hook-module/consent.ts +96 -0
- package/src/plugin/hook-module/events.ts +177 -0
- package/src/plugin/hook-module/host.ts +649 -0
- package/src/plugin/hook-module/index.ts +52 -0
- package/src/plugin/hook-module/scan.ts +1004 -0
- package/src/plugin/hook-module/worker-source.ts +500 -0
- package/src/plugin/index.ts +13 -1
- package/src/plugin/lifecycle.ts +179 -17
- package/src/plugin/loader.ts +97 -18
- package/src/plugin/shell-hook-env.ts +7 -0
- package/src/plugin/shell-hook.ts +91 -70
- package/src/public-runtime.ts +35 -0
- package/src/skills/loader.ts +26 -9
- package/src/skills/registry.ts +9 -1
- package/src/types/plugin/index.ts +81 -24
- package/src/types/skills/index.ts +7 -0
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads'
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
PluginHookContext,
|
|
5
|
+
PluginHookDefinition,
|
|
6
|
+
PluginHookResult,
|
|
7
|
+
} from '../../types/plugin/index.js'
|
|
8
|
+
import { toErrorMessage } from '../../utils/error.js'
|
|
9
|
+
import type { Logger } from '../../utils/logger.js'
|
|
10
|
+
import {
|
|
11
|
+
type ShellHookCall,
|
|
12
|
+
type ShellHookEvent,
|
|
13
|
+
type ShellHookOptions,
|
|
14
|
+
shellHookInputFor,
|
|
15
|
+
shellHookPayload,
|
|
16
|
+
shellHookVerdict,
|
|
17
|
+
} from '../shell-hook.js'
|
|
18
|
+
import { type CapabilityBridge, createCapabilityBridge } from './capabilities.js'
|
|
19
|
+
import {
|
|
20
|
+
MODULE_HOOK_EVENTS,
|
|
21
|
+
classicEventName,
|
|
22
|
+
classicWrittenName,
|
|
23
|
+
resolvePattern,
|
|
24
|
+
} from './events.js'
|
|
25
|
+
import { type HookModuleScan, SUPPORTED_CAPABILITY_CALLS, scanHookModule } from './scan.js'
|
|
26
|
+
import { HOOK_WORKER_SOURCE } from './worker-source.js'
|
|
27
|
+
|
|
28
|
+
/** What a hook has to answer in, as the module is told by `next.budget`. */
|
|
29
|
+
export const HOOK_MODULE_BUDGET_MS = 10_000
|
|
30
|
+
/**
|
|
31
|
+
* The most time one dispatch may take in all, calls on `$` included, as a
|
|
32
|
+
* multiple of the budget. The budget itself stands still while a call is
|
|
33
|
+
* outstanding; this is what keeps a chain of calls from holding a hook open.
|
|
34
|
+
*/
|
|
35
|
+
export const HOOK_MODULE_CEILING_FACTOR = 6
|
|
36
|
+
/** How long a `.catch` has to answer once its hook overran. */
|
|
37
|
+
export const HOOK_MODULE_CATCH_MS = 1_000
|
|
38
|
+
|
|
39
|
+
/** The worker as the host sees it, so a test can stand in for it. */
|
|
40
|
+
export interface HookModuleTransport {
|
|
41
|
+
post(message: unknown): void
|
|
42
|
+
onMessage(listener: (message: any) => void): void
|
|
43
|
+
/** Called once when the worker is gone, with why. */
|
|
44
|
+
onExit(listener: (reason: string) => void): void
|
|
45
|
+
terminate(): Promise<void>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type HookModuleTransportFactory = () => HookModuleTransport
|
|
49
|
+
|
|
50
|
+
/** The clock the budgets run on. A test drives its own. */
|
|
51
|
+
export interface HookModuleClock {
|
|
52
|
+
now(): number
|
|
53
|
+
setTimeout(callback: () => void, ms: number): unknown
|
|
54
|
+
clearTimeout(handle: unknown): void
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const realClock: HookModuleClock = {
|
|
58
|
+
now: () => performance.now(),
|
|
59
|
+
setTimeout: (callback, ms) => setTimeout(callback, ms),
|
|
60
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A worker thread running {@link HOOK_WORKER_SOURCE}. It never keeps the process alive. */
|
|
64
|
+
export const workerTransport: HookModuleTransportFactory = () => {
|
|
65
|
+
const worker = new Worker(HOOK_WORKER_SOURCE, {
|
|
66
|
+
eval: true,
|
|
67
|
+
env: {},
|
|
68
|
+
stdout: true,
|
|
69
|
+
stderr: true,
|
|
70
|
+
resourceLimits: { maxOldGenerationSizeMb: 256, maxYoungGenerationSizeMb: 32 },
|
|
71
|
+
})
|
|
72
|
+
worker.unref()
|
|
73
|
+
let exited = false
|
|
74
|
+
return {
|
|
75
|
+
post: (message) => worker.postMessage(message),
|
|
76
|
+
onMessage: (listener) => {
|
|
77
|
+
worker.on('message', listener)
|
|
78
|
+
},
|
|
79
|
+
onExit: (listener) => {
|
|
80
|
+
const once = (reason: string): void => {
|
|
81
|
+
if (exited) return
|
|
82
|
+
exited = true
|
|
83
|
+
listener(reason)
|
|
84
|
+
}
|
|
85
|
+
worker.on('error', (error) => once(toErrorMessage(error)))
|
|
86
|
+
worker.on('exit', (code) => once(`it exited with code ${code}`))
|
|
87
|
+
},
|
|
88
|
+
terminate: async () => {
|
|
89
|
+
await worker.terminate()
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface StartHookModuleOptions {
|
|
95
|
+
readonly plugin: {
|
|
96
|
+
readonly name: string
|
|
97
|
+
/** The plugin's folder. */
|
|
98
|
+
readonly root: string
|
|
99
|
+
/** The folder kept for the plugin's data (`NAMZU_PLUGIN_DATA`). */
|
|
100
|
+
readonly dataDir?: string
|
|
101
|
+
}
|
|
102
|
+
/** The module, relative to the plugin. */
|
|
103
|
+
readonly entry: string
|
|
104
|
+
readonly projectDir: string
|
|
105
|
+
/** How an event becomes the input a hook reads; the same options a command hook gets. */
|
|
106
|
+
readonly shell: ShellHookOptions
|
|
107
|
+
readonly log: Logger
|
|
108
|
+
/** The scan, when the caller has just made one. Read again otherwise. */
|
|
109
|
+
readonly scan?: HookModuleScan
|
|
110
|
+
/** The plugin's options. Empty until a plugin can ask for some. */
|
|
111
|
+
readonly options?: Readonly<Record<string, unknown>>
|
|
112
|
+
readonly budgetMs?: number
|
|
113
|
+
readonly catchMs?: number
|
|
114
|
+
readonly clock?: HookModuleClock
|
|
115
|
+
readonly transport?: HookModuleTransportFactory
|
|
116
|
+
readonly environment?: Readonly<Record<string, string | undefined>>
|
|
117
|
+
readonly fetch?: typeof fetch
|
|
118
|
+
/** Called once, with the reason, when the module stops running for any cause but being disposed. */
|
|
119
|
+
readonly onUnload?: (message: string) => void
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface HookModuleHandle {
|
|
123
|
+
readonly scan: HookModuleScan
|
|
124
|
+
readonly status: 'running' | 'unloaded'
|
|
125
|
+
/** Why the module is not running, when it is not. */
|
|
126
|
+
readonly message?: string
|
|
127
|
+
/** The hooks to attach to the plugin manager. */
|
|
128
|
+
readonly hooks: readonly PluginHookDefinition[]
|
|
129
|
+
/** End the worker. Safe to call again. */
|
|
130
|
+
dispose(): Promise<void>
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
interface Pending {
|
|
134
|
+
readonly resolve: (outcome: DispatchOutcome) => void
|
|
135
|
+
remaining: number
|
|
136
|
+
startedAt: number
|
|
137
|
+
timer: unknown
|
|
138
|
+
/** Fires when the dispatch has taken too long in all, whatever the hook is waiting on. */
|
|
139
|
+
ceiling: unknown
|
|
140
|
+
phase: 'budget' | 'grace'
|
|
141
|
+
paused: boolean
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
type DispatchOutcome =
|
|
145
|
+
| { readonly kind: 'value'; readonly value: unknown; readonly failures: readonly string[] }
|
|
146
|
+
| { readonly kind: 'failed'; readonly message: string }
|
|
147
|
+
|
|
148
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
149
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The first refusal of a scan, as one line. */
|
|
153
|
+
function refusalLine(scan: HookModuleScan): string {
|
|
154
|
+
const first = scan.refusals[0]
|
|
155
|
+
if (first === undefined) return 'the module was refused'
|
|
156
|
+
const more = scan.refusals.length > 1 ? ` (and ${scan.refusals.length - 1} more)` : ''
|
|
157
|
+
return `${first.file}:${first.line}: ${first.message}${more}`
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* What a module is shown for a tool call: the tool, the id of the call and the
|
|
162
|
+
* tool's own arguments beside them. `tool` and `tool_use_id` are the engine's,
|
|
163
|
+
* so no argument can stand over them.
|
|
164
|
+
*/
|
|
165
|
+
function toolEnvelope(payload: Record<string, unknown>): Record<string, unknown> {
|
|
166
|
+
const input = isRecord(payload.tool_input) ? payload.tool_input : {}
|
|
167
|
+
return { ...input, tool: payload.tool_name, tool_use_id: payload.tool_use_id }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The module's answer for a classic event as the JSON a command hook prints.
|
|
172
|
+
* Both kinds of hook then go through the same reading, so the same answer has
|
|
173
|
+
* the same effect whichever wrote it.
|
|
174
|
+
*/
|
|
175
|
+
function answerAsJson(
|
|
176
|
+
event: ShellHookEvent,
|
|
177
|
+
value: unknown,
|
|
178
|
+
): { readonly json: Record<string, unknown> } | { readonly problem: string } {
|
|
179
|
+
if (!isRecord(value)) return { problem: 'its answer is not an object' }
|
|
180
|
+
const top: Record<string, unknown> = {}
|
|
181
|
+
const specific: Record<string, unknown> = {}
|
|
182
|
+
const strings = (key: string): string[] | undefined | 'bad' => {
|
|
183
|
+
const list = value[key]
|
|
184
|
+
if (list === undefined) return undefined
|
|
185
|
+
return Array.isArray(list) && list.every((item) => typeof item === 'string')
|
|
186
|
+
? (list as string[])
|
|
187
|
+
: 'bad'
|
|
188
|
+
}
|
|
189
|
+
const context = strings('additionalContext')
|
|
190
|
+
if (context === 'bad') return { problem: '`additionalContext` is a list of strings' }
|
|
191
|
+
if (context !== undefined && context.length > 0) specific.additionalContext = context.join('\n')
|
|
192
|
+
|
|
193
|
+
if (event === 'pre_tool_use') {
|
|
194
|
+
const { allow, ask, deny, updatedInput } = value
|
|
195
|
+
if (allow !== undefined && allow !== true) return { problem: 'an allow that is not true' }
|
|
196
|
+
if (ask !== undefined && typeof ask !== 'string')
|
|
197
|
+
return { problem: 'an ask that is not a string' }
|
|
198
|
+
if (deny !== undefined && typeof deny !== 'string')
|
|
199
|
+
return { problem: 'a deny that is not a string' }
|
|
200
|
+
const given = [allow, ask, deny].filter((item) => item !== undefined).length
|
|
201
|
+
if (given > 1) return { problem: 'allow, ask and deny are one answer: only one is given' }
|
|
202
|
+
if (allow === true) specific.permissionDecision = 'allow'
|
|
203
|
+
if (typeof ask === 'string') {
|
|
204
|
+
specific.permissionDecision = 'ask'
|
|
205
|
+
specific.permissionDecisionReason = ask
|
|
206
|
+
}
|
|
207
|
+
if (typeof deny === 'string') {
|
|
208
|
+
specific.permissionDecision = 'deny'
|
|
209
|
+
specific.permissionDecisionReason = deny
|
|
210
|
+
}
|
|
211
|
+
if (updatedInput !== undefined) {
|
|
212
|
+
if (!isRecord(updatedInput)) return { problem: '`updatedInput` is an object' }
|
|
213
|
+
specific.updatedInput = updatedInput
|
|
214
|
+
}
|
|
215
|
+
} else {
|
|
216
|
+
if (value.block !== undefined) {
|
|
217
|
+
if (typeof value.block !== 'string') return { problem: '`block` is a string' }
|
|
218
|
+
top.decision = 'block'
|
|
219
|
+
top.reason = value.block
|
|
220
|
+
}
|
|
221
|
+
if (value.preventContinuation !== undefined) {
|
|
222
|
+
if (value.preventContinuation !== true) return { problem: '`preventContinuation` is true' }
|
|
223
|
+
top.continue = false
|
|
224
|
+
}
|
|
225
|
+
if (value.stopReason !== undefined) {
|
|
226
|
+
if (typeof value.stopReason !== 'string') return { problem: '`stopReason` is a string' }
|
|
227
|
+
top.stopReason = value.stopReason
|
|
228
|
+
}
|
|
229
|
+
const watch = strings('watchPaths')
|
|
230
|
+
if (watch === 'bad') return { problem: '`watchPaths` is a list of strings' }
|
|
231
|
+
if (watch !== undefined) specific.watchPaths = watch
|
|
232
|
+
if (value.updatedToolOutput !== undefined) specific.updatedToolOutput = value.updatedToolOutput
|
|
233
|
+
if (value.updatedMCPToolOutput !== undefined) {
|
|
234
|
+
specific.updatedMCPToolOutput = value.updatedMCPToolOutput
|
|
235
|
+
}
|
|
236
|
+
if (value.decision !== undefined) {
|
|
237
|
+
if (!isRecord(value.decision))
|
|
238
|
+
return { problem: '`decision` is {behavior: "allow"} or {behavior: "deny"}' }
|
|
239
|
+
specific.decision = value.decision
|
|
240
|
+
}
|
|
241
|
+
if (value.permissionDecision !== undefined) {
|
|
242
|
+
if (!['allow', 'deny', 'ask'].includes(String(value.permissionDecision))) {
|
|
243
|
+
return { problem: '`permissionDecision` is "allow", "deny" or "ask"' }
|
|
244
|
+
}
|
|
245
|
+
specific.permissionDecision = value.permissionDecision
|
|
246
|
+
if (typeof value.permissionDecisionReason === 'string') {
|
|
247
|
+
specific.permissionDecisionReason = value.permissionDecisionReason
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (Object.keys(specific).length > 0) {
|
|
252
|
+
top.hookSpecificOutput = { hookEventName: classicWrittenName(event), ...specific }
|
|
253
|
+
}
|
|
254
|
+
return { json: top }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Start the hooks module of one plugin: read it, and run it in a worker of its
|
|
259
|
+
* own. The result lists the hooks to attach. A module that is refused, throws
|
|
260
|
+
* where it loads or registers nothing that runs here is reported in `message`
|
|
261
|
+
* and runs nothing; the plugin's other hooks are not touched.
|
|
262
|
+
*
|
|
263
|
+
* The worker is started when the first event it hooks arrives, not before, so a
|
|
264
|
+
* plugin that is enabled and never reaches one of its events costs nothing.
|
|
265
|
+
*/
|
|
266
|
+
export async function startHookModule(options: StartHookModuleOptions): Promise<HookModuleHandle> {
|
|
267
|
+
const { plugin, log } = options
|
|
268
|
+
const clock = options.clock ?? realClock
|
|
269
|
+
const budgetMs = options.budgetMs ?? HOOK_MODULE_BUDGET_MS
|
|
270
|
+
const catchMs = options.catchMs ?? HOOK_MODULE_CATCH_MS
|
|
271
|
+
const scan = options.scan ?? scanHookModule(plugin.root, options.entry)
|
|
272
|
+
const label = `${plugin.name}/${options.entry}`
|
|
273
|
+
const attrs = { 'namzu.plugin.name': plugin.name, 'namzu.hook_module.entry': options.entry }
|
|
274
|
+
|
|
275
|
+
let status: 'running' | 'unloaded' = 'running'
|
|
276
|
+
let message: string | undefined
|
|
277
|
+
const unload = (why: string): void => {
|
|
278
|
+
if (status === 'unloaded') return
|
|
279
|
+
status = 'unloaded'
|
|
280
|
+
message = why
|
|
281
|
+
log.warn('Hooks module not loaded', { ...attrs, 'namzu.hook_module.reason': why })
|
|
282
|
+
options.onUnload?.(why)
|
|
283
|
+
}
|
|
284
|
+
const unloaded = (why: string): HookModuleHandle => {
|
|
285
|
+
unload(why)
|
|
286
|
+
return { scan, status, message: why, hooks: [], dispose: async () => undefined }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (scan.refusals.length > 0 || scan.program === undefined) {
|
|
290
|
+
return unloaded(`hooks module ${label} not loaded: ${refusalLine(scan)}`)
|
|
291
|
+
}
|
|
292
|
+
const program = scan.program
|
|
293
|
+
const runnable = new Set<ShellHookEvent>()
|
|
294
|
+
for (const hook of scan.hooks) for (const event of hook.runs) runnable.add(event)
|
|
295
|
+
if (runnable.size === 0) {
|
|
296
|
+
return unloaded(
|
|
297
|
+
scan.hooks.length === 0
|
|
298
|
+
? `hooks module ${label} registers no hook, so it is not loaded.`
|
|
299
|
+
: `hooks module ${label} registers hooks that Namzu has no event for, so it is not loaded.`,
|
|
300
|
+
)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const bridge: CapabilityBridge = createCapabilityBridge({
|
|
304
|
+
root: plugin.root,
|
|
305
|
+
...(plugin.dataDir !== undefined ? { dataDir: plugin.dataDir } : {}),
|
|
306
|
+
projectDir: options.projectDir,
|
|
307
|
+
envNames: scan.envNames,
|
|
308
|
+
...(options.environment !== undefined ? { environment: options.environment } : {}),
|
|
309
|
+
...(options.fetch !== undefined ? { fetch: options.fetch } : {}),
|
|
310
|
+
log,
|
|
311
|
+
pluginName: plugin.name,
|
|
312
|
+
})
|
|
313
|
+
|
|
314
|
+
// --- the worker --------------------------------------------------------
|
|
315
|
+
let transport: HookModuleTransport | undefined
|
|
316
|
+
let ready: Promise<void> | undefined
|
|
317
|
+
/** For each registration, in order: the Namzu events it runs on. */
|
|
318
|
+
let registrationEvents: ReadonlySet<ShellHookEvent>[] = []
|
|
319
|
+
const pending = new Map<number, Pending>()
|
|
320
|
+
let nextId = 1
|
|
321
|
+
let outstandingCalls = 0
|
|
322
|
+
let loaded:
|
|
323
|
+
| ((registrations: { pattern: string; hasMatcher: boolean }[] | string) => void)
|
|
324
|
+
| undefined
|
|
325
|
+
|
|
326
|
+
const settle = (id: number, outcome: DispatchOutcome): void => {
|
|
327
|
+
const entry = pending.get(id)
|
|
328
|
+
if (entry === undefined) return
|
|
329
|
+
pending.delete(id)
|
|
330
|
+
clock.clearTimeout(entry.timer)
|
|
331
|
+
clock.clearTimeout(entry.ceiling)
|
|
332
|
+
entry.resolve(outcome)
|
|
333
|
+
// Nothing is waiting on a program the module started any more.
|
|
334
|
+
if (pending.size === 0) bridge.endProcesses()
|
|
335
|
+
}
|
|
336
|
+
/** A cancelled dispatch whose worker has not answered yet: it is ended if it stays silent. */
|
|
337
|
+
const abandoned = new Map<number, unknown>()
|
|
338
|
+
const forgetAbandoned = (id: number): void => {
|
|
339
|
+
const timer = abandoned.get(id)
|
|
340
|
+
if (timer === undefined) return
|
|
341
|
+
abandoned.delete(id)
|
|
342
|
+
clock.clearTimeout(timer)
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const armTimer = (id: number): void => {
|
|
346
|
+
const entry = pending.get(id)
|
|
347
|
+
if (entry === undefined) return
|
|
348
|
+
entry.startedAt = clock.now()
|
|
349
|
+
entry.paused = false
|
|
350
|
+
entry.timer = clock.setTimeout(() => onTimer(id), entry.remaining)
|
|
351
|
+
}
|
|
352
|
+
const onTimer = (id: number): void => {
|
|
353
|
+
const entry = pending.get(id)
|
|
354
|
+
if (entry === undefined) return
|
|
355
|
+
if (entry.phase === 'budget') {
|
|
356
|
+
// The hook overran: tell it, and give its `.catch` the grace to answer.
|
|
357
|
+
entry.phase = 'grace'
|
|
358
|
+
entry.remaining = catchMs
|
|
359
|
+
transport?.post({ t: 'overrun', id })
|
|
360
|
+
armTimer(id)
|
|
361
|
+
return
|
|
362
|
+
}
|
|
363
|
+
transport?.post({ t: 'grace-over', id })
|
|
364
|
+
settle(id, { kind: 'failed', message: `exceeded ${budgetMs}ms budget` })
|
|
365
|
+
// A worker that did not answer in the grace may be stuck in a loop: end it, and load afresh next time.
|
|
366
|
+
void endWorker('the hooks worker was ended after a hook overran')
|
|
367
|
+
}
|
|
368
|
+
const pauseAll = (): void => {
|
|
369
|
+
for (const entry of pending.values()) {
|
|
370
|
+
if (entry.paused) continue
|
|
371
|
+
entry.remaining = Math.max(0, entry.remaining - (clock.now() - entry.startedAt))
|
|
372
|
+
clock.clearTimeout(entry.timer)
|
|
373
|
+
entry.paused = true
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
const resumeAll = (): void => {
|
|
377
|
+
for (const id of pending.keys()) {
|
|
378
|
+
const entry = pending.get(id)
|
|
379
|
+
if (entry?.paused) armTimer(id)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const endWorker = async (reason: string): Promise<void> => {
|
|
384
|
+
const current = transport
|
|
385
|
+
transport = undefined
|
|
386
|
+
ready = undefined
|
|
387
|
+
if (current === undefined) return
|
|
388
|
+
for (const id of [...pending.keys()]) settle(id, { kind: 'failed', message: reason })
|
|
389
|
+
for (const id of [...abandoned.keys()]) forgetAbandoned(id)
|
|
390
|
+
outstandingCalls = 0
|
|
391
|
+
bridge.endProcesses()
|
|
392
|
+
try {
|
|
393
|
+
await current.terminate()
|
|
394
|
+
} catch {
|
|
395
|
+
// A worker that is already gone cannot be ended again.
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const onMessage =
|
|
400
|
+
(worker: HookModuleTransport) =>
|
|
401
|
+
(incoming: any): void => {
|
|
402
|
+
if (transport !== worker) return
|
|
403
|
+
switch (incoming?.t) {
|
|
404
|
+
case 'loaded':
|
|
405
|
+
loaded?.(incoming.error !== undefined ? String(incoming.error) : incoming.registrations)
|
|
406
|
+
return
|
|
407
|
+
case 'result':
|
|
408
|
+
forgetAbandoned(incoming.id)
|
|
409
|
+
settle(
|
|
410
|
+
incoming.id,
|
|
411
|
+
incoming.ok
|
|
412
|
+
? { kind: 'value', value: incoming.value, failures: incoming.failures ?? [] }
|
|
413
|
+
: { kind: 'failed', message: String(incoming.message) },
|
|
414
|
+
)
|
|
415
|
+
return
|
|
416
|
+
case 'log':
|
|
417
|
+
log.debug('Plugin hooks module console output', {
|
|
418
|
+
...attrs,
|
|
419
|
+
'namzu.hook_module.console_level': String(incoming.level),
|
|
420
|
+
'namzu.hook_module.text': String(incoming.text),
|
|
421
|
+
})
|
|
422
|
+
return
|
|
423
|
+
case 'call': {
|
|
424
|
+
outstandingCalls += 1
|
|
425
|
+
if (outstandingCalls === 1) pauseAll()
|
|
426
|
+
const reply = (body: Record<string, unknown>): void => {
|
|
427
|
+
outstandingCalls = Math.max(0, outstandingCalls - 1)
|
|
428
|
+
if (outstandingCalls === 0) resumeAll()
|
|
429
|
+
if (transport === worker) worker.post({ t: 'call-result', cid: incoming.cid, ...body })
|
|
430
|
+
}
|
|
431
|
+
bridge
|
|
432
|
+
.call(
|
|
433
|
+
String(incoming.noun),
|
|
434
|
+
String(incoming.method),
|
|
435
|
+
Array.isArray(incoming.args) ? incoming.args : [],
|
|
436
|
+
)
|
|
437
|
+
.then(
|
|
438
|
+
(value) => reply({ ok: true, value }),
|
|
439
|
+
(error) => reply({ ok: false, message: toErrorMessage(error) }),
|
|
440
|
+
)
|
|
441
|
+
return
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const start = (): Promise<void> => {
|
|
447
|
+
if (ready !== undefined) return ready
|
|
448
|
+
const worker = (options.transport ?? workerTransport)()
|
|
449
|
+
transport = worker
|
|
450
|
+
worker.onMessage(onMessage(worker))
|
|
451
|
+
worker.onExit((reason) => {
|
|
452
|
+
if (transport !== worker) return
|
|
453
|
+
transport = undefined
|
|
454
|
+
ready = undefined
|
|
455
|
+
for (const id of [...pending.keys()]) {
|
|
456
|
+
settle(id, { kind: 'failed', message: `the hooks worker died (${reason})` })
|
|
457
|
+
}
|
|
458
|
+
loaded?.(`the hooks worker died (${reason})`)
|
|
459
|
+
})
|
|
460
|
+
const attempt = new Promise<void>((resolve, reject) => {
|
|
461
|
+
const timer = clock.setTimeout(() => {
|
|
462
|
+
loaded = undefined
|
|
463
|
+
reject(new Error(`it did not finish loading within ${budgetMs}ms`))
|
|
464
|
+
}, budgetMs)
|
|
465
|
+
loaded = (registrations) => {
|
|
466
|
+
clock.clearTimeout(timer)
|
|
467
|
+
loaded = undefined
|
|
468
|
+
if (typeof registrations === 'string') {
|
|
469
|
+
reject(new Error(registrations))
|
|
470
|
+
return
|
|
471
|
+
}
|
|
472
|
+
// What the module registered is judged here, where the patterns are known.
|
|
473
|
+
const events: ReadonlySet<ShellHookEvent>[] = []
|
|
474
|
+
const seen = new Map<string, number>()
|
|
475
|
+
for (const [index, registration] of registrations.entries()) {
|
|
476
|
+
const resolved = resolvePattern(registration.pattern)
|
|
477
|
+
if (!resolved.ok) {
|
|
478
|
+
reject(new Error(resolved.message))
|
|
479
|
+
return
|
|
480
|
+
}
|
|
481
|
+
if (!registration.hasMatcher) {
|
|
482
|
+
const earlier = seen.get(registration.pattern)
|
|
483
|
+
if (earlier !== undefined) {
|
|
484
|
+
reject(
|
|
485
|
+
new Error(
|
|
486
|
+
`on("${registration.pattern}") is registered twice without a matcher; the first is registration ${earlier + 1}`,
|
|
487
|
+
),
|
|
488
|
+
)
|
|
489
|
+
return
|
|
490
|
+
}
|
|
491
|
+
seen.set(registration.pattern, index)
|
|
492
|
+
}
|
|
493
|
+
events.push(new Set(resolved.runs))
|
|
494
|
+
}
|
|
495
|
+
if (registrations.length === 0) {
|
|
496
|
+
reject(new Error('it registers nothing'))
|
|
497
|
+
return
|
|
498
|
+
}
|
|
499
|
+
registrationEvents = events
|
|
500
|
+
resolve()
|
|
501
|
+
}
|
|
502
|
+
worker.post({
|
|
503
|
+
t: 'load',
|
|
504
|
+
program,
|
|
505
|
+
name: plugin.name,
|
|
506
|
+
root: plugin.root,
|
|
507
|
+
options: options.options ?? {},
|
|
508
|
+
nouns: Object.fromEntries(
|
|
509
|
+
Object.entries(SUPPORTED_CAPABILITY_CALLS).map(([noun, methods]) => [noun, [...methods]]),
|
|
510
|
+
),
|
|
511
|
+
})
|
|
512
|
+
})
|
|
513
|
+
ready = attempt.catch(async (error) => {
|
|
514
|
+
await endWorker('the hooks worker was ended')
|
|
515
|
+
throw error
|
|
516
|
+
})
|
|
517
|
+
return ready
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const dispatch = async (
|
|
521
|
+
name: string,
|
|
522
|
+
e: unknown,
|
|
523
|
+
registrations: readonly number[],
|
|
524
|
+
signal: AbortSignal | undefined,
|
|
525
|
+
): Promise<DispatchOutcome> => {
|
|
526
|
+
try {
|
|
527
|
+
await start()
|
|
528
|
+
} catch (error) {
|
|
529
|
+
const why = `hooks module ${label} failed to load: ${toErrorMessage(error)}`
|
|
530
|
+
unload(why)
|
|
531
|
+
return { kind: 'failed', message: why }
|
|
532
|
+
}
|
|
533
|
+
const worker = transport
|
|
534
|
+
if (worker === undefined) return { kind: 'failed', message: 'the hooks worker is not running' }
|
|
535
|
+
const id = nextId++
|
|
536
|
+
return new Promise<DispatchOutcome>((resolve) => {
|
|
537
|
+
const entry: Pending = {
|
|
538
|
+
resolve,
|
|
539
|
+
remaining: budgetMs,
|
|
540
|
+
startedAt: clock.now(),
|
|
541
|
+
timer: undefined,
|
|
542
|
+
ceiling: clock.setTimeout(() => {
|
|
543
|
+
if (!pending.has(id)) return
|
|
544
|
+
settle(id, {
|
|
545
|
+
kind: 'failed',
|
|
546
|
+
message: `exceeded ${budgetMs * HOOK_MODULE_CEILING_FACTOR}ms in all, the time spent in calls included`,
|
|
547
|
+
})
|
|
548
|
+
void endWorker('the hooks worker was ended after a hook held its dispatch open')
|
|
549
|
+
}, budgetMs * HOOK_MODULE_CEILING_FACTOR),
|
|
550
|
+
phase: 'budget',
|
|
551
|
+
paused: outstandingCalls > 0,
|
|
552
|
+
}
|
|
553
|
+
pending.set(id, entry)
|
|
554
|
+
if (!entry.paused) armTimer(id)
|
|
555
|
+
signal?.addEventListener(
|
|
556
|
+
'abort',
|
|
557
|
+
() => {
|
|
558
|
+
if (!pending.has(id)) return
|
|
559
|
+
transport?.post({ t: 'abort', id })
|
|
560
|
+
settle(id, { kind: 'failed', message: 'the turn was cancelled' })
|
|
561
|
+
// A hook stuck in a loop never answers: if the worker is silent for the grace, it is ended.
|
|
562
|
+
abandoned.set(
|
|
563
|
+
id,
|
|
564
|
+
clock.setTimeout(() => {
|
|
565
|
+
abandoned.delete(id)
|
|
566
|
+
void endWorker('the hooks worker was ended after a cancelled hook did not stop')
|
|
567
|
+
}, catchMs),
|
|
568
|
+
)
|
|
569
|
+
},
|
|
570
|
+
{ once: true },
|
|
571
|
+
)
|
|
572
|
+
worker.post({ t: 'dispatch', id, name, e, regs: registrations })
|
|
573
|
+
})
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// --- the hooks ---------------------------------------------------------
|
|
577
|
+
const commandLabel = `module ${label}`
|
|
578
|
+
const failurePolicy = (event: ShellHookEvent, why: string): PluginHookResult => {
|
|
579
|
+
log.warn('Hooks module hook failed', {
|
|
580
|
+
...attrs,
|
|
581
|
+
'namzu.hook.event': event,
|
|
582
|
+
'namzu.hook_module.reason': why,
|
|
583
|
+
})
|
|
584
|
+
const line = `${commandLabel}: ${why}`
|
|
585
|
+
// A guard that failed does not wave the call through: the call is refused and the model is told why.
|
|
586
|
+
if (event === 'pre_tool_use') return { action: 'error', message: line }
|
|
587
|
+
if (event === 'pre_skill_shell_command') return { action: 'skip', reason: line }
|
|
588
|
+
return { action: 'continue', notice: line }
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const hooks: PluginHookDefinition[] = []
|
|
592
|
+
for (const event of MODULE_HOOK_EVENTS) {
|
|
593
|
+
if (!runnable.has(event)) continue
|
|
594
|
+
const eventName = classicEventName(event) as string
|
|
595
|
+
hooks.push({
|
|
596
|
+
event,
|
|
597
|
+
handler: async (context: PluginHookContext): Promise<PluginHookResult> => {
|
|
598
|
+
if (status === 'unloaded') return { action: 'continue' }
|
|
599
|
+
const input = shellHookInputFor(event, context, options.shell, { toolNames: 'written' })
|
|
600
|
+
const payload = JSON.parse(shellHookPayload(input)) as Record<string, unknown>
|
|
601
|
+
const e = event === 'pre_tool_use' ? toolEnvelope(payload) : payload
|
|
602
|
+
// The module may not have been started yet; its registrations tell which hooks hear this.
|
|
603
|
+
try {
|
|
604
|
+
await start()
|
|
605
|
+
} catch (error) {
|
|
606
|
+
const why = `hooks module ${label} failed to load: ${toErrorMessage(error)}`
|
|
607
|
+
unload(why)
|
|
608
|
+
return { action: 'continue', notice: why }
|
|
609
|
+
}
|
|
610
|
+
const registrations: number[] = []
|
|
611
|
+
for (const [index, events] of registrationEvents.entries()) {
|
|
612
|
+
if (events.has(event)) registrations.push(index)
|
|
613
|
+
}
|
|
614
|
+
if (registrations.length === 0) return { action: 'continue' }
|
|
615
|
+
const outcome = await dispatch(eventName, e, registrations, context.signal)
|
|
616
|
+
if (outcome.kind === 'failed') return failurePolicy(event, outcome.message)
|
|
617
|
+
if (outcome.failures.length > 0) return failurePolicy(event, outcome.failures.join('; '))
|
|
618
|
+
const json = answerAsJson(event, outcome.value)
|
|
619
|
+
if ('problem' in json) return failurePolicy(event, json.problem)
|
|
620
|
+
const call: ShellHookCall = {
|
|
621
|
+
...(context.toolName !== undefined ? { toolName: context.toolName } : {}),
|
|
622
|
+
...(context.toolInput !== undefined ? { toolInput: context.toolInput } : {}),
|
|
623
|
+
}
|
|
624
|
+
return shellHookVerdict(
|
|
625
|
+
event,
|
|
626
|
+
{ type: 'command', command: commandLabel },
|
|
627
|
+
{ exitCode: 0, timedOut: false, stdout: JSON.stringify(json.json), stderr: '' },
|
|
628
|
+
log,
|
|
629
|
+
call,
|
|
630
|
+
)
|
|
631
|
+
},
|
|
632
|
+
} as PluginHookDefinition)
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
return {
|
|
636
|
+
scan,
|
|
637
|
+
get status() {
|
|
638
|
+
return status
|
|
639
|
+
},
|
|
640
|
+
get message() {
|
|
641
|
+
return message
|
|
642
|
+
},
|
|
643
|
+
hooks,
|
|
644
|
+
dispose: async () => {
|
|
645
|
+
status = 'unloaded'
|
|
646
|
+
await endWorker('the hooks worker was stopped')
|
|
647
|
+
},
|
|
648
|
+
}
|
|
649
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export {
|
|
2
|
+
CLASSIC_HOOK_EVENTS,
|
|
3
|
+
MODULE_HOOK_EVENTS,
|
|
4
|
+
classicEventName,
|
|
5
|
+
classicWrittenName,
|
|
6
|
+
resolvePattern,
|
|
7
|
+
} from './events.js'
|
|
8
|
+
export type { ResolvedPattern } from './events.js'
|
|
9
|
+
export {
|
|
10
|
+
MAX_MODULE_FILE_BYTES,
|
|
11
|
+
MAX_MODULE_FILES,
|
|
12
|
+
MAX_MODULE_TOTAL_BYTES,
|
|
13
|
+
SUPPORTED_CAPABILITY_CALLS,
|
|
14
|
+
locateHookModule,
|
|
15
|
+
readPluginFile,
|
|
16
|
+
scanHookModule,
|
|
17
|
+
} from './scan.js'
|
|
18
|
+
export type {
|
|
19
|
+
HookModuleLocation,
|
|
20
|
+
HookModuleProgram,
|
|
21
|
+
HookModuleScan,
|
|
22
|
+
PluginFileRead,
|
|
23
|
+
ScanRefusal,
|
|
24
|
+
ScannedCall,
|
|
25
|
+
ScannedHook,
|
|
26
|
+
} from './scan.js'
|
|
27
|
+
export {
|
|
28
|
+
HOOK_MODULE_BUDGET_MS,
|
|
29
|
+
HOOK_MODULE_CATCH_MS,
|
|
30
|
+
startHookModule,
|
|
31
|
+
workerTransport,
|
|
32
|
+
} from './host.js'
|
|
33
|
+
export type {
|
|
34
|
+
HookModuleClock,
|
|
35
|
+
HookModuleHandle,
|
|
36
|
+
HookModuleTransport,
|
|
37
|
+
HookModuleTransportFactory,
|
|
38
|
+
StartHookModuleOptions,
|
|
39
|
+
} from './host.js'
|
|
40
|
+
export {
|
|
41
|
+
createCapabilityBridge,
|
|
42
|
+
MAX_CAPABILITY_BYTES,
|
|
43
|
+
MAX_STORE_BYTES,
|
|
44
|
+
STORE_FILE,
|
|
45
|
+
} from './capabilities.js'
|
|
46
|
+
export type { CapabilityBridge, CapabilityBridgeOptions } from './capabilities.js'
|
|
47
|
+
export {
|
|
48
|
+
hookModuleConsentEntry,
|
|
49
|
+
hookModuleConsentLines,
|
|
50
|
+
summarizeHookModule,
|
|
51
|
+
} from './consent.js'
|
|
52
|
+
export type { HookModuleConsentEntry, HookModuleSummary } from './consent.js'
|