universal-plugin-hub 1.5.5 → 1.6.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/README.md +2 -0
- package/README.zh.md +2 -0
- package/assets/icon.svg +20 -20
- package/client/client.js +1502 -616
- package/package.json +5 -10
- package/scripts/postinstall.js +3 -3
- package/src/hooks.js +1644 -0
- package/src/index.js +93 -9
- package/src/install.js +520 -146
- package/src/local.js +208 -24
- package/src/parser.js +119 -25
- package/src/routes.js +197 -50
- package/src/store.js +31 -3
- package/assets/Add-plugin-source.png +0 -0
- package/assets/MCP.png +0 -0
- package/assets/Plugin-management.png +0 -0
- package/assets/Plugins-official.png +0 -0
- package/assets/Skills.png +0 -0
- package/screenshots.json +0 -7
package/src/hooks.js
ADDED
|
@@ -0,0 +1,1644 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH-native Cordis hook runtime for Claude Code & Codex plugin hooks.
|
|
3
|
+
*
|
|
4
|
+
* Replaces the external `@deepseek-ai/dsh-hooks-claude-code` `cordis.patch.yml` bridge:
|
|
5
|
+
* executes hooks directly inside `universal-plugin-hub` on DSH's canonical Cordis seams
|
|
6
|
+
* with hot-reload cache invalidation, unconfined `ctx.shell` / Git Bash / exec-form `args`,
|
|
7
|
+
* and full Claude Code v2.1+ event/field fidelity.
|
|
8
|
+
*/
|
|
9
|
+
import { spawn as nodeSpawn } from 'node:child_process'
|
|
10
|
+
import { randomUUID } from 'node:crypto'
|
|
11
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { createRequire } from 'node:module'
|
|
13
|
+
import { tmpdir } from 'node:os'
|
|
14
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
15
|
+
import { compiledHooksPath, dshHome, installedDir, pluginDataDir, readState, resolveOptionalService, statePath, stateRevision } from './store.js'
|
|
16
|
+
import { canonicalizeHookEventName, compileResolvedHooks, readPluginManifest } from './parser.js'
|
|
17
|
+
import { findDshMainNodeModules } from './install.js'
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_HOOK_TIMEOUT_MS = 600_000
|
|
20
|
+
export const USER_PROMPT_SUBMIT_TIMEOUT_MS = 30_000
|
|
21
|
+
export const SESSION_END_TIMEOUT_MS = 10_000
|
|
22
|
+
export const DEFAULT_STDERR_SUMMARY_MAX_CHARS = 500
|
|
23
|
+
export const DEFAULT_MAX_STOP_CONTINUATIONS = 10
|
|
24
|
+
|
|
25
|
+
const CONTEXT_SOURCE = Object.freeze({ kind: 'hooks-claude-code' })
|
|
26
|
+
const CLAUDE_LITERAL_MATCHER_RE = /^[A-Za-z0-9_|]+$/
|
|
27
|
+
const SENSITIVE_ENV_KEY_RE = /KEY|PASSWORD|SECRET|TOKEN/i
|
|
28
|
+
const ENV_PLACEHOLDER_RE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)\b/g
|
|
29
|
+
const PROJECT_DIR_TOKEN_RE = /(?<![A-Za-z0-9_.])(?:\$\{CLAUDE_PROJECT_DIR\}|\$CLAUDE_PROJECT_DIR\b)/g
|
|
30
|
+
const PLAIN_STDOUT_CONTEXT_EVENTS = new Set(['SessionStart', 'UserPromptSubmit', 'SubagentStart', 'Setup'])
|
|
31
|
+
const MISSING_SCRIPT_GUARDED_EVENTS = new Set(['Stop', 'SubagentStop', 'UserPromptSubmit', 'TaskCompleted', 'TeammateIdle'])
|
|
32
|
+
const BLOCKED_SESSION_ENV_KEYS = new Set([
|
|
33
|
+
'PATH', 'PATHEXT', 'COMSPEC',
|
|
34
|
+
'NODE_OPTIONS', 'NODE_PATH',
|
|
35
|
+
'LD_PRELOAD', 'LD_LIBRARY_PATH',
|
|
36
|
+
'DYLD_INSERT_LIBRARIES', 'DYLD_LIBRARY_PATH',
|
|
37
|
+
'ELECTRON_RUN_AS_NODE',
|
|
38
|
+
'BASH_ENV', 'ENV', 'PROMPT_COMMAND', 'IFS',
|
|
39
|
+
'CLAUDE_PLUGIN_ROOT', 'CLAUDE_PLUGIN_DATA', 'CLAUDE_PROJECT_DIR', 'CLAUDE_SESSION_ID', 'CLAUDE_ENV_FILE',
|
|
40
|
+
'PLUGIN_ROOT', 'PLUGIN_DATA',
|
|
41
|
+
])
|
|
42
|
+
|
|
43
|
+
const DSH_TO_CLAUDE_TOOL_ALIASES = new Map([
|
|
44
|
+
['bash', ['bash', 'Bash']],
|
|
45
|
+
['pwsh', ['pwsh', 'Bash']],
|
|
46
|
+
['bash_persistent', ['bash_persistent', 'Bash']],
|
|
47
|
+
['pwsh_persistent', ['pwsh_persistent', 'Bash']],
|
|
48
|
+
['edit', ['edit', 'Edit']],
|
|
49
|
+
['apply_patch', ['apply_patch', 'Edit', 'Write']],
|
|
50
|
+
['read', ['read', 'Read']],
|
|
51
|
+
['write', ['write', 'Write']],
|
|
52
|
+
['grep', ['grep', 'Grep']],
|
|
53
|
+
['glob', ['glob', 'Glob']],
|
|
54
|
+
['web_fetch', ['web_fetch', 'WebFetch']],
|
|
55
|
+
['web_search', ['web_search', 'WebSearch']],
|
|
56
|
+
['skill', ['skill', 'Skill']],
|
|
57
|
+
['todo_write', ['todo_write', 'TodoWrite']],
|
|
58
|
+
['ask_user_question', ['ask_user_question', 'AskUserQuestion']],
|
|
59
|
+
])
|
|
60
|
+
|
|
61
|
+
let hooksCacheEpoch = 0
|
|
62
|
+
let cachedHooksRegistry = null // { home, stamp, plugins }
|
|
63
|
+
let cachedCreateUserMessage = null
|
|
64
|
+
let cachedGitBashKey = null
|
|
65
|
+
let cachedGitBashPath = null
|
|
66
|
+
|
|
67
|
+
export function invalidateHooksCache() {
|
|
68
|
+
hooksCacheEpoch += 1
|
|
69
|
+
cachedHooksRegistry = null
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Return canonical DSH + Claude Code tool-name aliases for matcher / `if` checks. */
|
|
73
|
+
export function claudeToolAliases(toolName) {
|
|
74
|
+
if (typeof toolName !== 'string' || !toolName) return []
|
|
75
|
+
const mapped = DSH_TO_CLAUDE_TOOL_ALIASES.get(toolName)
|
|
76
|
+
return mapped ? [...mapped] : [toolName]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isMatchAllMatcher(matcher) {
|
|
80
|
+
return matcher === undefined || matcher === '' || matcher === '*'
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function compileMatcherRegex(pattern) {
|
|
84
|
+
try {
|
|
85
|
+
return new RegExp(pattern)
|
|
86
|
+
} catch {
|
|
87
|
+
return undefined
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function matcherDiagnostic(matcher, mode = 'claude-code') {
|
|
92
|
+
if (isMatchAllMatcher(matcher)) return undefined
|
|
93
|
+
if (typeof matcher !== 'string') return `invalid matcher ${JSON.stringify(matcher)}`
|
|
94
|
+
if (mode === 'claude-code' && CLAUDE_LITERAL_MATCHER_RE.test(matcher)) return undefined
|
|
95
|
+
return compileMatcherRegex(matcher) ? undefined : `invalid ${mode} regex matcher ${JSON.stringify(matcher)}`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Test whether `matcher` matches any candidate string in `subjects` under Claude/Codex rules. */
|
|
99
|
+
export function matchesHookMatcher(matcher, subjects, mode = 'claude-code') {
|
|
100
|
+
if (isMatchAllMatcher(matcher)) return true
|
|
101
|
+
if (typeof matcher !== 'string') return false
|
|
102
|
+
const list = Array.isArray(subjects)
|
|
103
|
+
? subjects.filter((s) => s !== undefined && s !== null).map(String)
|
|
104
|
+
: (subjects === undefined || subjects === null ? [] : [String(subjects)])
|
|
105
|
+
if (list.length === 0) return false
|
|
106
|
+
if (mode === 'claude-code' && CLAUDE_LITERAL_MATCHER_RE.test(matcher)) {
|
|
107
|
+
const alts = matcher.split('|')
|
|
108
|
+
return list.some((s) => alts.includes(s))
|
|
109
|
+
}
|
|
110
|
+
const re = compileMatcherRegex(matcher)
|
|
111
|
+
return re ? list.some((s) => re.test(s)) : false
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function wildcardToRegex(pattern) {
|
|
115
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
|
|
116
|
+
return new RegExp(`^${escaped}$`, 's')
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function extractToolInputCandidates(toolInput) {
|
|
120
|
+
const out = []
|
|
121
|
+
if (typeof toolInput === 'string') {
|
|
122
|
+
out.push(toolInput, toolInput.replace(/\\/g, '/'))
|
|
123
|
+
return out
|
|
124
|
+
}
|
|
125
|
+
if (!toolInput || typeof toolInput !== 'object') return out
|
|
126
|
+
for (const key of ['command', 'cmd', 'file_path', 'path', 'filePath', 'pattern', 'url', 'query', 'skill']) {
|
|
127
|
+
const val = toolInput[key]
|
|
128
|
+
if (typeof val === 'string' && val.length > 0) {
|
|
129
|
+
out.push(val)
|
|
130
|
+
const norm = val.replace(/\\/g, '/')
|
|
131
|
+
if (norm !== val) out.push(norm)
|
|
132
|
+
if (key === 'file_path' || key === 'path' || key === 'filePath') {
|
|
133
|
+
const base = basename(norm)
|
|
134
|
+
if (base) out.push(base)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return out
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Evaluate Claude Code hook permission-rule `if` filter (e.g. `Bash(git *)`, `Edit(*.ts)`). */
|
|
142
|
+
export function matchesHookIfCondition(condition, toolName, toolInput) {
|
|
143
|
+
if (typeof condition !== 'string' || !condition.trim()) return true
|
|
144
|
+
const trimmed = condition.trim()
|
|
145
|
+
const match = trimmed.match(/^([^(]+?)(?:\(([\s\S]*)\))?$/)
|
|
146
|
+
if (!match) return false
|
|
147
|
+
const toolPat = match[1].trim()
|
|
148
|
+
const argPat = match[2]
|
|
149
|
+
const toolRe = wildcardToRegex(toolPat)
|
|
150
|
+
const aliases = claudeToolAliases(toolName)
|
|
151
|
+
if (!aliases.some((alias) => toolRe.test(alias))) return false
|
|
152
|
+
if (argPat === undefined || argPat.trim() === '' || argPat.trim() === '*') return true
|
|
153
|
+
|
|
154
|
+
const normalizedArgPat = argPat.trim().replace(/:\*$/, ' *')
|
|
155
|
+
const argRe = wildcardToRegex(normalizedArgPat)
|
|
156
|
+
const colonPrefix = argPat.trim().endsWith(':*') ? argPat.trim().slice(0, -2) : null
|
|
157
|
+
const candidates = extractToolInputCandidates(toolInput)
|
|
158
|
+
return candidates.some((c) => {
|
|
159
|
+
if (argRe.test(c)) return true
|
|
160
|
+
if (colonPrefix !== null && (c === colonPrefix || c.startsWith(`${colonPrefix} `))) return true
|
|
161
|
+
return false
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function asPlainObject(value) {
|
|
166
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function topLevelDecisionOf(val) {
|
|
170
|
+
return val === 'approve' || val === 'block' ? val : undefined
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function permissionDecisionOf(val) {
|
|
174
|
+
return val === 'allow' || val === 'deny' || val === 'ask' ? val : undefined
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Decode hook process/HTTP outcome under Claude Code exit-code + JSON/stdout protocol. */
|
|
178
|
+
export function parseHookOutput(exitCode, stdout, stderr, opts = {}) {
|
|
179
|
+
const {
|
|
180
|
+
expectedEventName,
|
|
181
|
+
allowPlainStdout = PLAIN_STDOUT_CONTEXT_EVENTS.has(expectedEventName),
|
|
182
|
+
onFailure,
|
|
183
|
+
isMissingScriptGuarded = MISSING_SCRIPT_GUARDED_EVENTS.has(expectedEventName),
|
|
184
|
+
} = opts
|
|
185
|
+
|
|
186
|
+
const trimmedErr = String(stderr ?? '').trim()
|
|
187
|
+
const trimmedOut = String(stdout ?? '').replace(/^\uFEFF/, '').trim()
|
|
188
|
+
const output = { exitCode, stderr: trimmedErr, stdout: trimmedOut }
|
|
189
|
+
|
|
190
|
+
if (exitCode === 2 && isMissingScriptGuarded && !trimmedOut && /no such file|can't open/i.test(trimmedErr)) {
|
|
191
|
+
return output
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (exitCode === 2) {
|
|
195
|
+
output.decision = 'block'
|
|
196
|
+
if (trimmedErr.length > 0) output.reason = trimmedErr
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
let parsed
|
|
200
|
+
let jsonMalformed = false
|
|
201
|
+
if (trimmedOut.startsWith('{') && trimmedOut.endsWith('}')) {
|
|
202
|
+
try {
|
|
203
|
+
parsed = asPlainObject(JSON.parse(trimmedOut))
|
|
204
|
+
if (!parsed) jsonMalformed = true
|
|
205
|
+
} catch {
|
|
206
|
+
jsonMalformed = true
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (parsed && (exitCode === 0 || exitCode === 2 || typeof exitCode === 'number')) {
|
|
211
|
+
if (typeof parsed.continue === 'boolean') output.continue = parsed.continue
|
|
212
|
+
if (typeof parsed.stopReason === 'string') output.stopReason = parsed.stopReason
|
|
213
|
+
if (typeof parsed.systemMessage === 'string') output.systemMessage = parsed.systemMessage
|
|
214
|
+
if (typeof parsed.reason === 'string') output.reason = parsed.reason
|
|
215
|
+
|
|
216
|
+
const topDecision = topLevelDecisionOf(typeof parsed.decision === 'string' ? parsed.decision : undefined)
|
|
217
|
+
if (topDecision !== undefined) {
|
|
218
|
+
if (!(exitCode === 2 && topDecision === 'approve')) {
|
|
219
|
+
output.decision = topDecision
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// On Stop/SubagentStop, explicit `continue: false` takes precedence over exit code 2.
|
|
224
|
+
if (output.continue === false && (expectedEventName === 'Stop' || expectedEventName === 'SubagentStop') && exitCode === 2 && !topDecision) {
|
|
225
|
+
delete output.decision
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const hso = asPlainObject(parsed.hookSpecificOutput)
|
|
229
|
+
if (hso) {
|
|
230
|
+
const eventName = typeof hso.hookEventName === 'string' ? hso.hookEventName : undefined
|
|
231
|
+
if (eventName !== undefined) output.hookEventName = eventName
|
|
232
|
+
if (expectedEventName === undefined || eventName === expectedEventName) {
|
|
233
|
+
const permDecision = permissionDecisionOf(typeof hso.permissionDecision === 'string' ? hso.permissionDecision : undefined)
|
|
234
|
+
if (permDecision !== undefined) {
|
|
235
|
+
if (!(exitCode === 2 && permDecision === 'allow')) {
|
|
236
|
+
output.decision = permDecision
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (typeof hso.permissionDecisionReason === 'string') {
|
|
240
|
+
output.reason = hso.permissionDecisionReason
|
|
241
|
+
}
|
|
242
|
+
const reqDecision = asPlainObject(hso.decision)
|
|
243
|
+
if (reqDecision && (reqDecision.behavior === 'allow' || reqDecision.behavior === 'deny')) {
|
|
244
|
+
output.decision = reqDecision.behavior
|
|
245
|
+
if (typeof reqDecision.message === 'string') output.reason = reqDecision.message
|
|
246
|
+
}
|
|
247
|
+
if (typeof hso.additionalContext === 'string' && hso.additionalContext.length > 0) {
|
|
248
|
+
output.additionalContext = hso.additionalContext
|
|
249
|
+
}
|
|
250
|
+
const updatedInput = asPlainObject(hso.updatedInput)
|
|
251
|
+
if (updatedInput !== undefined) output.updatedInput = updatedInput
|
|
252
|
+
if (hso.updatedMCPToolOutput !== undefined) {
|
|
253
|
+
output.updatedToolOutput = hso.updatedMCPToolOutput
|
|
254
|
+
} else if (hso.updatedToolOutput !== undefined) {
|
|
255
|
+
output.updatedToolOutput = hso.updatedToolOutput
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
} else if (exitCode === 0 && allowPlainStdout && trimmedOut.length > 0 && !jsonMalformed && !(trimmedOut.startsWith('{') && trimmedOut.endsWith('}'))) {
|
|
260
|
+
output.additionalContext = trimmedOut
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (onFailure === 'block' && exitCode !== 0 && exitCode !== 2) {
|
|
264
|
+
output.decision = 'deny'
|
|
265
|
+
output.reason = output.reason || trimmedErr || `hook execution failed (${exitCode ?? 'error'})`
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return output
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function decisionRank(decision) {
|
|
272
|
+
switch (decision) {
|
|
273
|
+
case 'deny':
|
|
274
|
+
case 'block':
|
|
275
|
+
return 3
|
|
276
|
+
case 'ask':
|
|
277
|
+
return 2
|
|
278
|
+
case 'approve':
|
|
279
|
+
case 'allow':
|
|
280
|
+
return 1
|
|
281
|
+
default:
|
|
282
|
+
return 0
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function decisionForRank(rank) {
|
|
287
|
+
switch (rank) {
|
|
288
|
+
case 3: return 'deny'
|
|
289
|
+
case 2: return 'ask'
|
|
290
|
+
case 1: return 'allow'
|
|
291
|
+
default: return 'none'
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Merge multiple matched hook outputs using most-restrictive precedence (`deny > ask > allow`). */
|
|
296
|
+
export function mergeHookOutputs(outputs) {
|
|
297
|
+
let maxRank = 0
|
|
298
|
+
const reasonsByRank = new Map()
|
|
299
|
+
let stop = false
|
|
300
|
+
let stopReason
|
|
301
|
+
const additionalContext = []
|
|
302
|
+
const systemMessages = []
|
|
303
|
+
let updatedToolOutput
|
|
304
|
+
let updatedInput
|
|
305
|
+
|
|
306
|
+
for (const out of outputs || []) {
|
|
307
|
+
if (!out) continue
|
|
308
|
+
const rank = decisionRank(out.decision)
|
|
309
|
+
if (rank > maxRank) maxRank = rank
|
|
310
|
+
if ((rank === 3 || rank === 2) && typeof out.reason === 'string' && out.reason.length > 0) {
|
|
311
|
+
const list = reasonsByRank.get(rank) || []
|
|
312
|
+
list.push(out.reason)
|
|
313
|
+
reasonsByRank.set(rank, list)
|
|
314
|
+
}
|
|
315
|
+
if (out.continue === false && !stop) {
|
|
316
|
+
stop = true
|
|
317
|
+
if (out.stopReason !== undefined) stopReason = out.stopReason
|
|
318
|
+
}
|
|
319
|
+
if (typeof out.additionalContext === 'string' && out.additionalContext.length > 0) {
|
|
320
|
+
additionalContext.push(out.additionalContext)
|
|
321
|
+
}
|
|
322
|
+
if (typeof out.systemMessage === 'string' && out.systemMessage.length > 0) {
|
|
323
|
+
systemMessages.push(out.systemMessage)
|
|
324
|
+
}
|
|
325
|
+
if (out.updatedToolOutput !== undefined) updatedToolOutput = out.updatedToolOutput
|
|
326
|
+
if (out.updatedInput !== undefined) updatedInput = out.updatedInput
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const winningReasons = reasonsByRank.get(maxRank) || []
|
|
330
|
+
return {
|
|
331
|
+
decision: decisionForRank(maxRank),
|
|
332
|
+
...(winningReasons.length > 0 ? { reason: winningReasons.join('\n\n') } : {}),
|
|
333
|
+
stop,
|
|
334
|
+
...(stopReason !== undefined ? { stopReason } : {}),
|
|
335
|
+
additionalContext,
|
|
336
|
+
systemMessages,
|
|
337
|
+
...(updatedToolOutput !== undefined ? { updatedToolOutput } : {}),
|
|
338
|
+
...(updatedInput !== undefined ? { updatedInput } : {}),
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Map DSH/LLM error object or message to Claude Code `StopFailure.error_type`. */
|
|
343
|
+
export function mapStopFailureErrorType(error) {
|
|
344
|
+
const code = String(error?.code || '').toLowerCase()
|
|
345
|
+
const status = Number(error?.status ?? error?.statusCode)
|
|
346
|
+
const msg = String(error?.message || error || '').toLowerCase()
|
|
347
|
+
const combined = `${code} ${msg}`
|
|
348
|
+
|
|
349
|
+
if (status === 429 || /\brate_limit\b|rate[- ]limit|too many requests|throttle/.test(combined)) return 'rate_limit'
|
|
350
|
+
if (status === 401 || /authentication_failed|unauthorized|invalid[_ ]api[_ ]key|\bauth(?:entication)?\b/.test(combined)) return 'authentication_failed'
|
|
351
|
+
if (/oauth_org_not_allowed|org_not_allowed/.test(combined)) return 'oauth_org_not_allowed'
|
|
352
|
+
if (/account_on_hold|account[_ ]suspended/.test(combined)) return 'account_on_hold'
|
|
353
|
+
if (status === 402 || /billing_error|billing|insufficient|credit|quota|balance/.test(combined)) return 'billing_error'
|
|
354
|
+
if (status === 404 || /model_not_found|model not found/.test(combined)) return 'model_not_found'
|
|
355
|
+
if (/max_output_tokens|max_tokens/.test(combined)) return 'max_output_tokens'
|
|
356
|
+
if (/cloud_credential/.test(combined)) return 'cloud_credential_error'
|
|
357
|
+
if (status === 400 || status === 422 || /invalid_request|bad request/.test(combined)) return 'invalid_request'
|
|
358
|
+
if (status >= 500 && status <= 599 || /server_error|internal server error|overloaded/.test(combined)) return 'server_error'
|
|
359
|
+
return 'unknown'
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Parse shell-style `export KEY=VALUE` / `KEY="VALUE"` assignments written to `$CLAUDE_ENV_FILE`. */
|
|
363
|
+
export function parseEnvFileUpdates(text) {
|
|
364
|
+
const updates = {}
|
|
365
|
+
if (typeof text !== 'string' || !text) return updates
|
|
366
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
367
|
+
const trimmed = rawLine.trim()
|
|
368
|
+
if (!trimmed || trimmed.startsWith('#')) continue
|
|
369
|
+
const line = trimmed.startsWith('export ') ? trimmed.slice(7).trim() : trimmed
|
|
370
|
+
const match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/)
|
|
371
|
+
if (!match) continue
|
|
372
|
+
const key = match[1]
|
|
373
|
+
let val = match[2].trim()
|
|
374
|
+
if ((val.startsWith('"') && val.endsWith('"') && val.length >= 2) || (val.startsWith("'") && val.endsWith("'") && val.length >= 2)) {
|
|
375
|
+
val = val.slice(1, -1)
|
|
376
|
+
}
|
|
377
|
+
updates[key] = val
|
|
378
|
+
}
|
|
379
|
+
return updates
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function isExecutableCandidate(filePath) {
|
|
383
|
+
try {
|
|
384
|
+
const st = lstatSync(filePath)
|
|
385
|
+
return st.isFile() || st.isSymbolicLink()
|
|
386
|
+
} catch {
|
|
387
|
+
return false
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Locate Git Bash (`bash.exe`) on Windows, skipping WSL shims (`System32\bash.exe`, `WindowsApps`). */
|
|
392
|
+
export function resolveWindowsGitBash(env = process.env, platform = process.platform) {
|
|
393
|
+
if (platform !== 'win32') return null
|
|
394
|
+
const explicit = env.CLAUDE_CODE_GIT_BASH_PATH || ''
|
|
395
|
+
const pathVal = env.PATH || env.Path || ''
|
|
396
|
+
const cacheKey = `${platform}\0${explicit}\0${pathVal}`
|
|
397
|
+
if (cachedGitBashKey === cacheKey) return cachedGitBashPath
|
|
398
|
+
|
|
399
|
+
const candidates = []
|
|
400
|
+
if (explicit.trim()) candidates.push(explicit.trim())
|
|
401
|
+
const pf = env.ProgramFiles || 'C:\\Program Files'
|
|
402
|
+
const pf86 = env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)'
|
|
403
|
+
const localAppData = env.LocalAppData || env.LOCALAPPDATA
|
|
404
|
+
candidates.push(
|
|
405
|
+
join(pf, 'Git', 'bin', 'bash.exe'),
|
|
406
|
+
join(pf, 'Git', 'usr', 'bin', 'bash.exe'),
|
|
407
|
+
join(pf86, 'Git', 'bin', 'bash.exe'),
|
|
408
|
+
)
|
|
409
|
+
if (localAppData) {
|
|
410
|
+
candidates.push(
|
|
411
|
+
join(localAppData, 'Programs', 'Git', 'bin', 'bash.exe'),
|
|
412
|
+
join(localAppData, 'Programs', 'Git', 'usr', 'bin', 'bash.exe'),
|
|
413
|
+
)
|
|
414
|
+
}
|
|
415
|
+
const sysRoot = (env.SystemRoot || 'C:\\Windows').toLowerCase()
|
|
416
|
+
for (const dirEntry of pathVal.split(';')) {
|
|
417
|
+
const cleanDir = dirEntry.trim().replace(/^"|"$/g, '')
|
|
418
|
+
if (!cleanDir) continue
|
|
419
|
+
const lowerDir = cleanDir.toLowerCase().replace(/[\\/]+$/, '')
|
|
420
|
+
if (lowerDir === `${sysRoot}\\system32` || lowerDir.endsWith('\\microsoft\\windowsapps')) continue
|
|
421
|
+
candidates.push(join(cleanDir, 'bash.exe'))
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
let found = null
|
|
425
|
+
for (const cand of candidates) {
|
|
426
|
+
if (isExecutableCandidate(cand)) {
|
|
427
|
+
found = cand
|
|
428
|
+
break
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
cachedGitBashKey = cacheKey
|
|
432
|
+
cachedGitBashPath = found
|
|
433
|
+
return found
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function isBlockedSessionEnvKey(key) {
|
|
437
|
+
const upper = String(key || '').toUpperCase()
|
|
438
|
+
return BLOCKED_SESSION_ENV_KEYS.has(upper) || upper.startsWith('DSH_')
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** Construct hook child environment preserving Claude/Codex host parity. */
|
|
442
|
+
export function buildHookEnv(plugin, context = {}) {
|
|
443
|
+
const env = {}
|
|
444
|
+
const pluginRoot = plugin?.pluginRoot ? resolve(plugin.pluginRoot) : ''
|
|
445
|
+
const pluginData = plugin?.pluginData ? resolve(plugin.pluginData) : ''
|
|
446
|
+
const projectDir = context.projectDir ? resolve(context.projectDir) : ''
|
|
447
|
+
|
|
448
|
+
if (context.sessionEnv && typeof context.sessionEnv === 'object') {
|
|
449
|
+
for (const [k, v] of Object.entries(context.sessionEnv)) {
|
|
450
|
+
if (typeof v === 'string' && !isBlockedSessionEnvKey(k)) env[k] = v
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (pluginRoot) env.CLAUDE_PLUGIN_ROOT = pluginRoot
|
|
455
|
+
if (pluginData) env.CLAUDE_PLUGIN_DATA = pluginData
|
|
456
|
+
if (projectDir) env.CLAUDE_PROJECT_DIR = projectDir
|
|
457
|
+
if (context.sessionId) env.CLAUDE_SESSION_ID = String(context.sessionId)
|
|
458
|
+
if (context.envFile) env.CLAUDE_ENV_FILE = String(context.envFile)
|
|
459
|
+
|
|
460
|
+
if (plugin?.dialect === 'codex' || plugin?.usesCodexEnvVars === true) {
|
|
461
|
+
if (pluginRoot) env.PLUGIN_ROOT = pluginRoot
|
|
462
|
+
if (pluginData) env.PLUGIN_DATA = pluginData
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
if (context.hookEnv && typeof context.hookEnv === 'object') {
|
|
466
|
+
for (const [k, v] of Object.entries(context.hookEnv)) {
|
|
467
|
+
if (v !== undefined) env[k] = substituteRuntimeProjectDir(String(v), projectDir, false)
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return env
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function substituteRuntimeProjectDir(str, projectDir, forwardSlashes = false) {
|
|
474
|
+
if (typeof str !== 'string' || !projectDir) return str
|
|
475
|
+
const replacement = forwardSlashes ? projectDir.replace(/\\/g, '/') : projectDir
|
|
476
|
+
return str.replace(PROJECT_DIR_TOKEN_RE, () => replacement)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function statSignature(filePath) {
|
|
480
|
+
try {
|
|
481
|
+
const st = statSync(filePath)
|
|
482
|
+
return `${st.mtimeMs}:${st.size}`
|
|
483
|
+
} catch {
|
|
484
|
+
return 'missing'
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function computeHooksStamp(state) {
|
|
489
|
+
const plugins = Array.isArray(state?.plugins) ? state.plugins : []
|
|
490
|
+
const parts = [String(hooksCacheEpoch), String(stateRevision()), statSignature(statePath())]
|
|
491
|
+
for (const rec of plugins) {
|
|
492
|
+
if (!rec?.name || rec.name === 'user-mcp' || rec.enabled === false) continue
|
|
493
|
+
const compiledFile = compiledHooksPath(rec.name)
|
|
494
|
+
parts.push(`${rec.name}=${statSignature(compiledFile)}`)
|
|
495
|
+
if (!existsSync(compiledFile)) {
|
|
496
|
+
const target = installedDir(rec.name)
|
|
497
|
+
parts.push(statSignature(join(target, 'hooks', 'hooks.json')))
|
|
498
|
+
parts.push(statSignature(join(target, '.claude-plugin', 'plugin.json')))
|
|
499
|
+
parts.push(statSignature(join(target, '.codex-plugin', 'plugin.json')))
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return parts.join('|')
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function compileAndCachePluginHooks(pluginName, logger) {
|
|
506
|
+
const target = installedDir(pluginName)
|
|
507
|
+
if (!existsSync(target)) return null
|
|
508
|
+
const dataDir = pluginDataDir(pluginName)
|
|
509
|
+
const compiled = compileResolvedHooks(target, readPluginManifest(target), dataDir)
|
|
510
|
+
if (!compiled) return null
|
|
511
|
+
try {
|
|
512
|
+
const outFile = compiledHooksPath(pluginName)
|
|
513
|
+
mkdirSync(dirname(outFile), { recursive: true })
|
|
514
|
+
mkdirSync(dataDir, { recursive: true })
|
|
515
|
+
writeFileSync(outFile, JSON.stringify(compiled, null, 2), 'utf8')
|
|
516
|
+
} catch (err) {
|
|
517
|
+
logger?.warn?.(`[universal-plugin-hub] hook "${pluginName}" failed to cache compiled hooks: ${err?.message || err}`)
|
|
518
|
+
}
|
|
519
|
+
return compiled
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function validateCompiledPlugin(pluginName, raw, logger) {
|
|
523
|
+
const events = {}
|
|
524
|
+
const mode = raw.dialect === 'codex' ? 'codex' : 'claude-code'
|
|
525
|
+
const rawHooks = asPlainObject(raw.hooks) || {}
|
|
526
|
+
for (const [rawEvent, rawGroups] of Object.entries(rawHooks)) {
|
|
527
|
+
const event = canonicalizeHookEventName(rawEvent)
|
|
528
|
+
if (!event || !Array.isArray(rawGroups)) continue
|
|
529
|
+
const validGroups = []
|
|
530
|
+
for (const group of rawGroups) {
|
|
531
|
+
if (!group || typeof group !== 'object' || !Array.isArray(group.hooks) || group.hooks.length === 0) continue
|
|
532
|
+
const diag = (event === 'UserPromptSubmit' || event === 'Stop')
|
|
533
|
+
? undefined
|
|
534
|
+
: matcherDiagnostic(group.matcher, mode)
|
|
535
|
+
if (diag) {
|
|
536
|
+
logger?.warn?.(`[universal-plugin-hub] hook "${pluginName}" skipping group: ${diag}`)
|
|
537
|
+
continue
|
|
538
|
+
}
|
|
539
|
+
validGroups.push({
|
|
540
|
+
...(group.matcher !== undefined && event !== 'UserPromptSubmit' && event !== 'Stop' ? { matcher: group.matcher } : {}),
|
|
541
|
+
...(typeof group.if === 'string' ? { if: group.if } : {}),
|
|
542
|
+
hooks: group.hooks,
|
|
543
|
+
})
|
|
544
|
+
}
|
|
545
|
+
if (validGroups.length > 0) events[event] = validGroups
|
|
546
|
+
}
|
|
547
|
+
return {
|
|
548
|
+
name: pluginName,
|
|
549
|
+
pluginRoot: raw.pluginRoot || installedDir(pluginName),
|
|
550
|
+
pluginData: raw.pluginData || pluginDataDir(pluginName),
|
|
551
|
+
dialect: mode,
|
|
552
|
+
usesCodexEnvVars: raw.usesCodexEnvVars === true || mode === 'codex',
|
|
553
|
+
events,
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Load active enabled plugin hook definitions from `compiled-hooks/` (lazy-compiling if needed). */
|
|
558
|
+
export function loadActivePluginHooks(logger) {
|
|
559
|
+
const home = dshHome()
|
|
560
|
+
const state = readState()
|
|
561
|
+
const stamp = computeHooksStamp(state)
|
|
562
|
+
if (cachedHooksRegistry && cachedHooksRegistry.home === home && cachedHooksRegistry.stamp === stamp) {
|
|
563
|
+
return cachedHooksRegistry.plugins
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const plugins = []
|
|
567
|
+
const rows = Array.isArray(state?.plugins) ? state.plugins : []
|
|
568
|
+
for (const rec of rows) {
|
|
569
|
+
if (!rec?.name || rec.name === 'user-mcp' || rec.enabled === false) continue
|
|
570
|
+
const compiledFile = compiledHooksPath(rec.name)
|
|
571
|
+
let raw = null
|
|
572
|
+
if (existsSync(compiledFile)) {
|
|
573
|
+
try {
|
|
574
|
+
const parsed = JSON.parse(readFileSync(compiledFile, 'utf8'))
|
|
575
|
+
if (parsed && typeof parsed === 'object' && parsed.pluginRoot && parsed.dialect) {
|
|
576
|
+
raw = parsed
|
|
577
|
+
}
|
|
578
|
+
} catch {}
|
|
579
|
+
}
|
|
580
|
+
if (!raw) {
|
|
581
|
+
raw = compileAndCachePluginHooks(rec.name, logger)
|
|
582
|
+
}
|
|
583
|
+
if (!raw || !raw.hooks || Object.keys(raw.hooks).length === 0) continue
|
|
584
|
+
plugins.push(validateCompiledPlugin(rec.name, raw, logger))
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
cachedHooksRegistry = { home, stamp, plugins }
|
|
588
|
+
return plugins
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function getUserMessageCreator(resolveDshModules = findDshMainNodeModules) {
|
|
592
|
+
if (cachedCreateUserMessage) return cachedCreateUserMessage
|
|
593
|
+
try {
|
|
594
|
+
const main = resolveDshModules?.()
|
|
595
|
+
if (main) {
|
|
596
|
+
const req = createRequire(join(main, '.universal-plugin-hub-resolve.cjs'))
|
|
597
|
+
const llm = req('@deepseek-ai/dsh-llm')
|
|
598
|
+
if (typeof llm?.createUserMessage === 'function') {
|
|
599
|
+
cachedCreateUserMessage = llm.createUserMessage
|
|
600
|
+
return cachedCreateUserMessage
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
} catch {}
|
|
604
|
+
const deepFreeze = (value) => {
|
|
605
|
+
if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value
|
|
606
|
+
Object.freeze(value)
|
|
607
|
+
for (const v of Object.values(value)) deepFreeze(v)
|
|
608
|
+
return value
|
|
609
|
+
}
|
|
610
|
+
return (input) => {
|
|
611
|
+
const payload = { role: 'user', ...input, id: randomUUID() }
|
|
612
|
+
const cloned = typeof structuredClone === 'function'
|
|
613
|
+
? structuredClone(payload)
|
|
614
|
+
: JSON.parse(JSON.stringify(payload))
|
|
615
|
+
return deepFreeze(cloned)
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function extractTextContent(content) {
|
|
620
|
+
if (typeof content === 'string') return content
|
|
621
|
+
if (!Array.isArray(content)) return ''
|
|
622
|
+
return content
|
|
623
|
+
.filter((b) => b && b.type === 'text' && typeof b.text === 'string')
|
|
624
|
+
.map((b) => b.text)
|
|
625
|
+
.join('')
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function readLastAssistantText(session) {
|
|
629
|
+
if (typeof session?.snapshotEvents !== 'function') return undefined
|
|
630
|
+
const events = session.snapshotEvents()
|
|
631
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
632
|
+
const ev = events[i]
|
|
633
|
+
if (ev?.type === 'assistant/message') {
|
|
634
|
+
const text = extractTextContent(ev.data?.message?.content)
|
|
635
|
+
if (text) return text
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return undefined
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function summarizeStderr(stderr, maxChars = DEFAULT_STDERR_SUMMARY_MAX_CHARS) {
|
|
642
|
+
const t = String(stderr || '').trim()
|
|
643
|
+
if (!t) return undefined
|
|
644
|
+
return t.length > maxChars ? `${t.slice(0, maxChars)}…` : t
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function createDetachedRuns() {
|
|
648
|
+
const active = new Set()
|
|
649
|
+
const controller = new AbortController()
|
|
650
|
+
return {
|
|
651
|
+
get signal() { return controller.signal },
|
|
652
|
+
track(promise) {
|
|
653
|
+
const p = Promise.resolve(promise).catch(() => {})
|
|
654
|
+
active.add(p)
|
|
655
|
+
p.finally(() => active.delete(p))
|
|
656
|
+
return p
|
|
657
|
+
},
|
|
658
|
+
async drain() {
|
|
659
|
+
controller.abort()
|
|
660
|
+
await Promise.allSettled([...active])
|
|
661
|
+
},
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function defaultTimeoutForPoint(point, override) {
|
|
666
|
+
if (typeof override === 'number' && Number.isFinite(override) && override > 0) return override
|
|
667
|
+
if (point === 'UserPromptSubmit') return USER_PROMPT_SUBMIT_TIMEOUT_MS
|
|
668
|
+
if (point === 'SessionEnd') return SESSION_END_TIMEOUT_MS
|
|
669
|
+
return DEFAULT_HOOK_TIMEOUT_MS
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function interpolateAllowedEnvVars(template, allowedEnvVars) {
|
|
673
|
+
if (typeof template !== 'string') return ''
|
|
674
|
+
const allowSet = new Set(Array.isArray(allowedEnvVars) ? allowedEnvVars : [])
|
|
675
|
+
return template.replace(ENV_PLACEHOLDER_RE, (_, v1, v2) => {
|
|
676
|
+
const varName = v1 || v2
|
|
677
|
+
if (!allowSet.has(varName)) return ''
|
|
678
|
+
return process.env[varName] ?? ''
|
|
679
|
+
})
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function scrubbedFallbackEnv(extra) {
|
|
683
|
+
const out = {}
|
|
684
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
685
|
+
if (v !== undefined && !SENSITIVE_ENV_KEY_RE.test(k) && !k.toUpperCase().startsWith('DSH_')) {
|
|
686
|
+
out[k] = v
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (process.platform === 'win32' && extra) {
|
|
690
|
+
let entries = Object.entries(out)
|
|
691
|
+
for (const [k, v] of Object.entries(extra)) {
|
|
692
|
+
const upper = k.toUpperCase()
|
|
693
|
+
entries = entries.filter(([ek]) => ek.toUpperCase() !== upper)
|
|
694
|
+
if (v !== undefined) entries.push([k, v])
|
|
695
|
+
}
|
|
696
|
+
return Object.fromEntries(entries)
|
|
697
|
+
}
|
|
698
|
+
return { ...out, ...extra }
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
async function runSubprocessCommand(subprocess, argv, { cwd, stdin, env, timeoutMs, signal }) {
|
|
702
|
+
let resolvedExe = argv[0]
|
|
703
|
+
if (typeof subprocess?.resolveExecutable === 'function') {
|
|
704
|
+
try {
|
|
705
|
+
resolvedExe = await subprocess.resolveExecutable(argv[0], env, signal)
|
|
706
|
+
} catch {
|
|
707
|
+
resolvedExe = argv[0]
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
const finalArgv = [resolvedExe, ...argv.slice(1)]
|
|
711
|
+
const deadlineAc = new AbortController()
|
|
712
|
+
let timedOut = false
|
|
713
|
+
let timer
|
|
714
|
+
const forwardAbort = () => deadlineAc.abort(signal?.reason)
|
|
715
|
+
if (signal) {
|
|
716
|
+
if (signal.aborted) deadlineAc.abort(signal.reason)
|
|
717
|
+
else signal.addEventListener('abort', forwardAbort, { once: true })
|
|
718
|
+
}
|
|
719
|
+
if (typeof timeoutMs === 'number' && timeoutMs > 0 && Number.isFinite(timeoutMs)) {
|
|
720
|
+
timer = setTimeout(() => {
|
|
721
|
+
timedOut = true
|
|
722
|
+
deadlineAc.abort(new Error('hook timed out'))
|
|
723
|
+
}, timeoutMs)
|
|
724
|
+
timer.unref?.()
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
try {
|
|
728
|
+
if (typeof subprocess?.spawn === 'function') {
|
|
729
|
+
const handle = subprocess.spawn({
|
|
730
|
+
argv: finalArgv,
|
|
731
|
+
cwd,
|
|
732
|
+
stdio: {
|
|
733
|
+
stdin: { data: stdin },
|
|
734
|
+
stdout: { maxBytes: 1024 * 1024 },
|
|
735
|
+
stderr: { maxBytes: 256 * 1024 },
|
|
736
|
+
},
|
|
737
|
+
graceMs: 3_000,
|
|
738
|
+
signal: deadlineAc.signal,
|
|
739
|
+
env,
|
|
740
|
+
})
|
|
741
|
+
const outcome = await handle.done
|
|
742
|
+
const outText = handle.collected?.stdout?.readFrom?.(0)?.text ?? ''
|
|
743
|
+
const errText = handle.collected?.stderr?.readFrom?.(0)?.text ?? ''
|
|
744
|
+
return {
|
|
745
|
+
exitCode: outcome?.exitCode ?? handle.exitCode ?? undefined,
|
|
746
|
+
stdout: outText,
|
|
747
|
+
stderr: timedOut && !errText ? 'hook timed out' : errText,
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// Fallback when mock/test context omits ctx.subprocess
|
|
752
|
+
return await new Promise((resolveRun) => {
|
|
753
|
+
let stdout = ''
|
|
754
|
+
let stderr = ''
|
|
755
|
+
const child = nodeSpawn(finalArgv[0], finalArgv.slice(1), {
|
|
756
|
+
cwd,
|
|
757
|
+
env: scrubbedFallbackEnv(env),
|
|
758
|
+
shell: false,
|
|
759
|
+
windowsHide: true,
|
|
760
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
761
|
+
})
|
|
762
|
+
const onDeadline = () => { try { child.kill() } catch {} }
|
|
763
|
+
deadlineAc.signal.addEventListener('abort', onDeadline, { once: true })
|
|
764
|
+
child.stdout.setEncoding('utf8')
|
|
765
|
+
child.stderr.setEncoding('utf8')
|
|
766
|
+
child.stdout.on('data', (c) => { stdout += c })
|
|
767
|
+
child.stderr.on('data', (c) => { stderr += c })
|
|
768
|
+
child.stdin.end(stdin)
|
|
769
|
+
child.once('error', (err) => {
|
|
770
|
+
deadlineAc.signal.removeEventListener('abort', onDeadline)
|
|
771
|
+
resolveRun({ exitCode: undefined, stdout, stderr: err.message })
|
|
772
|
+
})
|
|
773
|
+
child.once('close', (code) => {
|
|
774
|
+
deadlineAc.signal.removeEventListener('abort', onDeadline)
|
|
775
|
+
resolveRun({ exitCode: code ?? undefined, stdout, stderr: timedOut && !stderr ? 'hook timed out' : stderr })
|
|
776
|
+
})
|
|
777
|
+
})
|
|
778
|
+
} catch (err) {
|
|
779
|
+
return {
|
|
780
|
+
exitCode: undefined,
|
|
781
|
+
stdout: '',
|
|
782
|
+
stderr: timedOut ? 'hook timed out' : (err instanceof Error ? err.message : String(err)),
|
|
783
|
+
}
|
|
784
|
+
} finally {
|
|
785
|
+
clearTimeout(timer)
|
|
786
|
+
signal?.removeEventListener('abort', forwardAbort)
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
async function runHttpHook(hook, payload, timeoutMs, signal, expectedEventName) {
|
|
791
|
+
const ac = new AbortController()
|
|
792
|
+
let timedOut = false
|
|
793
|
+
let timer
|
|
794
|
+
const onAbort = () => ac.abort(signal?.reason)
|
|
795
|
+
if (signal) {
|
|
796
|
+
if (signal.aborted) ac.abort(signal.reason)
|
|
797
|
+
else signal.addEventListener('abort', onAbort, { once: true })
|
|
798
|
+
}
|
|
799
|
+
if (typeof timeoutMs === 'number' && timeoutMs > 0 && Number.isFinite(timeoutMs)) {
|
|
800
|
+
timer = setTimeout(() => {
|
|
801
|
+
timedOut = true
|
|
802
|
+
ac.abort(new Error('HTTP hook timed out'))
|
|
803
|
+
}, timeoutMs)
|
|
804
|
+
timer.unref?.()
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
try {
|
|
808
|
+
const headers = { 'Content-Type': 'application/json' }
|
|
809
|
+
if (hook.headers && typeof hook.headers === 'object') {
|
|
810
|
+
for (const [k, v] of Object.entries(hook.headers)) {
|
|
811
|
+
headers[k] = interpolateAllowedEnvVars(String(v), hook.allowedEnvVars)
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
const resp = await fetch(hook.url, {
|
|
815
|
+
method: 'POST',
|
|
816
|
+
headers,
|
|
817
|
+
body: JSON.stringify(payload),
|
|
818
|
+
signal: ac.signal,
|
|
819
|
+
})
|
|
820
|
+
const bodyText = await resp.text()
|
|
821
|
+
if (!resp.ok) {
|
|
822
|
+
return parseHookOutput(1, '', bodyText || `HTTP ${resp.status}`, {
|
|
823
|
+
expectedEventName,
|
|
824
|
+
allowPlainStdout: false,
|
|
825
|
+
onFailure: hook.onFailure,
|
|
826
|
+
})
|
|
827
|
+
}
|
|
828
|
+
if (!bodyText.trim()) {
|
|
829
|
+
return parseHookOutput(0, '', '', { expectedEventName, allowPlainStdout: false, onFailure: hook.onFailure })
|
|
830
|
+
}
|
|
831
|
+
try {
|
|
832
|
+
const parsed = asPlainObject(JSON.parse(bodyText))
|
|
833
|
+
if (!parsed) {
|
|
834
|
+
return parseHookOutput(1, '', 'HTTP hook returned non-object JSON', {
|
|
835
|
+
expectedEventName,
|
|
836
|
+
allowPlainStdout: false,
|
|
837
|
+
onFailure: hook.onFailure,
|
|
838
|
+
})
|
|
839
|
+
}
|
|
840
|
+
return parseHookOutput(0, bodyText, '', { expectedEventName, allowPlainStdout: false, onFailure: hook.onFailure })
|
|
841
|
+
} catch (err) {
|
|
842
|
+
return parseHookOutput(1, '', err instanceof Error ? err.message : String(err), {
|
|
843
|
+
expectedEventName,
|
|
844
|
+
allowPlainStdout: false,
|
|
845
|
+
onFailure: hook.onFailure,
|
|
846
|
+
})
|
|
847
|
+
}
|
|
848
|
+
} catch (err) {
|
|
849
|
+
const message = timedOut ? 'HTTP hook timed out' : (err instanceof Error ? err.message : String(err))
|
|
850
|
+
return parseHookOutput(undefined, '', message, {
|
|
851
|
+
expectedEventName,
|
|
852
|
+
allowPlainStdout: false,
|
|
853
|
+
onFailure: hook.onFailure,
|
|
854
|
+
})
|
|
855
|
+
} finally {
|
|
856
|
+
clearTimeout(timer)
|
|
857
|
+
signal?.removeEventListener('abort', onAbort)
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
/**
|
|
862
|
+
* Attach DSH-native plugin hook listeners to `hostCtx`.
|
|
863
|
+
* Returns an async disposer that unhooks every listener, aborts & drains detached runs,
|
|
864
|
+
* and deletes per-session temporary `CLAUDE_ENV_FILE` files.
|
|
865
|
+
*/
|
|
866
|
+
export function attachPluginHooksRuntime(hostCtx, options = {}) {
|
|
867
|
+
if (!hostCtx || typeof hostCtx.on !== 'function') return async () => {}
|
|
868
|
+
|
|
869
|
+
const createUserMessageFn = options.createUserMessage || getUserMessageCreator(options.findDshMainNodeModules)
|
|
870
|
+
const maxStopContinuations = Number.isInteger(options.maxStopContinuations) && options.maxStopContinuations >= 0
|
|
871
|
+
? options.maxStopContinuations
|
|
872
|
+
: DEFAULT_MAX_STOP_CONTINUATIONS
|
|
873
|
+
const stderrSummaryMaxChars = Number.isInteger(options.stderrSummaryMaxChars) && options.stderrSummaryMaxChars > 0
|
|
874
|
+
? options.stderrSummaryMaxChars
|
|
875
|
+
: DEFAULT_STDERR_SUMMARY_MAX_CHARS
|
|
876
|
+
|
|
877
|
+
const detached = createDetachedRuns()
|
|
878
|
+
const agentsBySessionId = new Map()
|
|
879
|
+
const subagentChildren = new Map()
|
|
880
|
+
const sessionEnvFiles = new Map()
|
|
881
|
+
const sessionEnvVars = new Map()
|
|
882
|
+
const onceExecuted = new Map()
|
|
883
|
+
const stopContinuations = new Map()
|
|
884
|
+
const stopFailureNotified = new Set()
|
|
885
|
+
const lastWorkdirBySession = new Map()
|
|
886
|
+
const compactionState = new Map()
|
|
887
|
+
const pendingPreToolContexts = new Map()
|
|
888
|
+
const unsupportedWarnings = new Set()
|
|
889
|
+
let handlerSeq = 0
|
|
890
|
+
|
|
891
|
+
function nextHandlerId(dialect, pluginName, point) {
|
|
892
|
+
const d = dialect === 'codex' ? 'codex' : 'claude-code'
|
|
893
|
+
return `${d}:${pluginName}:${point}:${++handlerSeq}`
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function contextMessageFrom(texts) {
|
|
897
|
+
if (!Array.isArray(texts) || texts.length === 0) return undefined
|
|
898
|
+
const content = texts.map((text) => ({ type: 'text', text }))
|
|
899
|
+
return createUserMessageFn({ content, source: CONTEXT_SOURCE })
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
function ensureEnvFile(sessionId) {
|
|
903
|
+
if (!sessionId) return undefined
|
|
904
|
+
let file = sessionEnvFiles.get(sessionId)
|
|
905
|
+
if (!file) {
|
|
906
|
+
const safeId = String(sessionId).replace(/[^A-Za-z0-9._-]/g, '_')
|
|
907
|
+
file = join(tmpdir(), `uph-claude-env-${safeId}-${randomUUID().slice(0, 8)}.env`)
|
|
908
|
+
sessionEnvFiles.set(sessionId, file)
|
|
909
|
+
try { writeFileSync(file, '', 'utf8') } catch {}
|
|
910
|
+
}
|
|
911
|
+
return file
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
function syncEnvFileUpdates(sessionId, envFile) {
|
|
915
|
+
if (!sessionId || !envFile || !existsSync(envFile)) return
|
|
916
|
+
try {
|
|
917
|
+
const parsed = parseEnvFileUpdates(readFileSync(envFile, 'utf8'))
|
|
918
|
+
if (Object.keys(parsed).length > 0) {
|
|
919
|
+
const current = sessionEnvVars.get(sessionId) || {}
|
|
920
|
+
sessionEnvVars.set(sessionId, { ...current, ...parsed })
|
|
921
|
+
}
|
|
922
|
+
} catch {}
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
async function resolveWorkdir(agent, session, directoryMode, signal) {
|
|
926
|
+
const wdService = resolveOptionalService(hostCtx, 'workingDirectory')
|
|
927
|
+
let candidate
|
|
928
|
+
try {
|
|
929
|
+
if (directoryMode !== 'committed' && agent && typeof wdService?.ensure === 'function') {
|
|
930
|
+
candidate = await wdService.ensure(agent, signal)
|
|
931
|
+
} else if (session && typeof wdService?.get === 'function') {
|
|
932
|
+
candidate = wdService.get(session)
|
|
933
|
+
}
|
|
934
|
+
} catch {}
|
|
935
|
+
if (typeof candidate === 'string' && candidate && existsSync(candidate)) return candidate
|
|
936
|
+
const headerCwd = session?.header?.cwd
|
|
937
|
+
if (typeof headerCwd === 'string' && headerCwd && existsSync(headerCwd)) return headerCwd
|
|
938
|
+
return process.cwd()
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
function collectMatchingHandlers(point, subjects, { toolName, toolInput, sessionId } = {}) {
|
|
942
|
+
const activePlugins = loadActivePluginHooks(hostCtx.logger)
|
|
943
|
+
const matched = []
|
|
944
|
+
for (const plugin of activePlugins) {
|
|
945
|
+
const groups = plugin.events[point]
|
|
946
|
+
if (!Array.isArray(groups) || groups.length === 0) continue
|
|
947
|
+
for (const group of groups) {
|
|
948
|
+
if (point !== 'UserPromptSubmit' && point !== 'Stop' && !matchesHookMatcher(group.matcher, subjects, plugin.dialect)) {
|
|
949
|
+
continue
|
|
950
|
+
}
|
|
951
|
+
if (group.if && !matchesHookIfCondition(group.if, toolName, toolInput)) continue
|
|
952
|
+
for (let hi = 0; hi < group.hooks.length; hi++) {
|
|
953
|
+
const hook = group.hooks[hi]
|
|
954
|
+
if (hook.if && !matchesHookIfCondition(hook.if, toolName, toolInput)) continue
|
|
955
|
+
if (hook.once && sessionId) {
|
|
956
|
+
const seen = onceExecuted.get(sessionId) || new Set()
|
|
957
|
+
const onceKey = `${plugin.name}:${point}:${group.matcher || '*'}:${hi}:${hook.command || hook.url || ''}`
|
|
958
|
+
if (seen.has(onceKey)) continue
|
|
959
|
+
matched.push({ plugin, group, hook, onceKey })
|
|
960
|
+
} else {
|
|
961
|
+
matched.push({ plugin, group, hook, onceKey: null })
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
return matched
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
async function executeSingleHandler(entry, point, payload, { workdir, sessionId, signal, envFile }) {
|
|
970
|
+
const { plugin, hook, onceKey } = entry
|
|
971
|
+
if (onceKey && sessionId) {
|
|
972
|
+
let seen = onceExecuted.get(sessionId)
|
|
973
|
+
if (!seen) {
|
|
974
|
+
seen = new Set()
|
|
975
|
+
onceExecuted.set(sessionId, seen)
|
|
976
|
+
}
|
|
977
|
+
seen.add(onceKey)
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
const hookType = hook.type || 'command'
|
|
981
|
+
const timeoutMs = defaultTimeoutForPoint(
|
|
982
|
+
point,
|
|
983
|
+
typeof hook.timeout === 'number' && Number.isFinite(hook.timeout) && hook.timeout > 0 ? hook.timeout * 1000 : undefined,
|
|
984
|
+
)
|
|
985
|
+
const fullPayload = { ...payload, cwd: workdir }
|
|
986
|
+
|
|
987
|
+
if (hookType === 'http') {
|
|
988
|
+
const output = await runHttpHook(hook, fullPayload, timeoutMs, signal, point)
|
|
989
|
+
return output
|
|
990
|
+
}
|
|
991
|
+
if (hookType !== 'command') {
|
|
992
|
+
const warnKey = `${plugin.name}:${point}:${hookType}`
|
|
993
|
+
if (!unsupportedWarnings.has(warnKey)) {
|
|
994
|
+
unsupportedWarnings.add(warnKey)
|
|
995
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] hook "${plugin.name}" skipping unsupported "${hookType}" hook on ${point}`)
|
|
996
|
+
}
|
|
997
|
+
return parseHookOutput(0, '', '', { expectedEventName: point })
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
const env = buildHookEnv(plugin, {
|
|
1001
|
+
projectDir: workdir,
|
|
1002
|
+
sessionId,
|
|
1003
|
+
envFile,
|
|
1004
|
+
sessionEnv: sessionId ? sessionEnvVars.get(sessionId) : undefined,
|
|
1005
|
+
hookEnv: hook.env,
|
|
1006
|
+
})
|
|
1007
|
+
const stdin = `${JSON.stringify(fullPayload)}\n`
|
|
1008
|
+
|
|
1009
|
+
if (Array.isArray(hook.args)) {
|
|
1010
|
+
const exe = substituteRuntimeProjectDir(hook.command, workdir, false)
|
|
1011
|
+
const args = hook.args.map((a) => substituteRuntimeProjectDir(String(a), workdir, false))
|
|
1012
|
+
const raw = await runSubprocessCommand(resolveOptionalService(hostCtx, 'subprocess'), [exe, ...args], {
|
|
1013
|
+
cwd: workdir, stdin, env, timeoutMs, signal,
|
|
1014
|
+
})
|
|
1015
|
+
return parseHookOutput(raw.exitCode, raw.stdout, raw.stderr, {
|
|
1016
|
+
expectedEventName: point,
|
|
1017
|
+
onFailure: hook.onFailure,
|
|
1018
|
+
})
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
const shellExecutor = resolveOptionalService(hostCtx, 'shell')
|
|
1022
|
+
const subprocess = resolveOptionalService(hostCtx, 'subprocess')
|
|
1023
|
+
const isWin = process.platform === 'win32'
|
|
1024
|
+
const explicitPwsh = hook.shell === 'powershell'
|
|
1025
|
+
const gitBash = isWin && !explicitPwsh ? resolveWindowsGitBash() : null
|
|
1026
|
+
|
|
1027
|
+
let raw
|
|
1028
|
+
if (isWin && !explicitPwsh && gitBash && subprocess && typeof subprocess.spawn === 'function') {
|
|
1029
|
+
const bashCmd = substituteRuntimeProjectDir(hook.command, workdir, true)
|
|
1030
|
+
raw = await runSubprocessCommand(subprocess, [gitBash, '-c', bashCmd], {
|
|
1031
|
+
cwd: workdir, stdin, env, timeoutMs, signal,
|
|
1032
|
+
})
|
|
1033
|
+
} else if (shellExecutor && typeof shellExecutor.execute === 'function' && typeof shellExecutor.resolve === 'function') {
|
|
1034
|
+
const cmdStr = substituteRuntimeProjectDir(hook.command, workdir, !isWin || !explicitPwsh)
|
|
1035
|
+
const clampedTimeout = Math.min(timeoutMs, DEFAULT_HOOK_TIMEOUT_MS)
|
|
1036
|
+
try {
|
|
1037
|
+
const spec = shellExecutor.resolve({
|
|
1038
|
+
command: cmdStr,
|
|
1039
|
+
workdir,
|
|
1040
|
+
timeoutMs: clampedTimeout,
|
|
1041
|
+
stdin,
|
|
1042
|
+
env,
|
|
1043
|
+
signal,
|
|
1044
|
+
sandboxPolicy: { mode: 'danger-full-access', workspaceRoot: workdir },
|
|
1045
|
+
})
|
|
1046
|
+
const res = await (await shellExecutor.execute(spec)).result()
|
|
1047
|
+
raw = {
|
|
1048
|
+
exitCode: res?.exitCode ?? undefined,
|
|
1049
|
+
stdout: res?.stdout?.text ?? '',
|
|
1050
|
+
stderr: res?.stderr?.text ?? '',
|
|
1051
|
+
}
|
|
1052
|
+
} catch (err) {
|
|
1053
|
+
raw = { exitCode: undefined, stdout: '', stderr: err instanceof Error ? err.message : String(err) }
|
|
1054
|
+
}
|
|
1055
|
+
} else if (gitBash) {
|
|
1056
|
+
const bashCmd = substituteRuntimeProjectDir(hook.command, workdir, true)
|
|
1057
|
+
raw = await runSubprocessCommand(null, [gitBash, '-c', bashCmd], {
|
|
1058
|
+
cwd: workdir, stdin, env, timeoutMs, signal,
|
|
1059
|
+
})
|
|
1060
|
+
} else {
|
|
1061
|
+
const cmdStr = substituteRuntimeProjectDir(hook.command, workdir, true)
|
|
1062
|
+
const fallbackShell = isWin ? ['cmd.exe', '/d', '/s', '/c', cmdStr] : ['sh', '-c', cmdStr]
|
|
1063
|
+
raw = await runSubprocessCommand(subprocess, fallbackShell, {
|
|
1064
|
+
cwd: workdir, stdin, env, timeoutMs, signal,
|
|
1065
|
+
})
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
return parseHookOutput(raw.exitCode, raw.stdout, raw.stderr, {
|
|
1069
|
+
expectedEventName: point,
|
|
1070
|
+
onFailure: hook.onFailure,
|
|
1071
|
+
})
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
async function runPoint(point, matchSubjects, payload, opts = {}) {
|
|
1075
|
+
const agent = opts.agent
|
|
1076
|
+
const session = opts.session || agent?.session
|
|
1077
|
+
const sessionId = session?.header?.id || session?.id || ''
|
|
1078
|
+
const matched = collectMatchingHandlers(point, matchSubjects, {
|
|
1079
|
+
toolName: opts.toolName,
|
|
1080
|
+
toolInput: opts.toolInput,
|
|
1081
|
+
sessionId,
|
|
1082
|
+
})
|
|
1083
|
+
if (matched.length === 0) return mergeHookOutputs([])
|
|
1084
|
+
|
|
1085
|
+
const workdir = await resolveWorkdir(agent, session, opts.directory, opts.signal)
|
|
1086
|
+
const envFile = opts.enableEnvFile && sessionId ? ensureEnvFile(sessionId) : sessionEnvFiles.get(sessionId)
|
|
1087
|
+
const agentsService = resolveOptionalService(hostCtx, 'agents')
|
|
1088
|
+
const boundary = session ? agentsService?.turnBoundaryOf?.(session) : undefined
|
|
1089
|
+
const effectiveTurn = opts.turn ?? boundary?.lastTurn
|
|
1090
|
+
const canLogTurn = Boolean(
|
|
1091
|
+
opts.logTurn === true
|
|
1092
|
+
&& session
|
|
1093
|
+
&& typeof session.append === 'function'
|
|
1094
|
+
&& Number.isSafeInteger(effectiveTurn)
|
|
1095
|
+
&& effectiveTurn >= 0
|
|
1096
|
+
&& (boundary === undefined || boundary.openTurnStartSeq !== null),
|
|
1097
|
+
)
|
|
1098
|
+
|
|
1099
|
+
const outputs = []
|
|
1100
|
+
for (const entry of matched) {
|
|
1101
|
+
const { plugin, group, hook } = entry
|
|
1102
|
+
const handlerId = nextHandlerId(plugin.dialect, plugin.name, point)
|
|
1103
|
+
const isAsync = Boolean(hook.async || hook.asyncRewake)
|
|
1104
|
+
|
|
1105
|
+
if (isAsync) {
|
|
1106
|
+
const bgRun = (async () => {
|
|
1107
|
+
const out = await executeSingleHandler(entry, point, payload, {
|
|
1108
|
+
workdir, sessionId, signal: detached.signal, envFile,
|
|
1109
|
+
})
|
|
1110
|
+
if (opts.enableEnvFile) syncEnvFileUpdates(sessionId, envFile)
|
|
1111
|
+
if (hook.asyncRewake && out.exitCode === 2 && agent && typeof agent.steer === 'function') {
|
|
1112
|
+
const msgText = out.stderr || out.stdout || `Background ${point} hook failed (exit 2)`
|
|
1113
|
+
agent.steer(createUserMessageFn({ content: [{ type: 'text', text: msgText }], source: CONTEXT_SOURCE }))
|
|
1114
|
+
} else if (out.additionalContext && agent && typeof agent.inject === 'function') {
|
|
1115
|
+
const msg = contextMessageFrom([out.additionalContext])
|
|
1116
|
+
if (msg) agent.inject(msg)
|
|
1117
|
+
}
|
|
1118
|
+
})().catch((err) => {
|
|
1119
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] async hook "${plugin.name}" ${point} failed: ${err?.message || err}`)
|
|
1120
|
+
})
|
|
1121
|
+
detached.track(bgRun)
|
|
1122
|
+
continue
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
if (canLogTurn) {
|
|
1126
|
+
try {
|
|
1127
|
+
session.append('hook/invoked', {
|
|
1128
|
+
turn: effectiveTurn,
|
|
1129
|
+
point,
|
|
1130
|
+
dialect: plugin.dialect === 'codex' ? 'codex' : 'claude-code',
|
|
1131
|
+
...(group.matcher !== undefined ? { matcher: group.matcher } : {}),
|
|
1132
|
+
handlerId,
|
|
1133
|
+
})
|
|
1134
|
+
} catch {}
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
const started = performance.now()
|
|
1138
|
+
const output = await executeSingleHandler(entry, point, payload, {
|
|
1139
|
+
workdir, sessionId, signal: opts.signal, envFile,
|
|
1140
|
+
})
|
|
1141
|
+
const durationMs = Math.max(0, performance.now() - started)
|
|
1142
|
+
if (opts.enableEnvFile) syncEnvFileUpdates(sessionId, envFile)
|
|
1143
|
+
outputs.push(output)
|
|
1144
|
+
|
|
1145
|
+
if (output.updatedInput !== undefined) {
|
|
1146
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] hook "${plugin.name}" ${point} requested updatedInput, which is not yet honored (ignored)`)
|
|
1147
|
+
}
|
|
1148
|
+
if (output.systemMessage !== undefined) {
|
|
1149
|
+
hostCtx.logger?.info?.(`[universal-plugin-hub] hook "${plugin.name}" ${point}: ${output.systemMessage}`)
|
|
1150
|
+
}
|
|
1151
|
+
if (canLogTurn) {
|
|
1152
|
+
try {
|
|
1153
|
+
const stderrSummary = summarizeStderr(output.stderr, stderrSummaryMaxChars)
|
|
1154
|
+
session.append('hook/result', {
|
|
1155
|
+
turn: effectiveTurn,
|
|
1156
|
+
point,
|
|
1157
|
+
handlerId,
|
|
1158
|
+
decision: output.decision ?? (output.continue === false ? 'stop' : 'pass'),
|
|
1159
|
+
...(Number.isSafeInteger(output.exitCode) ? { exitCode: output.exitCode } : {}),
|
|
1160
|
+
...(stderrSummary !== undefined ? { stderrSummary } : {}),
|
|
1161
|
+
durationMs,
|
|
1162
|
+
})
|
|
1163
|
+
} catch {}
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
return mergeHookOutputs(outputs)
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
function basePayload(session, eventName) {
|
|
1171
|
+
let transcriptPath = ''
|
|
1172
|
+
if (session?.header) {
|
|
1173
|
+
try {
|
|
1174
|
+
const loc = resolveOptionalService(hostCtx, 'sessionPersistence')?.locate?.(session.header)
|
|
1175
|
+
if (typeof loc?.path === 'string') transcriptPath = loc.path
|
|
1176
|
+
} catch {}
|
|
1177
|
+
}
|
|
1178
|
+
return {
|
|
1179
|
+
session_id: session?.header?.id || session?.id || '',
|
|
1180
|
+
transcript_path: transcriptPath,
|
|
1181
|
+
hook_event_name: eventName,
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
const offs = []
|
|
1186
|
+
const on = (evt, fn) => {
|
|
1187
|
+
const off = hostCtx.on(evt, fn)
|
|
1188
|
+
if (typeof off === 'function') offs.push(off)
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
// 1. agent/created -> SessionStart
|
|
1192
|
+
on('agent/created', async ({ agent, source, signal } = {}) => {
|
|
1193
|
+
if (!agent?.session) return
|
|
1194
|
+
const sessionId = agent.session.header?.id || agent.session.id || ''
|
|
1195
|
+
if (sessionId) {
|
|
1196
|
+
agentsBySessionId.set(sessionId, agent)
|
|
1197
|
+
lastWorkdirBySession.set(sessionId, agent.session.header?.cwd || '')
|
|
1198
|
+
}
|
|
1199
|
+
const ownerSignal = signal === undefined
|
|
1200
|
+
? detached.signal
|
|
1201
|
+
: (typeof AbortSignal.any === 'function' ? AbortSignal.any([signal, detached.signal]) : signal)
|
|
1202
|
+
const startSource = typeof source === 'string' && source ? source : 'startup'
|
|
1203
|
+
const run = runPoint('SessionStart', startSource, { ...basePayload(agent.session, 'SessionStart'), source: startSource }, {
|
|
1204
|
+
agent, signal: ownerSignal, logTurn: false, enableEnvFile: true,
|
|
1205
|
+
}).then((merged) => {
|
|
1206
|
+
const msg = contextMessageFrom(merged.additionalContext)
|
|
1207
|
+
if (msg) agent.inject(msg)
|
|
1208
|
+
}).catch((err) => {
|
|
1209
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] SessionStart hook failed: ${err?.message || err}`)
|
|
1210
|
+
})
|
|
1211
|
+
detached.track(run)
|
|
1212
|
+
await run
|
|
1213
|
+
})
|
|
1214
|
+
|
|
1215
|
+
// 2. agent/disposed -> SessionEnd + session state cleanup
|
|
1216
|
+
on('agent/disposed', ({ agent } = {}) => {
|
|
1217
|
+
const session = agent?.session
|
|
1218
|
+
const sessionId = session?.header?.id || session?.id || ''
|
|
1219
|
+
const envFile = sessionId ? sessionEnvFiles.get(sessionId) : undefined
|
|
1220
|
+
const hasEndHooks = collectMatchingHandlers('SessionEnd', 'other', { sessionId }).length > 0
|
|
1221
|
+
|
|
1222
|
+
const cleanup = () => {
|
|
1223
|
+
if (sessionId) {
|
|
1224
|
+
agentsBySessionId.delete(sessionId)
|
|
1225
|
+
sessionEnvFiles.delete(sessionId)
|
|
1226
|
+
sessionEnvVars.delete(sessionId)
|
|
1227
|
+
onceExecuted.delete(sessionId)
|
|
1228
|
+
lastWorkdirBySession.delete(sessionId)
|
|
1229
|
+
for (const key of [...stopContinuations.keys()]) {
|
|
1230
|
+
if (key.startsWith(`${sessionId}:`)) stopContinuations.delete(key)
|
|
1231
|
+
}
|
|
1232
|
+
for (const key of [...stopFailureNotified]) {
|
|
1233
|
+
if (key.startsWith(`${sessionId}:`)) stopFailureNotified.delete(key)
|
|
1234
|
+
}
|
|
1235
|
+
for (const [callId, entry] of pendingPreToolContexts) {
|
|
1236
|
+
if (entry?.sessionId === sessionId) pendingPreToolContexts.delete(callId)
|
|
1237
|
+
}
|
|
1238
|
+
for (const [key, entry] of compactionState) {
|
|
1239
|
+
if (key === sessionId || entry?.sessionId === sessionId) compactionState.delete(key)
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
if (envFile) {
|
|
1243
|
+
try { rmSync(envFile, { force: true }) } catch {}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
if (!session || !hasEndHooks) {
|
|
1248
|
+
cleanup()
|
|
1249
|
+
return
|
|
1250
|
+
}
|
|
1251
|
+
detached.track(
|
|
1252
|
+
runPoint('SessionEnd', 'other', { ...basePayload(session, 'SessionEnd'), reason: 'other' }, {
|
|
1253
|
+
agent, session, directory: 'committed', signal: detached.signal, logTurn: false,
|
|
1254
|
+
}).catch((err) => {
|
|
1255
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] SessionEnd hook failed: ${err?.message || err}`)
|
|
1256
|
+
}).finally(cleanup),
|
|
1257
|
+
)
|
|
1258
|
+
})
|
|
1259
|
+
|
|
1260
|
+
// 3. agent/pre-step -> UserPromptSubmit (strictly user-sourced messages)
|
|
1261
|
+
on('agent/pre-step', async ({ agent, messages, turn, signal } = {}, next) => {
|
|
1262
|
+
const list = Array.isArray(messages) ? messages : []
|
|
1263
|
+
const userMessages = list.filter((m) => m?.source?.kind === 'user')
|
|
1264
|
+
if (userMessages.length === 0) return next()
|
|
1265
|
+
|
|
1266
|
+
const promptText = extractTextContent(userMessages.flatMap((m) => m.content || []))
|
|
1267
|
+
const merged = await runPoint('UserPromptSubmit', '', {
|
|
1268
|
+
...basePayload(agent?.session, 'UserPromptSubmit'),
|
|
1269
|
+
prompt: promptText,
|
|
1270
|
+
}, { agent, turn, signal, logTurn: true })
|
|
1271
|
+
|
|
1272
|
+
if (merged.decision === 'deny' || merged.stop) {
|
|
1273
|
+
return { kind: 'reject' }
|
|
1274
|
+
}
|
|
1275
|
+
const downstream = await next()
|
|
1276
|
+
const ours = contextMessageFrom(merged.additionalContext)
|
|
1277
|
+
if (!ours || downstream?.kind !== 'enter') return downstream
|
|
1278
|
+
return {
|
|
1279
|
+
...downstream,
|
|
1280
|
+
messages: [...(Array.isArray(downstream.messages) ? downstream.messages : []), ours],
|
|
1281
|
+
}
|
|
1282
|
+
})
|
|
1283
|
+
|
|
1284
|
+
// 4. tools/pre-execute -> PreToolUse
|
|
1285
|
+
on('tools/pre-execute', async (exec, next) => {
|
|
1286
|
+
const session = exec?.agent?.session
|
|
1287
|
+
const aliases = claudeToolAliases(exec?.name)
|
|
1288
|
+
const merged = await runPoint('PreToolUse', aliases, {
|
|
1289
|
+
...basePayload(session, 'PreToolUse'),
|
|
1290
|
+
tool_name: exec?.name || '',
|
|
1291
|
+
tool_input: exec?.arguments,
|
|
1292
|
+
tool_use_id: exec?.callId || '',
|
|
1293
|
+
}, {
|
|
1294
|
+
agent: exec?.agent,
|
|
1295
|
+
session,
|
|
1296
|
+
toolName: exec?.name,
|
|
1297
|
+
toolInput: exec?.arguments,
|
|
1298
|
+
signal: exec?.signal,
|
|
1299
|
+
logTurn: true,
|
|
1300
|
+
})
|
|
1301
|
+
|
|
1302
|
+
if (merged.stop) {
|
|
1303
|
+
try {
|
|
1304
|
+
exec?.agent?.cancel?.({ kind: 'hook', reason: merged.stopReason || 'stopped by PreToolUse hook' })
|
|
1305
|
+
} catch {}
|
|
1306
|
+
return { kind: 'cancel' }
|
|
1307
|
+
}
|
|
1308
|
+
if (merged.decision === 'deny') {
|
|
1309
|
+
return {
|
|
1310
|
+
kind: 'deny',
|
|
1311
|
+
reason: merged.reason ?? 'blocked by PreToolUse hook',
|
|
1312
|
+
info: { name: 'HookError', code: 'HOOK_DENIED' },
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
if (exec?.callId && merged.additionalContext.length > 0) {
|
|
1316
|
+
while (pendingPreToolContexts.size >= 256) {
|
|
1317
|
+
const oldestKey = pendingPreToolContexts.keys().next().value
|
|
1318
|
+
if (oldestKey === undefined) break
|
|
1319
|
+
pendingPreToolContexts.delete(oldestKey)
|
|
1320
|
+
}
|
|
1321
|
+
pendingPreToolContexts.set(exec.callId, {
|
|
1322
|
+
sessionId: session?.header?.id || session?.id || '',
|
|
1323
|
+
texts: merged.additionalContext,
|
|
1324
|
+
})
|
|
1325
|
+
}
|
|
1326
|
+
if (merged.decision === 'ask') {
|
|
1327
|
+
return { kind: 'ask', ...(merged.reason !== undefined ? { reason: merged.reason } : {}) }
|
|
1328
|
+
}
|
|
1329
|
+
return next()
|
|
1330
|
+
})
|
|
1331
|
+
|
|
1332
|
+
// 5. tools/post-execute -> PostToolUse OR PostToolUseFailure
|
|
1333
|
+
on('tools/post-execute', async (exec, result, next) => {
|
|
1334
|
+
const preEntry = exec?.callId ? pendingPreToolContexts.get(exec.callId) : undefined
|
|
1335
|
+
const preTexts = Array.isArray(preEntry?.texts) ? preEntry.texts : []
|
|
1336
|
+
if (exec?.callId) pendingPreToolContexts.delete(exec.callId)
|
|
1337
|
+
|
|
1338
|
+
const session = exec?.agent?.session
|
|
1339
|
+
const aliases = claudeToolAliases(exec?.name)
|
|
1340
|
+
const isErr = Boolean(result?.isError)
|
|
1341
|
+
|
|
1342
|
+
if (isErr) {
|
|
1343
|
+
const errCode = result?.error?.info?.code
|
|
1344
|
+
const merged = await runPoint('PostToolUseFailure', aliases, {
|
|
1345
|
+
...basePayload(session, 'PostToolUseFailure'),
|
|
1346
|
+
tool_name: exec?.name || '',
|
|
1347
|
+
tool_input: exec?.arguments,
|
|
1348
|
+
tool_use_id: exec?.callId || '',
|
|
1349
|
+
error: result?.error?.message || extractTextContent(result?.content) || 'tool failed',
|
|
1350
|
+
is_interrupt: errCode === 'ABORTED' || errCode === 'ABORTED_BEFORE_DISPATCH',
|
|
1351
|
+
}, {
|
|
1352
|
+
agent: exec?.agent,
|
|
1353
|
+
session,
|
|
1354
|
+
toolName: exec?.name,
|
|
1355
|
+
toolInput: exec?.arguments,
|
|
1356
|
+
signal: exec?.signal,
|
|
1357
|
+
logTurn: true,
|
|
1358
|
+
})
|
|
1359
|
+
|
|
1360
|
+
const downstream = await next()
|
|
1361
|
+
const allTexts = [...preTexts, ...merged.additionalContext]
|
|
1362
|
+
const msg = contextMessageFrom(allTexts)
|
|
1363
|
+
if (!msg) return downstream
|
|
1364
|
+
return {
|
|
1365
|
+
...downstream,
|
|
1366
|
+
additionalContexts: [msg, ...(downstream?.additionalContexts || [])],
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
const merged = await runPoint('PostToolUse', aliases, {
|
|
1371
|
+
...basePayload(session, 'PostToolUse'),
|
|
1372
|
+
tool_name: exec?.name || '',
|
|
1373
|
+
tool_input: exec?.arguments,
|
|
1374
|
+
tool_use_id: exec?.callId || '',
|
|
1375
|
+
tool_response: extractTextContent(result?.content),
|
|
1376
|
+
}, {
|
|
1377
|
+
agent: exec?.agent,
|
|
1378
|
+
session,
|
|
1379
|
+
toolName: exec?.name,
|
|
1380
|
+
toolInput: exec?.arguments,
|
|
1381
|
+
signal: exec?.signal,
|
|
1382
|
+
logTurn: true,
|
|
1383
|
+
})
|
|
1384
|
+
|
|
1385
|
+
const allTexts = [...preTexts, ...merged.additionalContext]
|
|
1386
|
+
const msg = contextMessageFrom(allTexts)
|
|
1387
|
+
|
|
1388
|
+
if (merged.decision === 'deny') {
|
|
1389
|
+
return {
|
|
1390
|
+
kind: 'block',
|
|
1391
|
+
feedback: [{ type: 'text', text: merged.reason ?? 'blocked by PostToolUse hook' }],
|
|
1392
|
+
info: { name: 'HookError', code: 'HOOK_BLOCKED' },
|
|
1393
|
+
...(msg ? { additionalContexts: [msg] } : {}),
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
const downstream = await next()
|
|
1398
|
+
const contentOverride = merged.updatedToolOutput !== undefined && downstream?.kind === 'accept' && downstream.content === undefined && downstream.value === undefined
|
|
1399
|
+
? (Array.isArray(merged.updatedToolOutput)
|
|
1400
|
+
? merged.updatedToolOutput
|
|
1401
|
+
: [{ type: 'text', text: typeof merged.updatedToolOutput === 'string' ? merged.updatedToolOutput : JSON.stringify(merged.updatedToolOutput) }])
|
|
1402
|
+
: undefined
|
|
1403
|
+
|
|
1404
|
+
if (!msg && !contentOverride) return downstream
|
|
1405
|
+
return {
|
|
1406
|
+
...downstream,
|
|
1407
|
+
...(contentOverride ? { content: contentOverride } : {}),
|
|
1408
|
+
...(msg ? { additionalContexts: [msg, ...(downstream?.additionalContexts || [])] } : {}),
|
|
1409
|
+
}
|
|
1410
|
+
})
|
|
1411
|
+
|
|
1412
|
+
// 6. agent/turn-stopping -> Stop
|
|
1413
|
+
on('agent/turn-stopping', async ({ agent, turn, signal } = {}) => {
|
|
1414
|
+
if (!agent?.session) return
|
|
1415
|
+
const sessionId = agent.session.header?.id || agent.session.id || ''
|
|
1416
|
+
const hasValidTurn = Number.isSafeInteger(turn)
|
|
1417
|
+
const stopKey = hasValidTurn ? `${sessionId}:${turn}` : null
|
|
1418
|
+
const count = stopKey !== null ? (stopContinuations.get(stopKey) ?? 0) : 0
|
|
1419
|
+
if (stopKey !== null && count >= maxStopContinuations) {
|
|
1420
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] Stop hook loop guard reached (${maxStopContinuations}); stopping turn ${turn}`)
|
|
1421
|
+
return
|
|
1422
|
+
}
|
|
1423
|
+
const stopHookActive = count > 0
|
|
1424
|
+
const lastAssistantMessage = readLastAssistantText(agent.session)
|
|
1425
|
+
|
|
1426
|
+
const merged = await runPoint('Stop', '', {
|
|
1427
|
+
...basePayload(agent.session, 'Stop'),
|
|
1428
|
+
stop_hook_active: stopHookActive,
|
|
1429
|
+
...(lastAssistantMessage !== undefined ? { last_assistant_message: lastAssistantMessage } : {}),
|
|
1430
|
+
}, { agent, turn, signal, logTurn: true })
|
|
1431
|
+
|
|
1432
|
+
if (merged.stop) return
|
|
1433
|
+
if (merged.decision === 'deny') {
|
|
1434
|
+
if (stopKey !== null) stopContinuations.set(stopKey, count + 1)
|
|
1435
|
+
const text = merged.reason ?? 'continue: blocked by Stop hook'
|
|
1436
|
+
agent.steer(createUserMessageFn({ content: [{ type: 'text', text }], source: CONTEXT_SOURCE }))
|
|
1437
|
+
}
|
|
1438
|
+
})
|
|
1439
|
+
|
|
1440
|
+
function emitStopFailure(agent, session, turn, error) {
|
|
1441
|
+
const sessionId = session?.header?.id || session?.id || ''
|
|
1442
|
+
const errorType = mapStopFailureErrorType(error)
|
|
1443
|
+
if (collectMatchingHandlers('StopFailure', errorType, { sessionId }).length === 0) return
|
|
1444
|
+
|
|
1445
|
+
const dedupeKey = Number.isSafeInteger(turn) ? `${sessionId}:${turn}` : null
|
|
1446
|
+
if (dedupeKey !== null) {
|
|
1447
|
+
if (stopFailureNotified.has(dedupeKey)) return
|
|
1448
|
+
stopFailureNotified.add(dedupeKey)
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
const lastAssistantMessage = readLastAssistantText(session)
|
|
1452
|
+
detached.track(
|
|
1453
|
+
runPoint('StopFailure', errorType, {
|
|
1454
|
+
...basePayload(session, 'StopFailure'),
|
|
1455
|
+
error_type: errorType,
|
|
1456
|
+
...(error?.message ? { error: String(error.message) } : {}),
|
|
1457
|
+
...(lastAssistantMessage !== undefined ? { last_assistant_message: lastAssistantMessage } : {}),
|
|
1458
|
+
}, { agent, session, directory: 'committed', signal: detached.signal, logTurn: false }).catch((err) => {
|
|
1459
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] StopFailure hook failed: ${err?.message || err}`)
|
|
1460
|
+
}),
|
|
1461
|
+
)
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// 7. agent/error -> StopFailure (deduplicated against turn/end)
|
|
1465
|
+
on('agent/error', ({ agent, turn, error } = {}) => {
|
|
1466
|
+
if (!agent?.session) return
|
|
1467
|
+
emitStopFailure(agent, agent.session, turn, error)
|
|
1468
|
+
})
|
|
1469
|
+
|
|
1470
|
+
// 8. subagent/start & subagent/end -> SubagentStart / SubagentStop
|
|
1471
|
+
on('subagent/start', (info = {}) => {
|
|
1472
|
+
const child = resolveOptionalService(hostCtx, 'agents')?.get?.(info.id)
|
|
1473
|
+
if (child !== undefined) subagentChildren.set(info.runId, child)
|
|
1474
|
+
const rawType = info.agentType || info.provider || child?.session?.header?.agentPreset
|
|
1475
|
+
const agentType = rawType || 'general-purpose'
|
|
1476
|
+
const subjects = rawType && rawType !== 'general-purpose' ? [rawType, 'general-purpose'] : ['general-purpose']
|
|
1477
|
+
detached.track(
|
|
1478
|
+
runPoint('SubagentStart', subjects, {
|
|
1479
|
+
...basePayload(child?.session, 'SubagentStart'),
|
|
1480
|
+
agent_id: info.id,
|
|
1481
|
+
agent_type: agentType,
|
|
1482
|
+
}, { agent: child, session: child?.session, signal: detached.signal, logTurn: false }).then((merged) => {
|
|
1483
|
+
const msg = contextMessageFrom(merged.additionalContext)
|
|
1484
|
+
if (msg && child) child.inject(msg)
|
|
1485
|
+
}).catch((err) => {
|
|
1486
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] SubagentStart hook failed: ${err?.message || err}`)
|
|
1487
|
+
}),
|
|
1488
|
+
)
|
|
1489
|
+
})
|
|
1490
|
+
|
|
1491
|
+
on('subagent/end', (info = {}) => {
|
|
1492
|
+
const child = subagentChildren.get(info.runId) ?? resolveOptionalService(hostCtx, 'agents')?.get?.(info.id)
|
|
1493
|
+
subagentChildren.delete(info.runId)
|
|
1494
|
+
const rawType = info.agentType || info.provider || child?.session?.header?.agentPreset
|
|
1495
|
+
const agentType = rawType || 'general-purpose'
|
|
1496
|
+
const subjects = rawType && rawType !== 'general-purpose' ? [rawType, 'general-purpose'] : ['general-purpose']
|
|
1497
|
+
const lastAssistantMessage = readLastAssistantText(child?.session)
|
|
1498
|
+
detached.track(
|
|
1499
|
+
runPoint('SubagentStop', subjects, {
|
|
1500
|
+
...basePayload(child?.session, 'SubagentStop'),
|
|
1501
|
+
agent_id: info.id,
|
|
1502
|
+
agent_type: agentType,
|
|
1503
|
+
stop_hook_active: false,
|
|
1504
|
+
...(lastAssistantMessage !== undefined ? { last_assistant_message: lastAssistantMessage } : {}),
|
|
1505
|
+
}, { agent: child, session: child?.session, directory: 'committed', signal: detached.signal, logTurn: false }).catch((err) => {
|
|
1506
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] SubagentStop hook failed: ${err?.message || err}`)
|
|
1507
|
+
}),
|
|
1508
|
+
)
|
|
1509
|
+
})
|
|
1510
|
+
|
|
1511
|
+
// 9. approval/request -> PermissionRequest
|
|
1512
|
+
on('approval/request', async (req = {}, next) => {
|
|
1513
|
+
const aliases = claudeToolAliases(req.toolName)
|
|
1514
|
+
const session = req.agent?.session
|
|
1515
|
+
const sessionId = session?.header?.id || session?.id || ''
|
|
1516
|
+
if (collectMatchingHandlers('PermissionRequest', aliases, { sessionId }).length === 0) {
|
|
1517
|
+
return next()
|
|
1518
|
+
}
|
|
1519
|
+
const merged = await runPoint('PermissionRequest', aliases, {
|
|
1520
|
+
...basePayload(session, 'PermissionRequest'),
|
|
1521
|
+
tool_name: req.toolName || '',
|
|
1522
|
+
...(req.callId ? { tool_use_id: req.callId } : {}),
|
|
1523
|
+
...(req.reason ? { message: req.reason } : {}),
|
|
1524
|
+
}, { agent: req.agent, session, toolName: req.toolName, signal: req.signal, logTurn: true })
|
|
1525
|
+
|
|
1526
|
+
if (merged.decision === 'allow') return 'allowed-once'
|
|
1527
|
+
if (merged.decision === 'deny') return 'rejected'
|
|
1528
|
+
return next()
|
|
1529
|
+
})
|
|
1530
|
+
|
|
1531
|
+
// 10. session/event -> compaction, CwdChanged, turn/end error, Notification
|
|
1532
|
+
on('session/event', (session, event) => {
|
|
1533
|
+
if (!session || !event || typeof event !== 'object') return
|
|
1534
|
+
const sessionId = session.header?.id || session.id || ''
|
|
1535
|
+
const agent = agentsBySessionId.get(sessionId)
|
|
1536
|
+
|
|
1537
|
+
if (event.type === 'compaction/start') {
|
|
1538
|
+
const trigger = event.data?.sourceCommandId ? 'manual' : 'auto'
|
|
1539
|
+
const key = event.data?.compactionId || sessionId
|
|
1540
|
+
compactionState.set(key, { sessionId, trigger, summary: '' })
|
|
1541
|
+
detached.track(
|
|
1542
|
+
runPoint('PreCompact', trigger, {
|
|
1543
|
+
...basePayload(session, 'PreCompact'),
|
|
1544
|
+
trigger,
|
|
1545
|
+
custom_instructions: '',
|
|
1546
|
+
}, { agent, session, directory: 'committed', signal: detached.signal, logTurn: false }).catch((err) => {
|
|
1547
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] PreCompact hook failed: ${err?.message || err}`)
|
|
1548
|
+
}),
|
|
1549
|
+
)
|
|
1550
|
+
return
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
if (event.type === 'compaction/summary') {
|
|
1554
|
+
const key = event.data?.compactionId || sessionId
|
|
1555
|
+
const entry = compactionState.get(key) || { sessionId, trigger: 'auto', summary: '' }
|
|
1556
|
+
entry.summary = extractTextContent(event.data?.summary)
|
|
1557
|
+
compactionState.set(key, entry)
|
|
1558
|
+
return
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
if (event.type === 'compaction/end') {
|
|
1562
|
+
const key = event.data?.compactionId || sessionId
|
|
1563
|
+
const stateEntry = compactionState.get(key) || { trigger: 'auto', summary: '' }
|
|
1564
|
+
compactionState.delete(key)
|
|
1565
|
+
if (event.data?.error) return
|
|
1566
|
+
detached.track(
|
|
1567
|
+
runPoint('PostCompact', stateEntry.trigger, {
|
|
1568
|
+
...basePayload(session, 'PostCompact'),
|
|
1569
|
+
trigger: stateEntry.trigger,
|
|
1570
|
+
compact_summary: stateEntry.summary,
|
|
1571
|
+
}, { agent, session, directory: 'committed', signal: detached.signal, logTurn: false }).catch((err) => {
|
|
1572
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] PostCompact hook failed: ${err?.message || err}`)
|
|
1573
|
+
}),
|
|
1574
|
+
)
|
|
1575
|
+
return
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
if (event.type === 'workspace-root/change' || event.type === 'working-directory/change') {
|
|
1579
|
+
const nextCwd = event.data?.cwd
|
|
1580
|
+
if (typeof nextCwd !== 'string' || !nextCwd) return
|
|
1581
|
+
const prevCwd = lastWorkdirBySession.get(sessionId) ?? session.header?.cwd ?? ''
|
|
1582
|
+
if (nextCwd === prevCwd) return
|
|
1583
|
+
lastWorkdirBySession.set(sessionId, nextCwd)
|
|
1584
|
+
detached.track(
|
|
1585
|
+
runPoint('CwdChanged', '', {
|
|
1586
|
+
...basePayload(session, 'CwdChanged'),
|
|
1587
|
+
old_cwd: prevCwd,
|
|
1588
|
+
new_cwd: nextCwd,
|
|
1589
|
+
}, { agent, session, directory: 'committed', signal: detached.signal, logTurn: false, enableEnvFile: true }).catch((err) => {
|
|
1590
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] CwdChanged hook failed: ${err?.message || err}`)
|
|
1591
|
+
}),
|
|
1592
|
+
)
|
|
1593
|
+
return
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
if (event.type === 'turn/end') {
|
|
1597
|
+
const turn = event.data?.turn
|
|
1598
|
+
if (Number.isSafeInteger(turn)) {
|
|
1599
|
+
stopContinuations.delete(`${sessionId}:${turn}`)
|
|
1600
|
+
}
|
|
1601
|
+
const reason = event.data?.reason
|
|
1602
|
+
if (reason?.kind === 'error') {
|
|
1603
|
+
emitStopFailure(agent, session, turn, reason.error)
|
|
1604
|
+
} else if (reason?.kind === 'max-tokens') {
|
|
1605
|
+
emitStopFailure(agent, session, turn, { code: 'max_output_tokens', message: 'max output tokens reached' })
|
|
1606
|
+
}
|
|
1607
|
+
return
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
if (event.type === 'approval/asked') {
|
|
1611
|
+
const msg = event.data?.reason || `Permission requested for ${event.data?.toolName || 'tool'}`
|
|
1612
|
+
detached.track(
|
|
1613
|
+
runPoint('Notification', 'permission_prompt', {
|
|
1614
|
+
...basePayload(session, 'Notification'),
|
|
1615
|
+
notification_type: 'permission_prompt',
|
|
1616
|
+
message: msg,
|
|
1617
|
+
title: event.data?.toolName || 'Permission',
|
|
1618
|
+
}, { agent, session, directory: 'committed', signal: detached.signal, logTurn: false }).catch((err) => {
|
|
1619
|
+
hostCtx.logger?.warn?.(`[universal-plugin-hub] Notification hook failed: ${err?.message || err}`)
|
|
1620
|
+
}),
|
|
1621
|
+
)
|
|
1622
|
+
}
|
|
1623
|
+
})
|
|
1624
|
+
|
|
1625
|
+
return async () => {
|
|
1626
|
+
for (const off of offs) {
|
|
1627
|
+
try { off() } catch {}
|
|
1628
|
+
}
|
|
1629
|
+
await detached.drain()
|
|
1630
|
+
for (const envFile of sessionEnvFiles.values()) {
|
|
1631
|
+
try { rmSync(envFile, { force: true }) } catch {}
|
|
1632
|
+
}
|
|
1633
|
+
sessionEnvFiles.clear()
|
|
1634
|
+
sessionEnvVars.clear()
|
|
1635
|
+
agentsBySessionId.clear()
|
|
1636
|
+
subagentChildren.clear()
|
|
1637
|
+
onceExecuted.clear()
|
|
1638
|
+
stopContinuations.clear()
|
|
1639
|
+
stopFailureNotified.clear()
|
|
1640
|
+
lastWorkdirBySession.clear()
|
|
1641
|
+
compactionState.clear()
|
|
1642
|
+
pendingPreToolContexts.clear()
|
|
1643
|
+
}
|
|
1644
|
+
}
|