export type ClawclawPluginKind = 'strategy' | 'intent' | 'perception'; export interface PluginApiVersionStatus { readonly api_version: number | null; readonly expected_api_version: number; readonly loadable: boolean; readonly compatibility_error?: string; } /** Reads one top-level numeric apiVersion without evaluating module source. */ export function literalPluginApiVersion(manifestSource: string): number | undefined { let depth = 0; let quote: "'" | '"' | '`' | undefined; let escaped = false; let lineComment = false; let blockComment = false; for (let index = 0; index < manifestSource.length; index += 1) { const char = manifestSource[index]; const next = manifestSource[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 || !manifestSource.startsWith('apiVersion', index)) continue; const before = manifestSource[index - 1] ?? ''; const after = manifestSource[index + 'apiVersion'.length] ?? ''; if (/[A-Za-z0-9_$]/.test(before) || /[A-Za-z0-9_$]/.test(after)) continue; const match = /^\s*:\s*([0-9]+(?:_[0-9]+)*)\s*(?=,|})/ .exec(manifestSource.slice(index + 'apiVersion'.length)); if (!match) return undefined; const value = Number(match[1].replaceAll('_', '')); return Number.isSafeInteger(value) ? value : undefined; } return undefined; } export function pluginApiVersionDiagnostic( code: string, expected: number, received: number | undefined, ): string { return `${code}:expected=${expected}:received=${received ?? 'missing'}`; } export function assertPluginApiVersion( code: string, expected: number, received: number | undefined, ): void { if (received !== expected) { throw new Error(pluginApiVersionDiagnostic(code, expected, received)); } } export function pluginApiVersionStatus( kind: ClawclawPluginKind, expected: number, received: number | undefined, sourceCompatibilityError?: string, ): PluginApiVersionStatus { const versionLoadable = received === expected; const loadable = versionLoadable && sourceCompatibilityError === undefined; return { api_version: received ?? null, expected_api_version: expected, loadable, ...(loadable ? {} : { compatibility_error: versionLoadable ? sourceCompatibilityError : pluginApiVersionDiagnostic( `${kind}_api_version_unsupported`, expected, received, ), }), }; }