import { parentPort } from "node:worker_threads"; import { createCapabilityGateway, createPluginSandbox, type CapabilityCallInfo, type CapabilityHostFnMap, type PluginCapabilityGrant, type PluginInvocationResult, type PluginManifest, } from "@hivegrid/plugin-runtime"; type SandboxWorkerRequest = { wasmBuffer: Uint8Array; manifest: PluginManifest; capabilityGrants: ReadonlyArray; hookName: string; payload: unknown; memoryLimitMb: number; fuelLimit: number; maxCapabilityCallEntries?: number; }; type HostLogEntry = { level: "info" | "warn"; record: Record; message: string; }; const HOST_IMPORT_FUEL_COST = 100; const MAX_HOST_LOG_ENTRIES = 1_024; const MAX_CAPABILITY_CALL_ENTRIES = 2_048; export type SandboxWorkerResponse = { result: PluginInvocationResult; capabilityCalls: CapabilityCallInfo[]; droppedCapabilityCallCount: number; hostLogs: HostLogEntry[]; }; function stringifyError(error: unknown): string { return error instanceof Error ? error.message : String(error); } export function createPluginSandboxHostFns(args: { manifest: PluginManifest; pushHostLog: (entry: HostLogEntry) => void; }): CapabilityHostFnMap { const { manifest, pushHostLog } = args; return { log: (value: unknown) => { pushHostLog({ level: "info", record: { pluginId: manifest.id, version: manifest.version, value }, message: "plugin.invoke.host.log" }); return 0; }, audit: (value: unknown) => { pushHostLog({ level: "info", record: { pluginId: manifest.id, version: manifest.version, value }, message: "plugin.invoke.host.audit" }); return 0; }, }; } export async function runSandboxForTest({ wasmBuffer, manifest, capabilityGrants, hookName, payload, memoryLimitMb, fuelLimit, maxCapabilityCallEntries = MAX_CAPABILITY_CALL_ENTRIES, }: SandboxWorkerRequest): Promise { const capabilityCalls: CapabilityCallInfo[] = []; const hostLogs: HostLogEntry[] = []; const capabilityCallEntryLimit = Number.isFinite(maxCapabilityCallEntries) ? Math.max(0, Math.floor(maxCapabilityCallEntries)) : MAX_CAPABILITY_CALL_ENTRIES; let droppedCapabilityCallCount = 0; let hostFuelExhausted = false; const pushHostLog = (entry: HostLogEntry) => { if (hostLogs.length < MAX_HOST_LOG_ENTRIES) { hostLogs.push(entry); } }; const hostFns = createPluginSandboxHostFns({ manifest, pushHostLog }); const gateway = createCapabilityGateway({ manifest, approvedGrants: capabilityGrants, hostFns, fuelCostPerCall: HOST_IMPORT_FUEL_COST, onDenied: (info) => { pushHostLog({ level: "warn", record: { pluginId: manifest.id, version: manifest.version, capability: info.capability, reason: info.reason }, message: "plugin.invoke.capability_denied", }); }, onCall: (info) => { if (capabilityCalls.length < capabilityCallEntryLimit) { capabilityCalls.push(info); } else { droppedCapabilityCallCount += 1; } }, }); const invokeHostSync = (capability: "log" | "audit", value: number) => { if (gateway.fuelCharged() + HOST_IMPORT_FUEL_COST > fuelLimit) { hostFuelExhausted = true; throw new Error("plugin host import fuel exhausted"); } return gateway.invokeSync(capability, { value }); }; const sandbox = createPluginSandbox({ wasmBuffer, manifest, memoryLimitMb, fuelLimit, hostImports: { env: { toolctrl_log: (value: number) => invokeHostSync("log", value), toolctrl_audit_record: (value: number) => invokeHostSync("audit", value), }, }, }); try { const result = await sandbox.invoke(hookName, payload); const fuelUsed = Math.min(fuelLimit, result.fuelUsed + gateway.fuelCharged()); if (hostFuelExhausted) { return { result: { ok: false, reason: "fuel_exhausted", fuelUsed, message: "plugin host import fuel exhausted" }, capabilityCalls, droppedCapabilityCallCount, hostLogs, }; } return { result: result.ok ? { ...result, fuelUsed } : { ...result, fuelUsed }, capabilityCalls, droppedCapabilityCallCount, hostLogs, }; } finally { sandbox.close(); } } parentPort?.on("message", (request: SandboxWorkerRequest) => { void runSandboxForTest(request) .then((response) => parentPort?.postMessage(response)) .catch((error: unknown) => parentPort?.postMessage({ result: { ok: false, reason: "trap", fuelUsed: 0, message: stringifyError(error) }, capabilityCalls: [], droppedCapabilityCallCount: 0, hostLogs: [], } satisfies SandboxWorkerResponse) ); });