From 6f012d419a6cf699cf8d0ea4c820ed8d5b8b2097 Mon Sep 17 00:00:00 2001 From: suzmii Date: Fri, 18 Sep 2026 11:11:07 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DMac=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E9=9A=8F=E5=8C=85=E8=BF=90=E8=A1=8C=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=E7=BC=BA=E5=A4=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 统一Codex平台布局并补齐macOS原生组件、完整性清单和资源加载路径 补齐macOS插件资源并保留Windows专属原生桥接边界 增加隔离安装包验证、平台配置门禁与侧车回归测试 声明macOS 15最低系统版本并同步规范及Windows待验收计划 --- .gitignore | 6 + .../scripts/build-release.mjs | 7 + .../scripts/build-release.test.mjs | 16 ++ .../scripts/check-config.mjs | 39 ++- .../scripts/check-macos-bundle.mjs | 222 ++++++++++++++++++ apps/ai-game-creator-shell/src-tauri/build.rs | 130 ++++++---- .../src-tauri/build_support/codex_bundle.rs | 133 +++++++++++ .../【声明】Mac内置Codex组件-2026-09-18.md | 14 ++ .../src-tauri/src/agent/codex_cli.rs | 172 +++++++++----- .../src-tauri/tauri.macos.conf.json | 25 ++ ...计划】Mac客户端随包运行依赖补齐-2026-09-18.md | 25 ++ ...碑】Mac客户端随包运行依赖补齐-2026-09-18.md | 34 +++ docs/project-memory/shared-memory/pitfalls.md | 4 + ...案】AGC通用插件宿主与编辑器适配-2026-09-09.md | 2 + ...案】AI游戏创作智能体App实施计划-2026-06-24.md | 4 + 15 files changed, 729 insertions(+), 104 deletions(-) create mode 100644 apps/ai-game-creator-shell/scripts/check-macos-bundle.mjs create mode 100644 apps/ai-game-creator-shell/src-tauri/build_support/codex_bundle.rs create mode 100644 apps/ai-game-creator-shell/src-tauri/resources/codex/【声明】Mac内置Codex组件-2026-09-18.md create mode 100644 apps/ai-game-creator-shell/src-tauri/tauri.macos.conf.json create mode 100644 docs/project-memory/plans/【实施计划】Mac客户端随包运行依赖补齐-2026-09-18.md create mode 100644 docs/project-memory/plans/【里程碑】Mac客户端随包运行依赖补齐-2026-09-18.md diff --git a/.gitignore b/.gitignore index 2770d44c8..34e0fbde7 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,12 @@ temp*build*/ /apps/ai-game-creator-shell/src-tauri/resources/codex/win-x64/codex-resources/ /apps/ai-game-creator-shell/src-tauri/resources/codex/win-x64/codex-package.json /apps/ai-game-creator-shell/src-tauri/resources/plugins/ +/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/bin/ +/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-path/ +/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-resources/ +/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-package.json +/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/manifest.json +/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/NOTICE.md /plugins/agc-cocos-editor/native/payload/ /apps/ai-game-creator-shell/logs/ /apps/ai-game-creator-shell/.llm-drafts/ diff --git a/apps/ai-game-creator-shell/scripts/build-release.mjs b/apps/ai-game-creator-shell/scripts/build-release.mjs index fc4bbc8f4..ffaa6854b 100644 --- a/apps/ai-game-creator-shell/scripts/build-release.mjs +++ b/apps/ai-game-creator-shell/scripts/build-release.mjs @@ -342,6 +342,11 @@ export function buildTauriBuildArguments( .find((value) => value.startsWith('--target=')) ?.slice('--target='.length); const targetArgs = noBundle || explicitTarget ? [] : ['--target', target]; + if ((explicitTarget || target) === 'universal-apple-darwin') { + throw new Error( + '内置 Codex 资源仅支持 macOS 单架构构建,请使用 aarch64-apple-darwin 或 x86_64-apple-darwin', + ); + } const features = defaultEditorFeatures( explicitTarget || (noBundle ? platform : target), ); @@ -680,6 +685,8 @@ if ( path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) ) { const args = process.argv.slice(2); + // 目标校验必须先于远端版本读取与本地版本文件写入。 + buildTauriBuildArguments(args); if (!args.includes('--no-bundle')) await prepareReleaseVersion(); runTauriBuild(args); if (!args.includes('--no-bundle')) await generateUpdateManifest(); diff --git a/apps/ai-game-creator-shell/scripts/build-release.test.mjs b/apps/ai-game-creator-shell/scripts/build-release.test.mjs index de0134267..1582e12c6 100644 --- a/apps/ai-game-creator-shell/scripts/build-release.test.mjs +++ b/apps/ai-game-creator-shell/scripts/build-release.test.mjs @@ -14,6 +14,7 @@ import { fileURLToPath } from 'node:url'; import { agcReleasePathPatterns, + buildTauriBuildArguments, collectRecentReleaseCommits, collectReleaseCommits, compareVersions, @@ -34,6 +35,21 @@ import { const windowsTarget = 'x86_64-pc-windows-msvc'; const universalTarget = 'universal-apple-darwin'; +test('native sidecar builds reject universal targets and accept each macOS architecture', () => { + assert.throws(() => buildTauriBuildArguments([], universalTarget), /单架构/); + assert.throws( + () => buildTauriBuildArguments(['--target=universal-apple-darwin']), + /单架构/, + ); + for (const target of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) { + assert.deepEqual(buildTauriBuildArguments([], target), [ + 'build', + '--target', + target, + ]); + } +}); + function withEnv(overrides, run) { const previous = new Map(); for (const [key, value] of Object.entries(overrides)) { diff --git a/apps/ai-game-creator-shell/scripts/check-config.mjs b/apps/ai-game-creator-shell/scripts/check-config.mjs index ab7a0270c..fe8943608 100644 --- a/apps/ai-game-creator-shell/scripts/check-config.mjs +++ b/apps/ai-game-creator-shell/scripts/check-config.mjs @@ -35,6 +35,12 @@ const windowsTauriConfig = JSON.parse( 'utf8', ), ); +const macosTauriConfig = JSON.parse( + fs.readFileSync( + new URL('../src-tauri/tauri.macos.conf.json', import.meta.url), + 'utf8', + ), +); const cargoManifestSource = fs.readFileSync( new URL('../src-tauri/Cargo.toml', import.meta.url), 'utf8', @@ -1358,6 +1364,37 @@ if (windowsTauriConfig.bundle?.useLocalToolsDir !== true) { 'AI game creator shell Windows Tauri config must cache bundling tools in the project target directory', ); } +assert.deepEqual( + macosTauriConfig.bundle?.resources, + Object.fromEntries([ + ...[ + 'bin/codex', + 'bin/codex-code-mode-host', + 'codex-path/rg', + 'codex-resources/zsh/bin/zsh', + 'codex-package.json', + 'NOTICE.md', + 'manifest.json', + ].map((file) => [ + `resources/codex/mac-native/${file}`, + `coding-agent/mac-native/${file}`, + ]), + ['resources/plugins', 'plugins'], + ]), + 'macOS must bundle the complete native Codex layout and plugin workspace', +); +assert.deepEqual( + macosTauriConfig.plugins?.updater?.endpoints, + [ + 'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/dev-mac/latest.json', + ], + 'macOS local builds must not use the Windows update channel', +); +assert.equal( + macosTauriConfig.bundle?.macOS?.minimumSystemVersion, + '15.0', + 'macOS deployment baseline must cover the bundled native zsh requirement', +); if (tauriConfig.app?.withGlobalTauri !== true) { throw new Error( @@ -1722,7 +1759,7 @@ for (const snippet of [ 'fn append_local_permission_log_at(', '"command.auto"', 'GameCreationAppPermission::Auto', - 'GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH', + 'fn game_creator_bundled_codex_cli_path', 'validate_game_creator_bundled_codex_cli', '内置 Codex CLI 完整性校验失败', ]) { diff --git a/apps/ai-game-creator-shell/scripts/check-macos-bundle.mjs b/apps/ai-game-creator-shell/scripts/check-macos-bundle.mjs new file mode 100644 index 000000000..78e38fdd9 --- /dev/null +++ b/apps/ai-game-creator-shell/scripts/check-macos-bundle.mjs @@ -0,0 +1,222 @@ +import assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +// 只操作临时复制品;不启动 GUI、不读取开发机凭据、不访问 Provider。 +assert.equal(process.platform, 'darwin', '此验证必须在 macOS 执行'); +const source = path.resolve(process.argv[2] || ''); +assert.ok( + source.endsWith('.app') && fs.statSync(source).isDirectory(), + '请传入 .app 绝对路径', +); +const root = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), 'agc-macos-bundle-')), +); +const app = path.join(root, '陶泥儿 隔离测试.app'); +const home = path.join(root, 'home'); +const config = path.join(root, 'config'); +const tmp = path.join(root, 'tmp'); +const codexHome = path.join(root, 'codex-home'); +for (const directory of [home, config, tmp, codexHome]) { + fs.mkdirSync(directory, { mode: 0o700 }); +} +const env = { + HOME: home, + PATH: '/usr/bin:/bin', + TMPDIR: tmp, + CODEX_HOME: codexHome, +}; + +function run(command, args) { + const result = spawnSync(command, args, { + cwd: root, + env, + encoding: 'utf8', + timeout: 30_000, + maxBuffer: 1024 * 1024, + }); + assert.ifError(result.error); + return result; +} + +async function hashFile(file) { + const hash = createHash('sha256'); + for await (const chunk of fs.createReadStream(file)) hash.update(chunk); + return hash.digest('hex'); +} + +async function handshake(executable) { + const child = spawn(executable, ['app-server'], { + cwd: root, + env, + stdio: ['pipe', 'pipe', 'pipe'], + }); + let buffered = ''; + let stderrBytes = 0; + try { + await new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error('app-server 初始化超时')), + 15_000, + ); + const finish = (error) => { + clearTimeout(timer); + if (error) reject(error); + else resolve(); + }; + child.on('error', finish); + child.on('exit', (code) => + finish(new Error(`app-server 提前退出 ${code}`)), + ); + child.stderr.on('data', (chunk) => { + stderrBytes += chunk.length; + if (stderrBytes > 1024 * 1024) + finish(new Error('app-server stderr 超限')); + }); + child.stdout.on('data', (chunk) => { + buffered += chunk.toString('utf8'); + if (buffered.length > 1024 * 1024) + return finish(new Error('app-server stdout 超限')); + let end; + while ((end = buffered.indexOf('\n')) >= 0) { + const line = buffered.slice(0, end); + buffered = buffered.slice(end + 1); + try { + const message = JSON.parse(line); + if (message.id !== 1) continue; + assert.ok(message.result?.userAgent, '初始化必须返回真实服务身份'); + assert.equal(message.error, undefined); + child.stdin.write(`${JSON.stringify({ method: 'initialized' })}\n`); + finish(); + } catch (error) { + finish(error); + } + } + }); + child.stdin.on('error', finish); + child.stdin.write( + `${JSON.stringify({ + id: 1, + method: 'initialize', + params: { + clientInfo: { + name: 'agc_bundle_smoke', + title: 'AGC bundle smoke', + version: '1', + }, + capabilities: { experimentalApi: true }, + }, + })}\n`, + ); + }); + } finally { + if (child.exitCode === null && child.signalCode === null) { + await new Promise((resolve) => { + const timer = setTimeout(() => child.kill('SIGKILL'), 3000); + child.once('exit', () => { + clearTimeout(timer); + resolve(); + }); + child.kill('SIGTERM'); + }); + } + } +} + +try { + fs.cpSync(source, app, { recursive: true }); + const resources = path.join(app, 'Contents/Resources'); + const bundle = path.join(resources, 'coding-agent/mac-native'); + const executable = path.join(bundle, 'bin/codex'); + const main = path.join( + app, + 'Contents/MacOS/genarrative-ai-game-creator-shell', + ); + const manifest = JSON.parse( + fs.readFileSync(path.join(bundle, 'manifest.json'), 'utf8'), + ); + assert.equal(manifest.schemaVersion, 'genarrative-codex-sidecar.v2'); + assert.equal( + manifest.platform, + process.arch === 'arm64' ? 'darwin-arm64' : 'darwin-x64', + ); + assert.equal(manifest.version, 'codex-cli 0.147.0'); + const components = [ + 'bin/codex', + 'bin/codex-code-mode-host', + 'codex-path/rg', + 'codex-resources/zsh/bin/zsh', + 'codex-package.json', + ]; + assert.deepEqual(Object.keys(manifest.files).sort(), [...components].sort()); + for (const component of components) { + const file = path.join(bundle, component); + assert.equal(await hashFile(file), manifest.files[component], component); + if (component !== 'codex-package.json') { + fs.accessSync(file, fs.constants.X_OK); + const arch = run('/usr/bin/lipo', ['-archs', file]); + assert.equal(arch.status, 0, component); + assert.equal( + arch.stdout.trim(), + process.arch === 'arm64' ? 'arm64' : 'x86_64', + component, + ); + } + } + assert.ok(fs.existsSync(path.join(bundle, 'NOTICE.md'))); + const plugin = path.join(resources, 'plugins/agc-cocos-editor'); + for (const file of [ + 'plugin.json', + 'src/entry.mjs', + 'panels/cocos-editor.html', + ]) { + assert.ok(fs.existsSync(path.join(plugin, file)), file); + } + const packageFiles = fs.readdirSync(resources, { recursive: true }); + assert.ok( + !packageFiles.some((file) => + /(^|\/)(\.env[^/]*|auth\.json|node_modules|target|\.git)(\/|$)|\.(exe|dll)$/.test( + file, + ), + ), + ); + assert.equal(run(executable, ['--version']).stdout.trim(), manifest.version); + assert.equal( + run(path.join(bundle, 'codex-path/rg'), ['--version']).status, + 0, + ); + assert.equal( + run(path.join(bundle, 'codex-resources/zsh/bin/zsh'), ['--version']).status, + 0, + ); + + // 使用正式 AGC 查找/校验入口,而非只证明 sidecar 可以独立执行。 + const status = run(main, ['--config-dir', config, '--llm-status']); + const statusText = `${status.stdout}\n${status.stderr}`; + assert.ok(!statusText.includes('Codex CLI 未安装'), statusText); + assert.ok( + statusText.includes('authentication-required'), + '隔离账号应仅被登录门禁拒绝', + ); + await handshake(executable); + + // 临时复制品缺少辅助程序时,正式入口必须拒绝内置程序;PATH 无全局 Codex 可兜底。 + fs.renameSync( + path.join(bundle, 'bin/codex-code-mode-host'), + path.join(root, 'saved-code-mode-host'), + ); + const broken = run(main, ['--config-dir', config, '--llm-status']); + assert.notEqual(broken.status, 0); + assert.match(`${broken.stdout}\n${broken.stderr}`, /Codex CLI 未安装/); + console.log( + 'PASS: 隔离安装包资源、架构、摘要、权限、正式 Codex 查找、app-server 握手及缺组件拒绝', + ); + console.log( + '未验证:GUI、真实登录/Provider 对话、Cocos macOS 原生桥接;插件 Node 仍为外部前提', + ); +} finally { + fs.rmSync(root, { recursive: true, force: true }); +} diff --git a/apps/ai-game-creator-shell/src-tauri/build.rs b/apps/ai-game-creator-shell/src-tauri/build.rs index e9f6642e0..6bca6d67a 100644 --- a/apps/ai-game-creator-shell/src-tauri/build.rs +++ b/apps/ai-game-creator-shell/src-tauri/build.rs @@ -1,31 +1,18 @@ +#[path = "build_support/codex_bundle.rs"] +mod codex_bundle; #[path = "build_support/frontend_dist_guard.rs"] mod frontend_dist_guard; #[path = "build_support/runtime_prompt_bundle.rs"] mod runtime_prompt_bundle; -#[cfg(windows)] use sha2::{Digest, Sha256}; use std::collections::BTreeSet; use std::env; use std::fs; use std::path::PathBuf; -#[cfg(windows)] use std::io::{BufReader, Read}; -const BUNDLED_CODEX_CLI_VERSION: &str = "codex-cli 0.147.0"; - -#[cfg(windows)] -const BUNDLED_CODEX_FILES: [&str; 6] = [ - "bin/codex.exe", - "bin/codex-code-mode-host.exe", - "codex-path/rg.exe", - "codex-resources/codex-command-runner.exe", - "codex-resources/codex-windows-sandbox-setup.exe", - "codex-package.json", -]; - -#[cfg(windows)] fn sha256_file(path: &std::path::Path) -> Result { let file = fs::File::open(path)?; let mut reader = BufReader::new(file); @@ -42,7 +29,15 @@ fn sha256_file(path: &std::path::Path) -> Result { } fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) { - #[cfg(windows)] + let target = env::var("TARGET").expect("Cargo TARGET"); + println!("cargo:rustc-env=AGC_BUILD_TARGET={target}"); + let Some(layout) = codex_bundle::for_target(&target) else { + assert!( + !target.contains("windows") && !target.contains("apple-darwin"), + "不支持的 Codex 随包目标:{target}" + ); + return; + }; { let app_root = manifest_dir .parent() @@ -51,24 +46,23 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) { .parent() .and_then(|apps_dir| apps_dir.parent()) .expect("AI 游戏创作应用必须位于仓库 apps 目录下"); - let source_candidates = [ - app_root.join( - "node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc", - ), - app_root.join( - "node_modules/@openai/codex/node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc", - ), - repo_root.join( - "node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc", - ), - repo_root.join( - "node_modules/@openai/codex/node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc", - ), - ]; + let package = layout.npm_package; + let source_candidates = [app_root, repo_root] + .into_iter() + .flat_map(|root| { + [ + root.join(format!("node_modules/@openai/{package}/vendor/{target}")), + root.join(format!( + "node_modules/@openai/codex/node_modules/@openai/{package}/vendor/{target}" + )), + ] + }) + .collect::>(); let source = source_candidates .iter() .find(|path| { - BUNDLED_CODEX_FILES + layout + .files .iter() .all(|relative| path.join(relative).is_file()) }) @@ -83,14 +77,26 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) { .join(";") ) }); - let target_dir = manifest_dir.join("resources/codex/win-x64"); + let metadata: serde_json::Value = serde_json::from_slice( + &fs::read(source.join("codex-package.json")).expect("读取 Codex 原生包元数据失败"), + ) + .expect("Codex 原生包元数据无效"); + codex_bundle::validate_package_metadata(&metadata, &target, layout) + .unwrap_or_else(|error| panic!("{error}")); + let target_dir = manifest_dir.join("resources/codex").join(layout.directory); let notice = target_dir.join("NOTICE.md"); + if target.contains("apple-darwin") { + let source_notice = + manifest_dir.join("resources/codex/【声明】Mac内置Codex组件-2026-09-18.md"); + stage_plugin_file(&source_notice, ¬ice); + println!("cargo:rerun-if-changed={}", source_notice.display()); + } if !notice.is_file() { panic!("内置 Codex CLI 第三方声明缺失:{}", notice.display()); } fs::create_dir_all(&target_dir).expect("创建内置 Codex CLI 资源目录失败"); let mut file_hashes = serde_json::Map::new(); - for relative in BUNDLED_CODEX_FILES { + for relative in layout.files { let source_path = source.join(relative); let target_path = target_dir.join(relative); if let Some(parent) = target_path.parent() { @@ -104,15 +110,23 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) { if !target_matches_source { fs::copy(&source_path, &target_path).expect("复制内置 Codex CLI 资源失败"); } + // 内容相同但曾被错误 chmod 的 staging 文件也必须恢复执行权限。 + fs::set_permissions( + &target_path, + fs::metadata(&source_path) + .expect("读取组件权限失败") + .permissions(), + ) + .expect("保留内置 Codex CLI 组件权限失败"); file_hashes.insert( relative.to_string(), serde_json::Value::String(source_sha256), ); } let manifest = serde_json::json!({ - "schemaVersion": "genarrative-codex-sidecar.v2", - "platform": "win32-x64", - "version": BUNDLED_CODEX_CLI_VERSION, + "schemaVersion": codex_bundle::SCHEMA, + "platform": layout.platform, + "version": codex_bundle::CLI_VERSION, "files": file_hashes, }); let manifest_path = target_dir.join("manifest.json"); @@ -126,7 +140,7 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) { { fs::write(&manifest_path, manifest_payload).expect("写入内置 Codex CLI 清单失败"); } - for relative in BUNDLED_CODEX_FILES { + for relative in layout.files { println!("cargo:rerun-if-changed={}", source.join(relative).display()); } println!("cargo:rerun-if-changed={}", notice.display()); @@ -256,8 +270,11 @@ fn stage_cocos_editor_payload(_manifest_dir: &std::path::Path) {} /// /// 只复制插件运行需要的清单、入口、面板和 native payload,不复制 native 源码、 /// Cargo target 目录或 node_modules。 -#[cfg(windows)] fn stage_plugin_workspace(manifest_dir: &std::path::Path) { + let target = env::var("TARGET").expect("Cargo TARGET"); + if !target.contains("windows") && !target.contains("apple-darwin") { + return; + } let repo_root = manifest_dir .parent() .and_then(|app_root| app_root.parent()) @@ -266,6 +283,10 @@ fn stage_plugin_workspace(manifest_dir: &std::path::Path) { .to_path_buf(); let workspace = repo_root.join("plugins"); let destination_root = manifest_dir.join("resources/plugins"); + // staging 是专用生成目录;重建清除跨目标 payload 与已删除插件的残留。 + if destination_root.exists() { + std::fs::remove_dir_all(&destination_root).expect("清理插件 staging 失败"); + } std::fs::create_dir_all(&destination_root).expect("创建插件资源目录失败"); let entries = match std::fs::read_dir(&workspace) { Ok(entries) => entries, @@ -273,6 +294,13 @@ fn stage_plugin_workspace(manifest_dir: &std::path::Path) { }; for entry in entries.flatten() { let plugin_root = entry.path(); + assert!( + !entry + .file_type() + .expect("读取插件目录类型失败") + .is_symlink(), + "插件工作区不允许符号链接" + ); if !plugin_root.is_dir() || !plugin_root.join("plugin.json").is_file() { continue; } @@ -287,17 +315,18 @@ fn stage_plugin_workspace(manifest_dir: &std::path::Path) { std::path::PathBuf::from("panels"), std::path::PathBuf::from("native/payload"), ] { + if relative == std::path::Path::new("native/payload") && !target.contains("windows") { + continue; + } copy_plugin_tree(&plugin_root.join(&relative), &destination.join(&relative)); } println!("cargo:rerun-if-changed={}", plugin_root.display()); } } -#[cfg(windows)] fn stage_plugin_file(source: &std::path::Path, destination: &std::path::Path) { - let Ok(bytes) = std::fs::read(source) else { - return; - }; + let bytes = std::fs::read(source) + .unwrap_or_else(|error| panic!("读取随包资源失败 {}:{error}", source.display())); if std::fs::read(destination).is_ok_and(|existing| existing == bytes) { return; } @@ -307,7 +336,6 @@ fn stage_plugin_file(source: &std::path::Path, destination: &std::path::Path) { std::fs::write(destination, bytes).expect("复制插件资源失败"); } -#[cfg(windows)] fn copy_plugin_tree(source: &std::path::Path, destination: &std::path::Path) { let entries = match std::fs::read_dir(source) { Ok(entries) => entries, @@ -316,10 +344,17 @@ fn copy_plugin_tree(source: &std::path::Path, destination: &std::path::Path) { for entry in entries.flatten() { let target = destination.join(entry.file_name()); let path = entry.path(); + assert!( + !entry + .file_type() + .expect("读取插件文件类型失败") + .is_symlink(), + "插件资源不允许符号链接" + ); if path.is_dir() { let name = entry.file_name(); let name = name.to_string_lossy(); - if matches!(name.as_ref(), "target" | "node_modules" | ".git") { + if name.starts_with('.') || matches!(name.as_ref(), "target" | "node_modules") { continue; } std::fs::create_dir_all(&target).expect("创建插件资源目录失败"); @@ -331,12 +366,14 @@ fn copy_plugin_tree(source: &std::path::Path, destination: &std::path::Path) { if name.contains(".test.") { continue; } + if name.starts_with('.') { + continue; + } stage_plugin_file(&path, &target); } } } -#[cfg(windows)] fn copy_plugin_file(source: &std::path::Path, destination: &std::path::Path) { if !source.is_file() { return; @@ -345,6 +382,3 @@ fn copy_plugin_file(source: &std::path::Path, destination: &std::path::Path) { .expect("创建插件资源目录失败"); std::fs::copy(source, destination).expect("复制插件资源失败"); } - -#[cfg(not(windows))] -fn stage_plugin_workspace(_manifest_dir: &std::path::Path) {} diff --git a/apps/ai-game-creator-shell/src-tauri/build_support/codex_bundle.rs b/apps/ai-game-creator-shell/src-tauri/build_support/codex_bundle.rs new file mode 100644 index 000000000..1811f6a25 --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/build_support/codex_bundle.rs @@ -0,0 +1,133 @@ +//! 构建与运行共用的平台布局;只允许分发锁定原生包里的明确组件。 + +pub const VERSION: &str = "0.147.0"; +pub const CLI_VERSION: &str = "codex-cli 0.147.0"; +pub const SCHEMA: &str = "genarrative-codex-sidecar.v2"; + +#[derive(Clone, Copy, Debug)] +pub struct Layout { + pub platform: &'static str, + pub npm_package: &'static str, + pub directory: &'static str, + pub executable: &'static str, + pub files: &'static [&'static str], +} + +const WINDOWS_FILES: &[&str] = &[ + "bin/codex.exe", + "bin/codex-code-mode-host.exe", + "codex-path/rg.exe", + "codex-resources/codex-command-runner.exe", + "codex-resources/codex-windows-sandbox-setup.exe", + "codex-package.json", +]; +const MAC_FILES: &[&str] = &[ + "bin/codex", + "bin/codex-code-mode-host", + "codex-path/rg", + "codex-resources/zsh/bin/zsh", + "codex-package.json", +]; + +pub fn for_target(target: &str) -> Option { + match target { + "x86_64-pc-windows-msvc" => Some(Layout { + platform: "win32-x64", + npm_package: "codex-win32-x64", + directory: "win-x64", + executable: "bin/codex.exe", + files: WINDOWS_FILES, + }), + "aarch64-apple-darwin" | "x86_64-apple-darwin" => Some(Layout { + platform: if target.starts_with("aarch64") { + "darwin-arm64" + } else { + "darwin-x64" + }, + npm_package: if target.starts_with("aarch64") { + "codex-darwin-arm64" + } else { + "codex-darwin-x64" + }, + directory: "mac-native", + executable: "bin/codex", + files: MAC_FILES, + }), + _ => None, + } +} + +pub fn validate_package_metadata( + metadata: &serde_json::Value, + target: &str, + layout: Layout, +) -> Result<(), String> { + if metadata["layoutVersion"] == 1 + && metadata["version"] == VERSION + && metadata["target"] == target + && metadata["entrypoint"] == layout.executable + && metadata["resourcesDir"] == "codex-resources" + && metadata["pathDir"] == "codex-path" + { + Ok(()) + } else { + Err(format!("Codex 原生包版本、布局或架构不匹配目标 {target}")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn platform_layouts_are_explicit_and_preserve_upstream_components() { + let mac = for_target("aarch64-apple-darwin").unwrap(); + assert_eq!(mac.platform, "darwin-arm64"); + assert_eq!(mac.npm_package, "codex-darwin-arm64"); + assert!(mac.files.contains(&"codex-resources/zsh/bin/zsh")); + assert!(mac.files.contains(&"bin/codex-code-mode-host")); + assert!(!mac.files.iter().any(|file| file.ends_with(".exe"))); + let intel = for_target("x86_64-apple-darwin").unwrap(); + assert_eq!(intel.platform, "darwin-x64"); + assert_eq!(intel.npm_package, "codex-darwin-x64"); + let windows = for_target("x86_64-pc-windows-msvc").unwrap(); + assert_eq!(windows.directory, "win-x64"); + assert_eq!(windows.files.len(), 6); + assert!(windows + .files + .contains(&"codex-resources/codex-windows-sandbox-setup.exe")); + assert!(for_target("universal-apple-darwin").is_none()); + assert!(for_target("aarch64-pc-windows-msvc").is_none()); + assert!(for_target("x86_64-unknown-linux-gnu").is_none()); + } + + #[test] + fn metadata_rejects_version_architecture_and_layout_drift() { + let target = "aarch64-apple-darwin"; + let layout = for_target(target).unwrap(); + let valid = serde_json::json!({ + "layoutVersion": 1, + "version": VERSION, + "target": target, + "entrypoint": "bin/codex", + "resourcesDir": "codex-resources", + "pathDir": "codex-path", + }); + assert!(validate_package_metadata(&valid, target, layout).is_ok()); + for (key, value) in [ + ("layoutVersion", serde_json::json!(2)), + ("version", serde_json::json!("0.0.0")), + ("target", serde_json::json!("x86_64-apple-darwin")), + ("entrypoint", serde_json::json!("bin/codex.exe")), + ("resourcesDir", serde_json::json!("../private")), + ("pathDir", serde_json::json!(null)), + ] { + let mut invalid = valid.clone(); + invalid[key] = value; + assert!( + validate_package_metadata(&invalid, target, layout).is_err(), + "{key}" + ); + } + } +} diff --git a/apps/ai-game-creator-shell/src-tauri/resources/codex/【声明】Mac内置Codex组件-2026-09-18.md b/apps/ai-game-creator-shell/src-tauri/resources/codex/【声明】Mac内置Codex组件-2026-09-18.md new file mode 100644 index 000000000..affea34fb --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/resources/codex/【声明】Mac内置Codex组件-2026-09-18.md @@ -0,0 +1,14 @@ +# 内置 Codex CLI + +本安装包包含锁定版本 Codex CLI 0.147.0 的 macOS 原生组件。 + +Codex CLI 按 Apache License 2.0 分发,源码与许可证见 +https://github.com/openai/codex。 + +组件来自项目锁定的 `@openai/codex` 原生 npm 依赖,保留上游的 +`bin/codex`、`bin/codex-code-mode-host`、`codex-path/rg`、 +`codex-resources/zsh/bin/zsh` 和 `codex-package.json` 相对布局。 +原生依赖中的 ripgrep 与 zsh 按各自上游许可证分发: +https://github.com/BurntSushi/ripgrep 和 https://www.zsh.org/。 + +安装包不包含 API Key、登录状态、用户配置或项目数据。 diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/codex_cli.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/codex_cli.rs index 863b8cdad..79e3aedd1 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/codex_cli.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/codex_cli.rs @@ -5,18 +5,10 @@ use std::process::Stdio; use sha2::{Digest, Sha256}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; +#[path = "../../build_support/codex_bundle.rs"] +mod codex_bundle; + const GAME_CREATOR_CODEX_CLI_EXECUTABLE: &str = "codex"; -const GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH: &str = "coding-agent/win-x64/bin/codex.exe"; -const GAME_CREATOR_BUNDLED_CODEX_CLI_MANIFEST_RELATIVE_PATH: &str = - "coding-agent/win-x64/manifest.json"; -const GAME_CREATOR_BUNDLED_CODEX_CLI_REQUIRED_FILES: [&str; 6] = [ - "bin/codex.exe", - "bin/codex-code-mode-host.exe", - "codex-path/rg.exe", - "codex-resources/codex-command-runner.exe", - "codex-resources/codex-windows-sandbox-setup.exe", - "codex-package.json", -]; const GAME_CREATOR_CODEX_CLI_PROMPT_MAX_BYTES: usize = 4 * 1024 * 1024; const GAME_CREATOR_CODEX_CLI_STDOUT_MAX_BYTES: usize = 4 * 1024 * 1024; const GAME_CREATOR_CODEX_CLI_STDERR_MAX_BYTES: usize = 256 * 1024; @@ -38,11 +30,11 @@ fn game_creator_codex_cli_executable_candidates_for( path: Option<&std::ffi::OsStr>, ) -> Vec { let mut candidates = Vec::new(); + if let Some(bundled) = game_creator_bundled_codex_cli_path(resource_dir) { + candidates.push(bundled); + } #[cfg(windows)] { - if let Some(resource_dir) = resource_dir { - candidates.push(resource_dir.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH)); - } fn append_native_npm_candidates(candidates: &mut Vec, npm_root: &Path) { let vendor_root = npm_root .join("node_modules") @@ -109,52 +101,71 @@ fn game_creator_codex_cli_executable_candidates() -> Vec { } fn game_creator_bundled_resource_dir() -> Option { + let executable = std::env::current_exe().ok()?; + game_creator_bundled_resource_dir_for(&executable) +} + +fn game_creator_bundled_resource_dir_for(executable: &Path) -> Option { #[cfg(windows)] { - std::env::current_exe() - .ok() - .and_then(|path| path.parent().map(Path::to_path_buf)) + executable.parent().map(Path::to_path_buf) } - #[cfg(not(windows))] + #[cfg(target_os = "macos")] { + let macos = executable.parent()?; + let contents = macos.parent()?; + // 只接受真正的 app bundle 结构,开发态不从任意相邻目录加载程序。 + if macos.file_name()? != "MacOS" + || contents.file_name()? != "Contents" + || contents.parent()?.extension()? != "app" + { + return None; + } + Some(contents.join("Resources")) + } + #[cfg(not(any(windows, target_os = "macos")))] + { + let _ = executable; None } } fn game_creator_bundled_codex_cli_path(resource_dir: Option<&Path>) -> Option { - resource_dir.map(|resource_dir| resource_dir.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH)) + let layout = codex_bundle::for_target(env!("AGC_BUILD_TARGET"))?; + Some( + resource_dir? + .join("coding-agent") + .join(layout.directory) + .join(layout.executable), + ) } fn validate_game_creator_bundled_codex_cli(executable: &Path) -> Result { + let layout = codex_bundle::for_target(env!("AGC_BUILD_TARGET")) + .ok_or_else(|| "当前平台不支持内置 Codex CLI".to_string())?; let bundle_root = executable .parent() .and_then(Path::parent) .ok_or_else(|| "内置 Codex CLI 路径无效".to_string())?; - let manifest_path = bundle_root.join( - Path::new(GAME_CREATOR_BUNDLED_CODEX_CLI_MANIFEST_RELATIVE_PATH) - .file_name() - .expect("bundled Codex manifest file name"), - ); + let manifest_path = bundle_root.join("manifest.json"); let manifest = std::fs::read_to_string(&manifest_path) .map_err(|_| "内置 Codex CLI 缺少完整性清单".to_string()) .and_then(|value| { serde_json::from_str::(&value) .map_err(|_| "内置 Codex CLI 完整性清单无效".to_string()) })?; - if manifest.schema_version != "genarrative-codex-sidecar.v2" - || manifest.platform != "win32-x64" + if manifest.schema_version != codex_bundle::SCHEMA + || manifest.platform != layout.platform || manifest.version.trim().is_empty() - || GAME_CREATOR_BUNDLED_CODEX_CLI_REQUIRED_FILES - .iter() - .any(|relative| { - manifest.files.get(*relative).map_or(true, |hash| { - hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit()) - }) + || layout.files.iter().any(|relative| { + manifest.files.get(*relative).map_or(true, |hash| { + hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit()) }) + }) { return Err("内置 Codex CLI 完整性清单不受支持".to_string()); } - for relative in GAME_CREATOR_BUNDLED_CODEX_CLI_REQUIRED_FILES { + for relative in layout.files { let path = bundle_root.join(relative); let bytes = std::fs::read(&path).map_err(|_| { format!( @@ -163,7 +174,7 @@ fn validate_game_creator_bundled_codex_cli(executable: &Path) -> Result expect(activeTurns).toEqual([]))` 在 Hook 初始状态就能成功,不能证明首次异步读取已经完成。引用稳定性回归应显式控制 Promise 完成,并同时检查首次空响应与禁用后的引用;快照签名初值必须与初始空数组一致。窗口同步测试应验证未变化状态不重复发布,不能依赖一次多余的空态更新。 diff --git a/docs/technical/【技术方案】AGC通用插件宿主与编辑器适配-2026-09-09.md b/docs/technical/【技术方案】AGC通用插件宿主与编辑器适配-2026-09-09.md index 778dddf1f..462d9929c 100644 --- a/docs/technical/【技术方案】AGC通用插件宿主与编辑器适配-2026-09-09.md +++ b/docs/technical/【技术方案】AGC通用插件宿主与编辑器适配-2026-09-09.md @@ -69,6 +69,8 @@ OpenAI 的标准模型是“Plugin 作为可安装包,组合 Skills、可选 M 除 AppData 导入外,宿主还扫描 `plugins/` 工作区:每个含根目录 `plugin.json` 的一级子目录是一个插件包。解析顺序为环境变量 `AGC_PLUGIN_WORKSPACE`、随包资源目录 `/plugins`、开发构建的仓库 `plugins/`。仓库工作区约定见 [`plugins/README.md`](../../../plugins/README.md)。 +Windows 与 macOS 构建都将内置插件的清单、JS 入口与面板复制到应用资源目录;staging 每次重建,避免已删除插件或跨目标原生 payload 残留。macOS 不携带 Windows native payload。Cocos 进程桥接仍仅按既有 Windows 平台实现提供,插件文件可被发现不代表 macOS 已支持编辑器控制;JS 入口的系统 Node 前提不变。 + ### 内置插件与可用开关 `plugins/` 工作区里的插件是**内置插件**:随客户端分发,用户不能卸载或删除,只能通过可用开关控制是否生效。开关状态持久化在 AppData `extensions/builtin-plugins.json`(`schemaVersion = agc.builtin-plugins.v1`,`enabled` 是 id 到布尔的映射);文件缺失按插件 manifest 的 `enabled` 处理,坏文件失败关闭。内置插件优先级高于同名导入插件,AppData 里的同名 Plugin 不会覆盖或间接卸载它。 diff --git a/docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md b/docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md index 40b9aa9b4..3cb988ec5 100644 --- a/docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md +++ b/docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md @@ -352,6 +352,10 @@ Supervisor 认领该回执后,由父 run 自己为每个原 delivery 逐一创 - 调度边界:正式 DAG、manifest、Agent task/session/run 身份、队列、锁、委派、all-join、完成门、Provider lifecycle、持久 retry/handoff 与 `needs-reconciliation` 继续由现有 AGC Runtime 掌控。每个被调度节点在 `codex_cli` 模式下直接启动一次非交互 `codex exec` 充当该节点的推理 Agent;Codex 返回当前 Runtime 广告函数的结构化调用,Runtime 仍是唯一 ToolHost,不允许 CLI 自己写项目、执行命令、调用 MCP 或形成第二套 revision / verification 真相。 - 安装包侧车:Windows x64 release 固定随 Tauri resource 打包 `@openai/codex@0.147.0` 的原生 `codex.exe`;Rust build script 从 AGC 子包锁定依赖 stage 到 resource,并写入版本与 SHA-256 清单。Windows 侧车映射只写入 `tauri.windows.conf.json`,通用 `tauri.conf.json` 不得让 Linux / macOS 构建依赖未生成的 Windows 二进制。运行时只在文件摘要和 `codex-cli` 版本同时匹配清单时优先选内置侧车;缺失、损坏或版本漂移时跳过它,按既有 npm 安装、PATH 顺序回退。安装包同时携带 Apache-2.0 第三方声明;API Key、`auth.json`、Cookie、Token、用户 `CODEX_HOME`、用户配置和项目数据绝不打包。 - Windows x64 release 安装包只生成 NSIS,不生成 MSI:`tauri.windows.conf.json` 的 `bundle.targets` 固定为 `["nsis"]`,通用配置继续保留其它平台的默认打包目标。安装后的产品名、开始菜单 / 桌面快捷方式和 EXE 产品描述统一由 `tauri.conf.json` 的 `productName: "陶泥儿"` 生成;应用 identifier 与内部可执行文件名保持稳定。内置 Codex 资源安装到顶层 `coding-agent/win-x64/`,运行时从同一路径查找 `bin/codex.exe` 与 `manifest.json`;仓库 staging 仍使用 `resources/codex/win-x64/`,包内子目录、组件名、版本和完整性校验保持原合同。 +- macOS 单架构安装包同样必须携带锁定版本的原生 Codex、`codex-code-mode-host`、`rg`、上游 zsh、`codex-package.json` 和第三方声明,保留上游相对布局;构建时按 Cargo 目标选择 npm 原生依赖,缺文件、版本或目标不匹配立即失败,不借用开发机 PATH 里的 Codex。资源只在 `tauri.macos.conf.json` 映射到 `Contents/Resources/coding-agent/mac-native/`。构建与运行共享平台文件白名单,运行时由当前 `.app/Contents/MacOS` 定位相邻 `Resources`,完整性与版本验证通过后优先使用内置组件;失败沿既有外部安装回退,不能运行未校验的内置文件。单架构资源不能冒充 universal 包。 +- 内置插件的清单、运行入口与面板同时在 Windows/macOS 随包分发,继续由既有 PluginHost 的应用资源目录扫描入口发现;不携带开发依赖、缓存、测试或私有配置。插件文件随包不等于原生适配器跨平台:Cocos 进程桥接仍受现有 Windows 实现和 feature 门禁约束,macOS 原生桥接另行设计与验收,不复制 Windows DLL 冒充支持。系统 Node、用户 Cocos Creator、账号登录、网络和生成工程的 npm 工具链仍是现有外部前提,不在此次 Codex 侧车补齐中隐式变更。 +- macOS 安装包验收必须包括:脱离仓库位置的 `.app` 资源与架构检查、受限 PATH/隔离 HOME 下内置 Codex 启动和 app-server 握手、必需文件缺失/篡改/平台错误的拒绝测试,以及 DMG 完整性检查。真实登录、Provider 对话、GUI 和 Cocos 操作必须独立列出证据,不能用压缩包生成或 `--version` 成功替代。未配置正式签名、公证的本地测试包不得作为公开发行包。 +- macOS 安装包的系统下限取主程序和全部原生组件中的最高要求;锁定 Codex 0.147.0 原生依赖所携带的 zsh 要求 macOS 15.0,因此 `bundle.macOS.minimumSystemVersion` 明确为 `15.0`。更新原生依赖时重新检查 Mach-O 的系统下限,不能只按 AGC 主程序宣称兼容版本。 - CLI 安全边界:CLI 固定使用 argv 启动,禁止 shell 拼接;工作目录使用本次请求专用的空临时目录,不把游戏项目绝对路径写入 prompt、stdout、stderr 或持久记录。调用固定使用 ephemeral、忽略用户配置和 exec rules、read-only sandbox、never approval,并关闭 Codex shell tool;只继承 CLI 运行和认证所需的最小环境,显式移除宿主 `CODEX_API_KEY`。用户级 Codex 登录态继续由本机 Codex 自己读取,API Key、auth 文件、Cookie、Token、`CODEX_HOME` 私有内容不得复制到项目配置、Runtime sidecar、Agent DB、conversation 或日志;stdout / stderr 无换行时也受硬上限约束,stderr 诊断只记录固定分类、字节数和 SHA-256。 - 协议边界:Runtime 把既有 `LlmRunRequest` 的消息和当前函数目录编码为有界 prompt,并从同一函数 JSON Schema 生成 Codex structured-output schema。CLI 输出转换为现有 `LlmRunResponse / LlmToolCall` 后,继续经过 native tool / MCP 参数校验、动作上限、权限、pending、receipt、验证与格式修复链;最终回复仍走唯一提交路径,不新增平行响应协议。 - 取消与恢复:Codex 子进程绑定当前 Provider request lifecycle,取消、暂停、Runner draining 或 GUI owner 丢失时终止并回收当前进程;started 后没有可信终态仍沿现有 Provider reconciliation 处理。`agentMode`、CLI 可执行身份和影响输出的 Codex 参数进入 `providerConfigFingerprint`,模式切换不得消费另一模式遗留的 retry/handoff。