#!/usr/bin/env node import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { tsImport } from 'tsx/esm/api'; import { spawnSync } from 'node:child_process'; // Plugin declarations resolve workspace packages to authoring sources after an // install-only checkout; generated lib/ artifacts are never a prerequisite. if (!process.execArgv.includes('--conditions=development')) { const result = spawnSync(process.execPath, ['--conditions=development', ...process.argv.slice(1)], { stdio: 'inherit' }); if (result.error) throw result.error; process.exit(result.status ?? 1); } const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const checkOnly = process.argv.includes('--check'); const hostSource = 'packages/host/gateway/src/config/configuration-projection.ts'; const hostReferencePath = 'packages/im/runtime/src/host-config-schema.json'; const planReferencePath = 'packages/im/ai/provider-plan.schema.json'; const planReference = JSON.parse(fs.readFileSync(path.join(repoRoot, planReferencePath), 'utf8')); const hostReference = JSON.parse(fs.readFileSync(path.join(repoRoot, hostReferencePath), 'utf8')); const hostRuntimeSource = fs.readFileSync(path.join(repoRoot, hostSource), 'utf8'); const composerSource = 'packages/im/runtime/src/config-composer.ts'; const composer = fs.readFileSync(path.join(repoRoot, composerSource), 'utf8'); if (!hostRuntimeSource.includes("import { HOST_CONFIG_KEYS") || !composer.includes("import hostConfigSchema from './host-config-schema.json'") || !composer.includes('...HOST_CONFIG_SCHEMA.properties')) { throw new Error(`${hostReferencePath} must remain the shared Runtime/Console Host configuration Schema`); } function listPluginRoots() { const result = []; const root = path.join(repoRoot, 'plugins'); for (const category of fs.readdirSync(root, { withFileTypes: true })) { if (!category.isDirectory()) continue; for (const plugin of fs.readdirSync(path.join(root, category.name), { withFileTypes: true })) { if (!plugin.isDirectory()) continue; const pluginRoot = path.join(root, category.name, plugin.name); if (fs.existsSync(path.join(pluginRoot, 'package.json'))) result.push(pluginRoot); } } return result.sort(); } function resolveSchema(schema, rootSchema, fieldPath) { if (!schema?.$ref) return schema; if (typeof schema.$ref !== 'string' || !schema.$ref.startsWith('#/')) { throw new Error(`${fieldPath}: only local JSON Schema references are supported`); } let resolved = rootSchema; for (const rawSegment of schema.$ref.slice(2).split('/')) { const segment = rawSegment.replaceAll('~1', '/').replaceAll('~0', '~'); resolved = resolved?.[segment]; } if (!resolved || typeof resolved !== 'object' || Array.isArray(resolved)) { throw new Error(`${fieldPath}: unresolved JSON Schema reference ${schema.$ref}`); } const { $ref: _reference, ...siblings } = schema; return { ...resolved, ...siblings }; } function displayType(schema, fieldPath, rootSchema = schema) { const resolved = resolveSchema(schema, rootSchema, fieldPath); if (Array.isArray(resolved.anyOf)) { if (resolved.anyOf.length === 0) throw new Error(`${fieldPath}: anyOf must not be empty`); return resolved.anyOf.map((option, index) => displayType(option, `${fieldPath}.anyOf[${index}]`, rootSchema)).join(' | '); } if (Object.hasOwn(resolved, 'const')) { return formatValue(resolved.const); } if (resolved.type === 'array' && resolved.items) { return `array<${displayType(resolved.items, `${fieldPath}.items`, rootSchema)}>`; } const type = Array.isArray(resolved.type) ? resolved.type.join(' | ') : resolved.type; const base = typeof type === 'string' ? type : resolved.enum ? 'enum' : resolved.properties ? 'object' : undefined; if (!base) throw new Error(`${fieldPath}: unsupported Schema shape; add explicit generator support`); return resolved.enum ? `${base}: ${resolved.enum.map(formatValue).join(', ')}` : base; } function formatValue(value) { return value === undefined ? '—' : `\`${JSON.stringify(value)}\``; } function escapeCell(value) { return String(value ?? '—') .replaceAll('&', '&') .replaceAll('<', '<') .replaceAll('>', '>') .replaceAll('|', '\\|') .replaceAll('\n', ' '); } function flattenProperties(schema, prefix, inheritedRequired = new Set(), rootSchema = schema) { const resolvedSchema = resolveSchema(schema, rootSchema, prefix); const properties = resolvedSchema?.properties && typeof resolvedSchema.properties === 'object' ? resolvedSchema.properties : {}; const required = new Set(Array.isArray(resolvedSchema?.required) ? resolvedSchema.required : inheritedRequired); const rows = []; for (const [key, value] of Object.entries(properties)) { if (!value || typeof value !== 'object' || Array.isArray(value)) continue; const fieldPath = prefix ? `${prefix}.${key}` : key; const resolvedValue = resolveSchema(value, rootSchema, fieldPath); rows.push({ path: fieldPath, type: displayType(resolvedValue, fieldPath, rootSchema), required: required.has(key), defaultValue: formatValue(resolvedValue.default), description: resolvedValue['x-i18n']?.en?.description ?? resolvedValue.description ?? resolvedValue['x-descriptionZh'] ?? '—', descriptionZh: resolvedValue['x-i18n']?.['zh-CN']?.description ?? resolvedValue['x-descriptionZh'] ?? resolvedValue.description ?? '—', }); if (resolvedValue.type === 'object' || resolvedValue.properties) { rows.push(...flattenProperties(resolvedValue, fieldPath, new Set(), rootSchema)); } else if (resolvedValue.type === 'array' && resolvedValue.items) { const resolvedItems = resolveSchema(resolvedValue.items, rootSchema, `${fieldPath}[]`); if (resolvedItems.properties) { rows.push(...flattenProperties(resolvedItems, `${fieldPath}[]`, new Set(), rootSchema)); } } if (resolvedValue.additionalProperties && typeof resolvedValue.additionalProperties === 'object' && !Array.isArray(resolvedValue.additionalProperties)) { const placeholder = resolvedValue['x-keyPlaceholder'] ?? ''; rows.push(...flattenProperties( resolvedValue.additionalProperties, `${fieldPath}.${placeholder}`, new Set(), rootSchema, )); } } return rows; } /** Root `x-zhin-config` layered declaration (ADR 0050 / 0055) plus the properties narrowed to global. */ function featureLevels(schema) { const meta = schema['x-zhin-config']; if (!meta || !Array.isArray(meta.levels) || meta.levels.length <= 1) return undefined; const globalOnly = Object.entries(schema.properties ?? {}) .filter(([, child]) => { const levels = child?.['x-zhin-config']?.levels; return Array.isArray(levels) && levels.length === 1 && levels[0] === 'global'; }) .map(([name]) => name); return { levels: meta.levels, conversationFields: meta.conversationFields ?? [], selfServiceFields: meta.selfServiceFields ?? [], chatAdminFields: meta.chatAdminFields, globalOnly, fieldCount: Object.keys(schema.properties ?? {}).length, }; } function renderFeatureLevels(feature, zh) { const list = items => items.map(item => `\`${item}\``).join(zh ? '、' : ', '); const parts = [`${zh ? '层级' : 'Levels'}: ${list(feature.levels)}`]; if (feature.fieldCount > 0) { parts.push(feature.globalOnly.length === feature.fieldCount ? (zh ? '字段仅全局' : 'fields: global only') : feature.globalOnly.length ? `${zh ? '仅全局(其余字段可在适配器 / 账号层覆盖)' : 'global only (other fields can be overridden per adapter / account)'}: ${list(feature.globalOnly)}` : (zh ? '全部字段可在适配器 / 账号层覆盖' : 'every field can be overridden per adapter / account')); } if (feature.levels.includes('conversation')) { parts.push(`${zh ? '会话层字段' : 'conversation fields'}: ${feature.conversationFields.length ? list(feature.conversationFields) : (zh ? '仅开关' : 'switch only')}`); if (feature.selfServiceFields.length) parts.push(`${zh ? '群内自助' : 'in-chat self-service'}: ${list(feature.selfServiceFields)}`); if (feature.chatAdminFields?.length) parts.push(`${zh ? '聊天中上级层字段' : 'chat admin fields'}: ${list(feature.chatAdminFields)}`); } return `> ${zh ? '分层配置(ADR 0050 / 0055)' : 'Layered configuration (ADR 0050 / 0055)'} — ${parts.join(zh ? ';' : '; ')}`; } async function pluginEntries() { const { readPluginConfigSchema } = await tsImport( pathToFileURL(path.join(repoRoot, 'packages/im/runtime/src/plugin-config-schema.ts')).href, import.meta.url, ); const result = []; for (const root of listPluginRoots()) { const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); if (packageJson.zhin?.type !== 'plugin') continue; const file = path.join(root, 'schema.json'); const hasFileSchema = fs.existsSync(file); const entry = path.join(root, packageJson.zhin.entry); const typescriptEntry = entry.endsWith('.js') ? entry.slice(0, -3) + '.ts' : entry; // Documentation points at the canonical source even while prepack has // temporarily generated the corresponding package-root JavaScript entry. const sourceEntry = fs.existsSync(typescriptEntry) ? typescriptEntry : entry; const modules = !hasFileSchema && packageJson.zhin.runtime !== 'isolated' && fs.existsSync(sourceEntry) ? { load: () => tsImport(pathToFileURL(sourceEntry).href, import.meta.url) } : undefined; const schema = await readPluginConfigSchema({ root, name: packageJson.name, packageJson }, modules); if (!schema) continue; const configHelper = path.join(root, 'src/config.ts'); const importedConfigHelper = !hasFileSchema && fs.existsSync(configHelper) && /from\s+['"]\.\/src\/config\.js['"]/u.test(fs.readFileSync(sourceEntry, 'utf8')) && /Schema\.object\(/u.test(fs.readFileSync(configHelper, 'utf8')); const relative = path.relative(repoRoot, hasFileSchema ? file : importedConfigHelper ? configHelper : sourceEntry).split(path.sep).join('/'); const key = path.basename(root); result.push({ key, relative, rows: flattenProperties(schema, key, new Set(), schema), feature: featureLevels(schema) }); } return result; } const plugins = await pluginEntries(); function tableHeader(locale) { return locale === 'zh' ? '| 路径 | 类型 | 必填 | 默认值 | 说明 |\n| --- | --- | --- | --- | --- |' : '| Path | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |'; } function render(locale) { const zh = locale === 'zh'; const lines = [ '---', `title: ${zh ? '自动生成配置字段参考' : 'Generated configuration field reference'}`, 'outline: [2, 3]', '---', '', `# ${zh ? '自动生成配置字段参考' : 'Generated configuration field reference'}`, '', zh ? '> 本页由源码与 JSON Schema 自动生成,请勿手工编辑。叙事、示例与配置方法见[配置参考](./)。' : '> Generated from runtime source and JSON Schema. Do not edit manually. See [Configuration](./) for narrative guidance and examples.', '', `- ${zh ? '生成命令' : 'Generator'}: \`pnpm docs:config\``, `- ${zh ? '漂移检查' : 'Drift check'}: \`pnpm check:config-reference\``, '', `## ${zh ? 'Host 顶层字段' : 'Host top-level fields'}`, '', zh ? `权威契约来自 Runtime 实际消费的 [\`${hostReferencePath}\`](https://github.com/zhinjs/zhin/blob/main/${hostReferencePath});消费位置见 [\`${hostSource}\`](https://github.com/zhinjs/zhin/blob/main/${hostSource})。` : `The authoritative contract is [\`${hostReferencePath}\`](https://github.com/zhinjs/zhin/blob/main/${hostReferencePath}), consumed by the Runtime at [\`${hostSource}\`](https://github.com/zhinjs/zhin/blob/main/${hostSource}).`, '', tableHeader(locale), ]; for (const row of flattenProperties(hostReference, '', new Set(), hostReference)) { lines.push(`| \`${row.path}\` | ${escapeCell(row.type)} | ${row.required ? (zh ? '是' : 'yes') : (zh ? '否' : 'no')} | ${escapeCell(row.defaultValue)} | ${escapeCell(zh ? row.descriptionZh : row.description)} |`); } lines.push('', `## ${zh ? '独立 AI 导入提案' : 'Standalone AI import proposal'}`, '', zh ? '`ai.plan.yml` 仅供显式预览、应用和导出,不是启动配置,不会自动加载或覆盖运行时图。' : '`ai.plan.yml` is for explicit review, apply and export. It is not startup configuration and never automatically replaces the runtime graph.', '', `[\`${planReferencePath}\`](https://github.com/zhinjs/zhin/blob/main/${planReferencePath})`, '', tableHeader(locale)); for (const row of flattenProperties(planReference, '', new Set(), planReference)) { lines.push(`| \`${row.path}\` | ${escapeCell(row.type)} | ${row.required ? (zh ? '是' : 'yes') : (zh ? '否' : 'no')} | ${escapeCell(row.defaultValue)} | ${escapeCell(zh ? row.descriptionZh : row.description)} |`); } lines.push('', `## ${zh ? '插件实例字段' : 'Plugin instance fields'}`, ''); lines.push(zh ? '以下字段通过 Runtime 的统一读取器从 trusted 插件的 `config: Schema.object(...)` 声明或 `schema.json` 生成;isolated 插件只能使用 `schema.json`。顶层 `` 是默认 instanceKey;`plugins.` 仅保存包引用。' : 'These fields use the Runtime schema reader for trusted plugins’ `config: Schema.object(...)` declarations or `schema.json`; isolated plugins must use `schema.json`. Top-level `` is the default instanceKey; `plugins.` only stores the package reference.'); for (const plugin of plugins) { lines.push('', `### ${plugin.key}`, ''); lines.push(`[\`${plugin.relative}\`](https://github.com/zhinjs/zhin/blob/main/${plugin.relative})`, ''); if (plugin.feature) lines.push(renderFeatureLevels(plugin.feature, zh), ''); if (plugin.rows.length === 0) { lines.push(zh ? '_该 Schema 没有声明字段。_' : '_This Schema declares no fields._'); continue; } lines.push(tableHeader(locale)); for (const row of plugin.rows) { lines.push(`| \`${row.path}\` | ${escapeCell(row.type)} | ${row.required ? (zh ? '是' : 'yes') : (zh ? '否' : 'no')} | ${escapeCell(row.defaultValue)} | ${escapeCell(zh ? row.descriptionZh : row.description)} |`); } } return `${lines.join('\n')}\n`; } const outputs = new Map([ ['docs/configuration/generated.md', render('zh')], ['docs/en/configuration/generated.md', render('en')], ]); const stale = []; for (const [relative, content] of outputs) { const absolute = path.join(repoRoot, relative); if (checkOnly) { if (!fs.existsSync(absolute) || fs.readFileSync(absolute, 'utf8') !== content) stale.push(relative); } else { fs.mkdirSync(path.dirname(absolute), { recursive: true }); fs.writeFileSync(absolute, content); } } if (stale.length > 0) { console.error(`Generated configuration reference is stale:\n- ${stale.join('\n- ')}\nRun pnpm docs:config.`); process.exitCode = 1; } else { console.log(checkOnly ? 'Generated configuration reference is current.' : 'Generated configuration reference updated.'); }