#!/usr/bin/env node /** * 将当前 env 中的 code-run 灰度配置写入 h5_agent_code_run_config(一次性迁移)。 * * Usage: * node scripts/migrate-agent-code-run-config-from-env.mjs * node scripts/migrate-agent-code-run-config-from-env.mjs --dry-run * node scripts/migrate-agent-code-run-config-from-env.mjs --updated-by */ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { loadH5Environment } from './load-env.mjs'; import { createDbPool } from '../db.mjs'; import { agentCodeRunAdminConfigInternals, createAgentCodeRunAdminConfigService, } from '../agent-code-run-admin-config.mjs'; const repoRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); function parseArgs(argv) { const options = { dryRun: false, updatedBy: null, force: false }; for (let i = 0; i < argv.length; i += 1) { const arg = argv[i]; if (arg === '--dry-run') options.dryRun = true; else if (arg === '--force') options.force = true; else if (arg === '--updated-by' && argv[i + 1]) options.updatedBy = argv[++i]; else if (arg === '-h' || arg === '--help') { console.log('Usage: node scripts/migrate-agent-code-run-config-from-env.mjs [--dry-run] [--force] [--updated-by ]'); process.exit(0); } else { throw new Error(`未知参数: ${arg}`); } } return options; } async function main() { loadH5Environment(import.meta.dirname); const options = parseArgs(process.argv.slice(2)); if (String(process.env.MEMIND_CODE_RUN_POLICY_SOURCE ?? '').trim().toLowerCase() === 'env') { throw new Error('MEMIND_CODE_RUN_POLICY_SOURCE=env 时不应写入 admin-db'); } const pool = createDbPool(); const service = createAgentCodeRunAdminConfigService(pool, { env: process.env }); const current = await service.getAdminConfig(); const envConfig = agentCodeRunAdminConfigInternals.buildConfigFromEnv(process.env); console.log('==> migrate agent code run config from env'); console.log(` current source: ${current.source}`); console.log(` env enabled: ${envConfig.codeRun.enabled}`); console.log(` env clientEnabled: ${envConfig.codeRun.clientEnabled}`); console.log(` env pageDataDev.autodetect: ${envConfig.pageDataDev.autodetect}`); if (current.source === 'admin-db' && !options.force) { console.log('\nadmin-db 已有配置;加 --force 才会覆盖'); await pool.end(); process.exit(0); } if (options.dryRun) { console.log('\n(dry-run) 将写入:'); console.log(JSON.stringify(envConfig, null, 2)); await pool.end(); process.exit(0); } const saved = await service.updateAdminConfig( { config: envConfig, meta: { notes: 'migrated from env via migrate-agent-code-run-config-from-env.mjs' } }, { updatedBy: options.updatedBy }, ); console.log('\n✔ 已写入 admin-db'); console.log(JSON.stringify(saved, null, 2)); await pool.end(); } main().catch((error) => { console.error(error instanceof Error ? error.stack ?? error.message : error); process.exit(1); });