import type { BehaviorNormalizationApi, BehaviorTiming, ClawclawBehavior, ClawclawBehaviorClass, ClawclawBehaviorManifest, } from '../../../../sdk/behavior-plugin/index.js'; import type { StrategyWorkerLease } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js'; import { normalizeBehaviorInput } from '../../behavior-input-fields.js'; import { deepFreezeBehaviorValue } from './behavior-manifest.js'; import type { ResolvedClawclawBehaviorSource } from './behavior-source.js'; const MIN_RUNTIME_MS = 1_000; const MAX_RUNTIME_MS = 120_000; export interface PreparedClawclawBehavior { /** Host-owned display text, separate from the executable manifest. */ readonly display?: Readonly<{ name: string; description: string }>; /** Owner-local instance exists only for explicitly serial trusted execution. */ readonly module?: ClawclawBehavior; readonly createModule?: () => ClawclawBehavior; readonly manifest: Readonly; readonly input: Readonly>; /** Schema input before optional author normalization; used when applying later parameter patches. */ readonly rawInput?: Readonly>; /** Static source identity required only by isolated parallel execution. */ readonly source?: ResolvedClawclawBehaviorSource; readonly worker?: StrategyWorkerLease; /** Present only when the request/module materialized a finite budget. */ readonly timing?: Readonly; } function own(value: object, key: string): boolean { return Object.prototype.hasOwnProperty.call(value, key); } function requestRecord(value: unknown): Readonly> { const prototype = value && typeof value === 'object' ? Object.getPrototypeOf(value) : undefined; if ( !value || typeof value !== 'object' || Array.isArray(value) || (prototype !== Object.prototype && prototype !== null) ) throw new Error('behavior_request_invalid'); return value as Readonly>; } function immutableRecord(value: unknown): Readonly> { const record = requestRecord(value); try { return deepFreezeBehaviorValue(structuredClone(record)); } catch { throw new Error('behavior_request_not_cloneable'); } } /** Builds the immutable helpers handed to a module's one-time normalize(). */ export function createBehaviorNormalizationApi( manifest: Readonly, ): BehaviorNormalizationApi { const string = (value: unknown, field: string): string => { if (typeof value !== 'string' || !value.trim() || value.trim().length > 120) { throw new Error(`behavior_${field}_invalid`); } return value.trim(); }; return Object.freeze({ manifest, timing: (input: Readonly>): BehaviorTiming => { if (input.duration_ms !== undefined && input.timeout_ms !== undefined) { throw new Error('behavior_runtime_ms_ambiguous'); } const explicitDuration = input.duration_ms !== undefined; const raw = input.duration_ms ?? input.timeout_ms ?? manifest.runtime?.defaultMs; if (raw === undefined) throw new Error('behavior_runtime_default_missing'); const value = Number(raw); if (!Number.isSafeInteger(value) || value < MIN_RUNTIME_MS || value > MAX_RUNTIME_MS) { throw new Error('behavior_runtime_ms_invalid'); } return explicitDuration ? { duration_ms: value } : { timeout_ms: value }; }, string, optionalString: (value: unknown, field: string) => ( value === undefined || value === null || value === '' ? undefined : string(value, field) ), number: ( value: unknown, field: string, constraints: Readonly<{ min?: number; max?: number; integer?: boolean }> = {}, ) => { const number = Number(value); if ( !Number.isFinite(number) || (constraints.integer === true && !Number.isInteger(number)) || (constraints.min !== undefined && number < constraints.min) || (constraints.max !== undefined && number > constraints.max) ) throw new Error(`behavior_${field}_invalid`); return number; }, stringArray: ( value: unknown, field: string, constraints: Readonly<{ maxItems?: number }> = {}, ) => { if ( !Array.isArray(value) || (constraints.maxItems !== undefined && value.length > constraints.maxItems) ) throw new Error(`behavior_${field}_invalid`); return Object.freeze(value.map((entry) => string(entry, field))); }, choice: (value: unknown, field: string, values: readonly T[]): T => { if (typeof value !== 'string' || !values.includes(value as T)) { throw new Error(`behavior_${field}_invalid`); } return value as T; }, }); } function materializedTiming( raw: Readonly>, normalized: Readonly>, api: BehaviorNormalizationApi, ): Readonly | undefined { if ( (own(raw, 'duration_ms') && raw.duration_ms !== undefined) || (own(raw, 'timeout_ms') && raw.timeout_ms !== undefined) ) return Object.freeze(api.timing(raw)); if ( (own(normalized, 'duration_ms') && normalized.duration_ms !== undefined) || (own(normalized, 'timeout_ms') && normalized.timeout_ms !== undefined) ) return Object.freeze(api.timing(normalized)); return undefined; } /** Applies schema defaults and optional author normalization without choosing an Activation layer. */ export function prepareClawclawBehavior( BehaviorClass: ClawclawBehaviorClass, manifest: Readonly, value: unknown, source?: ResolvedClawclawBehaviorSource, ): PreparedClawclawBehavior { const raw = requestRecord(value); if (raw.duration_ms !== undefined && raw.timeout_ms !== undefined) { throw new Error('behavior_runtime_ms_ambiguous'); } const declared = normalizeBehaviorInput(raw, manifest.inputs, { allowedKeys: ['timeout_ms', 'duration_ms'], }); const module = new BehaviorClass(); const api = createBehaviorNormalizationApi(manifest); const normalized = typeof module.normalize === 'function' ? immutableRecord(module.normalize(declared, api)) : immutableRecord(declared); const timing = materializedTiming(raw, normalized, api); return Object.freeze({ module, rawInput: immutableRecord(declared), createModule: () => new BehaviorClass(), manifest, input: normalized, ...(source === undefined ? {} : { source }), ...(timing === undefined ? {} : { timing }), }); }