import { BEHAVIOR_PLUGIN_API_VERSION, hasValidClawclawResourceLocalizations, type BehaviorRuntimeDefaults, type ClawclawBehaviorManifest, } from '../../../../sdk/behavior-plugin/index.js'; import { isClawclawFixedEventType } from '../../../clawclaw-event-catalog.js'; import { normalizeBehaviorInputFields } from '../../behavior-input-fields.js'; import { assertPluginApiVersion } from '../plugin-api-version.js'; const EVENT_TYPE = /^[a-z][a-z0-9_.-]*$/; const BEHAVIOR_ID = /^[a-z0-9][a-z0-9._-]*$/; const MANIFEST_FIELDS = new Set([ 'apiVersion', 'id', 'name', 'description', 'localizations', 'inputs', 'execution', 'stateMode', 'everyTicks', 'produces', 'runtime', ]); const RUNTIME_FIELDS = new Set(['defaultMs', 'deadlineOutcome', 'controlGraceMs']); function own(value: object, key: string): boolean { return Object.prototype.hasOwnProperty.call(value, key); } export function deepFreezeBehaviorValue(value: T): T { if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value; Object.freeze(value); for (const child of Object.values(value as Record)) { deepFreezeBehaviorValue(child); } return value; } export function behaviorProducesDiagnostic( produces: unknown, options: Readonly<{ allowReservedProduces?: readonly string[] }> = {}, ): string | undefined { if (!Array.isArray(produces)) return 'behavior_produces_invalid'; const seen = new Set(); const allowedReserved = new Set(options.allowReservedProduces ?? []); for (const candidate of produces) { if (typeof candidate !== 'string' || !EVENT_TYPE.test(candidate)) { return `behavior_produces_invalid:${String(candidate)}`; } if (seen.has(candidate)) return `behavior_produces_duplicate:${candidate}`; seen.add(candidate); if (isClawclawFixedEventType(candidate) && !allowedReserved.has(candidate)) { return `behavior_produces_reserved:${candidate}`; } } return undefined; } export function normalizeBehaviorRuntimeDefaults( value: unknown, ): Readonly { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error('behavior_runtime_invalid'); } const runtime = value as Readonly>; const unknownField = Object.keys(runtime).find((field) => !RUNTIME_FIELDS.has(field)); if (unknownField) throw new Error(`behavior_runtime_field_unknown:${unknownField}`); if (!Number.isSafeInteger(runtime.defaultMs) || (runtime.defaultMs as number) < 1_000 || (runtime.defaultMs as number) > 120_000) { throw new Error('behavior_runtime_default_invalid'); } if ( runtime.deadlineOutcome !== undefined && runtime.deadlineOutcome !== 'completed' && runtime.deadlineOutcome !== 'failed' ) throw new Error('behavior_runtime_deadline_outcome_invalid'); if ( runtime.controlGraceMs !== undefined && ( !Number.isSafeInteger(runtime.controlGraceMs) || (runtime.controlGraceMs as number) < 0 || (runtime.controlGraceMs as number) > 30_000 ) ) throw new Error('behavior_runtime_control_grace_invalid'); return deepFreezeBehaviorValue({ defaultMs: runtime.defaultMs as number, ...(runtime.deadlineOutcome === undefined ? {} : { deadlineOutcome: runtime.deadlineOutcome as 'completed' | 'failed' }), ...(runtime.controlGraceMs === undefined ? {} : { controlGraceMs: runtime.controlGraceMs as number }), }); } function nonEmpty(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; } /** Validates, detaches, canonicalizes, and deeply freezes a loaded manifest. */ export function normalizeClawclawBehaviorManifest( value: unknown, options: Readonly<{ allowReservedProduces?: readonly string[] }> = {}, ): Readonly { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error('behavior_manifest_missing'); } const manifest = value as Readonly>; const unknownField = Object.keys(manifest).find((field) => !MANIFEST_FIELDS.has(field)); if (unknownField) throw new Error(`behavior_manifest_field_unknown:${unknownField}`); assertPluginApiVersion( 'behavior_manifest_api_version_unsupported', BEHAVIOR_PLUGIN_API_VERSION, typeof manifest.apiVersion === 'number' ? manifest.apiVersion : undefined, ); const id = nonEmpty(manifest.id) ? manifest.id.trim() : ''; if (!BEHAVIOR_ID.test(id)) throw new Error('behavior_id_invalid'); if (manifest.name !== undefined && !nonEmpty(manifest.name)) throw new Error('behavior_name_invalid'); if (!nonEmpty(manifest.description)) throw new Error('behavior_description_invalid'); if (!hasValidClawclawResourceLocalizations( manifest.localizations as ClawclawBehaviorManifest['localizations'], )) throw new Error('behavior_localizations_invalid'); if (!own(manifest, 'inputs')) throw new Error('behavior_inputs_missing'); const inputs = normalizeBehaviorInputFields(manifest.inputs); const reserved = inputs.find(({ id: inputId }) => ( inputId === 'timeout_ms' || inputId === 'duration_ms' )); if (reserved) throw new Error(`behavior_input_id_reserved:${reserved.id}`); if ( manifest.execution !== undefined && manifest.execution !== 'parallel' && manifest.execution !== 'serial' ) throw new Error('behavior_execution_invalid'); const everyTicks = manifest.everyTicks ?? 1; if (manifest.stateMode !== undefined && manifest.stateMode !== 'isolated' && manifest.stateMode !== 'snapshot') { throw new Error('behavior_state_mode_invalid'); } if (manifest.stateMode === 'snapshot' && manifest.execution === 'serial') { throw new Error('behavior_snapshot_requires_parallel'); } if (!Number.isSafeInteger(everyTicks) || (everyTicks as number) <= 0) { throw new Error('behavior_every_ticks_invalid'); } if (manifest.produces !== undefined) { const diagnostic = behaviorProducesDiagnostic(manifest.produces, options); if (diagnostic) throw new Error(diagnostic); } const runtime = manifest.runtime === undefined ? undefined : normalizeBehaviorRuntimeDefaults(manifest.runtime); let localizations: ClawclawBehaviorManifest['localizations']; try { localizations = manifest.localizations === undefined ? undefined : structuredClone(manifest.localizations) as ClawclawBehaviorManifest['localizations']; } catch { throw new Error('behavior_localizations_not_cloneable'); } return deepFreezeBehaviorValue({ apiVersion: BEHAVIOR_PLUGIN_API_VERSION, id, name: ((manifest.name ?? manifest.id) as string).trim(), description: (manifest.description as string).trim(), ...(localizations === undefined ? {} : { localizations }), inputs, ...(manifest.stateMode === undefined ? {} : { stateMode: manifest.stateMode as 'isolated' | 'snapshot' }), ...(manifest.execution === undefined ? {} : { execution: manifest.execution as 'parallel' | 'serial' }), ...(manifest.everyTicks === undefined ? {} : { everyTicks: everyTicks as number }), ...(manifest.produces === undefined ? {} : { produces: [...manifest.produces as readonly string[]] }), ...(runtime === undefined ? {} : { runtime }), }); }