import { existsSync, readFileSync, readdirSync, realpathSync, } from 'node:fs'; import { dirname, isAbsolute, join, relative, } from 'node:path'; import { getWorkspaceDir } from '../../../../lib/init-command.js'; import { ensureUserDataLayout, getUserDataPerceptionsDir, } from '../../../../lib/user-data.js'; import type { ClawclawPerceptionEventMetadata, ClawclawPerceptionManifest, ClawclawResourceLocalizations, } from './contracts.js'; import { PERCEPTION_PLUGIN_API_VERSION } from './contracts.js'; import { literalPluginApiVersion } from '../plugin-api-version.js'; import { parseLiteralModuleManifest } from '../behavior-input-source.js'; import { normalizeReactionManifest } from '../../reaction-manifest.js'; import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js'; import { normalizeReminderManifest } from '../../reminder-manifest.js'; import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js'; import { normalizePerceptionModuleManifest, REMOVED_PERCEPTION_INPUT_TYPES } from '../../perception-module-manifest.js'; import type { PerceptionModuleManifest } from '../../../../sdk/perception-plugin/module.js'; export const MAX_PERCEPTION_FILES = 512; const MAX_PERCEPTION_SOURCE_BYTES = 2 * 1024 * 1024; const SAFE_IMPORT = /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/perception-plugin/; const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+(ClawclawPerception|ClawclawParallelPerception|ClawclawReminder|ClawclawReaction)(?:\s*<[^>{}]*>)?\s*\{/; const STATIC_MANIFEST = /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/; export interface ResolvedClawclawPerceptionSource { /** Literal source declaration; retained so the loader can diagnose unsupported modules. */ readonly apiVersion?: number; readonly compatibilityError?: string; readonly id: string; readonly declaredId?: string; readonly workingCopyPath?: string; readonly name: string; readonly display?: Readonly<{ name: string; description: string }>; readonly description: string; readonly manifest: ClawclawPerceptionManifest; /** Non-visual execution contract; manifest above is the common resource descriptor. */ readonly reminder?: ClawclawReminderManifest; readonly module?: PerceptionModuleManifest; readonly reaction?: ClawclawReactionManifest; readonly embedded?: Readonly<{ strategyId: string; sha256: string; declaredManifest: PerceptionModuleManifest }>; readonly sourcePath: string; readonly sourceRoot: string; } export function expectedPerceptionApiVersion(source: ResolvedClawclawPerceptionSource): number { return source.reaction ? 2 : source.module ? 3 : 2; } export function isSupportedPerceptionSource(source: ResolvedClawclawPerceptionSource): boolean { return !source.compatibilityError && source.apiVersion === expectedPerceptionApiVersion(source); } function pathInside(root: string, candidate: string): boolean { const child = relative(root, candidate); return child === '' || (!child.startsWith('..') && !isAbsolute(child)); } function balancedBlock(source: string, open: number, openChar: '{' | '[', closeChar: '}' | ']'): string | null { let depth = 0; let quote: "'" | '"' | '`' | undefined; let escaped = false; let lineComment = false; let blockComment = false; for (let index = open; 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 === openChar) depth += 1; if (char !== closeChar) continue; depth -= 1; if (depth === 0) return source.slice(open, index + 1); if (depth < 0) return null; } return null; } function topLevelObjectPropertyBlock(source: string, property: string): string | null | undefined { let depth = 0; 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; 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; continue; } if (char === '}') { depth -= 1; continue; } if (depth !== 1 || !source.startsWith(property, index)) continue; const before = source[index - 1] ?? ''; const afterName = source[index + property.length] ?? ''; if (/[A-Za-z0-9_$]/.test(before) || /[A-Za-z0-9_$]/.test(afterName)) continue; const match = /^\s*:\s*\{/.exec(source.slice(index + property.length)); if (!match) continue; const open = index + property.length + match[0].lastIndexOf('{'); return balancedBlock(source, open, '{', '}'); } return undefined; } function decodeString(raw: string, quote: "'" | '"' | '`'): string | null { let decoded = ''; for (let index = 0; index < raw.length; index += 1) { const char = raw[index]!; if (char !== '\\') { if (quote !== '`' && (char === '\n' || char === '\r')) return null; decoded += char; continue; } const escaped = raw[index + 1]; if (escaped === undefined) return null; index += 1; if (escaped === '\n') continue; if (escaped === '\r') { if (raw[index + 1] === '\n') index += 1; continue; } const simple = { "'": "'", '"': '"', '`': '`', '\\': '\\', n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', v: '\v', 0: '\0', } as const; if (escaped in simple) { if (escaped === '0' && /[0-9]/.test(raw[index + 1] ?? '')) return null; decoded += simple[escaped as keyof typeof simple]; continue; } if (escaped === 'x') { const digits = raw.slice(index + 1, index + 3); if (!/^[0-9a-fA-F]{2}$/.test(digits)) return null; decoded += String.fromCharCode(Number.parseInt(digits, 16)); index += 2; continue; } if (escaped === 'u') { if (raw[index + 1] === '{') { const close = raw.indexOf('}', index + 2); if (close < 0) return null; const digits = raw.slice(index + 2, close); if (!/^[0-9a-fA-F]{1,6}$/.test(digits)) return null; const codePoint = Number.parseInt(digits, 16); if (codePoint > 0x10ffff) return null; decoded += String.fromCodePoint(codePoint); index = close; continue; } const digits = raw.slice(index + 1, index + 5); if (!/^[0-9a-fA-F]{4}$/.test(digits)) return null; decoded += String.fromCharCode(Number.parseInt(digits, 16)); index += 4; continue; } return null; } return decoded; } function literalProperty(source: string, property: string): string | null { const match = new RegExp(`\\b${property}\\s*:\\s*(["'\x60])`, 'm').exec(source); if (!match) return null; const quote = match[1]; const start = match.index + match[0].length; let escaped = false; for (let index = start; index < source.length; index += 1) { const char = source[index]; if (escaped) { escaped = false; continue; } if (char === '\\') { escaped = true; continue; } if (char !== quote) continue; const raw = source.slice(start, index); if (quote === '`' && raw.includes('${')) return null; return decodeString(raw, quote as "'" | '"' | '`'); } return null; } function literalStringArray(source: string, property: string): string[] | null { const match = new RegExp(`\\b${property}\\s*:\\s*\\[`, 'm').exec(source); if (!match) return null; const open = match.index + match[0].lastIndexOf('['); const block = balancedBlock(source, open, '[', ']'); if (!block) return null; const values: string[] = []; const matcher = /(["'\x60])((?:\\.|(?!\1)[\s\S])*)\1/g; let item: RegExpExecArray | null; while ((item = matcher.exec(block)) !== null) { if (item[1] === '`' && item[2].includes('${')) return null; const decoded = decodeString(item[2], item[1] as "'" | '"' | '`'); if (decoded === null) return null; values.push(decoded); } const residue = block.slice(1, -1).replace(matcher, '').replace(/[\s,]/g, ''); return residue.length === 0 ? values : null; } function literalLocalizations( source: string, ): ClawclawResourceLocalizations | null | undefined { const block = topLevelObjectPropertyBlock(source, 'localizations'); if (block === undefined || block === null) return block; const values: Record = {}; const entry = /(["'\x60])((?:\\.|(?!\1)[\s\S])*)\1\s*:\s*\{/g; let cursor = 1; let match: RegExpExecArray | null; while ((match = entry.exec(block)) !== null) { if (block.slice(cursor, match.index).replace(/[\s,]/g, '')) return null; if (match[1] === '`' && match[2].includes('${')) return null; const locale = decodeString(match[2], match[1] as "'" | '"' | '`')?.trim(); const entryOpen = match.index + match[0].lastIndexOf('{'); const entryBlock = balancedBlock(block, entryOpen, '{', '}'); if (!locale || !entryBlock || values[locale]) return null; const name = literalProperty(entryBlock, 'name')?.trim(); const description = literalProperty(entryBlock, 'description')?.trim(); if (!name || !description) return null; values[locale] = { name, description }; cursor = entryOpen + entryBlock.length; entry.lastIndex = cursor; } if (block.slice(cursor, -1).replace(/[\s,]/g, '')) return null; return values; } function literalEventMetadata( source: string, ): Readonly> | null | undefined { const block = topLevelObjectPropertyBlock(source, 'eventMetadata'); if (block === undefined || block === null) return block; const values: Record = {}; const entry = /(["'\x60])((?:\\.|(?!\1)[\s\S])*)\1\s*:\s*\{/g; let cursor = 1; let match: RegExpExecArray | null; while ((match = entry.exec(block)) !== null) { if (block.slice(cursor, match.index).replace(/[\s,]/g, '')) return null; if (match[1] === '`' && match[2].includes('${')) return null; const type = decodeString(match[2], match[1] as "'" | '"' | '`')?.trim(); const entryOpen = match.index + match[0].lastIndexOf('{'); const entryBlock = balancedBlock(block, entryOpen, '{', '}'); if (!type || !entryBlock || values[type]) return null; const name = literalProperty(entryBlock, 'name')?.trim(); const description = literalProperty(entryBlock, 'description')?.trim(); const localizations = literalLocalizations(entryBlock); if (!name || !description || localizations === null) return null; values[type] = { name, description, ...(localizations === undefined ? {} : { localizations }), }; cursor = entryOpen + entryBlock.length; entry.lastIndex = cursor; } if (block.slice(cursor, -1).replace(/[\s,]/g, '')) return null; return values; } function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPerceptionSource | null { let source: string; try { source = readFileSync(sourcePath, 'utf8'); } catch { return null; } if (Buffer.byteLength(source, 'utf8') > MAX_PERCEPTION_SOURCE_BYTES || !SAFE_IMPORT.test(source)) return null; const classMatch = DEFAULT_CLASS.exec(source); if (!classMatch) return null; const classOpen = classMatch.index + classMatch[0].lastIndexOf('{'); const classBody = balancedBlock(source, classOpen, '{', '}'); if (!classBody) return null; const manifestMatch = STATIC_MANIFEST.exec(classBody); if (!manifestMatch) return null; const manifestOpen = manifestMatch.index + manifestMatch[0].lastIndexOf('{'); const manifestBlock = balancedBlock(classBody, manifestOpen, '{', '}'); if (!manifestBlock) return null; if (classMatch[1] === 'ClawclawPerception' && /\bevaluate\s*\(/.test(classBody) && literalPluginApiVersion(manifestBlock) !== 2) { try { const module = normalizePerceptionModuleManifest(parseLiteralModuleManifest(manifestBlock), false, true); const { id, description, localizations } = module; return { ...removedInputDiagnosis(module.consumes ?? []), apiVersion: module.apiVersion, id, name: module.name ?? id, description, module, sourcePath, sourceRoot, // Existing resource metadata consumers use this v2-shaped descriptor; executable v3 stays in module. manifest: { apiVersion: PERCEPTION_PLUGIN_API_VERSION, id, name: module.name ?? id, description, localizations, subjectScope: 'self_and_others', produces: module.produces ?? [] } }; } catch { return null; } } if (classMatch[1] === 'ClawclawReaction') { try { const reaction = normalizeReactionManifest(parseLiteralModuleManifest(manifestBlock), false); const { kind: _kind, ...common } = reaction; const module: PerceptionModuleManifest = { ...common, apiVersion: 3 }; return { apiVersion: reaction.apiVersion, id: reaction.id, name: reaction.name ?? reaction.id, description: reaction.description, module, reaction, sourcePath, sourceRoot, manifest: { apiVersion: 2, id: reaction.id, name: reaction.name ?? reaction.id, description: reaction.description, localizations: reaction.localizations, subjectScope: 'self_and_others', produces: reaction.produces } }; } catch { return null; } } if (classMatch[1] === 'ClawclawReminder') { try { const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false, true); const { id, description, localizations } = reminder; const name = reminder.name ?? id; return { ...removedInputDiagnosis(reminder.consumes), apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot, manifest: { apiVersion: reminder.apiVersion, id, name, description, localizations, subjectScope: 'self_and_others', produces: [] } }; } catch { return null; } } const apiVersion = literalPluginApiVersion(manifestBlock) ?? null; const id = literalProperty(manifestBlock, 'id')?.trim(); const name = literalProperty(manifestBlock, 'name')?.trim() ?? id; const description = literalProperty(manifestBlock, 'description')?.trim(); const subjectScope = literalProperty(manifestBlock, 'subjectScope')?.trim(); const produces = literalStringArray(manifestBlock, 'produces'); const execution = literalProperty(manifestBlock, 'execution')?.trim(); const boundaryBaseline = literalProperty(manifestBlock, 'boundaryBaseline')?.trim(); const localizations = literalLocalizations(manifestBlock); const eventMetadata = literalEventMetadata(manifestBlock); const hasWakePolicy = /\bwakeAgent\s*:/.test(manifestBlock); const wakeValue = /\bwakeAgent\s*:\s*(true|false)\b\s*(?=,|}|\n|\/\/|\/\*)/.exec(manifestBlock)?.[1]; if (hasWakePolicy && wakeValue === undefined) return null; const parallelClass = classMatch[1] === 'ClawclawParallelPerception'; if ( !id || !name || !description || !/^[a-z0-9][a-z0-9._-]*$/.test(id) || !['others', 'self_and_others', 'visible_pairs', 'corpses'].includes(subjectScope ?? '') || !produces || produces.length === 0 || produces.some((type) => !/^visual\.[a-z0-9_.-]+$/.test(type)) || new Set(produces).size !== produces.length || (execution !== undefined && execution !== 'parallel_analysis') || ( boundaryBaseline !== undefined && (execution !== 'parallel_analysis' || boundaryBaseline !== 'current_only') ) || parallelClass !== (execution === 'parallel_analysis') || localizations === null || eventMetadata === null || ( eventMetadata !== undefined && ( Object.keys(eventMetadata).length !== produces.length || Object.keys(eventMetadata).some((type) => !produces.includes(type)) ) ) ) return null; const manifest = { ...(apiVersion === null ? {} : { apiVersion: apiVersion as typeof PERCEPTION_PLUGIN_API_VERSION, }), id, name, description, ...(localizations === undefined ? {} : { localizations }), ...(wakeValue === undefined ? {} : { wakeAgent: wakeValue === 'true' }), subjectScope: subjectScope as ClawclawPerceptionManifest['subjectScope'], produces, ...(eventMetadata === undefined ? {} : { eventMetadata }), ...(execution ? { execution: 'parallel_analysis' as const } : {}), ...(boundaryBaseline ? { boundaryBaseline: 'current_only' as const } : {}), } as ClawclawPerceptionManifest; return { ...(apiVersion === null ? {} : { apiVersion }), id, name, description, manifest, sourcePath, sourceRoot, }; } /** Lists one explicit perception directory without evaluating module code. */ export function listClawclawPerceptionSourcesInDirectory( configuredDir: string, ): ResolvedClawclawPerceptionSource[] { if (!existsSync(configuredDir)) return []; let root: string; let files: string[]; try { root = realpathSync(configuredDir); files = readdirSync(root) .filter((file) => ( !file.startsWith('_') && !file.endsWith('.d.ts') && !file.endsWith('.test.ts') && /\.(?:ts|js)$/.test(file) )) .sort() .slice(0, MAX_PERCEPTION_FILES); } catch { return []; } const sources: ResolvedClawclawPerceptionSource[] = []; for (const file of files) { try { const sourcePath = realpathSync(join(root, file)); if (!pathInside(root, sourcePath) || dirname(sourcePath) !== root) continue; const source = parseSource(sourcePath, root); if (!source) continue; sources.push(source); } catch {} } return sources; } /** Lists installed workspace perception classes by reading static manifests only. */ export function listClawclawPerceptionSources( workspaceDir = getWorkspaceDir(), ): ResolvedClawclawPerceptionSource[] { ensureUserDataLayout(workspaceDir); return listClawclawPerceptionSourcesInDirectory(getUserDataPerceptionsDir(workspaceDir)); } export function resolveClawclawPerceptionSource( id: string, workspaceDir = getWorkspaceDir(), ): ResolvedClawclawPerceptionSource { const source = listClawclawPerceptionSources(workspaceDir).find((candidate) => candidate.id === id); if (!source) throw new Error(`Unknown perception module '${id}'.`); return source; } function removedInputDiagnosis(consumes: readonly string[]): { compatibilityError?: string } { const removed = consumes.filter(type => REMOVED_PERCEPTION_INPUT_TYPES.has(type)); return removed.length ? { compatibilityError: `perception_input_removed:${removed.join(',')}:use gameState, frame or module-local taskChanges` } : {}; }