import { existsSync, readFileSync, readdirSync, realpathSync, } from 'node:fs'; import { dirname, isAbsolute, join, relative, } from 'node:path'; import { hasValidClawclawResourceLocalizations, MAX_TRIGGER_RUNTIME_MS, TRIGGER_PLUGIN_API_VERSION, type ClawclawResourceLocalizations, type ClawclawTriggerManifest, type TriggerRearm, } from '../../../../sdk/trigger-plugin/index.js'; import { normalizeBehaviorInput, } from '../../behavior-input-fields.js'; import { parseLiteralBehaviorInputFields } from '../behavior-input-source.js'; import { literalPluginApiVersion } from '../plugin-api-version.js'; export const MAX_TRIGGER_FILES = 512; const MAX_TRIGGER_SOURCE_BYTES = 2 * 1024 * 1024; const SAFE_IMPORT = /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/trigger-plugin|[./]trigger-plugin(?:\.[cm]?[jt]s)?["']/; const DEFAULT_CLASS = /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+ClawclawTrigger(?:\s*<[^>{}]*>)?\s*\{/; const STATIC_MANIFEST = /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/; const RESOURCE_ID = /^[a-z0-9][a-z0-9._-]*$/; const EVENT_TYPE = /^(?:\*|[a-z0-9][a-z0-9._-]*)$/; export interface ResolvedClawclawTriggerSource { /** Retained as a number so the loader can reject unsupported versions without evaluating code. */ readonly apiVersion: number; readonly id: string; readonly name: string; readonly description: string; readonly manifest: ClawclawTriggerManifest; readonly sourcePath: string; readonly sourceRoot: string; } interface ParsedValue { readonly value: unknown; readonly next: number; } class LiteralParseError extends Error {} 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('trigger_manifest_literal_invalid'); 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('trigger_manifest_literal_invalid'); } 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('trigger_manifest_not_literal'); } if (char !== '\\') { value += char; continue; } cursor += 1; if (cursor >= source.length) throw new LiteralParseError('trigger_manifest_literal_invalid'); 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 value += escaped; } throw new LiteralParseError('trigger_manifest_literal_invalid'); } 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('trigger_manifest_literal_invalid'); cursor = skipTrivia(source, cursor + 1); if (source[cursor] === ']') return { value: values, next: consumeAsConst(source, cursor + 1) }; } throw new LiteralParseError('trigger_manifest_literal_invalid'); } function parseObject(source: string, start: number): ParsedValue { const value = 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('trigger_manifest_literal_invalid'); key = identifier[0]; cursor = skipTrivia(source, cursor + key.length); } if (Object.hasOwn(value, key)) { throw new LiteralParseError(`trigger_manifest_duplicate_property:${key}`); } if (source[cursor] !== ':') throw new LiteralParseError('trigger_manifest_literal_invalid'); 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('trigger_manifest_literal_invalid'); cursor = skipTrivia(source, cursor + 1); if (source[cursor] === '}') return { value, next: consumeAsConst(source, cursor + 1) }; } throw new LiteralParseError('trigger_manifest_literal_invalid'); } 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 bool = /^(true|false)\b/.exec(source.slice(cursor)); if (bool) return { value: bool[1] === 'true', next: cursor + bool[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('trigger_manifest_literal_invalid'); return { value: parsed, next: cursor + number[0].length }; } throw new LiteralParseError('trigger_manifest_not_literal'); } /** Extract a balanced class/manifest block without evaluating JavaScript. */ function balancedBlock(source: string, open: number): 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') 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; else if (char === '}' && --depth === 0) return source.slice(open, index + 1); } return null; } function propertyStart(source: string, property: string): number | undefined { let depth = 0; for (let cursor = 0; cursor < source.length;) { cursor = skipTrivia(source, cursor); 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] === ':') return skipTrivia(source, colon + 1); } cursor = parsed.next; continue; } if (char === '{') { depth += 1; cursor += 1; continue; } if (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] === ':') return skipTrivia(source, colon + 1); } cursor += identifier.length; continue; } cursor += 1; } return undefined; } function literalProperty(source: string, property: string): unknown | undefined { const start = propertyStart(source, property); if (start === undefined) return undefined; const parsed = parseValue(source, start); const tail = skipTrivia(source, parsed.next); if (source[tail] !== ',' && source[tail] !== '}') { throw new LiteralParseError('trigger_manifest_literal_invalid'); } return parsed.value; } function finiteInteger(value: unknown, minimum: number): value is number { return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum; } function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawTriggerSource | null { let source: string; try { source = readFileSync(sourcePath, 'utf8'); } catch { return null; } if (Buffer.byteLength(source, 'utf8') > MAX_TRIGGER_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 manifestSource = balancedBlock(classBody, manifestOpen); if (!manifestSource) return null; try { const parsedManifest = parseObject(manifestSource, 0).value as Record; const allowedManifestFields = new Set([ 'apiVersion', 'id', 'name', 'description', 'localizations', 'inputs', 'consumes', 'defaultBehavior', 'defaultBehaviorInput', 'defaultReflexPriority', 'defaultCooldownMs', 'defaultRearm', 'defaultMaxRuntimeMs', ]); if (Object.keys(parsedManifest).some((field) => !allowedManifestFields.has(field))) return null; const apiVersion = literalPluginApiVersion(manifestSource); const id = literalProperty(manifestSource, 'id'); const name = literalProperty(manifestSource, 'name'); const description = literalProperty(manifestSource, 'description'); const consumes = literalProperty(manifestSource, 'consumes'); const defaultBehavior = literalProperty(manifestSource, 'defaultBehavior'); const defaultBehaviorInput = literalProperty(manifestSource, 'defaultBehaviorInput'); const defaultReflexPriority = literalProperty(manifestSource, 'defaultReflexPriority'); const defaultCooldownMs = literalProperty(manifestSource, 'defaultCooldownMs'); const defaultRearm = literalProperty(manifestSource, 'defaultRearm'); const defaultMaxRuntimeMs = literalProperty(manifestSource, 'defaultMaxRuntimeMs'); const localizations = literalProperty(manifestSource, 'localizations'); const parsedInputs = parseLiteralBehaviorInputFields(manifestSource); if ( apiVersion === undefined || typeof id !== 'string' || !RESOURCE_ID.test(id) || typeof name !== 'string' || !name.trim() || typeof description !== 'string' || !description.trim() || parsedInputs.status !== 'valid' || parsedInputs.inputs.some((field) => field.default === undefined) || !Array.isArray(consumes) || consumes.some((entry) => typeof entry !== 'string' || !EVENT_TYPE.test(entry)) || new Set(consumes).size !== consumes.length || typeof defaultBehavior !== 'string' || !RESOURCE_ID.test(defaultBehavior) || !defaultBehaviorInput || typeof defaultBehaviorInput !== 'object' || Array.isArray(defaultBehaviorInput) || !finiteInteger(defaultReflexPriority, Number.MIN_SAFE_INTEGER) || !finiteInteger(defaultCooldownMs, 0) || (defaultRearm !== 'after_clear' && defaultRearm !== 'after_cooldown') || !finiteInteger(defaultMaxRuntimeMs, 1) || defaultMaxRuntimeMs > MAX_TRIGGER_RUNTIME_MS || ( localizations !== undefined && ( localizations === null || typeof localizations !== 'object' || Array.isArray(localizations) || !hasValidClawclawResourceLocalizations( localizations as ClawclawResourceLocalizations, ) ) ) ) return null; // A newly enabled Trigger must have usable rule defaults without another // mandatory configuration round-trip. normalizeBehaviorInput({}, parsedInputs.inputs); const manifest: ClawclawTriggerManifest = { apiVersion: apiVersion as typeof TRIGGER_PLUGIN_API_VERSION, id, name: name.trim(), description: description.trim(), ...(localizations === undefined ? {} : { localizations: localizations as ClawclawResourceLocalizations, }), inputs: parsedInputs.inputs, consumes: consumes as string[], defaultBehavior, defaultBehaviorInput: structuredClone(defaultBehaviorInput as Record), defaultReflexPriority, defaultCooldownMs, defaultRearm: defaultRearm as TriggerRearm, defaultMaxRuntimeMs, }; return { apiVersion, id, name: manifest.name, description: manifest.description, manifest, sourcePath, sourceRoot, }; } catch { return null; } } /** Lists Trigger classes by reading literal manifests without evaluating source. */ export function listClawclawTriggerSources(triggersDir: string): ResolvedClawclawTriggerSource[] { if (!existsSync(triggersDir)) return []; let root: string; let files: string[]; try { root = realpathSync(triggersDir); files = readdirSync(root) .filter((file) => ( !file.startsWith('_') && !file.endsWith('.d.ts') && !file.endsWith('.test.ts') && /\.(?:ts|js)$/.test(file) )) .sort() .slice(0, MAX_TRIGGER_FILES); } catch { return []; } const grouped = new Map(); for (const file of files) { try { const sourcePath = realpathSync(join(root, file)); if (!pathInside(root, sourcePath) || dirname(sourcePath) !== root) continue; const parsed = parseSource(sourcePath, root); if (!parsed) continue; const duplicates = grouped.get(parsed.id) ?? []; duplicates.push(parsed); grouped.set(parsed.id, duplicates); } catch {} } // Trigger modules can preempt role control. Ambiguous duplicate identities // fail closed instead of inheriting the lower-privilege resource last-wins rule. return [...grouped.values()] .filter((sources) => sources.length === 1) .map(([source]) => source!); } export function resolveClawclawTriggerSource( id: string, triggersDir: string, ): ResolvedClawclawTriggerSource { const source = listClawclawTriggerSources(triggersDir).find((candidate) => candidate.id === id); if (!source) throw new Error(`Unknown or ambiguous trigger module '${id}'.`); return source; }