@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.
package/index.js ADDED
@@ -0,0 +1,793 @@
1
+ /**
2
+ * DSH Hook & Notification Plugin Host Entry (@tavlo-dsh/dsh-plugin-hooks).
3
+ * Mounts owner-only HTTP/RPC/SSE/upload routes, DSH event bridge, script runner,
4
+ * config & credential persistence, and multi-channel notification dispatcher.
5
+ */
6
+
7
+ import { readFile } from 'node:fs/promises'
8
+ import { homedir } from 'node:os'
9
+ import path from 'node:path'
10
+ import { clientRequestSchema } from '@deepseek-ai/dsh-client-connection'
11
+ import s from '@deepseek-ai/schemastery'
12
+ import { createConfigStore, ConfigStoreError } from './src/config-store.js'
13
+ import { createDshHookBridge } from './src/dsh-hook-bridge.js'
14
+ import { createEventHub } from './src/event-hub.js'
15
+ import { CATEGORY_META, HOOK_MOUNT_POINTS, getMountPoint } from './src/hook-catalog.js'
16
+ import { createNotificationDispatcher } from './src/notification-dispatcher.js'
17
+ import {
18
+ createScriptRunner,
19
+ MAX_SCRIPT_BYTES,
20
+ readScriptSource,
21
+ saveUploadedScript,
22
+ ScriptRunnerError,
23
+ } from './src/script-runner.js'
24
+ import {
25
+ clearCustomSound,
26
+ getCustomSoundInfo,
27
+ getCustomSoundPath,
28
+ MAX_WAV_BYTES,
29
+ saveCustomSound,
30
+ validateWavBuffer,
31
+ } from './src/sound-manager.js'
32
+ import { clearTaskbarAttention, isWsl } from './src/system-notifier.js'
33
+ import {
34
+ getSecretFieldKeys,
35
+ PROVIDER_DEFINITIONS,
36
+ PROVIDER_IDS,
37
+ validateProviderConfig,
38
+ } from './src/third-party-providers.js'
39
+
40
+ export const name = 'tavlo-hooks'
41
+ export const inject = ['connection', 'storageDomain', 'credentials']
42
+ export const Config = s.object({})
43
+
44
+ const RPC_METHOD = 'tavlo-hooks/rpc'
45
+ const RPC_PATH = `/api/${RPC_METHOD}`
46
+ const EVENTS_PATH = '/api/tavlo-hooks/events'
47
+ const CLIENT_STATE_PATH = '/api/tavlo-hooks/client-state'
48
+ const SCRIPT_UPLOAD_PATH = '/api/tavlo-hooks/scripts/upload'
49
+ const SCRIPT_SOURCE_PATH = '/api/tavlo-hooks/scripts/source'
50
+ const SOUND_UPLOAD_PATH = '/api/tavlo-hooks/sound/upload'
51
+ const SOUND_CURRENT_PATH = '/api/tavlo-hooks/sound/current'
52
+
53
+ const MAX_RPC_BODY_BYTES = 512 * 1024
54
+ const UPLOAD_TIMEOUT_MS = 30_000
55
+
56
+ const SAFE_CONTENT_HEADERS = {
57
+ 'Cache-Control': 'private, no-store',
58
+ 'X-Content-Type-Options': 'nosniff',
59
+ 'Content-Security-Policy': "sandbox; default-src 'none'",
60
+ }
61
+
62
+ const NO_STORE_HEADERS = {
63
+ 'cache-control': 'no-store',
64
+ }
65
+
66
+ function defaultDataDir(ctx) {
67
+ const resolver = ctx?.get?.('dshHomePath')
68
+ if (typeof resolver === 'function') {
69
+ return resolver()
70
+ }
71
+ const envHome = process.env.DSH_HOME?.trim()
72
+ return envHome ? path.resolve(envHome) : path.join(homedir(), '.dsh')
73
+ }
74
+
75
+ function isPlainObject(value) {
76
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
77
+ }
78
+
79
+ function errorPayload(code, message, details) {
80
+ return {
81
+ ok: false,
82
+ error: {
83
+ code,
84
+ message,
85
+ details: isPlainObject(details) ? details : {},
86
+ },
87
+ }
88
+ }
89
+
90
+ function mapError(error) {
91
+ if (error instanceof ConfigStoreError) {
92
+ return errorPayload(`hooks/${error.code}`, error.message)
93
+ }
94
+ if (error instanceof ScriptRunnerError) {
95
+ return errorPayload(error.code, error.message)
96
+ }
97
+ if (error?.code && typeof error.code === 'string' && error.code.includes('/')) {
98
+ return errorPayload(error.code, error.message || 'Operation failed')
99
+ }
100
+ return errorPayload('hooks/internal-error', error?.message || 'Operation failed')
101
+ }
102
+
103
+ async function readStreamedBody(request, maxBytes, timeoutMs = UPLOAD_TIMEOUT_MS) {
104
+ const reader = request.body?.getReader?.()
105
+ if (!reader) {
106
+ return { ok: false, status: 400, code: 'hooks/empty-body', message: 'Request body is required' }
107
+ }
108
+ const chunks = []
109
+ let size = 0
110
+ let expired = false
111
+ const timer = setTimeout(() => {
112
+ expired = true
113
+ void reader.cancel().catch(() => {})
114
+ }, timeoutMs)
115
+ timer.unref?.()
116
+
117
+ try {
118
+ for (;;) {
119
+ const { value, done } = await reader.read()
120
+ if (done) break
121
+ if (!value) continue
122
+ size += value.byteLength
123
+ if (size > maxBytes) {
124
+ return {
125
+ ok: false,
126
+ status: 413,
127
+ code: 'hooks/payload-too-large',
128
+ message: `Upload exceeds ${maxBytes} bytes limit`,
129
+ }
130
+ }
131
+ chunks.push(value)
132
+ }
133
+ } catch {
134
+ return expired
135
+ ? { ok: false, status: 408, code: 'hooks/upload-timeout', message: 'Upload timed out' }
136
+ : { ok: false, status: 400, code: 'hooks/bad-request', message: 'Failed to read upload body' }
137
+ } finally {
138
+ clearTimeout(timer)
139
+ try {
140
+ reader.releaseLock()
141
+ } catch {
142
+ // ignore
143
+ }
144
+ }
145
+
146
+ if (expired) {
147
+ return { ok: false, status: 408, code: 'hooks/upload-timeout', message: 'Upload timed out' }
148
+ }
149
+ if (size === 0) {
150
+ return { ok: false, status: 400, code: 'hooks/empty-body', message: 'Uploaded file is empty' }
151
+ }
152
+ return { ok: true, buffer: Buffer.concat(chunks, size) }
153
+ }
154
+
155
+ /**
156
+ * Create the complete Hooks plugin runtime (dependency-injectable for tests).
157
+ */
158
+ export async function createHooksPluginRuntime(ctx, opts = {}) {
159
+ const logger = opts.logger ?? ctx?.get?.('logger')
160
+ const platform = opts.platform ?? process.platform
161
+ const getDataDir = () => opts.dataDir ?? defaultDataDir(ctx)
162
+ const storageDomain = opts.storageDomain ?? ctx?.get?.('storageDomain')
163
+ const credentials = opts.credentials ?? ctx?.get?.('credentials')
164
+ const connection = opts.connection ?? ctx?.get?.('connection')
165
+ const getSubprocess = () => opts.subprocess ?? ctx?.get?.('subprocess')
166
+
167
+ const eventHub =
168
+ opts.eventHub ??
169
+ createEventHub({
170
+ heartbeatMs: opts.heartbeatMs,
171
+ maxBufferBytes: opts.maxBufferBytes,
172
+ clientTtlMs: opts.clientTtlMs,
173
+ })
174
+
175
+ const configStore =
176
+ opts.configStore ??
177
+ createConfigStore({
178
+ getDataDir,
179
+ storageDomain,
180
+ credentials,
181
+ logger,
182
+ })
183
+
184
+ await configStore.init()
185
+
186
+ const scriptRunner =
187
+ opts.scriptRunner ??
188
+ createScriptRunner({
189
+ getDataDir,
190
+ getSubprocess,
191
+ eventHub,
192
+ spawnImpl: opts.spawnImpl,
193
+ platform,
194
+ logger,
195
+ })
196
+
197
+ await scriptRunner.init?.()
198
+
199
+ const dispatcher =
200
+ opts.dispatcher ??
201
+ createNotificationDispatcher({
202
+ getConfig: () => configStore.getSnapshot().config,
203
+ getResolvedSecrets: (targetId) => configStore.getResolvedSecrets(targetId),
204
+ getDataDir,
205
+ eventHub,
206
+ logger,
207
+ fetchImpl: opts.fetchImpl,
208
+ spawnImpl: opts.spawnImpl,
209
+ platform,
210
+ })
211
+
212
+ const bridge =
213
+ opts.bridge ??
214
+ createDshHookBridge({
215
+ ctx,
216
+ configStore,
217
+ scriptRunner,
218
+ dispatcher,
219
+ logger,
220
+ turnCompleteDebounceMs: opts.turnCompleteDebounceMs,
221
+ })
222
+
223
+ let hadUnfocusedOrFlashing = false
224
+
225
+ async function buildStateView() {
226
+ const { revision, config } = configStore.getSnapshot()
227
+ const customSound = await getCustomSoundInfo(getDataDir())
228
+ config.systemNotifications.customSoundFilename = customSound?.filename ?? null
229
+ return {
230
+ revision,
231
+ isWindows: platform === 'win32',
232
+ platform,
233
+ isWsl: isWsl({ platform }),
234
+ config,
235
+ customSound,
236
+ mountPoints: HOOK_MOUNT_POINTS,
237
+ categories: CATEGORY_META,
238
+ providers: PROVIDER_DEFINITIONS,
239
+ logs: scriptRunner.getLogs(),
240
+ }
241
+ }
242
+
243
+ function mergeTargetForTest(rawTarget) {
244
+ const inputTarget = isPlainObject(rawTarget) ? rawTarget : null
245
+ if (!inputTarget || !PROVIDER_IDS.includes(inputTarget.provider)) {
246
+ throw new ConfigStoreError('invalid-config', 'Invalid third-party provider')
247
+ }
248
+ const provider = inputTarget.provider
249
+ const secretKeys = getSecretFieldKeys(provider) ?? []
250
+ const secretSet = new Set(secretKeys)
251
+ const savedSecrets = inputTarget.id ? configStore.getResolvedSecrets(inputTarget.id) : {}
252
+
253
+ const rawConfig = isPlainObject(inputTarget.config) ? inputTarget.config : {}
254
+ const rawSecrets = isPlainObject(inputTarget.secrets) ? inputTarget.secrets : {}
255
+
256
+ const nonSecretConfig = {}
257
+ for (const [k, v] of Object.entries(rawConfig)) {
258
+ if (!secretSet.has(k) && v !== undefined) {
259
+ nonSecretConfig[k] = v
260
+ }
261
+ }
262
+
263
+ const mergedSecrets = {}
264
+ for (const key of secretKeys) {
265
+ const candidate = rawSecrets[key] !== undefined ? rawSecrets[key] : rawConfig[key]
266
+ if (typeof candidate === 'string' && candidate.trim() !== '') {
267
+ mergedSecrets[key] = candidate.trim()
268
+ } else if (typeof savedSecrets[key] === 'string' && savedSecrets[key].length > 0) {
269
+ mergedSecrets[key] = savedSecrets[key]
270
+ }
271
+ }
272
+
273
+ const check = validateProviderConfig(provider, { ...nonSecretConfig, ...mergedSecrets })
274
+ if (check && check.valid === false) {
275
+ throw new ConfigStoreError('invalid-config', check.message || check.error || 'Invalid provider configuration')
276
+ }
277
+
278
+ return {
279
+ target: {
280
+ id: typeof inputTarget.id === 'string' ? inputTarget.id : 'draft',
281
+ name: typeof inputTarget.name === 'string' && inputTarget.name.trim() ? inputTarget.name.trim() : provider,
282
+ provider,
283
+ enabled: true,
284
+ events: isPlainObject(inputTarget.events) ? inputTarget.events : {},
285
+ config: nonSecretConfig,
286
+ },
287
+ mergedSecrets,
288
+ }
289
+ }
290
+
291
+ async function executeRpc(operation, input = {}, signal) {
292
+ if (!isPlainObject(input)) {
293
+ return errorPayload('hooks/bad-request', 'RPC input must be a plain object')
294
+ }
295
+ try {
296
+ switch (operation) {
297
+ case 'getState':
298
+ return { ok: true, value: await buildStateView() }
299
+
300
+ case 'saveSettings':
301
+ await configStore.saveSettings(input)
302
+ return { ok: true, value: await buildStateView() }
303
+
304
+ case 'toggleMountPoint':
305
+ await configStore.toggleMountPoint(input)
306
+ return { ok: true, value: await buildStateView() }
307
+
308
+ case 'toggleMountPointBell':
309
+ await configStore.toggleMountPointBell(input)
310
+ return { ok: true, value: await buildStateView() }
311
+
312
+ case 'toggleScript':
313
+ await configStore.toggleScript(input)
314
+ return { ok: true, value: await buildStateView() }
315
+
316
+ case 'updateScriptMeta': {
317
+ const updated = await configStore.updateScriptMeta(input)
318
+ return { ok: true, value: { ...(await buildStateView()), script: updated.script } }
319
+ }
320
+
321
+ case 'deleteScript':
322
+ await configStore.deleteScript(input)
323
+ return { ok: true, value: await buildStateView() }
324
+
325
+ case 'resetDefaultScripts':
326
+ await configStore.resetDefaultScripts(input)
327
+ return { ok: true, value: await buildStateView() }
328
+
329
+ case 'testMountPoint': {
330
+ const outcome = await bridge.testMountPoint(input.mountPointId)
331
+ if (configStore.getSnapshot().config.systemNotifications.taskbarAttentionEnabled) {
332
+ hadUnfocusedOrFlashing = true
333
+ }
334
+ return { ok: true, value: { ...outcome, state: await buildStateView() } }
335
+ }
336
+
337
+ case 'testScript': {
338
+ const outcome = await bridge.testScript(input.mountPointId, input.scriptId)
339
+ return { ok: true, value: outcome }
340
+ }
341
+
342
+ case 'getExecutionLogs':
343
+ return { ok: true, value: { logs: scriptRunner.getLogs(input.limit) } }
344
+
345
+ case 'saveThirdPartyTarget':
346
+ await configStore.saveThirdPartyTarget({
347
+ target: input.target ?? input,
348
+ expectedRevision: input.expectedRevision,
349
+ })
350
+ return { ok: true, value: await buildStateView() }
351
+
352
+ case 'toggleThirdPartyTarget':
353
+ await configStore.toggleThirdPartyTarget(input)
354
+ return { ok: true, value: await buildStateView() }
355
+
356
+ case 'deleteThirdPartyTarget':
357
+ await configStore.deleteThirdPartyTarget(input)
358
+ return { ok: true, value: await buildStateView() }
359
+
360
+ case 'testThirdPartyTarget': {
361
+ let targetObj = isPlainObject(input.target) ? input.target : undefined
362
+ if (!targetObj && typeof input.targetId === 'string') {
363
+ targetObj = configStore
364
+ .getSnapshot()
365
+ .config.thirdParty.targets.find((t) => t.id === input.targetId)
366
+ } else if (!targetObj && typeof input.provider === 'string') {
367
+ targetObj = input
368
+ }
369
+ if (targetObj && typeof input.targetId === 'string' && !targetObj.id) {
370
+ targetObj = { ...targetObj, id: input.targetId }
371
+ }
372
+ const { target, mergedSecrets } = mergeTargetForTest(targetObj)
373
+ const res = await dispatcher.testThirdPartyTarget(target, mergedSecrets, { signal })
374
+ return { ok: true, value: res }
375
+ }
376
+
377
+ case 'clearCustomSound':
378
+ await clearCustomSound(getDataDir())
379
+ await configStore.setCustomSoundFilename({
380
+ filename: null,
381
+ expectedRevision: input.expectedRevision,
382
+ })
383
+ return { ok: true, value: await buildStateView() }
384
+
385
+ case 'testSystemNotification': {
386
+ const res = await dispatcher.testSystemNotification()
387
+ return { ok: true, value: res }
388
+ }
389
+
390
+ case 'testTaskbarFlash': {
391
+ hadUnfocusedOrFlashing = true
392
+ const res = await dispatcher.testTaskbarFlash(input)
393
+ return { ok: true, value: res }
394
+ }
395
+
396
+ default:
397
+ return errorPayload('hooks/not-found', `Unknown operation: ${String(operation)}`)
398
+ }
399
+ } catch (error) {
400
+ return mapError(error)
401
+ }
402
+ }
403
+
404
+ async function handleRpcRequest(request) {
405
+ const mediaType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase()
406
+ if (mediaType !== 'application/json') {
407
+ return new Response('content type must be application/json', { status: 415, headers: NO_STORE_HEADERS })
408
+ }
409
+ let text
410
+ try {
411
+ text = await request.text()
412
+ } catch {
413
+ return new Response('Bad request', { status: 400, headers: NO_STORE_HEADERS })
414
+ }
415
+ if (Buffer.byteLength(text, 'utf8') > MAX_RPC_BODY_BYTES) {
416
+ return new Response('Request too large', { status: 413, headers: NO_STORE_HEADERS })
417
+ }
418
+ let parsedJson
419
+ try {
420
+ parsedJson = JSON.parse(text)
421
+ } catch {
422
+ return new Response('body is not JSON', { status: 400, headers: NO_STORE_HEADERS })
423
+ }
424
+
425
+ const envelope = clientRequestSchema.safeParse(parsedJson)
426
+ if (envelope.success) {
427
+ const { rpcId, method, payload } = envelope.data
428
+ if (method !== RPC_METHOD) {
429
+ return Response.json(
430
+ {
431
+ type: 'server-response',
432
+ rpcId,
433
+ result: errorPayload('gateway/bad-request', `Unexpected RPC method: ${method}`),
434
+ },
435
+ { headers: NO_STORE_HEADERS },
436
+ )
437
+ }
438
+ if (!isPlainObject(payload) || typeof payload.operation !== 'string') {
439
+ return Response.json(
440
+ {
441
+ type: 'server-response',
442
+ rpcId,
443
+ result: errorPayload('hooks/bad-request', 'Expected { operation, input }'),
444
+ },
445
+ { headers: NO_STORE_HEADERS },
446
+ )
447
+ }
448
+ const result = await executeRpc(payload.operation, payload.input ?? {}, request.signal)
449
+ return Response.json({ type: 'server-response', rpcId, result }, { headers: NO_STORE_HEADERS })
450
+ }
451
+
452
+ if (isPlainObject(parsedJson) && parsedJson.type === 'client-request') {
453
+ const rpcId = typeof parsedJson.rpcId === 'string' ? parsedJson.rpcId : 'invalid-request'
454
+ return Response.json(
455
+ {
456
+ type: 'server-response',
457
+ rpcId,
458
+ result: errorPayload('gateway/bad-request', 'Invalid RPC envelope'),
459
+ },
460
+ { headers: NO_STORE_HEADERS },
461
+ )
462
+ }
463
+
464
+ if (isPlainObject(parsedJson) && typeof parsedJson.operation === 'string') {
465
+ const result = await executeRpc(parsedJson.operation, parsedJson.input ?? {}, request.signal)
466
+ return Response.json(result, { headers: NO_STORE_HEADERS })
467
+ }
468
+
469
+ return Response.json(errorPayload('hooks/bad-request', 'Invalid RPC request'), {
470
+ status: 400,
471
+ headers: NO_STORE_HEADERS,
472
+ })
473
+ }
474
+
475
+ async function handleClientStateRequest(request) {
476
+ let body
477
+ try {
478
+ body = await request.json()
479
+ } catch {
480
+ return Response.json(errorPayload('hooks/bad-request', 'Invalid JSON body'), {
481
+ status: 400,
482
+ headers: NO_STORE_HEADERS,
483
+ })
484
+ }
485
+ if (!isPlainObject(body) || typeof body.clientId !== 'string' || !body.clientId.trim()) {
486
+ return Response.json(errorPayload('hooks/bad-request', 'clientId is required'), {
487
+ status: 400,
488
+ headers: NO_STORE_HEADERS,
489
+ })
490
+ }
491
+
492
+ const focused = Boolean(body.focused)
493
+ const visible = Boolean(body.visible)
494
+ const closing = Boolean(body.closing)
495
+ const wasFocused = eventHub.hasFocusedVisibleClient()
496
+
497
+ if (!focused || !visible) {
498
+ hadUnfocusedOrFlashing = true
499
+ }
500
+
501
+ eventHub.updateClientState({
502
+ clientId: body.clientId,
503
+ focused,
504
+ visible,
505
+ closing,
506
+ })
507
+
508
+ if (focused && visible && !closing && (hadUnfocusedOrFlashing || !wasFocused)) {
509
+ hadUnfocusedOrFlashing = false
510
+ if (typeof dispatcher.clearTaskbarAttention === 'function') {
511
+ void dispatcher.clearTaskbarAttention().catch(() => {})
512
+ } else {
513
+ void clearTaskbarAttention({ platform, spawnImpl: opts.spawnImpl }).catch(() => {})
514
+ }
515
+ }
516
+
517
+ return Response.json(
518
+ {
519
+ ok: true,
520
+ value: {
521
+ focusedClients: eventHub.getFocusedClientCount(),
522
+ connectedClients: eventHub.getConnectedClientCount(),
523
+ },
524
+ },
525
+ { headers: NO_STORE_HEADERS },
526
+ )
527
+ }
528
+
529
+ async function handleScriptUploadRequest(request) {
530
+ const params = new URL(request.url).searchParams
531
+ const mountPointId = params.get('mountPointId') || ''
532
+ if (!getMountPoint(mountPointId)) {
533
+ return Response.json(errorPayload('hooks/not-found', `Unknown mount point: ${mountPointId}`), {
534
+ status: 404,
535
+ headers: NO_STORE_HEADERS,
536
+ })
537
+ }
538
+
539
+ const expectedRevRaw = params.get('expectedRevision')
540
+ const expectedRevision = expectedRevRaw !== null && expectedRevRaw !== '' ? Number(expectedRevRaw) : undefined
541
+ if (expectedRevision !== undefined && (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0)) {
542
+ return Response.json(errorPayload('hooks/bad-request', 'Invalid expectedRevision'), {
543
+ status: 400,
544
+ headers: NO_STORE_HEADERS,
545
+ })
546
+ }
547
+
548
+ const streamed = await readStreamedBody(request, MAX_SCRIPT_BYTES)
549
+ if (!streamed.ok) {
550
+ return Response.json(errorPayload(streamed.code, streamed.message), {
551
+ status: streamed.status,
552
+ headers: NO_STORE_HEADERS,
553
+ })
554
+ }
555
+
556
+ try {
557
+ const scriptEntry = await saveUploadedScript(getDataDir(), {
558
+ filename: params.get('filename') || '',
559
+ buffer: streamed.buffer,
560
+ name: params.get('name') || undefined,
561
+ matcher: params.get('matcher') ?? '',
562
+ timeoutSeconds: params.get('timeoutSeconds'),
563
+ })
564
+ try {
565
+ const saved = await configStore.addCustomScript({
566
+ mountPointId,
567
+ scriptEntry,
568
+ expectedRevision,
569
+ })
570
+ return Response.json(
571
+ { ok: true, value: { ...(await buildStateView()), script: saved.script } },
572
+ { headers: NO_STORE_HEADERS },
573
+ )
574
+ } catch (error) {
575
+ const { deleteCustomScriptFile } = await import('./src/script-runner.js')
576
+ await deleteCustomScriptFile(getDataDir(), scriptEntry.filename).catch(() => {})
577
+ const status = error instanceof ConfigStoreError && error.code === 'revision-conflict' ? 409 : 400
578
+ return Response.json(mapError(error), { status, headers: NO_STORE_HEADERS })
579
+ }
580
+ } catch (error) {
581
+ return Response.json(mapError(error), { status: 400, headers: NO_STORE_HEADERS })
582
+ }
583
+ }
584
+
585
+ async function handleScriptSourceRequest(request) {
586
+ const params = new URL(request.url).searchParams
587
+ const mountPointId = params.get('mountPointId') || ''
588
+ const scriptId = params.get('scriptId') || ''
589
+ const mp = configStore.getSnapshot().config.mountPoints?.[mountPointId]
590
+ const scriptEntry = mp?.scripts?.find((s) => s.id === scriptId)
591
+ if (!scriptEntry) {
592
+ return Response.json(errorPayload('hooks/not-found', 'Script not found'), {
593
+ status: 404,
594
+ headers: NO_STORE_HEADERS,
595
+ })
596
+ }
597
+
598
+ try {
599
+ const content = await readScriptSource(getDataDir(), scriptEntry)
600
+ return Response.json(
601
+ {
602
+ ok: true,
603
+ value: {
604
+ scriptId: scriptEntry.id,
605
+ mountPointId,
606
+ filename: scriptEntry.filename,
607
+ kind: scriptEntry.kind,
608
+ content,
609
+ },
610
+ },
611
+ { headers: { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' } },
612
+ )
613
+ } catch (error) {
614
+ const status = error instanceof ScriptRunnerError && error.code === 'hooks/script-not-found' ? 404 : 400
615
+ return Response.json(mapError(error), { status, headers: NO_STORE_HEADERS })
616
+ }
617
+ }
618
+
619
+ async function handleSoundUploadRequest(request) {
620
+ const params = new URL(request.url).searchParams
621
+ const expectedRevRaw = params.get('expectedRevision')
622
+ const expectedRevision = expectedRevRaw !== null && expectedRevRaw !== '' ? Number(expectedRevRaw) : undefined
623
+ if (expectedRevision !== undefined && (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0)) {
624
+ return Response.json(errorPayload('hooks/bad-request', 'Invalid expectedRevision'), {
625
+ status: 400,
626
+ headers: NO_STORE_HEADERS,
627
+ })
628
+ }
629
+ if (expectedRevision !== undefined && expectedRevision !== configStore.getSnapshot().revision) {
630
+ return Response.json(
631
+ errorPayload(
632
+ 'hooks/revision-conflict',
633
+ 'Revision conflict: settings changed. Reload the latest settings before saving.',
634
+ ),
635
+ { status: 409, headers: NO_STORE_HEADERS },
636
+ )
637
+ }
638
+
639
+ const streamed = await readStreamedBody(request, MAX_WAV_BYTES)
640
+ if (!streamed.ok) {
641
+ return Response.json(errorPayload(streamed.code, streamed.message), {
642
+ status: streamed.status,
643
+ headers: NO_STORE_HEADERS,
644
+ })
645
+ }
646
+
647
+ const wavCheck = validateWavBuffer(streamed.buffer)
648
+ if (!wavCheck.valid) {
649
+ return Response.json(errorPayload(wavCheck.errorCode || 'sound/invalid-wav', wavCheck.reason || 'Invalid WAV file'), {
650
+ status: 400,
651
+ headers: NO_STORE_HEADERS,
652
+ })
653
+ }
654
+
655
+ try {
656
+ const sound = await saveCustomSound(getDataDir(), streamed.buffer, params.get('filename') || 'custom.wav')
657
+ await configStore.setCustomSoundFilename({
658
+ filename: sound.filename,
659
+ expectedRevision,
660
+ })
661
+ return Response.json(
662
+ { ok: true, value: await buildStateView() },
663
+ { headers: NO_STORE_HEADERS },
664
+ )
665
+ } catch (error) {
666
+ const status = error instanceof ConfigStoreError && error.code === 'revision-conflict' ? 409 : 400
667
+ return Response.json(mapError(error), { status, headers: NO_STORE_HEADERS })
668
+ }
669
+ }
670
+
671
+ async function handleSoundCurrentRequest() {
672
+ const dataDir = getDataDir()
673
+ const info = await getCustomSoundInfo(dataDir)
674
+ if (!info) {
675
+ return Response.json(errorPayload('hooks/sound-not-found', 'No custom sound configured'), {
676
+ status: 404,
677
+ headers: NO_STORE_HEADERS,
678
+ })
679
+ }
680
+ try {
681
+ const bytes = await readFile(getCustomSoundPath(dataDir))
682
+ return new Response(bytes, {
683
+ status: 200,
684
+ headers: {
685
+ ...SAFE_CONTENT_HEADERS,
686
+ 'Content-Type': 'audio/wav',
687
+ },
688
+ })
689
+ } catch {
690
+ return Response.json(errorPayload('hooks/sound-not-found', 'Custom sound file unavailable'), {
691
+ status: 404,
692
+ headers: NO_STORE_HEADERS,
693
+ })
694
+ }
695
+ }
696
+
697
+ const routeDisposers = []
698
+ function registerRoutes() {
699
+ if (!connection?.fetch?.register) return
700
+ const register = (route) => {
701
+ const dispose = connection.fetch.register(route)
702
+ if (typeof dispose === 'function') routeDisposers.push(dispose)
703
+ }
704
+
705
+ register({
706
+ path: RPC_PATH,
707
+ methods: ['POST'],
708
+ requestBody: 'buffered',
709
+ fetch: handleRpcRequest,
710
+ })
711
+ register({
712
+ path: EVENTS_PATH,
713
+ methods: ['GET'],
714
+ requestBody: 'buffered',
715
+ fetch: (request) => eventHub.open(request),
716
+ })
717
+ register({
718
+ path: CLIENT_STATE_PATH,
719
+ methods: ['POST'],
720
+ requestBody: 'buffered',
721
+ fetch: handleClientStateRequest,
722
+ })
723
+ register({
724
+ path: SCRIPT_UPLOAD_PATH,
725
+ methods: ['POST'],
726
+ requestBody: 'streaming',
727
+ fetch: handleScriptUploadRequest,
728
+ })
729
+ register({
730
+ path: SCRIPT_SOURCE_PATH,
731
+ methods: ['GET'],
732
+ requestBody: 'buffered',
733
+ fetch: handleScriptSourceRequest,
734
+ })
735
+ register({
736
+ path: SOUND_UPLOAD_PATH,
737
+ methods: ['POST'],
738
+ requestBody: 'streaming',
739
+ fetch: handleSoundUploadRequest,
740
+ })
741
+ register({
742
+ path: SOUND_CURRENT_PATH,
743
+ methods: ['GET'],
744
+ requestBody: 'buffered',
745
+ fetch: handleSoundCurrentRequest,
746
+ })
747
+ }
748
+
749
+ bridge.mount()
750
+ registerRoutes()
751
+
752
+ async function dispose() {
753
+ while (routeDisposers.length > 0) {
754
+ const fn = routeDisposers.pop()
755
+ try {
756
+ await fn?.()
757
+ } catch {
758
+ // ignore route disposal failures
759
+ }
760
+ }
761
+ bridge.dispose()
762
+ eventHub.close()
763
+ await dispatcher.dispose?.()
764
+ await scriptRunner.flushLogs?.()
765
+ await configStore.close()
766
+ }
767
+
768
+ return {
769
+ configStore,
770
+ eventHub,
771
+ scriptRunner,
772
+ dispatcher,
773
+ bridge,
774
+ executeRpc,
775
+ buildStateView,
776
+ dispose,
777
+ }
778
+ }
779
+
780
+ /**
781
+ * Cordis plugin activation entry.
782
+ */
783
+ export async function apply(ctx) {
784
+ ctx.inject(['settings'], (child) => {
785
+ child.effect(() => child.settings.configure({ auto: false }, ctx.fiber))
786
+ })
787
+
788
+ const runtime = await createHooksPluginRuntime(ctx)
789
+ ctx.effect(() => () => runtime.dispose(), 'tavlo-hooks: runtime lifecycle')
790
+
791
+ const logger = ctx.get('logger')
792
+ logger?.info?.('tavlo-hooks: hook bridge, script runner, SSE events, and notification dispatcher ready')
793
+ }