import { createHash } from 'node:crypto'; import { existsSync, readFileSync, readdirSync, realpathSync, } from 'node:fs'; import { dirname, isAbsolute, join, relative, } from 'node:path'; import type { BehaviorInputFieldSpec, BehaviorRuntimeDefaults, ClawclawResourceLocalizations, } from '../../../../sdk/behavior-plugin/index.js'; import { hasValidClawclawResourceLocalizations, } from '../../../../sdk/behavior-plugin/index.js'; import { parseLiteralBehaviorInputFields, parseLiteralModuleManifest } from '../behavior-input-source.js'; import { normalizeStrategyPerception } from '../../behavior-trigger.js'; import { behaviorProducesDiagnostic, deepFreezeBehaviorValue, normalizeBehaviorRuntimeDefaults, } from './behavior-manifest.js'; const MAX_BEHAVIOR_FILES = 512; const MAX_BEHAVIOR_SOURCE_BYTES = 2 * 1024 * 1024; const SAFE_IMPORT = /(?:\bfrom\s*|\bimport\s*)["'](?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/(?:behavior|strategy)-plugin["']/; const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+Clawclaw(?:Behavior|Strategy)(?:\s*<[\s\S]{0,4000}?>)?\s*\{/; const NAMED_TRIGGER = /export\s+class\s+Trigger\b/; const TRIGGER_CLASS = /^export\s+class\s+Trigger\s+extends\s+ClawclawPerception(?:\s*<[\s\S]{0,4000}?>)?\s*\{/; const STATIC_MANIFEST = /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/; 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', ]); interface ParsedValue { readonly value: unknown; readonly next: number; } type LiteralProperty = | Readonly<{ status: 'missing' }> | Readonly<{ status: 'valid'; value: unknown }> | Readonly<{ status: 'invalid' }>; class LiteralParseError extends Error {} export interface ResolvedClawclawBehaviorSource { /** Optional so a statically identifiable legacy module remains reportable. */ readonly apiVersion?: number; readonly id: string; /** Host-assigned operation names never change the ID in the source file. */ readonly declaredId?: string; /** Host-only Hub identity used for optional perception dependency preferences. */ readonly resourceId?: string; readonly workingCopyPath?: string; readonly name: string; readonly display?: Readonly<{ name: string; description: string }>; readonly description: string; readonly localizations?: ClawclawResourceLocalizations; readonly inputs: readonly Readonly[]; readonly execution: 'parallel' | 'serial'; readonly stateMode?: 'isolated' | 'snapshot'; readonly everyTicks: number; readonly produces?: readonly string[]; readonly runtime?: Readonly; readonly trigger?: Readonly<{ manifest: ReturnType; sha256: string }>; readonly triggerError?: string; /** Host-authenticated origin. It is never parsed from module source. */ readonly provenance?: Readonly; /** Host-only trust grant. Static discovery never reads this from module source. */ readonly allowReservedProduces?: readonly string[]; /** Full Host-authenticated content hash rechecked immediately before import. */ readonly trustedSourceSha256?: string; /** Runtime-pinned code tree hash; prevents one Activation from mixing source versions. */ readonly trustedSourceTreeSha256?: string; /** Static discovery error that prevents import while keeping metadata visible. */ readonly compatibilityError?: string; readonly sourcePath: string; readonly sourceRoot: string; } export interface ClawclawBehaviorSourceProvenance { readonly kind: 'official'; readonly family: 'long' | 'finite'; readonly source: string; } function pathInside(root: string, candidate: string): boolean { const child = relative(root, candidate); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } function skipTrivia(source: string, start: number): number { let cursor = start; while (cursor < source.length) { if (/\s/.test(source[cursor])) { cursor += 1; continue; } if (source.startsWith('//', cursor)) { const end = source.indexOf('\n', cursor + 2); cursor = end < 0 ? source.length : end + 1; continue; } if (source.startsWith('/*', cursor)) { const end = source.indexOf('*/', cursor + 2); if (end < 0) throw new LiteralParseError(); cursor = end + 2; continue; } break; } return cursor; } function parseString(source: string, start: number): ParsedValue { const quote = source[start]; if (quote !== "'" && quote !== '"' && quote !== '`') throw new LiteralParseError(); let value = ''; for (let cursor = start + 1; cursor < source.length; cursor += 1) { const char = source[cursor]; if (char === quote) return { value, next: cursor + 1 }; if (quote === '`' && char === '$' && source[cursor + 1] === '{') { throw new LiteralParseError(); } if (char !== '\\') { value += char; continue; } cursor += 1; if (cursor >= source.length) throw new LiteralParseError(); const escaped = source[cursor]; if (escaped === 'n') value += '\n'; else if (escaped === 'r') value += '\r'; else if (escaped === 't') value += '\t'; else if (escaped === 'b') value += '\b'; else if (escaped === 'f') value += '\f'; else if (escaped === 'v') value += '\v'; else if (escaped === '0') value += '\0'; else if (escaped === '\n') continue; else if (escaped === '\r') { if (source[cursor + 1] === '\n') cursor += 1; } else if (escaped === 'x') { const hex = source.slice(cursor + 1, cursor + 3); if (!/^[0-9a-f]{2}$/i.test(hex)) throw new LiteralParseError(); value += String.fromCharCode(Number.parseInt(hex, 16)); cursor += 2; } else if (escaped === 'u') { const hex = source.slice(cursor + 1, cursor + 5); if (!/^[0-9a-f]{4}$/i.test(hex)) throw new LiteralParseError(); value += String.fromCharCode(Number.parseInt(hex, 16)); cursor += 4; } else value += escaped; } throw new LiteralParseError(); } function consumeAsConst(source: string, start: number): number { const cursor = skipTrivia(source, start); const match = /^as\s+const\b/.exec(source.slice(cursor)); return match ? cursor + match[0].length : start; } function parseArray(source: string, start: number): ParsedValue { const values: unknown[] = []; let cursor = skipTrivia(source, start + 1); if (source[cursor] === ']') return { value: values, next: consumeAsConst(source, cursor + 1) }; while (cursor < source.length) { const parsed = parseValue(source, cursor); values.push(parsed.value); cursor = skipTrivia(source, parsed.next); if (source[cursor] === ']') { return { value: values, next: consumeAsConst(source, cursor + 1) }; } if (source[cursor] !== ',') throw new LiteralParseError(); cursor = skipTrivia(source, cursor + 1); if (source[cursor] === ']') { return { value: values, next: consumeAsConst(source, cursor + 1) }; } } throw new LiteralParseError(); } function parseObject(source: string, start: number): ParsedValue { const value: Record = Object.create(null) as Record; let cursor = skipTrivia(source, start + 1); if (source[cursor] === '}') return { value, next: consumeAsConst(source, cursor + 1) }; while (cursor < source.length) { let key: string; if (source[cursor] === "'" || source[cursor] === '"' || source[cursor] === '`') { const parsed = parseString(source, cursor); key = String(parsed.value); cursor = skipTrivia(source, parsed.next); } else { const identifier = /^[A-Za-z_$][\w$]*/.exec(source.slice(cursor)); if (!identifier) throw new LiteralParseError(); key = identifier[0]; cursor = skipTrivia(source, cursor + key.length); } if (Object.prototype.hasOwnProperty.call(value, key)) throw new LiteralParseError(); if (source[cursor] !== ':') throw new LiteralParseError(); const parsed = parseValue(source, skipTrivia(source, cursor + 1)); Object.defineProperty(value, key, { configurable: true, enumerable: true, writable: true, value: parsed.value, }); cursor = skipTrivia(source, parsed.next); if (source[cursor] === '}') return { value, next: consumeAsConst(source, cursor + 1) }; if (source[cursor] !== ',') throw new LiteralParseError(); cursor = skipTrivia(source, cursor + 1); if (source[cursor] === '}') return { value, next: consumeAsConst(source, cursor + 1) }; } throw new LiteralParseError(); } function parseValue(source: string, start: number): ParsedValue { const cursor = skipTrivia(source, start); const char = source[cursor]; if (char === "'" || char === '"' || char === '`') return parseString(source, cursor); if (char === '[') return parseArray(source, cursor); if (char === '{') return parseObject(source, cursor); const boolean = /^(true|false)\b/.exec(source.slice(cursor)); if (boolean) return { value: boolean[1] === 'true', next: cursor + boolean[0].length }; const nil = /^null\b/.exec(source.slice(cursor)); if (nil) return { value: null, next: cursor + nil[0].length }; const number = /^-?(?:(?:\d(?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:e[+-]?\d(?:_?\d)*)?/i .exec(source.slice(cursor)); if (number) { const parsed = Number(number[0].replaceAll('_', '')); if (!Number.isFinite(parsed)) throw new LiteralParseError(); return { value: parsed, next: cursor + number[0].length }; } throw new LiteralParseError(); } function topLevelPropertyStarts(source: string, property: string): number[] { const starts: number[] = []; let depth = 0; for (let cursor = 0; cursor < source.length;) { const next = skipTrivia(source, cursor); if (next !== cursor) { cursor = next; continue; } const char = source[cursor]; if (char === "'" || char === '"' || char === '`') { const parsed = parseString(source, cursor); if (depth === 1 && parsed.value === property) { const colon = skipTrivia(source, parsed.next); if (source[colon] === ':') starts.push(skipTrivia(source, colon + 1)); } cursor = parsed.next; continue; } if (char === '{' || char === '[') { depth += 1; cursor += 1; continue; } if (char === '}' || char === ']') { depth -= 1; cursor += 1; continue; } if (depth === 1 && /[A-Za-z_$]/.test(char ?? '')) { const identifier = /^[A-Za-z_$][\w$]*/.exec(source.slice(cursor))![0]; if (identifier === property) { const colon = skipTrivia(source, cursor + identifier.length); if (source[colon] === ':') starts.push(skipTrivia(source, colon + 1)); } cursor += identifier.length; continue; } cursor += 1; } return starts; } function literalProperty(source: string, property: string): LiteralProperty { try { const starts = topLevelPropertyStarts(source, property); if (starts.length === 0) return Object.freeze({ status: 'missing' }); if (starts.length > 1) return Object.freeze({ status: 'invalid' }); const [start] = starts; const parsed = parseValue(source, start); const tail = skipTrivia(source, parsed.next); if (source[tail] !== ',' && source[tail] !== '}') return Object.freeze({ status: 'invalid' }); return Object.freeze({ status: 'valid', value: parsed.value }); } catch { return Object.freeze({ status: 'invalid' }); } } function maskNonCode(source: string, maskStrings: boolean): string { const output = [...source]; let quote: "'" | '"' | '`' | undefined; let escaped = false; let lineComment = false; let blockComment = false; for (let index = 0; index < source.length; index += 1) { const char = source[index]; const next = source[index + 1]; if (lineComment) { if (char === '\n' || char === '\r') lineComment = false; else output[index] = ' '; continue; } if (blockComment) { output[index] = char === '\n' || char === '\r' ? char : ' '; if (char === '*' && next === '/') { output[index + 1] = ' '; blockComment = false; index += 1; } continue; } if (quote) { if (maskStrings && char !== '\n' && char !== '\r') output[index] = ' '; if (escaped) escaped = false; else if (char === '\\') escaped = true; else if (char === quote) quote = undefined; continue; } if (char === '/' && next === '/') { output[index] = ' '; output[index + 1] = ' '; lineComment = true; index += 1; continue; } if (char === '/' && next === '*') { output[index] = ' '; output[index + 1] = ' '; blockComment = true; index += 1; continue; } if (char === "'" || char === '"' || char === '`') { quote = char; if (maskStrings) output[index] = ' '; } } return output.join(''); } function balancedBlock(source: string, openBrace: number): string | null { let depth = 0; let quote: "'" | '"' | '`' | undefined; let escaped = false; let lineComment = false; let blockComment = false; for (let index = openBrace; index < source.length; index += 1) { const char = source[index]; const next = source[index + 1]; if (lineComment) { if (char === '\n' || char === '\r') lineComment = false; continue; } if (blockComment) { if (char === '*' && next === '/') { blockComment = false; index += 1; } continue; } if (quote) { if (escaped) escaped = false; else if (char === '\\') escaped = true; else if (char === quote) quote = undefined; continue; } if (char === '/' && next === '/') { lineComment = true; index += 1; continue; } if (char === '/' && next === '*') { blockComment = true; index += 1; continue; } if (char === "'" || char === '"' || char === '`') { quote = char; continue; } if (char === '{') depth += 1; if (char !== '}') continue; depth -= 1; if (depth === 0) return source.slice(openBrace, index + 1); if (depth < 0) return null; } return null; } function sourceCompatibility( manifest: string, ): Omit & { readonly id?: string; } { let manifestFields: readonly string[]; try { manifestFields = Object.keys(parseObject(manifest, 0).value as Record); } catch { manifestFields = []; } const idProperty = literalProperty(manifest, 'id'); const id = idProperty.status === 'valid' && typeof idProperty.value === 'string' ? idProperty.value.trim() : undefined; if (!id || !BEHAVIOR_ID.test(id)) return { name: '', description: '', inputs: [], execution: 'parallel', everyTicks: 1, compatibilityError: 'behavior_id_invalid', }; const nameProperty = literalProperty(manifest, 'name'); const descriptionProperty = literalProperty(manifest, 'description'); const name = nameProperty.status === 'valid' && typeof nameProperty.value === 'string' ? nameProperty.value.trim() : nameProperty.status === 'missing' ? id : ''; const description = descriptionProperty.status === 'valid' && typeof descriptionProperty.value === 'string' ? descriptionProperty.value.trim() : ''; const localizationsProperty = literalProperty(manifest, 'localizations'); const localizations = localizationsProperty.status === 'valid' ? localizationsProperty.value as ClawclawResourceLocalizations : undefined; const executionProperty = literalProperty(manifest, 'execution'); const stateModeProperty = literalProperty(manifest, 'stateMode'); const stateMode = stateModeProperty.status === 'valid' ? stateModeProperty.value as 'isolated' | 'snapshot' : undefined; const execution = executionProperty.status === 'valid' && executionProperty.value === 'serial' ? 'serial' : 'parallel'; const everyTicksProperty = literalProperty(manifest, 'everyTicks'); const everyTicks = everyTicksProperty.status === 'valid' && Number.isSafeInteger(everyTicksProperty.value) && (everyTicksProperty.value as number) > 0 ? everyTicksProperty.value as number : 1; const producesProperty = literalProperty(manifest, 'produces'); const produces = producesProperty.status === 'valid' && Array.isArray(producesProperty.value) ? producesProperty.value as string[] : undefined; const runtimeProperty = literalProperty(manifest, 'runtime'); let runtime: Readonly | undefined; let runtimeError: string | undefined; if (runtimeProperty.status === 'valid') { try { runtime = normalizeBehaviorRuntimeDefaults(runtimeProperty.value); } catch (error) { runtimeError = error instanceof Error ? error.message : 'behavior_runtime_invalid'; } } else if (runtimeProperty.status === 'invalid') { runtimeError = 'behavior_runtime_invalid'; } const inputsProperty = literalProperty(manifest, 'inputs'); const parsedInputs = inputsProperty.status === 'missing' ? ({ status: 'missing' } as const) : inputsProperty.status === 'invalid' ? ({ status: 'invalid', diagnostic: 'behavior_inputs_not_literal' } as const) : parseLiteralBehaviorInputFields(manifest); const reservedInput = parsedInputs.status === 'valid' ? parsedInputs.inputs.find(({ id: inputId }) => ( inputId === 'timeout_ms' || inputId === 'duration_ms' )) : undefined; const inputs = parsedInputs.status === 'valid' ? parsedInputs.inputs : []; let compatibilityError: string | undefined; const unknownField = manifestFields.find((field) => !MANIFEST_FIELDS.has(field)); if (unknownField) compatibilityError = `behavior_manifest_field_unknown:${unknownField}`; else if (!name) compatibilityError = 'behavior_name_invalid'; else if (!description) compatibilityError = 'behavior_description_invalid'; else if (localizationsProperty.status === 'invalid' || !hasValidClawclawResourceLocalizations(localizations)) { compatibilityError = 'behavior_localizations_invalid'; } else if (parsedInputs.status === 'missing') compatibilityError = 'behavior_inputs_missing'; else if (parsedInputs.status === 'invalid') compatibilityError = parsedInputs.diagnostic; else if (reservedInput) compatibilityError = `behavior_input_id_reserved:${reservedInput.id}`; else if ( executionProperty.status === 'invalid' || ( executionProperty.status === 'valid' && executionProperty.value !== 'parallel' && executionProperty.value !== 'serial' ) ) compatibilityError = 'behavior_execution_invalid'; else if ( everyTicksProperty.status === 'invalid' || ( everyTicksProperty.status === 'valid' && (!Number.isSafeInteger(everyTicksProperty.value) || (everyTicksProperty.value as number) <= 0) ) ) compatibilityError = 'behavior_every_ticks_invalid'; else if (stateModeProperty.status === 'invalid' || (stateMode !== undefined && stateMode !== 'isolated' && stateMode !== 'snapshot')) compatibilityError = 'behavior_state_mode_invalid'; else if (stateMode === 'snapshot' && execution === 'serial') compatibilityError = 'behavior_snapshot_requires_parallel'; else if (runtimeError) compatibilityError = runtimeError; else if (producesProperty.status === 'invalid') compatibilityError = 'behavior_produces_invalid'; else if (produces !== undefined) compatibilityError = behaviorProducesDiagnostic(produces); return deepFreezeBehaviorValue({ id, name, description, ...(localizations === undefined ? {} : { localizations: structuredClone(localizations) }), inputs, execution, ...(stateMode === undefined ? {} : { stateMode }), everyTicks, ...(produces === undefined ? {} : { produces: [...produces] }), ...(runtime === undefined ? {} : { runtime }), ...(compatibilityError === undefined ? {} : { compatibilityError }), }); } /** Resolves a scanner diagnostic after applying a Host-authenticated Event grant. */ export function behaviorSourceCompatibilityError( source: ResolvedClawclawBehaviorSource, ): string | undefined { const error = source.compatibilityError; if (!error?.startsWith('behavior_produces_reserved:')) return error; const eventType = error.slice('behavior_produces_reserved:'.length); return source.allowReservedProduces?.includes(eventType) ? undefined : error; } /** Finds the literal manifest owned by one exported class, without importing its code. */ function classManifest(source: string, match: RegExpExecArray): string | undefined { const body = balancedBlock(source, match.index + match[0].lastIndexOf('{')); if (!body) return undefined; const maskedBody = maskNonCode(body, true); const manifest = STATIC_MANIFEST.exec(maskedBody); if (!manifest || STATIC_MANIFEST.test(maskedBody.slice(manifest.index + manifest[0].length))) return undefined; return balancedBlock(body, manifest.index + manifest[0].lastIndexOf('{')) ?? undefined; } /** Inspects one direct-child source using literal parsing only; it never imports player code. */ export function inspectClawclawBehaviorSource( sourcePath: string, sourceRoot: string, ): ResolvedClawclawBehaviorSource | null { let root: string; let path: string; let source: string; try { root = realpathSync(sourceRoot); path = realpathSync(sourcePath); if (!pathInside(root, path) || dirname(path) !== root) return null; source = readFileSync(path, 'utf8'); } catch { return null; } if ( Buffer.byteLength(source, 'utf8') > MAX_BEHAVIOR_SOURCE_BYTES || !SAFE_IMPORT.test(maskNonCode(source, false)) ) { return null; } const masked = maskNonCode(source, true); const classMatch = DEFAULT_CLASS.exec(masked); const manifest = classMatch && classManifest(source, classMatch); if (!manifest) return null; const compatible = sourceCompatibility(manifest); if (!compatible.id) return null; const apiVersionProperty = literalProperty(manifest, 'apiVersion'); const apiVersion = apiVersionProperty.status === 'valid' && Number.isSafeInteger(apiVersionProperty.value) ? apiVersionProperty.value as number : undefined; let trigger: ResolvedClawclawBehaviorSource['trigger']; let triggerError: string | undefined; const namedTrigger = NAMED_TRIGGER.exec(masked); if (namedTrigger) { try { const match = TRIGGER_CLASS.exec(masked.slice(namedTrigger.index)); if (!match) throw Error('strategy_trigger_requires_perception_v3'); match.index = namedTrigger.index; const literal = classManifest(source, match); trigger = { manifest: normalizeStrategyPerception(literal && parseLiteralModuleManifest(literal), compatible.id), sha256: createHash('sha256').update(source).digest('hex'), }; } catch (error) { triggerError = error instanceof Error ? error.message : 'strategy_trigger_manifest_invalid'; } } return deepFreezeBehaviorValue({ ...(trigger ? { trigger } : {}), ...(triggerError ? { triggerError } : {}), ...(apiVersion === undefined ? {} : { apiVersion }), ...compatible, id: compatible.id, sourcePath: path, sourceRoot: root, ...(trigger ? { trustedSourceSha256: trigger.sha256 } : {}), }); } /** Lists top-level ClawclawBehavior classes without evaluating module source. */ export function listClawclawBehaviorSources( behaviorsDir: string, ): readonly ResolvedClawclawBehaviorSource[] { if (!existsSync(behaviorsDir)) return []; let root: string; let files: string[]; try { root = realpathSync(behaviorsDir); files = readdirSync(root) .filter((file) => ( !file.startsWith('_') && !file.endsWith('.d.ts') && !file.endsWith('.test.ts') && /\.(?:ts|js)$/.test(file) )) .sort() .slice(0, MAX_BEHAVIOR_FILES); } catch { return []; } const sources: ResolvedClawclawBehaviorSource[] = []; for (const file of files) { const source = inspectClawclawBehaviorSource(join(root, file), root); if (source) sources.push(source); } return Object.freeze(sources); } export function resolveClawclawBehaviorSource( id: string, behaviorsDir: string, ): ResolvedClawclawBehaviorSource { const matches = listClawclawBehaviorSources(behaviorsDir) .filter((candidate) => candidate.id === id); if (matches.length === 0) throw new Error(`Unknown behavior module '${id}'.`); if (matches.length > 1) throw new Error(`Duplicate behavior module id '${id}'.`); return matches[0]; }