@tavlo-dsh/dsh-plugin-hooks 0.0.0-stage → 0.1.3

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.
@@ -0,0 +1,671 @@
1
+ /**
2
+ * Cross-platform custom/default hook script validation, storage, execution, and log ring buffer.
3
+ */
4
+
5
+ import { spawn as nodeSpawn } from 'node:child_process'
6
+ import { randomBytes, randomUUID } from 'node:crypto'
7
+ import { appendFile, chmod, lstat, mkdir, readFile, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises'
8
+ import path from 'node:path'
9
+ import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
10
+ import { getDefaultScriptById, getDefaultScriptsDir } from './default-scripts.js'
11
+
12
+ export const MAX_SCRIPT_BYTES = 512 * 1024
13
+ export const MAX_SCRIPT_OUTPUT_BYTES = 64 * 1024
14
+ export const MAX_EXECUTION_LOGS = 50
15
+ export const MAX_LOG_FILE_BYTES = 256 * 1024
16
+ export const ALLOWED_SCRIPT_EXTENSIONS = new Set([
17
+ '.mjs',
18
+ '.js',
19
+ '.cjs',
20
+ '.ps1',
21
+ '.sh',
22
+ '.py',
23
+ '.cmd',
24
+ '.bat',
25
+ ])
26
+
27
+ const CUSTOM_FILENAME_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.(mjs|js|cjs|ps1|sh|py|cmd|bat)$/i
28
+
29
+ export class ScriptRunnerError extends Error {
30
+ constructor(code, message) {
31
+ super(message)
32
+ this.code = code
33
+ }
34
+ }
35
+
36
+ export function getCustomScriptsDir(dataDir) {
37
+ if (typeof dataDir !== 'string' || !dataDir.trim()) {
38
+ throw new TypeError('dataDir must be a non-empty string')
39
+ }
40
+ return path.join(dataDir, 'hooks', 'scripts', 'custom')
41
+ }
42
+
43
+ export function getExecutionLogPath(dataDir) {
44
+ if (typeof dataDir !== 'string' || !dataDir.trim()) {
45
+ throw new TypeError('dataDir must be a non-empty string')
46
+ }
47
+ return path.join(dataDir, 'hooks', 'logs', 'execution.jsonl')
48
+ }
49
+
50
+ export function clampTimeoutSeconds(raw) {
51
+ if (raw === undefined || raw === null || raw === '') return 10
52
+ const n = Math.round(Number(raw))
53
+ if (!Number.isFinite(n)) return 10
54
+ return Math.min(60, Math.max(1, n))
55
+ }
56
+
57
+ function sanitizeDisplayName(rawName, fallback) {
58
+ const cleaned = (typeof rawName === 'string' ? rawName : '')
59
+ .replace(/[\x00-\x1f\x7f]/g, '')
60
+ .trim()
61
+ const base = cleaned || fallback || 'hook-script'
62
+ return base.slice(0, 120)
63
+ }
64
+
65
+ function sanitizeOriginalFilename(raw) {
66
+ const str = typeof raw === 'string' ? raw : ''
67
+ if (str.includes('\0')) {
68
+ throw new ScriptRunnerError('hooks/invalid-script-name', 'Invalid script filename')
69
+ }
70
+ const base = str.split(/[\\/]+/).pop()?.trim() ?? ''
71
+ return base.replace(/[\x00-\x1f\x7f<>:"/\\|?*]/g, '_').slice(0, 120)
72
+ }
73
+
74
+ function assertContained(baseDir, candidatePath) {
75
+ const resolvedBase = path.resolve(baseDir)
76
+ const resolvedTarget = path.resolve(candidatePath)
77
+ const prefix = resolvedBase.endsWith(path.sep) ? resolvedBase : resolvedBase + path.sep
78
+ if (!resolvedTarget.startsWith(prefix) || path.dirname(resolvedTarget) !== resolvedBase) {
79
+ throw new ScriptRunnerError('hooks/path-escape', 'Script path escapes allowed directory')
80
+ }
81
+ return resolvedTarget
82
+ }
83
+
84
+ export function resolveScriptFilePath(dataDir, scriptEntry) {
85
+ if (!scriptEntry || typeof scriptEntry !== 'object') {
86
+ throw new ScriptRunnerError('hooks/script-not-found', 'Invalid script entry')
87
+ }
88
+ const filename = typeof scriptEntry.filename === 'string' ? scriptEntry.filename : ''
89
+ if (!filename || filename.includes('\0') || filename.includes('/') || filename.includes('\\') || filename === '.' || filename === '..') {
90
+ throw new ScriptRunnerError('hooks/invalid-script-name', 'Invalid script filename')
91
+ }
92
+ if (scriptEntry.kind === 'default') {
93
+ const def = getDefaultScriptById(scriptEntry.id)
94
+ if (!def || def.filename !== filename) {
95
+ throw new ScriptRunnerError('hooks/script-not-found', 'Unknown default script')
96
+ }
97
+ return assertContained(getDefaultScriptsDir(dataDir), path.join(getDefaultScriptsDir(dataDir), def.filename))
98
+ }
99
+ if (scriptEntry.kind === 'custom') {
100
+ if (!CUSTOM_FILENAME_RE.test(filename)) {
101
+ throw new ScriptRunnerError('hooks/invalid-script-name', 'Invalid custom script filename')
102
+ }
103
+ const dir = getCustomScriptsDir(dataDir)
104
+ return assertContained(dir, path.join(dir, filename))
105
+ }
106
+ throw new ScriptRunnerError('hooks/script-not-found', 'Unknown script kind')
107
+ }
108
+
109
+ async function atomicWriteBuffer(targetPath, buf) {
110
+ const tmpPath = `${targetPath}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`
111
+ try {
112
+ await writeFile(tmpPath, buf)
113
+ await rename(tmpPath, targetPath)
114
+ } catch (error) {
115
+ await unlink(tmpPath).catch(() => {})
116
+ throw error
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Validate and persist an uploaded custom script under `$DSH_HOME/hooks/scripts/custom/`.
122
+ */
123
+ export async function saveUploadedScript(dataDir, { filename, buffer, name, matcher, timeoutSeconds }) {
124
+ const cleanOriginal = sanitizeOriginalFilename(filename)
125
+ const ext = path.extname(cleanOriginal).toLowerCase()
126
+ if (!ALLOWED_SCRIPT_EXTENSIONS.has(ext)) {
127
+ throw new ScriptRunnerError(
128
+ 'hooks/invalid-script-type',
129
+ `Unsupported script extension "${ext || '(none)'}". Allowed: ${[...ALLOWED_SCRIPT_EXTENSIONS].join(', ')}`,
130
+ )
131
+ }
132
+ const view = Buffer.isBuffer(buffer)
133
+ ? buffer
134
+ : buffer instanceof Uint8Array
135
+ ? Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)
136
+ : null
137
+ if (!view || view.byteLength === 0) {
138
+ throw new ScriptRunnerError('hooks/empty-script', 'Uploaded script file is empty')
139
+ }
140
+ if (view.byteLength > MAX_SCRIPT_BYTES) {
141
+ throw new ScriptRunnerError('hooks/script-too-large', `Script exceeds ${MAX_SCRIPT_BYTES} bytes limit`)
142
+ }
143
+
144
+ const customDir = getCustomScriptsDir(dataDir)
145
+ await mkdir(customDir, { recursive: true })
146
+
147
+ const id = randomUUID()
148
+ const storedFilename = `${id}${ext}`
149
+ const targetPath = assertContained(customDir, path.join(customDir, storedFilename))
150
+
151
+ await atomicWriteBuffer(targetPath, view)
152
+ if (process.platform !== 'win32') {
153
+ await chmod(targetPath, 0o700).catch(() => {})
154
+ }
155
+
156
+ return {
157
+ id,
158
+ kind: 'custom',
159
+ name: sanitizeDisplayName(name, cleanOriginal),
160
+ filename: storedFilename,
161
+ originalFilename: cleanOriginal,
162
+ enabled: true,
163
+ matcher: typeof matcher === 'string' ? matcher.trim().slice(0, 256) : '',
164
+ timeoutSeconds: clampTimeoutSeconds(timeoutSeconds),
165
+ createdAt: new Date().toISOString(),
166
+ }
167
+ }
168
+
169
+ export async function deleteCustomScriptFile(dataDir, filename) {
170
+ if (typeof filename !== 'string' || !CUSTOM_FILENAME_RE.test(filename)) return
171
+ const dir = getCustomScriptsDir(dataDir)
172
+ const targetPath = assertContained(dir, path.join(dir, filename))
173
+ try {
174
+ await unlink(targetPath)
175
+ } catch (error) {
176
+ if (error?.code !== 'ENOENT') throw error
177
+ }
178
+ }
179
+
180
+ export async function readScriptSource(dataDir, scriptEntry) {
181
+ const targetPath = resolveScriptFilePath(dataDir, scriptEntry)
182
+ const baseDir = scriptEntry.kind === 'default' ? getDefaultScriptsDir(dataDir) : getCustomScriptsDir(dataDir)
183
+ let realBase
184
+ let realTarget
185
+ try {
186
+ const linkInfo = await lstat(targetPath)
187
+ if (linkInfo.isSymbolicLink() || !linkInfo.isFile()) {
188
+ throw new ScriptRunnerError('hooks/script-not-found', 'Script file is not a regular file')
189
+ }
190
+ realBase = await realpath(baseDir)
191
+ realTarget = await realpath(targetPath)
192
+ } catch (error) {
193
+ if (error instanceof ScriptRunnerError) throw error
194
+ if (error?.code === 'ENOENT') {
195
+ throw new ScriptRunnerError('hooks/script-not-found', 'Script file not found')
196
+ }
197
+ throw error
198
+ }
199
+ const prefix = realBase.endsWith(path.sep) ? realBase : realBase + path.sep
200
+ if (!realTarget.startsWith(prefix)) {
201
+ throw new ScriptRunnerError('hooks/path-escape', 'Script path escapes allowed directory')
202
+ }
203
+ const info = await stat(realTarget)
204
+ if (info.size > MAX_SCRIPT_BYTES) {
205
+ throw new ScriptRunnerError('hooks/script-too-large', 'Script exceeds maximum readable size')
206
+ }
207
+ return await readFile(realTarget, 'utf8')
208
+ }
209
+
210
+ export function matchesScriptMatcher(matcher, hookEvent) {
211
+ const raw = typeof matcher === 'string' ? matcher.trim() : ''
212
+ if (!raw || raw === '*') return true
213
+ const target = String(hookEvent?.toolName ?? hookEvent?.matcherTarget ?? hookEvent?.hookPoint ?? '')
214
+ if (!target) return false
215
+ if (raw.length <= 256) {
216
+ try {
217
+ return new RegExp(raw).test(target)
218
+ } catch {
219
+ // Fallback to exact pipe-separated matching when regex syntax is invalid
220
+ }
221
+ }
222
+ const parts = raw.split('|').map((part) => part.trim()).filter(Boolean)
223
+ return parts.includes(target)
224
+ }
225
+
226
+ async function resolveInterpreter(resolvedPath, ext, platform = process.platform) {
227
+ switch (ext) {
228
+ case '.mjs':
229
+ case '.js':
230
+ case '.cjs':
231
+ return [process.execPath, resolvedPath]
232
+ case '.py':
233
+ return [platform === 'win32' ? 'python' : 'python3', resolvedPath]
234
+ case '.sh': {
235
+ try {
236
+ const head = (await readFile(resolvedPath, 'utf8')).slice(0, 128)
237
+ if (/^#![^\r\n]*\bbash\b/i.test(head)) return ['bash', resolvedPath]
238
+ } catch {
239
+ // Ignore read failure and let shell fail naturally
240
+ }
241
+ return ['sh', resolvedPath]
242
+ }
243
+ case '.ps1':
244
+ return [
245
+ platform === 'win32' ? 'powershell.exe' : 'pwsh',
246
+ '-NoProfile',
247
+ '-NonInteractive',
248
+ '-ExecutionPolicy',
249
+ 'Bypass',
250
+ '-File',
251
+ resolvedPath,
252
+ ]
253
+ case '.cmd':
254
+ case '.bat':
255
+ if (platform !== 'win32') {
256
+ throw new ScriptRunnerError('hooks/unsupported-platform', '.cmd/.bat scripts require Windows')
257
+ }
258
+ return ['cmd.exe', '/d', '/c', resolvedPath]
259
+ default:
260
+ throw new ScriptRunnerError('hooks/invalid-script-type', `Unsupported extension ${ext}`)
261
+ }
262
+ }
263
+
264
+ export function parseDirectiveOutput(stdout) {
265
+ if (typeof stdout !== 'string' || !stdout.trim()) return null
266
+ const lines = stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
267
+ for (let i = lines.length - 1; i >= 0; i--) {
268
+ const line = lines[i]
269
+ if (!line.startsWith('{') || !line.endsWith('}')) continue
270
+ try {
271
+ const parsed = JSON.parse(line)
272
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
273
+ const out = {}
274
+ if (typeof parsed.notify === 'boolean') out.notify = parsed.notify
275
+ if (typeof parsed.suppress === 'boolean') out.suppress = parsed.suppress
276
+ if (typeof parsed.title === 'string' && parsed.title.trim()) {
277
+ out.title = parsed.title.replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, 200)
278
+ }
279
+ if (typeof parsed.summary === 'string' && parsed.summary.trim()) {
280
+ out.summary = parsed.summary.replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, 500)
281
+ }
282
+ if (typeof parsed.level === 'string' && parsed.level.trim()) {
283
+ out.level = parsed.level.trim().slice(0, 40)
284
+ }
285
+ if (parsed.channels !== undefined && typeof parsed.channels === 'object') {
286
+ out.channels = parsed.channels
287
+ }
288
+ return out
289
+ } catch {
290
+ return null
291
+ }
292
+ }
293
+ return null
294
+ }
295
+
296
+ function truncateOutput(text, maxChars = 2000) {
297
+ if (typeof text !== 'string' || !text) return ''
298
+ return text.length > maxChars ? text.slice(0, maxChars) + '…' : text
299
+ }
300
+
301
+ function spawnFallback(spawnImpl, argv, { cwd, env, stdinData, timeoutMs, signal }) {
302
+ return new Promise((resolve) => {
303
+ let settled = false
304
+ let timedOut = false
305
+ const stdoutChunks = []
306
+ const stderrChunks = []
307
+ let stdoutBytes = 0
308
+ let stderrBytes = 0
309
+
310
+ let child
311
+ try {
312
+ child = spawnImpl(argv[0], argv.slice(1), {
313
+ cwd,
314
+ env,
315
+ windowsHide: true,
316
+ stdio: ['pipe', 'pipe', 'pipe'],
317
+ })
318
+ } catch (error) {
319
+ resolve({ exitCode: null, timedOut: false, stdout: '', stderr: '', error: error?.message || 'spawn failed' })
320
+ return
321
+ }
322
+
323
+ const finish = (result) => {
324
+ if (settled) return
325
+ settled = true
326
+ clearTimeout(timer)
327
+ signal?.removeEventListener?.('abort', onAbort)
328
+ resolve(result)
329
+ }
330
+
331
+ const killChild = () => {
332
+ try {
333
+ child.kill('SIGTERM')
334
+ } catch {
335
+ try {
336
+ child.kill()
337
+ } catch {
338
+ // ignore
339
+ }
340
+ }
341
+ setTimeout(() => {
342
+ try {
343
+ child.kill('SIGKILL')
344
+ } catch {
345
+ // ignore
346
+ }
347
+ }, 500).unref?.()
348
+ }
349
+
350
+ const onAbort = () => {
351
+ killChild()
352
+ finish({
353
+ exitCode: null,
354
+ timedOut: false,
355
+ stdout: Buffer.concat(stdoutChunks).toString('utf8'),
356
+ stderr: Buffer.concat(stderrChunks).toString('utf8'),
357
+ error: 'aborted',
358
+ })
359
+ }
360
+
361
+ if (signal?.aborted) {
362
+ onAbort()
363
+ return
364
+ }
365
+ signal?.addEventListener?.('abort', onAbort, { once: true })
366
+
367
+ const timer = setTimeout(() => {
368
+ timedOut = true
369
+ killChild()
370
+ finish({
371
+ exitCode: null,
372
+ timedOut: true,
373
+ stdout: Buffer.concat(stdoutChunks).toString('utf8'),
374
+ stderr: Buffer.concat(stderrChunks).toString('utf8'),
375
+ error: `Script timed out after ${timeoutMs}ms`,
376
+ })
377
+ }, timeoutMs)
378
+ timer.unref?.()
379
+
380
+ child.stdout?.on('data', (chunk) => {
381
+ if (stdoutBytes >= MAX_SCRIPT_OUTPUT_BYTES) return
382
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
383
+ const slice = buf.subarray(0, MAX_SCRIPT_OUTPUT_BYTES - stdoutBytes)
384
+ stdoutChunks.push(slice)
385
+ stdoutBytes += slice.byteLength
386
+ })
387
+ child.stderr?.on('data', (chunk) => {
388
+ if (stderrBytes >= MAX_SCRIPT_OUTPUT_BYTES) return
389
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
390
+ const slice = buf.subarray(0, MAX_SCRIPT_OUTPUT_BYTES - stderrBytes)
391
+ stderrChunks.push(slice)
392
+ stderrBytes += slice.byteLength
393
+ })
394
+
395
+ child.once('error', (error) => {
396
+ finish({
397
+ exitCode: null,
398
+ timedOut,
399
+ stdout: Buffer.concat(stdoutChunks).toString('utf8'),
400
+ stderr: Buffer.concat(stderrChunks).toString('utf8'),
401
+ error: error?.message || 'process error',
402
+ })
403
+ })
404
+
405
+ child.once('close', (code) => {
406
+ finish({
407
+ exitCode: code,
408
+ timedOut,
409
+ stdout: Buffer.concat(stdoutChunks).toString('utf8'),
410
+ stderr: Buffer.concat(stderrChunks).toString('utf8'),
411
+ error: code === 0 ? undefined : undefined,
412
+ })
413
+ })
414
+
415
+ try {
416
+ child.stdin?.end(stdinData)
417
+ } catch {
418
+ // ignore broken pipe
419
+ }
420
+ })
421
+ }
422
+
423
+ export function createScriptRunner({
424
+ getDataDir,
425
+ getSubprocess,
426
+ eventHub,
427
+ spawnImpl = nodeSpawn,
428
+ platform = process.platform,
429
+ now = Date.now,
430
+ logger,
431
+ } = {}) {
432
+ const logs = []
433
+ let writeTail = Promise.resolve()
434
+
435
+ function appendPersistedLog(entry) {
436
+ let dataDir
437
+ try {
438
+ dataDir = getDataDir?.()
439
+ } catch {
440
+ return writeTail
441
+ }
442
+ if (typeof dataDir !== 'string' || !dataDir.trim()) return writeTail
443
+ const logPath = getExecutionLogPath(dataDir)
444
+ const logDir = path.dirname(logPath)
445
+ const prevPath = path.join(logDir, 'execution.prev.jsonl')
446
+ const line = `${JSON.stringify(entry)}\n`
447
+
448
+ writeTail = writeTail
449
+ .then(async () => {
450
+ await mkdir(logDir, { recursive: true })
451
+ try {
452
+ const info = await stat(logPath)
453
+ if (info.size >= MAX_LOG_FILE_BYTES) {
454
+ await rename(logPath, prevPath).catch(() => {})
455
+ }
456
+ } catch (error) {
457
+ if (error?.code !== 'ENOENT') throw error
458
+ }
459
+ await appendFile(logPath, line, 'utf8')
460
+ })
461
+ .catch((error) => {
462
+ logger?.warn?.(`tavlo-hooks: failed to persist execution log: ${error?.message || error}`)
463
+ })
464
+ return writeTail
465
+ }
466
+
467
+ async function init() {
468
+ let dataDir
469
+ try {
470
+ dataDir = getDataDir?.()
471
+ } catch {
472
+ return
473
+ }
474
+ if (typeof dataDir !== 'string' || !dataDir.trim()) return
475
+ const logPath = getExecutionLogPath(dataDir)
476
+ let raw = ''
477
+ try {
478
+ raw = await readFile(logPath, 'utf8')
479
+ } catch (error) {
480
+ if (error?.code === 'ENOENT') return
481
+ logger?.warn?.(`tavlo-hooks: failed to read execution log: ${error?.message || error}`)
482
+ return
483
+ }
484
+ const parsed = []
485
+ for (const line of raw.split(/\r?\n/)) {
486
+ const trimmed = line.trim()
487
+ if (!trimmed) continue
488
+ try {
489
+ const obj = JSON.parse(trimmed)
490
+ if (obj && typeof obj === 'object' && (obj.kind === 'default' || obj.kind === 'custom')) {
491
+ parsed.push(obj)
492
+ }
493
+ } catch {
494
+ // Ignore malformed log line
495
+ }
496
+ }
497
+ if (parsed.length === 0) return
498
+ const recent = parsed.slice(-MAX_EXECUTION_LOGS).reverse()
499
+ const existingIds = new Set(logs.map((item) => item.id))
500
+ for (const item of recent) {
501
+ if (logs.length >= MAX_EXECUTION_LOGS) break
502
+ if (!existingIds.has(item.id)) {
503
+ logs.push(item)
504
+ existingIds.add(item.id)
505
+ }
506
+ }
507
+ }
508
+
509
+ function recordLog(entry) {
510
+ logs.unshift(entry)
511
+ if (logs.length > MAX_EXECUTION_LOGS) {
512
+ logs.length = MAX_EXECUTION_LOGS
513
+ }
514
+ eventHub?.broadcast?.('logs', { logs: [...logs] })
515
+ void appendPersistedLog(entry)
516
+ return entry
517
+ }
518
+
519
+ function recordTriggerLog(entry) {
520
+ const record = {
521
+ id: entry?.id || randomUUID(),
522
+ timestamp: entry?.timestamp || new Date(now()).toISOString(),
523
+ ...entry,
524
+ }
525
+ void appendPersistedLog(record)
526
+ return record
527
+ }
528
+
529
+ async function flushLogs() {
530
+ await writeTail
531
+ }
532
+
533
+ function getLogs(limit = MAX_EXECUTION_LOGS) {
534
+ const cap = Math.min(MAX_EXECUTION_LOGS, Math.max(1, Math.trunc(Number(limit) || MAX_EXECUTION_LOGS)))
535
+ return logs.slice(0, cap)
536
+ }
537
+
538
+ async function executeScript(script, hookEvent, { signal, dryRun = false } = {}) {
539
+ const startedAt = now()
540
+ const dataDir = getDataDir()
541
+ const eventId = String(hookEvent?.eventId || randomUUID())
542
+ const hookPoint = String(hookEvent?.hookPoint || '')
543
+ const category = String(hookEvent?.category || 'Notification')
544
+ const timestamp = String(hookEvent?.timestamp || new Date(startedAt).toISOString())
545
+ const turn = typeof hookEvent?.turn === 'number' && Number.isFinite(hookEvent.turn) ? hookEvent.turn : null
546
+
547
+ const stdinPayload = {
548
+ eventId,
549
+ hookPoint,
550
+ category,
551
+ timestamp,
552
+ sessionId: hookEvent?.sessionId ? String(hookEvent.sessionId) : null,
553
+ sessionTitle: hookEvent?.sessionTitle ? String(hookEvent.sessionTitle) : null,
554
+ projectName: hookEvent?.projectName ? String(hookEvent.projectName) : null,
555
+ summary: hookEvent?.summary ? String(hookEvent.summary) : '',
556
+ toolName: hookEvent?.toolName ? String(hookEvent.toolName) : null,
557
+ reason: hookEvent?.reason ? String(hookEvent.reason) : null,
558
+ approvalId: hookEvent?.approvalId ? String(hookEvent.approvalId) : null,
559
+ turn,
560
+ }
561
+
562
+ let exitCode = null
563
+ let timedOut = false
564
+ let stdout = ''
565
+ let stderr = ''
566
+ let errorMsg
567
+
568
+ try {
569
+ const resolvedPath = resolveScriptFilePath(dataDir, script)
570
+ const ext = path.extname(resolvedPath).toLowerCase()
571
+ const argv = await resolveInterpreter(resolvedPath, ext, platform)
572
+ const timeoutMs = clampTimeoutSeconds(script.timeoutSeconds) * 1000
573
+ const env = {
574
+ ...scrubbedParentEnv(),
575
+ DSH_HOOK_POINT: hookPoint,
576
+ DSH_HOOK_CATEGORY: category,
577
+ DSH_HOOK_EVENT_ID: eventId,
578
+ DSH_HOOK_SESSION_ID: stdinPayload.sessionId ?? '',
579
+ DSH_HOOK_PROJECT: stdinPayload.projectName ?? '',
580
+ }
581
+ const stdinData = `${JSON.stringify(stdinPayload)}\n`
582
+ const subprocess = getSubprocess?.()
583
+
584
+ if (subprocess && typeof subprocess.spawn === 'function') {
585
+ const timeoutController = new AbortController()
586
+ const timer = setTimeout(() => {
587
+ timedOut = true
588
+ timeoutController.abort()
589
+ }, timeoutMs)
590
+ timer.unref?.()
591
+ const runSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal
592
+ try {
593
+ const handle = subprocess.spawn({
594
+ argv,
595
+ cwd: path.dirname(resolvedPath),
596
+ env,
597
+ graceMs: 1000,
598
+ signal: runSignal,
599
+ stdio: {
600
+ stdin: { data: stdinData },
601
+ stdout: { maxBytes: MAX_SCRIPT_OUTPUT_BYTES },
602
+ stderr: { maxBytes: MAX_SCRIPT_OUTPUT_BYTES },
603
+ },
604
+ })
605
+ const outcome = await handle.done
606
+ exitCode = outcome?.exitCode ?? null
607
+ stdout = handle.collected?.stdout?.readFrom?.(0)?.text ?? ''
608
+ stderr = handle.collected?.stderr?.readFrom?.(0)?.text ?? ''
609
+ if (timedOut) {
610
+ errorMsg = `Script timed out after ${timeoutMs}ms`
611
+ } else if (signal?.aborted) {
612
+ errorMsg = 'aborted'
613
+ }
614
+ } finally {
615
+ clearTimeout(timer)
616
+ }
617
+ } else {
618
+ const res = await spawnFallback(spawnImpl, argv, {
619
+ cwd: path.dirname(resolvedPath),
620
+ env,
621
+ stdinData,
622
+ timeoutMs,
623
+ signal,
624
+ })
625
+ exitCode = res.exitCode
626
+ timedOut = res.timedOut
627
+ stdout = res.stdout
628
+ stderr = res.stderr
629
+ errorMsg = res.error
630
+ }
631
+ } catch (error) {
632
+ errorMsg = error?.message || String(error)
633
+ }
634
+
635
+ const elapsedMs = Math.max(0, now() - startedAt)
636
+ const directive = parseDirectiveOutput(stdout)
637
+ const suppressed = Boolean(directive && (directive.suppress === true || directive.notify === false))
638
+
639
+ return recordLog({
640
+ id: randomUUID(),
641
+ timestamp: new Date(startedAt).toISOString(),
642
+ mountPointId: hookPoint,
643
+ category,
644
+ scriptId: script.id,
645
+ scriptName: script.name,
646
+ kind: script.kind,
647
+ eventId,
648
+ sessionId: stdinPayload.sessionId,
649
+ turn,
650
+ reason: stdinPayload.reason,
651
+ summary: truncateOutput(stdinPayload.summary, 160),
652
+ exitCode,
653
+ timedOut,
654
+ elapsedMs,
655
+ suppressed,
656
+ ...(directive ? { directive } : {}),
657
+ stdout: truncateOutput(stdout),
658
+ stderr: truncateOutput(stderr),
659
+ ...(errorMsg ? { error: errorMsg } : {}),
660
+ ...(dryRun ? { dryRun: true } : {}),
661
+ })
662
+ }
663
+
664
+ return {
665
+ init,
666
+ executeScript,
667
+ getLogs,
668
+ recordTriggerLog,
669
+ flushLogs,
670
+ }
671
+ }