import { randomUUID } from 'node:crypto'; import { realpathSync } from 'node:fs'; import { isDeepStrictEqual } from 'node:util'; import { pathToFileURL } from 'node:url'; import { MAX_TRIGGER_RUNTIME_MS, TRIGGER_PLUGIN_API_VERSION, type ClawclawTriggerClass, type ClawclawTriggerManifest, } from '../../../../sdk/trigger-plugin/index.js'; import { normalizeBehaviorInput, normalizeBehaviorInputFields } from '../../behavior-input-fields.js'; import { importRuntimeModule, runtimeModuleThreadLoaderConfig, type RuntimeModuleThreadLoaderConfig, } from '../../../framework/modules/runtime-module-loader.js'; import { assertPluginApiVersion } from '../plugin-api-version.js'; import type { ResolvedClawclawTriggerSource } from './trigger-source.js'; function normalizedManifest(value: unknown): ClawclawTriggerManifest { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error('trigger_manifest_invalid'); } const manifest = value as Record; const allowedManifestFields = new Set([ 'apiVersion', 'id', 'name', 'description', 'localizations', 'inputs', 'consumes', 'defaultBehavior', 'defaultBehaviorInput', 'defaultReflexPriority', 'defaultCooldownMs', 'defaultRearm', 'defaultMaxRuntimeMs', ]); if (Object.keys(manifest).some((field) => !allowedManifestFields.has(field))) { throw new Error('trigger_manifest_field_unknown'); } assertPluginApiVersion( 'trigger_manifest_api_version_unsupported', TRIGGER_PLUGIN_API_VERSION, typeof manifest.apiVersion === 'number' ? manifest.apiVersion : undefined, ); const inputs = normalizeBehaviorInputFields(manifest.inputs); if (inputs.some((field) => field.default === undefined)) { throw new Error('trigger_manifest_input_default_missing'); } normalizeBehaviorInput({}, inputs); if ( typeof manifest.id !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/.test(manifest.id) || typeof manifest.name !== 'string' || !manifest.name.trim() || typeof manifest.description !== 'string' || !manifest.description.trim() || !Array.isArray(manifest.consumes) || manifest.consumes.some((entry) => ( typeof entry !== 'string' || !/^(?:\*|[a-z0-9][a-z0-9._-]*)$/.test(entry) )) || new Set(manifest.consumes).size !== manifest.consumes.length || typeof manifest.defaultBehavior !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/.test(manifest.defaultBehavior) || !manifest.defaultBehaviorInput || typeof manifest.defaultBehaviorInput !== 'object' || Array.isArray(manifest.defaultBehaviorInput) || !Number.isSafeInteger(manifest.defaultReflexPriority) || !Number.isSafeInteger(manifest.defaultCooldownMs) || Number(manifest.defaultCooldownMs) < 0 || (manifest.defaultRearm !== 'after_clear' && manifest.defaultRearm !== 'after_cooldown') || !Number.isSafeInteger(manifest.defaultMaxRuntimeMs) || Number(manifest.defaultMaxRuntimeMs) <= 0 || Number(manifest.defaultMaxRuntimeMs) > MAX_TRIGGER_RUNTIME_MS ) throw new Error('trigger_manifest_invalid'); return structuredClone({ ...manifest, inputs }) as unknown as ClawclawTriggerManifest; } export interface TriggerThreadModuleSpec { readonly triggerId: string; readonly sourceUrl: string; readonly source: ResolvedClawclawTriggerSource; } export function validateClawclawTriggerModule( loaded: Readonly>, source: ResolvedClawclawTriggerSource, ): ClawclawTriggerClass { const entry = 'default'; if (typeof loaded[entry] !== 'function') { throw new Error(`Trigger module '${source.id}' has no default class.`); } const ModuleClass = loaded[entry] as unknown as ClawclawTriggerClass; const manifest = normalizedManifest(ModuleClass.manifest); if (!isDeepStrictEqual(manifest, source.manifest)) { throw new Error(`Trigger module '${source.id}' changed after static discovery.`); } return ModuleClass; } /** One Runtime-scoped direct importer. Disabled Trigger sources never reach it. */ export class TriggerModuleLoader { private readonly runtimeId = randomUUID(); private readonly loaded = new Map>(); threadConfig(): RuntimeModuleThreadLoaderConfig { return runtimeModuleThreadLoaderConfig(); } threadSpec(source: ResolvedClawclawTriggerSource): TriggerThreadModuleSpec { assertPluginApiVersion( 'trigger_api_version_unsupported', TRIGGER_PLUGIN_API_VERSION, source.apiVersion, ); return { triggerId: source.id, sourceUrl: this.sourceUrl(source), source }; } load(source: ResolvedClawclawTriggerSource): Promise { try { assertPluginApiVersion( 'trigger_api_version_unsupported', TRIGGER_PLUGIN_API_VERSION, source.apiVersion, ); } catch (error) { return Promise.reject(error); } let pending = this.loaded.get(source.id); if (pending) return pending; pending = importRuntimeModule(new URL(this.sourceUrl(source))) .then((loaded) => validateClawclawTriggerModule(loaded, source)); this.loaded.set(source.id, pending); return pending; } stop(): void { this.loaded.clear(); } private sourceUrl(source: ResolvedClawclawTriggerSource): string { const value = pathToFileURL(realpathSync(source.sourcePath)); value.searchParams.set('ccl_runtime', this.runtimeId); return value.href; } }