import { createHash } from 'node:crypto'; import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'; import * as asyncFs from 'node:fs/promises'; import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { BEHAVIOR_PLUGIN_API_VERSION, type ClawclawBehaviorClass, type ClawclawBehaviorManifest, } from '../../../../sdk/behavior-plugin/index.js'; import { importRuntimeModule, runtimeModuleThreadLoaderConfig, } from '../../../framework/modules/runtime-module-loader.js'; import { assertPluginApiVersion } from '../plugin-api-version.js'; import { normalizeClawclawBehaviorManifest, } from './behavior-manifest.js'; import { behaviorSourceCompatibilityError, type ResolvedClawclawBehaviorSource, } from './behavior-source.js'; export interface LoadedClawclawBehaviorModule { readonly BehaviorClass: ClawclawBehaviorClass; readonly manifest: Readonly; readonly source?: ResolvedClawclawBehaviorSource; } export interface BehaviorThreadLoaderConfig { readonly hooksUrl: string; readonly sdkAliases: Readonly>; } /** Gives Behavior Worker Threads the exact same TS transform and SDK aliases as Owner imports. */ export function behaviorThreadLoaderConfig(): BehaviorThreadLoaderConfig { return runtimeModuleThreadLoaderConfig(); } function pathInside(root: string, candidate: string): boolean { const child = relative(root, candidate); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } const MAX_BEHAVIOR_SOURCE_TREE_FILES = 2_048; const MAX_BEHAVIOR_SOURCE_TREE_BYTES = 64 * 1024 * 1024; const RUNTIME_SOURCE_FILE = /\.(?:[cm]?[jt]sx?|json)$/i; /** Hash every local runtime source that one flat Behavior directory may import. */ export function behaviorSourceTreeSha256(sourceRoot: string): string { const root = realpathSync(resolve(sourceRoot)); const files: Array<{ path: string; relativePath: string; size: number }> = []; const visit = (directory: string): void => { for (const entry of readdirSync(directory, { withFileTypes: true })) { const candidate = join(directory, entry.name); if (entry.isSymbolicLink()) throw new Error('behavior_source_tree_symlink_unsupported'); if (entry.isDirectory()) { visit(candidate); continue; } if (!entry.isFile() || !RUNTIME_SOURCE_FILE.test(entry.name)) continue; const physical = realpathSync(candidate); if (!pathInside(root, physical)) throw new Error('behavior_source_tree_outside_root'); const stats = statSync(physical); files.push({ path: physical, relativePath: relative(root, physical).replaceAll('\\', '/'), size: stats.size, }); if (files.length > MAX_BEHAVIOR_SOURCE_TREE_FILES) { throw new Error('behavior_source_tree_file_limit_exceeded'); } } }; visit(root); files.sort((left, right) => left.relativePath.localeCompare(right.relativePath)); const totalBytes = files.reduce((total, file) => total + file.size, 0); if (totalBytes > MAX_BEHAVIOR_SOURCE_TREE_BYTES) { throw new Error('behavior_source_tree_byte_limit_exceeded'); } const hash = createHash('sha256'); for (const file of files) { hash.update(file.relativePath); hash.update('\0'); hash.update(readFileSync(file.path)); hash.update('\0'); } return hash.digest('hex'); } function equal(left: unknown, right: unknown): boolean { return JSON.stringify(left) === JSON.stringify(right); } function assertSourceParity( manifest: Readonly, source: ResolvedClawclawBehaviorSource, ): void { if ((manifest.stateMode ?? 'isolated') !== (source.stateMode ?? 'isolated')) { throw new Error('behavior_state_mode_source_mismatch'); } if (manifest.id !== (source.declaredId ?? source.id)) throw new Error('behavior_id_source_mismatch'); if (manifest.name !== source.name) throw new Error('behavior_name_source_mismatch'); if (manifest.description !== source.description) { throw new Error('behavior_description_source_mismatch'); } if (!equal(manifest.localizations, source.localizations)) { throw new Error('behavior_localizations_source_mismatch'); } if (!equal(manifest.inputs, source.inputs)) { throw new Error('behavior_inputs_source_mismatch'); } if ((manifest.execution ?? 'parallel') !== source.execution) { throw new Error('behavior_execution_source_mismatch'); } if ((manifest.everyTicks ?? 1) !== source.everyTicks) { throw new Error('behavior_every_ticks_source_mismatch'); } if (!equal(manifest.produces ?? [], source.produces ?? [])) { throw new Error('behavior_produces_source_mismatch'); } if (!equal(manifest.runtime, source.runtime)) { throw new Error('behavior_runtime_source_mismatch'); } } /** Validates one evaluated module and rechecks every statically scanned field. */ export function validateClawclawBehaviorModule( module: Readonly>, source?: ResolvedClawclawBehaviorSource, ): LoadedClawclawBehaviorModule { const candidate = module.default; if (typeof candidate !== 'function') throw new Error('behavior_default_class_missing'); const descriptor = Object.getOwnPropertyDescriptor(candidate, 'manifest'); if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) { throw new Error('behavior_manifest_missing'); } const BehaviorClass = candidate as unknown as ClawclawBehaviorClass; if (typeof BehaviorClass.prototype.decide !== 'function') { throw new Error('behavior_decide_missing'); } if ( BehaviorClass.prototype.normalize !== undefined && typeof BehaviorClass.prototype.normalize !== 'function' ) throw new Error('behavior_normalize_invalid'); const manifest = normalizeClawclawBehaviorManifest(descriptor.value, { allowReservedProduces: source?.allowReservedProduces, }); if (source) assertSourceParity(manifest, source); const effectiveManifest = source && source.id !== manifest.id ? Object.freeze({ ...manifest, id: source.id }) : manifest; return Object.freeze({ BehaviorClass, manifest: effectiveManifest, ...(source === undefined ? {} : { source }), }); } export function resolveBehaviorSource( source: ResolvedClawclawBehaviorSource, ): ResolvedClawclawBehaviorSource { const sourceRoot = realpathSync(resolve(source.sourceRoot)); const sourcePath = realpathSync(resolve(source.sourcePath)); if ( !pathInside(sourceRoot, sourcePath) || dirname(sourcePath) !== sourceRoot || !statSync(sourcePath).isFile() ) throw new Error(`Behavior '${source.id}' source is outside its root.`); if (source.trustedSourceSha256 !== undefined) { if (!/^[0-9a-f]{64}$/.test(source.trustedSourceSha256)) { throw new Error('behavior_trusted_source_hash_invalid'); } const current = createHash('sha256').update(readFileSync(sourcePath)).digest('hex'); if (current !== source.trustedSourceSha256) { throw new Error('behavior_trusted_source_changed'); } } if (source.trustedSourceTreeSha256 !== undefined) { if (!/^[0-9a-f]{64}$/.test(source.trustedSourceTreeSha256)) { throw new Error('behavior_source_tree_hash_invalid'); } if (behaviorSourceTreeSha256(sourceRoot) !== source.trustedSourceTreeSha256) { throw new Error('behavior_source_tree_changed'); } } return { ...source, sourceRoot, sourcePath }; } /** Freeze the local module tree used by Owner and every Worker in one Activation. */ export function pinBehaviorSource( source: ResolvedClawclawBehaviorSource, ): ResolvedClawclawBehaviorSource { const resolved = resolveBehaviorSource(source); if (resolved.trustedSourceTreeSha256 !== undefined) return resolved; return Object.freeze({ ...resolved, trustedSourceTreeSha256: behaviorSourceTreeSha256(resolved.sourceRoot), }); } /** Pin source before dispatch without making the Owner wait on synchronous disk reads. */ export async function pinBehaviorSourceAsync(source: ResolvedClawclawBehaviorSource): Promise { const sourceRoot = await asyncFs.realpath(source.sourceRoot); const sourcePath = await asyncFs.realpath(source.sourcePath); if (!pathInside(sourceRoot, sourcePath) || dirname(sourcePath) !== sourceRoot || !(await asyncFs.stat(sourcePath)).isFile()) { throw new Error(`Behavior '${source.id}' source is outside its root.`); } const files: Array<{ path: string; relativePath: string }> = []; const visit = async (directory: string): Promise => { for (const entry of await asyncFs.readdir(directory, { withFileTypes: true })) { const path = join(directory, entry.name); if (entry.isSymbolicLink()) throw new Error('behavior_source_tree_symlink_unsupported'); if (entry.isDirectory()) await visit(path); else if (entry.isFile() && RUNTIME_SOURCE_FILE.test(entry.name)) { if (files.length >= MAX_BEHAVIOR_SOURCE_TREE_FILES) throw new Error('behavior_source_tree_file_limit_exceeded'); const physical = await asyncFs.realpath(path); if (!pathInside(sourceRoot, physical)) throw new Error('behavior_source_tree_outside_root'); files.push({ path: physical, relativePath: relative(sourceRoot, physical).replaceAll('\\', '/') }); } } }; await visit(sourceRoot); files.sort((left, right) => left.relativePath.localeCompare(right.relativePath)); const hash = createHash('sha256'); let totalBytes = 0; for (const file of files) { if (totalBytes + (await asyncFs.stat(file.path)).size > MAX_BEHAVIOR_SOURCE_TREE_BYTES) { throw new Error('behavior_source_tree_byte_limit_exceeded'); } const content = await asyncFs.readFile(file.path); totalBytes += content.length; if (totalBytes > MAX_BEHAVIOR_SOURCE_TREE_BYTES) throw new Error('behavior_source_tree_byte_limit_exceeded'); if (file.path === sourcePath && source.trustedSourceSha256 !== undefined && createHash('sha256').update(content).digest('hex') !== source.trustedSourceSha256) { throw new Error('behavior_trusted_source_changed'); } hash.update(file.relativePath).update('\0').update(content).update('\0'); } const digest = hash.digest('hex'); if (source.trustedSourceTreeSha256 !== undefined && source.trustedSourceTreeSha256 !== digest) { throw new Error('behavior_source_tree_changed'); } return Object.freeze({ ...source, sourceRoot, sourcePath, trustedSourceTreeSha256: digest }); } /** Resolves one already-scanned source to the URL imported inside each Worker slot. */ export function behaviorSourceUrl(source: ResolvedClawclawBehaviorSource): string { const resolved = source; assertPluginApiVersion( 'behavior_api_version_unsupported', BEHAVIOR_PLUGIN_API_VERSION, resolved.apiVersion, ); const compatibilityError = behaviorSourceCompatibilityError(resolved); if (compatibilityError) throw new Error(compatibilityError); return pathToFileURL(resolved.sourcePath).href; } /** Imports one trusted Behavior only after an explicit load/prepare request. */ export async function loadClawclawBehaviorModule( source: ResolvedClawclawBehaviorSource, ): Promise { assertPluginApiVersion( 'behavior_api_version_unsupported', BEHAVIOR_PLUGIN_API_VERSION, source.apiVersion, ); const compatibilityError = behaviorSourceCompatibilityError(source); if (compatibilityError) throw new Error(compatibilityError); const pinned = pinBehaviorSource(source); const module = await importRuntimeModule(pinned.sourcePath); const stable = resolveBehaviorSource(pinned); return validateClawclawBehaviorModule(module, stable); }