A full-featured download manager.
import type { OperationExecution } from '../operations/operation-files'
// src/core/plugin/host/capability-bridge.ts
// dispatch table for all Phase 1A capabilities; per-plugin scoping closures;
// ffmpeg op handle map; hook ctx slot for Plan C.
//
// Architecture contract:
// - MUST NOT import electron, @main/, @server/.
// - Receives BridgeCallMessage from the worker thread; routes to the
// appropriate CapabilityHost member; returns BridgeResponseMessage.
// - Per-plugin scoping: fs.storage, config, http (cookie jar) are lazily
// created per bridge instance. storage + metadata close over pluginId.
// - Hook context slot (currentFsTaskHost, currentTaskId): set by Plan C
// BridgeHookEnter events. For Task 19, absent → throws clear error code.
// - ffmpeg ops map: tracks running FfmpegOpHandle instances by opId so the
// worker can poll progress, await result, or abort.
import { randomUUID } from 'node:crypto'
import { Worker } from 'node:worker_threads'
import type { SupportedLocale } from '@shared/constants/locales'
import {
CapabilityCallMessageSchema,
type CommandInvocationScopeV1,
HOOK_SCHEMA_VERSION,
type HookEffectsV1,
HookEffectsV1Schema,
HookEnterMessageSchema,
HookExitMessageSchema,
type HookInvocationScopeV1,
} from '@shared/schemas/plugin-hooks'
import type { PluginManifest } from '@shared/types/plugin'
import { z } from 'zod'
import type { FfmpegOpHandle, FfmpegProgress } from '../capabilities/ffmpeg'
import type { HttpCapabilityHost } from '../capabilities/http'
import type { CapabilityHost } from '../capabilities/interface'
import { validateFinalizePatch, validateHttpPatch } from '../hooks/ctx-update'
import { classifyFfmpegOutput } from '../hooks/ffmpeg-path-classify'
import type { Phase } from '../hooks/phase-matrix'
import { phaseMatrix } from '../hooks/phase-matrix'
import type { RoleBand } from '../hooks/role-band'
import type { StagedEffectStore } from '../hooks/staged-effects'
import type { FfmpegStaging } from '../hooks/staging-dir'
import type {
BridgeCallMessage,
BridgeDeactivate,
BridgeExecuteCommandResult,
BridgeInitMessage,
HookName,
HostToWorker,
WorkerToHost,
} from './bridge-protocol'
import { BridgeExecuteCommandResultSchema } from './bridge-protocol'
import { currentPluginCallChain, type PluginCallChain } from './plugin-lane'
export interface CapabilityBridgeOptions {
pluginId: string
manifest: PluginManifest
bundleSource: string
capabilityHost: CapabilityHost
workerScriptPath: string
heapMB: number
appVersion: string
runtime: 'electron' | 'server'
hostLanguage: SupportedLocale
/** Generation of the executable and effective policy bound to this worker. */
permissionGeneration?: number
/**
* Spec §I30 — runtime permission gate. `required ∪ (optional ∩ granted)`.
* Methods whose permission isn't in this set throw
* `plugin.capability.unavailable` with `reason: 'permission_denied'`.
* When omitted, gating is disabled (back-compat for tests / pre-Phase-2
* call sites). PluginHost passes the resolved set per activation; grant
* changes deactivate the plugin so the next activation gets a fresh set.
*/
effectivePermissions?: ReadonlySet<string>
}
/**
* Capability → permission name(s). Capabilities not listed here are
* auto-injected (log, app, i18n, crypto, lifecycle, commands, config, ctx)
* and bypass the gate. For capabilities with both read/write split
* (`fs.task`), the array is matched as "any of these"; the dispatch
* method-level check is left to the capability host (spec §I30 is
* capability-scope, not method-scope, in Phase 1A).
*/
/**
* How a hook invocation was cancelled. `HookAbortBudget` (see
* `@core/plugin/hooks/abort`) aborts its signal with the literal reason
* `'timeout'` when the chain deadline elapses; anything else — policy change,
* admission close, caller cancellation — is a plain abort.
*/
type HookAbortKind = 'timeout' | 'aborted'
/**
* Reason strings posted into the plugin VM's `onabort` event. Deliberately a
* closed set: an arbitrary host-side `signal.reason` must never cross the
* sandbox boundary.
*/
const HOOK_ABORT_REASON: Record<HookAbortKind, string> = {
timeout: 'plugin hook timed out',
aborted: 'plugin hook aborted',
}
/**
* Margin between the caller's deadline and this bridge's defensive timer, so
* the two never race for the same tick. See `callHook`.
*/
const HOOK_DEFENSIVE_TIMEOUT_GRACE_MS = 500
function abortKindOf(signal: AbortSignal): HookAbortKind {
return signal.reason === 'timeout' ? 'timeout' : 'aborted'
}
function hookAbortError(
kind: HookAbortKind,
timeoutMs: number
): Error & { code?: string } {
const e: Error & { code?: string } =
kind === 'timeout'
? new Error(`plugin hook timed out after ${timeoutMs}ms`)
: new Error(HOOK_ABORT_REASON.aborted)
e.code = kind === 'timeout' ? 'plugin.hook.timeout' : 'plugin.hook.aborted'
return e
}
const CAPABILITY_PERMISSIONS: Record<string, ReadonlyArray<string>> = {
http: ['http'],
notify: ['notify'],
ffmpeg: ['ffmpeg'],
'fs.task': ['fs.task.read', 'fs.task.write'],
'fs.storage': ['fs.storage'],
storage: ['storage'],
metadata: ['metadata'],
}
export interface BridgeEvents {
onRegister?(kind: 'hook' | 'command', key: string): void
onFatal?(code: string, message: string): void
onReady?(): void
}
/**
* Discriminated union for `CapabilityBridge.setHookContext`.
*
* Plan B callers pass only `{ fsTaskHost, taskId }` — the matrix gate stays
* idle. Plan C callers pass the full set; TS rejects half-filled args (e.g.,
* `{ fsTaskHost, taskId, phase: 'beforeCreate' }` without staged/role/saveDir)
* at compile time so the matrix gate cannot trip into the "staged store
* missing" path silently.
*/
export type HookContextArgs =
| {
fsTaskHost: ReturnType<CapabilityHost['fsTaskFor']>
taskId: string
effectivePermissions?: ReadonlySet<string>
}
| {
fsTaskHost: ReturnType<CapabilityHost['fsTaskFor']>
taskId: string
phase: Phase
staged: StagedEffectStore
role: RoleBand
saveDir: string
pluginStorageRoot: string // required in Plan C — ffmpeg gate uses it for path-escape validation
staging?: FfmpegStaging // optional — only beforeFinalize ffmpeg paths need it
effectivePermissions?: ReadonlySet<string>
}
/**
* Error carrying a stable `code` string, used by the dispatch catch block and
* the worker bridge to marshal `{ code, message }` back to the plugin VM.
*
* Behaviorally equivalent to the previous `Object.assign(new Error(msg), {
* code })` idiom: `.message` and own-enumerable `.code` are identical and
* `.name` stays `'Error'` (the constructor deliberately does not override it),
* so existing consumers that read `.code` / `.message` are unaffected.
*/
class PluginCodedError extends Error {
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
// ---------------------------------------------------------------------------
// Zod schemas for argument validation
// ---------------------------------------------------------------------------
const logArgsSchema = z.tuple([z.string()]).rest(z.unknown())
const cryptoRandomBytesSchema = z.tuple([z.number().int().min(1).max(4096)])
const cryptoHashSchema = z.tuple([
// md5 is hash-only (legacy signing schemes, e.g. bilibili WBI); the guest
// type (virtual-module.d.ts) already advertises it. Keep this enum in sync.
z.enum(['md5', 'sha1', 'sha256', 'sha384', 'sha512']),
z.union([z.string(), z.instanceof(Uint8Array)]),
])
const cryptoHmacSchema = z.tuple([
z.enum(['sha1', 'sha256', 'sha384', 'sha512']),
z.instanceof(Uint8Array),
z.union([z.string(), z.instanceof(Uint8Array)]),
])
const cryptoAesSchema = z.tuple([
z.object({
mode: z.enum(['cbc', 'gcm']),
op: z.enum(['encrypt', 'decrypt']),
key: z.instanceof(Uint8Array),
iv: z.instanceof(Uint8Array),
data: z.instanceof(Uint8Array),
}),
])
const storageGetSchema = z.tuple([z.string()])
const storageSetSchema = z.tuple([z.string(), z.unknown()])
const storageCasSchema = z.tuple([z.string(), z.number(), z.unknown()])
const storageDeleteSchema = z.tuple([z.string()])
const storageKeysSchema = z.tuple([]).or(z.tuple([z.string().optional()]))
const metadataGetSchema = z.tuple([z.string()])
const metadataSetSchema = z.tuple([z.string(), z.unknown()])
const metadataDeleteSchema = z.tuple([z.string()])
const httpRequestSchema = z.object({
url: z.string(),
method: z.string().optional(),
// Spec §4 L1171: headers as Array<{name, value}>; preserves duplicates and
// case. Object form is accepted for back-compat (a few internal call sites
// historically passed Record; they are folded into the array form at
// dispatch time).
headers: z
.union([
z.array(z.object({ name: z.string(), value: z.string() })),
z.record(z.string(), z.string()),
])
.optional(),
body: z
.object({
type: z.enum(['string', 'json', 'bytes']),
data: z.unknown(),
})
.optional(),
responseType: z.enum(['text', 'json', 'bytes']),
timeoutMs: z.number().optional(),
maxBodyBytes: z.number().optional(),
redirect: z.enum(['follow', 'manual', 'error']).optional(),
cookies: z.enum(['jar', 'none']).optional(),
range: z
.object({ start: z.number().int().nonnegative(), end: z.number().int() })
.optional(),
proxy: z.string().optional(),
})
const notifyShowSchema = z.object({
id: z.string().optional(),
title: z.string(),
body: z.string(),
icon: z.enum(['info', 'success', 'error']).optional(),
urgency: z.enum(['low', 'normal', 'critical']).optional(),
})
const configGetSchema = z.tuple([z.string()])
const fsStorageReadSchema = z.tuple([
z.string(),
z.object({ encoding: z.enum(['utf8', 'binary']).optional() }).optional(),
])
const fsStorageWriteSchema = z.tuple([
z.string(),
z.union([z.string(), z.instanceof(Uint8Array)]),
z
.object({
overwrite: z.boolean().optional(),
encoding: z.enum(['utf8', 'binary']).optional(),
})
.optional(),
])
const fsStorageDeleteSchema = z.tuple([z.string()])
const fsStorageRenameSchema = z.tuple([z.string(), z.string()])
const fsStorageMkdirSchema = z.tuple([
z.string(),
z.object({ recursive: z.boolean().optional() }).optional(),
])
const ffmpegRunSchema = z.object({
argv: z.array(z.string()),
outputPath: z.string(),
timeoutMs: z.number().optional(),
expectedDurationMs: z.number().optional(),
})
const ffmpegTranscodeSchema = z.object({
input: z.string(),
output: z.string(),
videoCodec: z.string().optional(),
audioCodec: z.string().optional(),
timeoutMs: z.number().optional(),
expectedDurationMs: z.number().optional(),
})
const ffmpegExtractAudioSchema = z.object({
input: z.string(),
output: z.string(),
codec: z.enum(['mp3', 'aac', 'flac', 'wav']).optional(),
timeoutMs: z.number().optional(),
expectedDurationMs: z.number().optional(),
})
const ffmpegMergeStreamsSchema = z.object({
videoInput: z.string(),
audioInput: z.string(),
output: z.string(),
expectedDurationMs: z.number().nonnegative().optional(),
timeoutMs: z.number().optional(),
})
const ffmpegThumbnailSchema = z.object({
input: z.string(),
output: z.string(),
timestampSec: z.number().optional(),
width: z.number().optional(),
height: z.number().optional(),
timeoutMs: z.number().optional(),
})
const ffmpegProbeSchema = z.object({ path: z.string() })
const ffmpegOpIdSchema = z.tuple([z.string()])
const commandsExecuteSchema = z.tuple([z.string(), z.unknown()])
// ---------------------------------------------------------------------------
// FfmpegOpEntry — tracks a running ffmpeg operation
// ---------------------------------------------------------------------------
interface FfmpegOpEntry {
handle: FfmpegOpHandle<{ outputPath: string }>
taskId: string | null
lastProgress: FfmpegProgress | null
lastEmitTs: number
// Drive the progress iterable so lastProgress stays current.
// The pump loop runs asynchronously and self-terminates when the iterator ends.
}
interface HttpCallEntry {
controller: AbortController
hookScope: HookInvocationScopeV1 | null
commandScope: CommandInvocationScopeV1 | null
settled: Promise<void>
markSettled: () => void
}
export interface CapabilityBridgeOperationState {
capabilityCalls: number
httpOperations: number
commandCalls: number
hookCalls: number
deactivationCalls: number
ffmpegOperations: number
}
// ---------------------------------------------------------------------------
// CapabilityBridge
// ---------------------------------------------------------------------------
export class CapabilityBridge {
private readonly worker: Worker
private readonly log: ReturnType<CapabilityHost['createLog']>
private disposed = false
private forceDisposing = false
// Per-plugin lazy instances (constructed once on first use).
private pluginHttpHost: HttpCapabilityHost | null = null
private pluginFsStorage: ReturnType<CapabilityHost['fsStorageFor']> | null =
null
private pluginConfig: ReturnType<CapabilityHost['configFor']> | null = null
// Hook context slot — populated by Plan C BridgeHookEnter handling.
// Task 19: stays null; callers that need it get plugin.fs.task.not_available_outside_hook.
private currentFsTaskHost: ReturnType<CapabilityHost['fsTaskFor']> | null =
null
private currentTaskId: string | null = null
private currentEffectivePermissions: ReadonlySet<string> | null = null
private currentInvocationScope: HookInvocationScopeV1 | null = null
// Phase × Capability matrix fields (Task 8 / Plan C).
private currentPhase: Phase | 'idle' = 'idle'
private staged: StagedEffectStore | null = null
private hookRole: RoleBand | null = null
private hookSaveDir: string | null = null
// Task 13: ffmpeg staging dir (set by Plan C for beforeFinalize only).
private hookStaging: FfmpegStaging | null = null
// Task 2: per-plugin storage root, used by ffmpeg gate for path-escape validation.
private hookPluginStorageRoot: string | null = null
/** Test-only probe — kept on the public surface because TS lacks a clean way
* to expose private state to vitest without a cast. Do not use from production code. */
_debugPluginStorageRoot(): string | null {
return this.hookPluginStorageRoot
}
// ffmpeg running op registry
private readonly ffmpegOps = new Map<string, FfmpegOpEntry>()
private operation?: { context: OperationExecution; invocationId: number }
private readonly httpCalls = new Map<number, HttpCallEntry>()
private inFlightCapabilityCalls = 0
// Pending callPlugin() promises: correlation id → {resolve, reject}
private readonly pendingCommandCalls = new Map<
number,
{
commandScope: CommandInvocationScopeV1
resolve: (v: unknown) => void
reject: (e: Error) => void
}
>()
private nextCommandCallId = 1
// Pending runDeactivate() resolve/reject — at most one in-flight at a time.
private pendingDeactivate: {
resolve: () => void
reject: (e: Error) => void
} | null = null
// Pending callHook() resolve/reject — at most one in-flight at a time. Plan C
// serializes hook calls per plugin, so a single slot is sufficient.
private pendingHook: {
scope: HookInvocationScopeV1
resolve: (effects: HookEffectsV1) => void
reject: (e: Error) => void
detach: () => void
} | null = null
constructor(
private readonly opts: CapabilityBridgeOptions,
private readonly events: BridgeEvents = {}
) {
this.log = opts.capabilityHost.createLog(opts.pluginId)
this.worker = new Worker(opts.workerScriptPath, {
resourceLimits: {
maxOldGenerationSizeMb: opts.heapMB,
stackSizeMb: 1,
},
})
this.worker.on('message', (msg: WorkerToHost) => this.onMessage(msg))
this.worker.on('error', (e) => {
this.failPendingHook(
'plugin.hook.worker_crashed',
'plugin worker crashed during Hook invocation'
)
this.events.onFatal?.(
'plugin.runtime.worker_crashed',
(e as Error).message
)
})
this.worker.on('exit', (code) => {
if (!this.disposed && code !== 0) {
this.failPendingHook(
'plugin.hook.worker_crashed',
`plugin worker exited with code ${code}`
)
this.events.onFatal?.(
'plugin.runtime.worker_exited',
`worker exited with code ${code}`
)
}
})
this.sendInit()
}
private sendInit(): void {
const init: BridgeInitMessage = {
type: 'init',
pluginId: this.opts.pluginId,
manifest: this.opts.manifest,
bundleSource: prepareBundle(this.opts.bundleSource),
ffmpeg: {
available:
this.permitted('ffmpeg') &&
(this.opts.capabilityHost.ffmpeg?.available ?? false),
version: this.opts.capabilityHost.ffmpeg?.version,
},
app: this.opts.capabilityHost.appSnapshot(),
i18n: this.opts.capabilityHost.i18nSnapshot(this.opts.pluginId),
limits: { heapMB: this.opts.heapMB, stackKB: 256 },
}
this.worker.postMessage(init)
}
private async onMessage(msg: WorkerToHost): Promise<void> {
if (this.disposed) return
if (msg.type === 'ready') {
this.events.onReady?.()
return
}
if (msg.type === 'register') {
this.events.onRegister?.(msg.kind, msg.key)
return
}
if (msg.type === 'fatal') {
this.events.onFatal?.(msg.code, msg.message)
return
}
if (msg.type === 'event' && msg.event === 'hookExit') {
const parsed = HookExitMessageSchema.safeParse(msg)
if (!parsed.success) {
this.failPendingHook(
'plugin.hook.output_invalid',
'worker returned an invalid Hook exit message'
)
return
}
const pending = this.pendingHook
if (!pending || !sameHookScope(parsed.data, pending.scope)) {
this.events.onFatal?.(
'plugin.hook.concurrent_protocol_violation',
'stale or mismatched Hook exit ignored'
)
return
}
this.pendingHook = null
pending.detach()
try {
if (parsed.data.ok) {
this.applyHookEffects(parsed.data.effects)
pending.resolve(parsed.data.effects)
} else {
const e = new PluginCodedError(
parsed.data.error.code,
parsed.data.error.message
)
pending.reject(e)
}
} catch (error) {
const code =
(error as { code?: string }).code ?? 'plugin.hook.output_invalid'
pending.reject(
new PluginCodedError(code, (error as Error).message ?? String(error))
)
} finally {
this.clearHookContext()
}
return
}
if (msg.type === 'event' && msg.event === 'executeCommandResult') {
const parsed = BridgeExecuteCommandResultSchema.safeParse(msg)
if (!parsed.success) {
this.events.onFatal?.(
'plugin.command.protocol_violation',
'worker returned an invalid command result message'
)
return
}
const result: BridgeExecuteCommandResult = parsed.data
const pending = this.pendingCommandCalls.get(result.id)
if (pending) {
if (!sameCommandScope(result.commandScope, pending.commandScope)) {
this.events.onFatal?.(
'plugin.command.protocol_violation',
'worker returned a command result for another lane entry'
)
return
}
this.pendingCommandCalls.delete(result.id)
this.abortHttpCalls(
(entry) =>
entry.commandScope !== null &&
sameCommandScope(entry.commandScope, result.commandScope)
)
if (result.ok) {
pending.resolve(result.result)
} else {
const e: Error & { code?: string } = new Error(result.errorMessage)
e.code = result.errorCode
pending.reject(e)
}
}
return
}
if (msg.type === 'event' && msg.event === 'deactivateComplete') {
const pending = this.pendingDeactivate
this.pendingDeactivate = null
if (pending) {
if (msg.ok) {
pending.resolve()
} else {
const e: Error & { code?: string } = new Error(
`plugin deactivate handler failed: ${msg.errorCode ?? 'unknown'}`
)
e.code = msg.errorCode
pending.reject(e)
}
}
return
}
if (msg.type === 'call') {
this.inFlightCapabilityCalls += 1
try {
await this.dispatchCall(msg)
} finally {
this.inFlightCapabilityCalls -= 1
}
return
}
}
// -------------------------------------------------------------------------
// Main dispatch table
// -------------------------------------------------------------------------
async dispatchCall(msg: BridgeCallMessage): Promise<void> {
const parsedMessage = CapabilityCallMessageSchema.safeParse(msg)
if (!parsedMessage.success) {
if (Number.isSafeInteger(msg.id) && msg.id > 0) {
this.sendError(
msg.id,
'plugin.hook.input_invalid',
'invalid capability call message'
)
}
return
}
msg = parsedMessage.data
const messageScope = hookScopeFromMessage(msg)
if (this.currentInvocationScope) {
if (
!messageScope ||
!sameHookScope(messageScope, this.currentInvocationScope)
) {
this.sendError(
msg,
'plugin.hook.concurrent_protocol_violation',
'capability call does not belong to the active Hook invocation'
)
return
}
} else if (messageScope) {
this.sendError(
msg,
'plugin.hook.concurrent_protocol_violation',
'stale invocation-scoped capability call'
)
return
}
const commandScope = commandScopeFromMessage(msg)
if (commandScope) {
const pending = this.pendingCommandCalls.get(
commandScope.commandInvocationId
)
if (
!pending ||
!sameCommandScope(commandScope, pending.commandScope) ||
commandScope.callChain.plugins.at(-1) !== this.opts.pluginId
) {
this.sendError(
msg,
'plugin.command.protocol_violation',
'capability call does not belong to the active command lane entry'
)
return
}
}
if (
messageScope &&
this.opts.permissionGeneration !== undefined &&
messageScope.permissionGeneration !== this.opts.permissionGeneration
) {
this.sendError(
msg,
'plugin.runtime.permission_generation_stale',
'capability call uses a stale permission generation'
)
return
}
if (this.operation && msg.capability === 'commands') {
this.sendError(
msg,
'plugin.command.access_denied',
'Nested commands are unavailable during an operation'
)
return
}
// Spec §I30 — runtime permission gate. Rejects capability calls whose
// permission isn't in `effectivePermissions`. Auto-injected capabilities
// (log/app/i18n/crypto/lifecycle/commands/config/ctx) bypass.
if (!this.permitted(msg.capability)) {
this.sendError(
msg,
'plugin.capability.unavailable',
`${msg.capability}.${msg.method} denied: optional permission not granted`
)
return
}
// Phase × Capability matrix gate (I28).
// When a hook is active, look up the verdict and handle staged/disallowed
// paths before the normal dispatch table. When idle, fall through as before.
if (this.currentPhase !== 'idle') {
const verdict = phaseMatrix(msg.capability, msg.method, this.currentPhase)
if (verdict === 'disallowed') {
this.sendError(
msg,
'plugin.capability.disallowed_in_phase',
`${msg.capability}.${msg.method} not allowed in ${this.currentPhase}`
)
return
}
if (verdict === 'staged') {
await this.handleStaged(msg)
return
}
}
try {
let result: unknown
switch (msg.capability) {
case 'operation': {
const operation = this.operation
const scope = commandScopeFromMessage(msg)
if (
!operation ||
scope?.commandInvocationId !== operation.invocationId
)
throw new PluginCodedError(
'plugin.command.access_denied',
'Operation context is unavailable'
)
const permissions =
this.currentEffectivePermissions ??
this.opts.effectivePermissions ??
new Set(this.opts.manifest.permissions)
const required =
msg.method === 'probe'
? ['ffmpeg', 'files.selected.read']
: msg.method === 'mergeStreams'
? ['ffmpeg', 'files.selected.read', 'files.selected.write']
: msg.method === 'readText'
? ['files.selected.read']
: msg.method === 'writeText'
? ['files.selected.write']
: []
if (required.some((permission) => !permissions.has(permission)))
throw new PluginCodedError(
'plugin.capability.unavailable',
'Operation permission is unavailable'
)
result = await operation.context.dispatch(msg.method, msg.args)
break
}
case 'log':
result = await this.dispatchLog(msg)
break
case 'app':
result = await this.dispatchApp(msg)
break
case 'i18n':
result = await this.dispatchI18n(msg)
break
case 'http':
result = await this.dispatchHttp(msg)
break
case 'fs.task':
result = await this.dispatchFsTask(msg)
break
case 'fs.storage':
result = await this.dispatchFsStorage(msg)
break
case 'storage':
result = await this.dispatchStorage(msg)
break
case 'metadata':
result = await this.dispatchMetadata(msg)
break
case 'crypto':
result = await this.dispatchCrypto(msg)
break
case 'config':
result = await this.dispatchConfig(msg)
break
case 'lifecycle':
result = await this.dispatchLifecycle(msg)
break
case 'commands':
result = await this.dispatchCommands(msg)
break
case 'notify':
result = await this.dispatchNotify(msg)
break
case 'ffmpeg':
result = await this.dispatchFfmpeg(msg)
break
default:
return this.sendError(
msg,
'plugin.capability.unknown',
`unknown capability: ${msg.capability}`
)
}
this.sendResponse(msg, result)
} catch (e: unknown) {
const code = (e as { code?: string }).code ?? 'plugin.runtime.fault'
const message = (e as Error).message ?? String(e)
this.sendError(msg, code, message)
}
}
// -------------------------------------------------------------------------
// Response helpers
// -------------------------------------------------------------------------
private sendResponse(
source: number | BridgeCallMessage,
result: unknown
): void {
const id = typeof source === 'number' ? source : source.id
const hookScope =
typeof source === 'number' ? null : hookScopeFromMessage(source)
const commandScope =
typeof source === 'number' ? null : commandScopeFromMessage(source)
const base = { type: 'response' as const, id, ok: true as const, result }
const resp: HostToWorker = hookScope
? commandScope
? { ...base, ...hookScope, commandScope }
: { ...base, ...hookScope }
: commandScope
? { ...base, commandScope }
: base
this.worker.postMessage(resp)
}
private sendError(
source: number | BridgeCallMessage,
code: string,
message: string
): void {
const id = typeof source === 'number' ? source : source.id
const hookScope =
typeof source === 'number' ? null : hookScopeFromMessage(source)
const commandScope =
typeof source === 'number' ? null : commandScopeFromMessage(source)
const base = {
type: 'response' as const,
id,
ok: false as const,
error: { code, message },
}
const resp: HostToWorker = hookScope
? commandScope
? { ...base, ...hookScope, commandScope }
: { ...base, ...hookScope }
: commandScope
? { ...base, commandScope }
: base
this.worker.postMessage(resp)
}
/**
* Returns true if the capability's required permission(s) are in the
* resolved effective set. Capabilities not in CAPABILITY_PERMISSIONS are
* always permitted (auto-injected). When `effectivePermissions` is
* undefined, all capabilities are permitted (back-compat for tests).
*/
private permitted(capability: string): boolean {
const required = CAPABILITY_PERMISSIONS[capability]
if (!required) return true
const eff =
this.currentEffectivePermissions ?? this.opts.effectivePermissions
if (!eff) return true
return required.some((p) => eff.has(p))
}
// -------------------------------------------------------------------------
// log
// -------------------------------------------------------------------------
private dispatchLog(msg: BridgeCallMessage): void {
const parsed = logArgsSchema.safeParse(msg.args)
if (!parsed.success) {
throw new PluginCodedError(
'plugin.capability.bad_args',
`log.${msg.method}: invalid args`
)
}
const [text, ...rest] = parsed.data
const fields = rest[0] as Record<string, unknown> | undefined
const fn = (
this.log as unknown as Record<string, (m: string, f?: object) => void>
)[msg.method]
if (typeof fn !== 'function') {
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown log method: ${msg.method}`
)
}
fn.call(this.log, String(text), fields)
}
// -------------------------------------------------------------------------
// app — snapshot only; worker reads app.* from the init message.
// Provide it here for completeness in case worker calls it post-init.
// -------------------------------------------------------------------------
private dispatchApp(_msg: BridgeCallMessage): unknown {
return this.opts.capabilityHost.appSnapshot()
}
// -------------------------------------------------------------------------
// i18n
// -------------------------------------------------------------------------
private dispatchI18n(msg: BridgeCallMessage): unknown {
const snap = this.opts.capabilityHost.i18nSnapshot(this.opts.pluginId)
if (msg.method === 'snapshot') {
return snap
}
if (msg.method === 't') {
const [key, params] = msg.args as [string, Record<string, unknown>?]
const dict = {
...snap.fallbackDict,
...snap.currentDict,
}
let str = dict[key] ?? key
if (params) {
// Simple {{variable}} interpolation
str = str.replace(/\{\{(\w+)\}\}/g, (_: string, k: string) =>
String(params[k] ?? `{{${k}}}`)
)
}
return str
}
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown i18n method: ${msg.method}`
)
}
// -------------------------------------------------------------------------
// http
// -------------------------------------------------------------------------
private getPluginHttpHost(): HttpCapabilityHost {
if (!this.pluginHttpHost) {
const jar = this.opts.capabilityHost.cookieJarFor(this.opts.pluginId)
this.pluginHttpHost = this.opts.capabilityHost.http.scoped({
cookieJar: jar,
// Confine outbound requests to the manifest's declared hosts — the
// consent screen presents hostPermissions as the plugin's reach, so
// the runtime must enforce it (no declaration ⇒ no hosts, rule I29).
hostPermissions: this.opts.manifest.hostPermissions ?? [],
})
}
return this.pluginHttpHost
}
private async dispatchHttp(msg: BridgeCallMessage): Promise<unknown> {
const host = this.getPluginHttpHost()
const entry = this.beginHttpCall(msg)
try {
if (msg.method === 'request') {
const [opts] = msg.args
const parsed = httpRequestSchema.parse(opts)
// Normalize legacy Record-shaped headers to the spec-aligned array form
// expected by HttpCapabilityHost.request().
const headers = parsed.headers
const normalizedHeaders = Array.isArray(headers)
? headers
: headers !== undefined
? Object.entries(headers).map(([name, value]) => ({ name, value }))
: undefined
const forHost = {
...parsed,
headers: normalizedHeaders,
signal: entry.controller.signal,
}
// Cast body.data to the expected union — Zod z.unknown() is wider than
// HttpRequestBody.data which is string | object | Uint8Array.
return await host.request(forHost as Parameters<typeof host.request>[0])
}
if (msg.method === 'get') {
const [url, opts] = msg.args as [string, object?]
return await host.get(url, {
...(opts ?? {}),
signal: entry.controller.signal,
} as Parameters<HttpCapabilityHost['get']>[1])
}
if (msg.method === 'post') {
const [url, body, opts] = msg.args as [
string,
Parameters<HttpCapabilityHost['post']>[1],
object?,
]
return await host.post(url, body, {
...(opts ?? {}),
signal: entry.controller.signal,
} as Parameters<HttpCapabilityHost['post']>[2])
}
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown http method: ${msg.method}`
)
} finally {
this.httpCalls.delete(msg.id)
entry.markSettled()
}
}
private beginHttpCall(msg: BridgeCallMessage): HttpCallEntry {
if (this.httpCalls.has(msg.id)) {
throw new PluginCodedError(
'plugin.command.protocol_violation',
`duplicate capability call id: ${msg.id}`
)
}
let markSettled: () => void = () => undefined
const settled = new Promise<void>((resolve) => {
markSettled = resolve
})
const entry: HttpCallEntry = {
controller: new AbortController(),
hookScope: hookScopeFromMessage(msg),
commandScope: commandScopeFromMessage(msg),
settled,
markSettled,
}
this.httpCalls.set(msg.id, entry)
return entry
}
// -------------------------------------------------------------------------
// fs.task — requires hook context (Plan C). Task 19 throws when no host.
// -------------------------------------------------------------------------
private async dispatchFsTask(msg: BridgeCallMessage): Promise<unknown> {
if (!this.currentFsTaskHost) {
throw new PluginCodedError(
'plugin.fs.task.not_available_outside_hook',
'fs.task is only available inside a hook invocation; no hook context is active'
)
}
const host = this.currentFsTaskHost
switch (msg.method) {
case 'stat':
return host.stat()
case 'exists':
return host.exists()
case 'computeHash': {
const [alg] = msg.args as [Parameters<typeof host.computeHash>[0]]
return host.computeHash(alg)
}
case 'rename': {
const [newName] = msg.args as [string]
return host.rename(newName)
}
case 'openReader': {
// openReader() returns a FsTaskReader with read()/close() methods.
// The reader object cannot cross the worker boundary directly.
// For Task 19 we return a sentinel so tests can verify the call reaches
// the host. Task 20 worker proxy wraps this into a streaming API.
// A real cross-boundary reader protocol is deferred to Task 20/Plan C.
const [readerOpts] = msg.args as [{ offset?: number; length?: number }?]
const reader = host.openReader(readerOpts ?? {})
// Auto-close immediately in this stub; Task 20 tracks reader handles.
reader.close()
return { opened: true }
}
default:
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown fs.task method: ${msg.method}`
)
}
}
// -------------------------------------------------------------------------
// fs.storage — per-plugin, lazily constructed
// -------------------------------------------------------------------------
private getFsStorage(): ReturnType<CapabilityHost['fsStorageFor']> {
if (!this.pluginFsStorage) {
this.pluginFsStorage = this.opts.capabilityHost.fsStorageFor(
this.opts.pluginId
)
}
return this.pluginFsStorage
}
private async dispatchFsStorage(msg: BridgeCallMessage): Promise<unknown> {
const host = this.getFsStorage()
switch (msg.method) {
case 'exists': {
const [relPath] = msg.args as [string]
return host.exists(relPath)
}
case 'stat': {
const [relPath] = msg.args as [string]
return host.stat(relPath)
}
case 'read': {
const [relPath, opts] = fsStorageReadSchema.parse(msg.args)
return host.read(relPath, opts)
}
case 'write': {
const [relPath, data, opts] = fsStorageWriteSchema.parse(msg.args)
return host.write(relPath, data, opts)
}
case 'delete': {
const [relPath] = fsStorageDeleteSchema.parse(msg.args)
return host.delete(relPath)
}
case 'rename': {
const [src, dst] = fsStorageRenameSchema.parse(msg.args)
return host.rename(src, dst)
}
case 'mkdir': {
const [relPath, opts] = fsStorageMkdirSchema.parse(msg.args)
return host.mkdir(relPath, opts)
}
default:
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown fs.storage method: ${msg.method}`
)
}
}
// -------------------------------------------------------------------------
// storage — shared SQLite KV; pluginId closed over
// -------------------------------------------------------------------------
private async dispatchStorage(msg: BridgeCallMessage): Promise<unknown> {
const host = this.opts.capabilityHost.storage
const pluginId = this.opts.pluginId
switch (msg.method) {
case 'get': {
const [key] = storageGetSchema.parse(msg.args)
return host.get(pluginId, key)
}
case 'set': {
const [key, value] = storageSetSchema.parse(msg.args)
return host.set(pluginId, key, value)
}
case 'compareAndSet': {
const [key, expectedVersion, value] = storageCasSchema.parse(msg.args)
return host.compareAndSet(pluginId, key, expectedVersion, value)
}
case 'delete': {
const [key] = storageDeleteSchema.parse(msg.args)
return host.delete(pluginId, key)
}
case 'keys': {
const args = storageKeysSchema.safeParse(msg.args)
const prefix = args.success
? (args.data[0] as string | undefined)
: undefined
return host.keys(pluginId, prefix)
}
default:
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown storage method: ${msg.method}`
)
}
}
// -------------------------------------------------------------------------
// metadata — requires hook context (taskId). Task 19 throws when none.
// -------------------------------------------------------------------------
private async dispatchMetadata(msg: BridgeCallMessage): Promise<unknown> {
if (!this.currentTaskId) {
throw new PluginCodedError(
'plugin.metadata.not_available_outside_hook',
'metadata is only available inside a hook invocation; no task context is active'
)
}
const host = this.opts.capabilityHost.metadata
const pluginId = this.opts.pluginId
const taskId = this.currentTaskId
switch (msg.method) {
case 'get': {
const [key] = metadataGetSchema.parse(msg.args)
return host.get(taskId, pluginId, key)
}
case 'has': {
const [key] = metadataGetSchema.parse(msg.args)
return host.has(taskId, pluginId, key)
}
case 'getAll':
return host.getAll(taskId, pluginId)
case 'keys':
return host.keys(taskId, pluginId)
case 'set': {
const [key, value] = metadataSetSchema.parse(msg.args)
return host.set(taskId, pluginId, key, value)
}
case 'delete': {
const [key] = metadataDeleteSchema.parse(msg.args)
return host.delete(taskId, pluginId, key)
}
default:
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown metadata method: ${msg.method}`
)
}
}
// -------------------------------------------------------------------------
// crypto — stateless
// -------------------------------------------------------------------------
private async dispatchCrypto(msg: BridgeCallMessage): Promise<unknown> {
const host = this.opts.capabilityHost.crypto
switch (msg.method) {
case 'randomBytes': {
const [n] = cryptoRandomBytesSchema.parse(msg.args)
return host.randomBytes(n)
}
case 'hash': {
const [alg, input] = cryptoHashSchema.parse(msg.args)
return host.hash(alg, input)
}
case 'hmac': {
const [alg, key, input] = cryptoHmacSchema.parse(msg.args)
return host.hmac(alg, key, input)
}
case 'aes': {
const [params] = cryptoAesSchema.parse(msg.args)
return host.aes(params)
}
default:
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown crypto method: ${msg.method}`
)
}
}
// -------------------------------------------------------------------------
// config — per-plugin, lazily constructed
// -------------------------------------------------------------------------
private getConfig(): ReturnType<CapabilityHost['configFor']> {
if (!this.pluginConfig) {
this.pluginConfig = this.opts.capabilityHost.configFor(this.opts.pluginId)
}
return this.pluginConfig
}
private async dispatchConfig(msg: BridgeCallMessage): Promise<unknown> {
const host = this.getConfig()
switch (msg.method) {
case 'get': {
const [key] = configGetSchema.parse(msg.args)
return host.get(key)
}
case 'getRaw': {
const [key] = configGetSchema.parse(msg.args)
return host.getRaw(key)
}
case 'getAll':
return host.getAll()
default:
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown config method: ${msg.method}`
)
}
}
// -------------------------------------------------------------------------
// lifecycle
// Plan B: onDeactivate cannot round-trip a callback reference across the
// worker boundary. Return {ok:true} immediately. Task 23 / Plan C will send
// a BridgeDeactivate event that the worker handles by calling its stored fn.
// -------------------------------------------------------------------------
private dispatchLifecycle(msg: BridgeCallMessage): unknown {
if (msg.method === 'onDeactivate') {
// Stub: worker stores the fn locally; host will signal via event on dispose.
// Task 23 wires the full deactivation protocol.
return { registered: true }
}
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown lifecycle method: ${msg.method}`
)
}
// -------------------------------------------------------------------------
// commands
// register: handled worker-side only (via 'register' event). Bridge just
// records registrations. execute: cross-plugin dispatch via CommandsCapabilityHost.
// -------------------------------------------------------------------------
private async dispatchCommands(msg: BridgeCallMessage): Promise<unknown> {
if (msg.method === 'execute') {
const [commandId, args] = commandsExecuteSchema.parse(msg.args)
return this.opts.capabilityHost.commands.execute(
this.opts.pluginId,
commandId,
args,
commandScopeFromMessage(msg)?.callChain
)
}
// 'register' is handled worker-side (the worker sends a 'register' event).
// The bridge does not need to do anything here.
if (msg.method === 'register') {
return { registered: true }
}
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown commands method: ${msg.method}`
)
}
// -------------------------------------------------------------------------
// notify
// -------------------------------------------------------------------------
private async dispatchNotify(msg: BridgeCallMessage): Promise<unknown> {
if (msg.method === 'show') {
const [opts] = msg.args
const parsed = notifyShowSchema.parse(opts)
return this.opts.capabilityHost.notify.show(this.opts.pluginId, parsed)
}
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown notify method: ${msg.method}`
)
}
// -------------------------------------------------------------------------
// ffmpeg — op handle pattern
//
// Launching methods (probe, run, transcode, extractAudio, mergeStreams,
// generateThumbnail): kick off the operation, register the handle in
// ffmpegOps, start a background pump loop that keeps lastProgress current,
// return { opId } immediately.
//
// op.result.await(opId): awaits handle.result; resolves with result payload
// or rejects with FfmpegError.
// op.progress.pull(opId): returns lastProgress (or keep-alive after 1s idle).
// op.abort(opId): calls handle.abort().
// -------------------------------------------------------------------------
private registerFfmpegHandle(
handle: FfmpegOpHandle<{ outputPath: string }>
): string {
// The command may fail before guest code awaits the operation result.
void handle.result.catch(() => undefined)
const opId = handle.id
const entry: FfmpegOpEntry = {
handle,
taskId: this.currentTaskId,
lastProgress: null,
lastEmitTs: 0,
}
this.ffmpegOps.set(opId, entry)
// Pump loop: drive the progress AsyncIterable to keep lastProgress current.
;(async () => {
try {
for await (const p of handle.progress) {
const e = this.ffmpegOps.get(opId)
if (e) {
e.lastProgress = p
e.lastEmitTs = Date.now()
}
}
} catch {
// progress iterable closed on abort/error; handle.result carries the error
} finally {
// Do not remove from map here — caller may still await result.
}
})()
return opId
}
/**
* Phase × kind gate for ffmpeg output paths. Classifies the user-supplied
* output against (hookSaveDir, hookPluginStorageRoot), then applies the
* (phase, kind) table from spec §3.1 — saveDir is staged-only in
* beforeFinalize, pluginStorage is immediate in all phases, anything else
* is rejected. Throws AppError-shaped { code, message } pairs that the
* dispatch catch block surfaces as plugin.ffmpeg.destination_phase_disallowed.
*
* Pre-Plan-C (orchestrator wires real pluginStorageRoot in PR-2), call sites
* pass `pluginStorageRoot: ''`. Empty pluginStorageRoot short-circuits the
* gate so legacy tests keep passing; once PR-2 lands, every Plan-C call site
* has a real root and the gate becomes effective everywhere.
*/
private async gateFfmpegOutput(userOutput: string): Promise<string> {
if (this.currentPhase === 'idle') return userOutput
if (!this.hookSaveDir || !this.hookPluginStorageRoot) {
// Plan-B context or pre-PR-2 placeholder — gate inactive.
return userOutput
}
const kind = classifyFfmpegOutput(
userOutput,
this.hookSaveDir,
this.hookPluginStorageRoot
)
if (kind === 'pluginStorage') return userOutput
if (kind === 'other') {
throw new PluginCodedError(
'plugin.ffmpeg.destination_phase_disallowed',
`ffmpeg output ${userOutput} resolves outside saveDir and plugin storage`
)
}
// kind === 'saveDir' — beforeFinalize + staging only.
if (this.currentPhase !== 'beforeFinalize') {
throw new PluginCodedError(
'plugin.ffmpeg.destination_phase_disallowed',
`ffmpeg cannot write to saveDir in ${this.currentPhase}; move this call into beforeFinalize or write to plugin storage`
)
}
if (!this.hookStaging) {
throw new PluginCodedError(
'plugin.ffmpeg.destination_phase_disallowed',
'ffmpeg saveDir write in beforeFinalize requires a FfmpegStaging in HookContextArgs'
)
}
const staged = this.hookStaging.redirectOutput(userOutput)
// ensureDir must precede assertQuota: assertQuota does a readdir of the staging dir.
await this.hookStaging.ensureDir()
await this.hookStaging.assertQuota()
return staged
}
private async dispatchFfmpeg(msg: BridgeCallMessage): Promise<unknown> {
if (
this.opts.manifest.contributes.operations &&
this.currentPhase === 'idle'
)
throw new PluginCodedError(
'plugin.command.access_denied',
'Selected-file access requires an operation context'
)
const ffmpeg = this.opts.capabilityHost.ffmpeg
// ── op lifecycle methods ───────────────────────────────────────────────
if (msg.method === 'op.result.await') {
const [opId] = ffmpegOpIdSchema.parse(msg.args)
const entry = this.ffmpegOps.get(opId)
if (!entry) {
throw new PluginCodedError(
'plugin.ffmpeg.op_not_found',
`ffmpeg op not found: ${opId}`
)
}
try {
const result = await entry.handle.result
this.ffmpegOps.delete(opId)
return result
} catch (e: unknown) {
this.ffmpegOps.delete(opId)
throw e
}
}
if (msg.method === 'op.progress.pull') {
const [opId] = ffmpegOpIdSchema.parse(msg.args)
const entry = this.ffmpegOps.get(opId)
if (!entry) {
throw new PluginCodedError(
'plugin.ffmpeg.op_not_found',
`ffmpeg op not found: ${opId}`
)
}
if (entry.lastProgress !== null) {
return entry.lastProgress
}
// Keep-alive: wait up to 1s for a progress event to arrive.
return new Promise<FfmpegProgress | null>((resolve) => {
let poll: ReturnType<typeof setInterval>
const deadline = setTimeout(() => {
clearInterval(poll)
resolve(null)
}, 1_000)
poll = setInterval(() => {
const e = this.ffmpegOps.get(opId)
if (e?.lastProgress !== null) {
clearTimeout(deadline)
clearInterval(poll)
resolve(e?.lastProgress ?? null)
}
}, 50)
})
}
if (msg.method === 'op.abort') {
const [opId] = ffmpegOpIdSchema.parse(msg.args)
const entry = this.ffmpegOps.get(opId)
if (!entry) {
// Already completed or never started — not an error.
return { aborted: false }
}
entry.handle.abort()
return { aborted: true }
}
// ── launch methods ─────────────────────────────────────────────────────
if (msg.method === 'probe') {
const [opts] = msg.args
const parsed = ffmpegProbeSchema.parse(opts)
// probe returns a Promise<MediaInfo> directly, not an op handle.
return ffmpeg.probe(parsed)
}
if (msg.method === 'run') {
const [opts] = msg.args
const parsed = ffmpegRunSchema.parse(opts)
parsed.outputPath = await this.gateFfmpegOutput(parsed.outputPath)
const handle = ffmpeg.run(parsed)
const opId = this.registerFfmpegHandle(handle)
return { opId }
}
if (msg.method === 'transcode') {
const [opts] = msg.args
const parsed = ffmpegTranscodeSchema.parse(opts)
parsed.output = await this.gateFfmpegOutput(parsed.output)
const handle = ffmpeg.transcode(parsed)
const opId = this.registerFfmpegHandle(handle)
return { opId }
}
if (msg.method === 'extractAudio') {
const [opts] = msg.args
const parsed = ffmpegExtractAudioSchema.parse(opts)
parsed.output = await this.gateFfmpegOutput(parsed.output)
const handle = ffmpeg.extractAudio(parsed)
const opId = this.registerFfmpegHandle(handle)
return { opId }
}
if (msg.method === 'mergeStreams') {
const [opts] = msg.args
const parsed = ffmpegMergeStreamsSchema.parse(opts)
parsed.output = await this.gateFfmpegOutput(parsed.output)
const handle = ffmpeg.mergeStreams(parsed)
const opId = this.registerFfmpegHandle(handle)
return { opId }
}
if (msg.method === 'generateThumbnail') {
const [opts] = msg.args
const parsed = ffmpegThumbnailSchema.parse(opts)
parsed.output = await this.gateFfmpegOutput(parsed.output)
const handle = ffmpeg.generateThumbnail(parsed)
const opId = this.registerFfmpegHandle(handle)
return { opId }
}
throw new PluginCodedError(
'plugin.capability.unavailable',
`unknown ffmpeg method: ${msg.method}`
)
}
// -------------------------------------------------------------------------
// Plan C injection points
// -------------------------------------------------------------------------
/**
* Called by Plan C when a hook invocation begins. Sets the fs.task,
* metadata, phase, staged-effect store, role and saveDir context for the
* duration of the hook.
*
* Accepts either:
* - `{ fsTaskHost, taskId }` — Plan B context only (matrix gate inactive)
* - `{ fsTaskHost, taskId, phase, staged, role, saveDir }` — full Plan C
* context (matrix gate active). The four Plan C fields are atomic: TS
* rejects partial Plan C args at compile time.
*/
setHookContext(args: HookContextArgs): void {
this.currentFsTaskHost = args.fsTaskHost
this.currentTaskId = args.taskId
this.currentEffectivePermissions = args.effectivePermissions ?? null
if ('phase' in args) {
this.currentPhase = args.phase
this.staged = args.staged
this.hookRole = args.role
this.hookSaveDir = args.saveDir
this.hookPluginStorageRoot = args.pluginStorageRoot
this.hookStaging = args.staging ?? null
} else {
this.currentPhase = 'idle'
this.staged = null
this.hookRole = null
this.hookSaveDir = null
this.hookPluginStorageRoot = null
this.hookStaging = null
}
}
/**
* Called by PluginHost when the host locale changes. Posts a `localeChange`
* event to the worker so the plugin runtime can update its translation dict.
*/
postLocaleChange(
lang: string,
dir: 'ltr' | 'rtl',
dict: Record<string, string>
): void {
if (this.disposed) return
this.worker.postMessage({
type: 'event',
event: 'localeChange',
lang,
dir,
dict,
})
}
/** Cancel only the invocation captured by callHook's signal/deadline. */
private notifyAbort(scope: HookInvocationScopeV1, kind: HookAbortKind): void {
if (
this.disposed ||
!this.currentInvocationScope ||
!sameHookScope(this.currentInvocationScope, scope)
) {
return
}
this.worker.postMessage({
type: 'event',
event: 'abort',
...scope,
reason: HOOK_ABORT_REASON[kind],
})
this.abortHttpCalls(
(entry) =>
entry.hookScope !== null && sameHookScope(entry.hookScope, scope)
)
}
/**
* Called by Plan C (or by the hookExit event handler) to clear hook context.
*/
clearHookContext(): void {
const scope = this.currentInvocationScope
if (scope) {
this.abortHttpCalls(
(entry) =>
entry.hookScope !== null && sameHookScope(entry.hookScope, scope)
)
}
this.currentFsTaskHost = null
this.currentTaskId = null
this.currentEffectivePermissions = null
this.currentInvocationScope = null
this.currentPhase = 'idle'
this.staged = null
this.hookRole = null
this.hookSaveDir = null
this.hookPluginStorageRoot = null
this.hookStaging = null
}
private failPendingHook(code: string, message: string): void {
const pending = this.pendingHook
this.pendingHook = null
if (pending) {
pending.detach()
pending.reject(new PluginCodedError(code, message))
}
this.clearHookContext()
}
private createCompatibilityHookScope(): HookInvocationScopeV1 {
const invocationId = randomUUID()
return {
invocationId,
callChainId: invocationId,
permissionGeneration: this.opts.permissionGeneration ?? 0,
}
}
/**
* Applies a validated Hook exit as one Host-side unit. The Worker never
* sends ctx.update or Hook metadata writes as asynchronous capability calls;
* therefore no effect can be overtaken by hookExit.
*/
private applyHookEffects(raw: HookEffectsV1): void {
const effects = HookEffectsV1Schema.parse(raw)
const phase = this.currentPhase
if (phase !== 'beforeCreate' && phase !== 'beforeFinalize') {
if (
effects.contextPatches.length > 0 ||
effects.metadataOperations.length > 0
) {
throw new PluginCodedError(
'plugin.hook.output_invalid',
`mutating effects are not allowed in ${phase}`
)
}
return
}
if (!this.staged || !this.hookRole || this.hookSaveDir === null) {
throw new PluginCodedError(
'plugin.hook.output_invalid',
'pre-Hook effects require a complete staged Host context'
)
}
if (
this.hookRole === 'audit' &&
(effects.contextPatches.length > 0 ||
effects.metadataOperations.length > 0)
) {
throw new PluginCodedError(
'plugin.hook.permission_denied',
'audit Hooks cannot mutate context or metadata'
)
}
if (effects.metadataOperations.length > 0 && !this.permitted('metadata')) {
throw new PluginCodedError(
'plugin.hook.permission_denied',
'Hook metadata writes require the metadata permission'
)
}
const validationOptions = {
permissions: new Set(
this.opts.effectivePermissions ?? this.opts.manifest.permissions ?? []
) as ReadonlySet<string>,
role: this.hookRole,
hook: phase,
saveDir: this.hookSaveDir,
}
const patches = effects.contextPatches.map((patch) =>
phase === 'beforeCreate'
? validateHttpPatch(patch, validationOptions)
: validateFinalizePatch(patch, validationOptions)
)
for (const patch of patches) {
if (phase === 'beforeCreate') {
this.staged.appendHttp(
this.opts.pluginId,
this.hookRole,
patch as Parameters<typeof this.staged.appendHttp>[2]
)
} else {
this.staged.setFinalizePath((patch as { filePath: string }).filePath)
}
}
for (const operation of effects.metadataOperations) {
this.staged.appendMeta({
pluginId: this.opts.pluginId,
...operation,
size:
operation.op === 'set'
? Buffer.byteLength(JSON.stringify(operation.value))
: undefined,
})
}
}
/**
* Routes a dispatch call to the staged-effect store when the phase matrix
* returns `'staged'`. Validates the patch/op and appends to the store.
* Sends a response (ok or error) to the worker.
*/
private async handleStaged(msg: BridgeCallMessage): Promise<void> {
if (!this.staged || !this.hookRole || this.hookSaveDir === null) {
this.sendError(msg, 'plugin.runtime.fault', 'staged store missing')
return
}
const perms = new Set(this.opts.manifest.permissions ?? [])
const opts = {
permissions: perms as ReadonlySet<string>,
role: this.hookRole,
hook: (this.currentPhase === 'beforeCreate'
? 'beforeCreate'
: 'beforeFinalize') as 'beforeCreate' | 'beforeFinalize',
saveDir: this.hookSaveDir,
}
if (msg.capability === 'ctx' && msg.method === 'update') {
try {
const patch = msg.args[0]
const validated =
this.currentPhase === 'beforeCreate'
? validateHttpPatch(patch, opts)
: validateFinalizePatch(patch, opts)
if (this.currentPhase === 'beforeCreate') {
this.staged.appendHttp(
this.opts.pluginId,
this.hookRole,
validated as Parameters<typeof this.staged.appendHttp>[2]
)
} else {
this.staged.setFinalizePath(
(validated as { filePath: string }).filePath
)
}
this.sendResponse(msg, undefined)
} catch (e: unknown) {
const code = (e as { code?: string }).code ?? 'plugin.runtime.fault'
const message = (e as Error).message ?? String(e)
this.sendError(msg, code, message)
}
return
}
if (msg.capability === 'metadata') {
if (msg.method === 'set') {
this.staged.appendMeta({
pluginId: this.opts.pluginId,
op: 'set',
key: msg.args[0] as string,
value: msg.args[1],
})
this.sendResponse(msg, undefined)
return
}
if (msg.method === 'delete') {
this.staged.appendMeta({
pluginId: this.opts.pluginId,
op: 'delete',
key: msg.args[0] as string,
})
this.sendResponse(msg, undefined)
return
}
}
// Unrecognized staged dispatch — should not happen if matrix is correct.
this.sendError(
msg,
'plugin.runtime.fault',
`staged dispatch not implemented for ${msg.capability}.${msg.method}`
)
}
async callOperation(
commandId: string,
args: unknown,
context: OperationExecution
): Promise<unknown> {
context.signal.throwIfAborted()
if (this.operation) throw new Error('Operation already running')
const invocationId = this.nextCommandCallId
this.operation = { context, invocationId }
const abort = () => {
context.seal()
this.worker.postMessage({
type: 'event',
event: 'operationAbort',
jobId: context.jobId,
} satisfies HostToWorker)
const pending = this.pendingCommandCalls.get(invocationId)
this.pendingCommandCalls.delete(invocationId)
pending?.reject(new Error('pluginOperations.cancelled'))
}
context.signal.addEventListener('abort', abort, { once: true })
try {
const result = await this.callPlugin(commandId, args, 60 * 60_000)
await context.drain()
context.signal.throwIfAborted()
return result
} catch (error) {
context.seal()
throw error
} finally {
context.signal.removeEventListener('abort', abort)
this.operation = undefined
}
}
/**
* Invoke a registered command inside the plugin VM and await its result.
* The command must have been registered during activation via commands.register().
* Used by test-helpers.ts and future Plan C invocations.
*
* @param commandId Fully-qualified command id (e.g. 'test.allcaps.echoAll').
* @param args Arguments passed to the command handler.
* @param timeoutMs Max wait time (default: 10s).
*/
callPlugin(
commandId: string,
args: unknown,
timeoutMs = 10_000,
callChain?: PluginCallChain
): Promise<unknown> {
if (
this.opts.manifest.contributes.commands?.some(
(command) =>
command.id === commandId && command.execution === 'operation'
) &&
this.operation?.invocationId !== this.nextCommandCallId
)
return Promise.reject(
new PluginCodedError(
'plugin.command.access_denied',
'Operation requires host authorization'
)
)
const id = this.nextCommandCallId++
const laneCallChain = callChain ?? currentPluginCallChain()
const commandScope: CommandInvocationScopeV1 = {
commandInvocationId: id,
callChain: laneCallChain
? { id: laneCallChain.id, plugins: [...laneCallChain.plugins] }
: { id: randomUUID(), plugins: [this.opts.pluginId] },
}
return new Promise<unknown>((resolve, reject) => {
const timer = setTimeout(() => {
if (this.pendingCommandCalls.has(id)) {
this.pendingCommandCalls.delete(id)
this.abortHttpCalls(
(entry) =>
entry.commandScope !== null &&
sameCommandScope(entry.commandScope, commandScope)
)
reject(
new Error(
`callPlugin('${commandId}') timed out after ${timeoutMs}ms`
)
)
}
}, timeoutMs)
this.pendingCommandCalls.set(id, {
commandScope,
resolve: (v) => {
clearTimeout(timer)
resolve(v)
},
reject: (e) => {
clearTimeout(timer)
reject(e)
},
})
const msg: HostToWorker = {
type: 'event',
event: 'executeCommand',
id,
commandId,
args,
commandScope,
...(this.operation?.invocationId === id
? { operation: { jobId: this.operation.context.jobId } }
: {}),
}
this.worker.postMessage(msg)
})
}
/**
* Signal the worker to run its registered `onDeactivate` handlers, then
* await `BridgeDeactivateComplete` with a 2-second budget. Throws if the
* worker reports an error or if the budget is exceeded.
*
* Must be called BEFORE `dispose()` so the worker thread is still alive.
*/
runDeactivate(budgetMs = 2_000): Promise<void> {
if (this.disposed) return Promise.resolve()
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
if (this.pendingDeactivate) {
this.pendingDeactivate = null
const e: Error & { code?: string } = new Error(
`plugin deactivate timed out after ${budgetMs}ms`
)
e.code = 'plugin.lifecycle.deactivate_timeout'
reject(e)
}
}, budgetMs)
this.pendingDeactivate = {
resolve: () => {
clearTimeout(timer)
resolve()
},
reject: (e) => {
clearTimeout(timer)
reject(e)
},
}
const msg: BridgeDeactivate = { type: 'event', event: 'deactivate' }
this.worker.postMessage(msg)
})
}
/**
* Plan C — invoke a registered hook in the worker and await its completion.
*
* Posts a `hookEnter` event with the supplied taskId; the worker dispatches
* to its registered handler (stored via `hooks.<name>(fn)` during activation)
* and replies with `hookExit { ok, errorCode? }` when the handler resolves
* or throws.
*
* The caller MUST call `setHookContext(...)` before this method so capability
* dispatch (fs.task, metadata, ctx.update) routes correctly. The bridge
* clears the context slot inside the `hookExit` handler.
*
* @param hook Hook name as registered by the plugin.
* @param taskId Stable task id to send in `hookEnter`.
* @param signal AbortSignal from the host-owned HookAbortBudget. A
* deadline overrun (reason `'timeout'`) rejects with
* `plugin.hook.timeout`; any other abort rejects with
* `plugin.hook.aborted`.
* @param timeoutMs Defensive timeout in case the worker never replies
* (e.g. crash). Armed at `timeoutMs` plus a grace margin
* so it never races the caller's own deadline.
*/
callHook(
hook: HookName,
taskId: string,
signal: AbortSignal,
timeoutMs: number,
ctxPayload?: Record<string, unknown>,
metadataSnapshot?: Record<string, unknown>,
requestedScope?: HookInvocationScopeV1
): Promise<HookEffectsV1> {
if (this.disposed) {
return Promise.reject(
new PluginCodedError(
'plugin.runtime.bridge_disposed',
'bridge disposed'
)
)
}
if (this.pendingHook) {
return Promise.reject(
new PluginCodedError(
'plugin.hook.concurrent',
`concurrent hook invocation rejected (one already in flight)`
)
)
}
const scope = requestedScope ?? this.createCompatibilityHookScope()
if (
this.opts.permissionGeneration !== undefined &&
scope.permissionGeneration !== this.opts.permissionGeneration
) {
this.clearHookContext()
return Promise.reject(
new PluginCodedError(
'plugin.runtime.permission_generation_stale',
'Hook invocation uses a stale permission generation'
)
)
}
const payload = normalizeBeforeFinalizeBtSource(hook, {
...(ctxPayload ?? {}),
schemaVersion: HOOK_SCHEMA_VERSION,
invocationId: scope.invocationId,
taskId,
})
const enter = HookEnterMessageSchema.safeParse({
type: 'event',
event: 'hookEnter',
hook,
...scope,
taskId,
ctxPayload: payload,
metadataSnapshot: metadataSnapshot ?? {},
})
if (!enter.success) {
this.clearHookContext()
return Promise.reject(
new PluginCodedError(
'plugin.hook.input_invalid',
`invalid ${hook} context: ${enter.error.issues[0]?.message ?? 'schema mismatch'}`
)
)
}
return new Promise<HookEffectsV1>((resolve, reject) => {
const settleAborted = (kind: HookAbortKind): void => {
if (
!this.pendingHook ||
!sameHookScope(this.pendingHook.scope, scope)
) {
return
}
this.notifyAbort(scope, kind)
this.pendingHook.detach()
this.pendingHook = null
this.clearHookContext()
reject(hookAbortError(kind, timeoutMs))
}
// The caller's budget and this defensive timer watch the same deadline.
// Without the grace margin the two fire in the same tick and whichever
// wins decides the message, so a plain deadline overrun could surface as
// the uninformative 'plugin hook aborted'. The caller's signal is the
// authority; this timer only covers callers that pass none.
const onAbort = () => settleAborted(abortKindOf(signal))
const timer = setTimeout(
() => settleAborted('timeout'),
timeoutMs + HOOK_DEFENSIVE_TIMEOUT_GRACE_MS
)
if (signal.aborted) {
clearTimeout(timer)
this.clearHookContext()
reject(hookAbortError(abortKindOf(signal), timeoutMs))
return
}
signal.addEventListener('abort', onAbort, { once: true })
this.currentInvocationScope = scope
if (this.currentPhase === 'idle') this.currentPhase = hook
this.pendingHook = {
scope,
resolve,
reject,
detach: () => {
clearTimeout(timer)
signal.removeEventListener('abort', onAbort)
},
}
this.worker.postMessage(enter.data)
})
}
/** Worker access for host lifecycle management and diagnostics. */
getWorker(): Worker {
return this.worker
}
/** Snapshot used by idle recycling and diagnostics; no mutable state leaks. */
operationState(): CapabilityBridgeOperationState {
return {
capabilityCalls: this.inFlightCapabilityCalls,
httpOperations: this.httpCalls.size,
commandCalls: this.pendingCommandCalls.size,
hookCalls: this.pendingHook ? 1 : 0,
deactivationCalls: this.pendingDeactivate ? 1 : 0,
ffmpegOperations: this.ffmpegOps.size,
}
}
/** True while the bridge owns any guest entry, capability lease, or op. */
hasInFlightOperations(): boolean {
const state = this.operationState()
return Object.values(state).some((count) => count > 0)
}
/** Abort and drain every Host-owned writer bound to one task artifact. */
async quiesceTaskWriters(taskId: string): Promise<void> {
const matches = [...this.ffmpegOps.entries()].filter(
([, entry]) => entry.taskId === taskId
)
for (const [, entry] of matches) entry.handle.abort()
await Promise.allSettled(matches.map(([, entry]) => entry.handle.result))
for (const [opId] of matches) this.ffmpegOps.delete(opId)
}
async dispose(force = false): Promise<void> {
if (force) this.forceDisposing = true
if (this.disposed) {
if (force) await this.worker.terminate()
return
}
this.disposed = true
this.failPendingHook('plugin.runtime.bridge_disposed', 'bridge disposed')
const httpCalls = this.abortHttpCalls(() => true)
// Abort any running ffmpeg ops
for (const entry of this.ffmpegOps.values()) {
entry.handle.abort()
}
this.ffmpegOps.clear()
if (!force) {
await Promise.allSettled(httpCalls.map((entry) => entry.settled))
if (!this.forceDisposing)
this.worker.postMessage({ type: 'event', event: 'shutdown' })
}
await this.worker.terminate()
}
private abortHttpCalls(
predicate: (entry: HttpCallEntry) => boolean
): HttpCallEntry[] {
const matches = [...this.httpCalls.values()].filter(predicate)
for (const entry of matches) entry.controller.abort('host_scope_closed')
return matches
}
}
function normalizeBeforeFinalizeBtSource(
hook: HookName,
payload: Record<string, unknown>
): Record<string, unknown> {
if (hook !== 'beforeFinalize') return payload
const task = payload.task
if (!task || typeof task !== 'object' || Array.isArray(task)) return payload
const taskRecord = task as Record<string, unknown>
if (taskRecord.type !== 'bt' && taskRecord.type !== 'magnet') return payload
const infoHash =
typeof taskRecord.infoHash === 'string' ? taskRecord.infoHash.trim() : ''
const canonicalInfoHash = /^(?:[0-9a-f]{40}|[a-z2-7]{32})$/i.test(infoHash)
? infoHash.toLowerCase()
: null
const stableTaskId =
typeof taskRecord.id === 'string' && taskRecord.id.length > 0
? taskRecord.id
: typeof payload.taskId === 'string'
? payload.taskId
: ''
return {
...payload,
sourceUrl: canonicalInfoHash
? `urn:btih:${canonicalInfoHash}`
: `urn:motrix:bt:${Buffer.from(stableTaskId, 'utf8').toString('base64url')}`,
}
}
export function prepareBundle(source: string): string {
// Replace `import { … } from 'motrix:plugin-api'` with a binding to
// globalThis.__motrix_plugin_api__. QuickJS supports ES modules but
// does not run a bundler resolver — we pre-transform at host-side.
//
// ES module import syntax uses `as` for renames:
// import { foo as bar } from 'motrix:plugin-api'
// Object destructuring uses `:` for the same thing:
// const { foo: bar } = ...
// Bundlers like esbuild emit `as`-renamed imports when minifying
// identifier names; we MUST convert each `name as alias` to
// `name: alias` here or the resulting `const { name as alias } = ...`
// is a SyntaxError at QuickJS module load.
const renameRe = /^([\w$]+)\s+as\s+([\w$]+)$/
return source.replace(
/import\s*\{([^}]+)\}\s*from\s*['"]motrix:plugin-api['"]\s*;?/g,
(_, members) => {
const names = members
.split(',')
.map((s: string) => s.trim())
.filter(Boolean)
.map((member: string) => {
const m = member.match(renameRe)
return m ? `${m[1]}: ${m[2]}` : member
})
return `const { ${names.join(', ')} } = globalThis.__motrix_plugin_api__;`
}
)
}
function hookScopeFromMessage(
message: BridgeCallMessage
): HookInvocationScopeV1 | null {
if (!('invocationId' in message)) return null
return {
invocationId: message.invocationId,
callChainId: message.callChainId,
permissionGeneration: message.permissionGeneration,
}
}
function commandScopeFromMessage(
message: BridgeCallMessage
): CommandInvocationScopeV1 | null {
return 'commandScope' in message ? message.commandScope : null
}
function sameCommandScope(
left: CommandInvocationScopeV1,
right: CommandInvocationScopeV1
): boolean {
return (
left.commandInvocationId === right.commandInvocationId &&
left.callChain.id === right.callChain.id &&
left.callChain.plugins.length === right.callChain.plugins.length &&
left.callChain.plugins.every(
(pluginId, index) => pluginId === right.callChain.plugins[index]
)
)
}
function sameHookScope(
left: HookInvocationScopeV1,
right: HookInvocationScopeV1
): boolean {
return (
left.invocationId === right.invocationId &&
left.callChainId === right.callChainId &&
left.permissionGeneration === right.permissionGeneration
)
}