合并最新主分支并保留策划退役清理
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust smoke (pull_request) Has been cancelled
Project CI / AI game creator shell Rust crates (pull_request) Has been cancelled
Project CI / Backend tests (pull_request) Has been cancelled
Project CI / Native shell tests (pull_request) Has been cancelled
Project CI / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (pull_request) Has been cancelled
Project CI / AI game creator shell web tests (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust smoke (pull_request) Has been cancelled
Project CI / AI game creator shell Rust crates (pull_request) Has been cancelled
Project CI / Backend tests (pull_request) Has been cancelled
Project CI / Native shell tests (pull_request) Has been cancelled
Project CI / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (pull_request) Has been cancelled
Project CI / AI game creator shell web tests (pull_request) Has been cancelled
合入 origin/master 的现役 Direct、Mac 随包资源、配置和测试变更 保留策划 Agent V1/V2 退役删除结果 仅在重叠文件保留当前分支的策划解耦代码 不额外处理 master 自身已有缺陷
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@genarrative/ai-game-creator-shell",
|
||||
"private": true,
|
||||
"version": "0.1.47",
|
||||
"version": "0.1.67",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node scripts/start-tauri-dev.mjs",
|
||||
|
||||
@@ -14,16 +14,71 @@ const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
// 提交摘要里的 pathspec 与 `git log` 都以仓库根为基准,不能在应用目录里执行。
|
||||
const repoRoot = path.resolve(appRoot, '..', '..');
|
||||
const defaultReleaseTarget = 'x86_64-pc-windows-msvc';
|
||||
const releaseTarget =
|
||||
process.env.AGC_BUILD_TARGET?.trim() || defaultReleaseTarget;
|
||||
const bundleRoot = path.join(
|
||||
appRoot,
|
||||
'src-tauri',
|
||||
'target',
|
||||
releaseTarget,
|
||||
'release',
|
||||
'bundle',
|
||||
);
|
||||
function defaultTarget() {
|
||||
return process.env.AGC_BUILD_TARGET?.trim() || defaultReleaseTarget;
|
||||
}
|
||||
|
||||
function explicitBuildTarget(args) {
|
||||
let target;
|
||||
const separator = args.indexOf('--');
|
||||
const options = separator < 0 ? args : args.slice(0, separator);
|
||||
for (let index = 0; index < options.length; index += 1) {
|
||||
const argument = options[index];
|
||||
let value;
|
||||
if (argument === '--target' || argument === '-t') {
|
||||
value = options[++index];
|
||||
} else if (argument.startsWith('--target=')) {
|
||||
value = argument.slice('--target='.length);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if (!value?.trim() || value.startsWith('-')) {
|
||||
throw new Error('--target 缺少有效目标');
|
||||
}
|
||||
if (target !== undefined) throw new Error('不能重复指定 --target');
|
||||
target = value.trim();
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
function validateReleaseTarget(target) {
|
||||
if (target === 'universal-apple-darwin') {
|
||||
throw new Error(
|
||||
'内置 Codex 资源仅支持 macOS 单架构构建,请使用 aarch64-apple-darwin 或 x86_64-apple-darwin',
|
||||
);
|
||||
}
|
||||
if (
|
||||
![
|
||||
'x86_64-pc-windows-msvc',
|
||||
'aarch64-apple-darwin',
|
||||
'x86_64-apple-darwin',
|
||||
].includes(target)
|
||||
) {
|
||||
throw new Error(`不支持的发布目标:${target}`);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/** 在入口冻结目标;所有发布步骤共享同一上下文,不再各自读取默认目标。 */
|
||||
export function resolveReleaseContext(args = [], env = process.env) {
|
||||
const target = validateReleaseTarget(
|
||||
explicitBuildTarget(args) ||
|
||||
env.AGC_BUILD_TARGET?.trim() ||
|
||||
defaultReleaseTarget,
|
||||
);
|
||||
return Object.freeze({
|
||||
target,
|
||||
channel: resolveReleaseChannel(env, target),
|
||||
bundleRoot: path.join(
|
||||
appRoot,
|
||||
'src-tauri',
|
||||
'target',
|
||||
target,
|
||||
'release',
|
||||
'bundle',
|
||||
),
|
||||
});
|
||||
}
|
||||
const packageJsonPath = path.join(appRoot, 'package.json');
|
||||
const rootPackageLockPath = path.resolve(appRoot, '../..', 'package-lock.json');
|
||||
const tauriConfigPath = path.join(appRoot, 'src-tauri', 'tauri.conf.json');
|
||||
@@ -99,7 +154,7 @@ export function nextPatchVersion(localVersion, remoteVersion) {
|
||||
return `${major}.${minor}.${patch + 1}`;
|
||||
}
|
||||
|
||||
export function resolveReleasePlatform(target = releaseTarget) {
|
||||
export function resolveReleasePlatform(target = defaultTarget()) {
|
||||
if (target.includes('windows')) return 'windows';
|
||||
if (target.includes('apple-darwin')) return 'darwin';
|
||||
if (target.includes('linux')) return 'linux';
|
||||
@@ -108,7 +163,7 @@ export function resolveReleasePlatform(target = releaseTarget) {
|
||||
|
||||
export function resolveReleaseChannel(
|
||||
env = process.env,
|
||||
target = releaseTarget,
|
||||
target = defaultTarget(),
|
||||
) {
|
||||
const platform = resolveReleasePlatform(target);
|
||||
const requested = env.AGC_UPDATE_CHANNEL?.trim();
|
||||
@@ -142,13 +197,10 @@ export function updateManifestUrl(channel = resolveReleaseChannel()) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新插件按运行时平台键查找清单条目:universal macOS 包同时挂
|
||||
* `darwin-aarch64` 与 `darwin-x86_64`,单架构目标只挂对应键。
|
||||
* 单架构产物只登记实际目标,不能把同一原生资源映射为另一架构。
|
||||
*/
|
||||
export function resolveManifestPlatformKeys(target = releaseTarget) {
|
||||
if (target === 'universal-apple-darwin') {
|
||||
return ['darwin-aarch64', 'darwin-x86_64'];
|
||||
}
|
||||
export function resolveManifestPlatformKeys(target = defaultTarget()) {
|
||||
validateReleaseTarget(target);
|
||||
if (target === 'aarch64-apple-darwin') return ['darwin-aarch64'];
|
||||
if (target === 'x86_64-apple-darwin') return ['darwin-x86_64'];
|
||||
if (target.includes('windows')) {
|
||||
@@ -256,8 +308,8 @@ function replaceVersionLine(source, version, pattern, label) {
|
||||
return source.replace(pattern, `$1${version}$3`);
|
||||
}
|
||||
|
||||
export async function prepareReleaseVersion() {
|
||||
const channel = resolveReleaseChannel();
|
||||
export async function prepareReleaseVersion(context = resolveReleaseContext()) {
|
||||
const { channel } = context;
|
||||
const localVersion = parseVersion(readPackageJson().version, '本地版本');
|
||||
const remoteVersion = await resolveRemoteHighWaterVersion(channel);
|
||||
const requestedVersion = process.env.AGC_RELEASE_VERSION?.trim();
|
||||
@@ -330,18 +382,14 @@ export async function prepareReleaseVersion() {
|
||||
|
||||
export function buildTauriBuildArguments(
|
||||
args = [],
|
||||
target = releaseTarget,
|
||||
target = defaultTarget(),
|
||||
platform = process.platform,
|
||||
) {
|
||||
const noBundle = args.includes('--no-bundle');
|
||||
const targetIndex = args.indexOf('--target');
|
||||
const explicitTarget =
|
||||
targetIndex >= 0
|
||||
? args[targetIndex + 1]
|
||||
: args
|
||||
.find((value) => value.startsWith('--target='))
|
||||
?.slice('--target='.length);
|
||||
const explicitTarget = explicitBuildTarget(args);
|
||||
const targetArgs = noBundle || explicitTarget ? [] : ['--target', target];
|
||||
if (!noBundle || explicitTarget)
|
||||
validateReleaseTarget(explicitTarget || target);
|
||||
const features = defaultEditorFeatures(
|
||||
explicitTarget || (noBundle ? platform : target),
|
||||
);
|
||||
@@ -374,18 +422,33 @@ function writeChannelConfigFile(channel) {
|
||||
return configPath;
|
||||
}
|
||||
|
||||
export function runTauriBuild(args = []) {
|
||||
const tauriArguments = buildTauriBuildArguments(args);
|
||||
if (!tauriArguments.includes('--config') && !tauriArguments.includes('-c')) {
|
||||
const channel = resolveReleaseChannel();
|
||||
const configPath = writeChannelConfigFile(channel);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 渠道 ${channel} 端点配置:${configPath}`,
|
||||
);
|
||||
tauriArguments.push('--config', configPath);
|
||||
export function runTauriBuild(
|
||||
args = [],
|
||||
context = resolveReleaseContext(args),
|
||||
{ spawn = spawnSync } = {},
|
||||
) {
|
||||
if (
|
||||
explicitBuildTarget(args) &&
|
||||
explicitBuildTarget(args) !== context.target
|
||||
) {
|
||||
throw new Error('构建参数与发布上下文目标不一致');
|
||||
}
|
||||
const tauriArguments = buildTauriBuildArguments(args, context.target);
|
||||
const { channel } = context;
|
||||
const configPath = writeChannelConfigFile(channel);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 渠道 ${channel} 端点配置:${configPath}`,
|
||||
);
|
||||
// 最后合并渠道配置,防止用户配置中的端点与实际发布目标分叉。
|
||||
const separator = tauriArguments.indexOf('--');
|
||||
tauriArguments.splice(
|
||||
separator < 0 ? tauriArguments.length : separator,
|
||||
0,
|
||||
'--config',
|
||||
configPath,
|
||||
);
|
||||
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
||||
const result = spawnSync(
|
||||
const result = spawn(
|
||||
npmCommand,
|
||||
['--prefix', '../..', 'exec', 'tauri', '--', ...tauriArguments],
|
||||
{ cwd: appRoot, stdio: 'inherit', shell: process.platform === 'win32' },
|
||||
@@ -402,11 +465,11 @@ function listFiles(root) {
|
||||
});
|
||||
}
|
||||
|
||||
function artifactPriority(filePath) {
|
||||
function artifactPriority(filePath, target) {
|
||||
const name = path.basename(filePath).toLowerCase();
|
||||
if (releaseTarget.includes('windows')) return name.endsWith('.exe') ? 0 : 99;
|
||||
if (target.includes('windows')) return name.endsWith('.exe') ? 0 : 99;
|
||||
// 更新链路要的是 updater 产物(macOS 为 .app.tar.gz),dmg 只作人工分发。
|
||||
if (releaseTarget.includes('apple-darwin')) {
|
||||
if (target.includes('apple-darwin')) {
|
||||
return name.endsWith('.app.tar.gz') ? 0 : 99;
|
||||
}
|
||||
if (name.endsWith('.appimage.tar.gz')) return 0;
|
||||
@@ -416,7 +479,8 @@ function artifactPriority(filePath) {
|
||||
return 99;
|
||||
}
|
||||
|
||||
export function selectReleaseArtifact(files) {
|
||||
export function selectReleaseArtifact(files, target = defaultTarget()) {
|
||||
validateReleaseTarget(target);
|
||||
const explicit = process.env.AGC_UPDATE_ARTIFACT?.trim();
|
||||
if (explicit) {
|
||||
const resolved = path.resolve(explicit);
|
||||
@@ -427,9 +491,10 @@ export function selectReleaseArtifact(files) {
|
||||
}
|
||||
return (
|
||||
[...files]
|
||||
.filter((filePath) => artifactPriority(filePath) < 99)
|
||||
.filter((filePath) => artifactPriority(filePath, target) < 99)
|
||||
.sort((left, right) => {
|
||||
const priority = artifactPriority(left) - artifactPriority(right);
|
||||
const priority =
|
||||
artifactPriority(left, target) - artifactPriority(right, target);
|
||||
return priority || left.localeCompare(right);
|
||||
})[0] ?? null
|
||||
);
|
||||
@@ -450,13 +515,15 @@ function readUpdaterSignature(artifactPath) {
|
||||
export function createUpdateManifest(
|
||||
artifactPath,
|
||||
{
|
||||
channel = resolveReleaseChannel(),
|
||||
target = releaseTarget,
|
||||
target = defaultTarget(),
|
||||
channel = resolveReleaseChannel(process.env, target),
|
||||
publishedAt = new Date().toISOString(),
|
||||
notes = readReleaseNotes(),
|
||||
commit = readHeadCommit(),
|
||||
} = {},
|
||||
) {
|
||||
validateReleaseTarget(target);
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }, target);
|
||||
const signature = readUpdaterSignature(artifactPath);
|
||||
const version = readPackageJson().version;
|
||||
const fileName = path.basename(artifactPath);
|
||||
@@ -604,9 +671,11 @@ export function createLegacyUpdateManifest(
|
||||
};
|
||||
}
|
||||
|
||||
export async function generateUpdateManifest() {
|
||||
const channel = resolveReleaseChannel();
|
||||
const artifact = selectReleaseArtifact(listFiles(bundleRoot));
|
||||
export async function generateUpdateManifest(
|
||||
context = resolveReleaseContext(),
|
||||
) {
|
||||
const { channel, target, bundleRoot } = context;
|
||||
const artifact = selectReleaseArtifact(listFiles(bundleRoot), target);
|
||||
if (!artifact) {
|
||||
throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`);
|
||||
}
|
||||
@@ -623,7 +692,7 @@ export async function generateUpdateManifest() {
|
||||
`[ai-game-creator-shell] 未生成自动更新摘要(上一发布 commit=${previousCommit ?? '未知'},客户端相关提交=${commits ? commits.length : '不可判定'},最近提交=${recentCommits ? recentCommits.length : '不可判定'})`,
|
||||
);
|
||||
}
|
||||
const manifest = createUpdateManifest(artifact, { channel, notes });
|
||||
const manifest = createUpdateManifest(artifact, { channel, target, notes });
|
||||
const manifestPath = path.join(bundleRoot, 'latest.json');
|
||||
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
const notesPath = path.join(bundleRoot, 'release-notes.txt');
|
||||
@@ -675,12 +744,24 @@ export async function generateUpdateManifest() {
|
||||
};
|
||||
}
|
||||
|
||||
export async function buildRelease(
|
||||
args = [],
|
||||
{
|
||||
prepareVersion = prepareReleaseVersion,
|
||||
build = runTauriBuild,
|
||||
generateManifest = generateUpdateManifest,
|
||||
} = {},
|
||||
) {
|
||||
const context = resolveReleaseContext(args);
|
||||
if (!args.includes('--no-bundle')) await prepareVersion(context);
|
||||
build(args, context);
|
||||
if (!args.includes('--no-bundle')) return generateManifest(context);
|
||||
}
|
||||
|
||||
if (
|
||||
process.argv[1] &&
|
||||
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
) {
|
||||
const args = process.argv.slice(2);
|
||||
if (!args.includes('--no-bundle')) await prepareReleaseVersion();
|
||||
runTauriBuild(args);
|
||||
if (!args.includes('--no-bundle')) await generateUpdateManifest();
|
||||
await buildRelease(args);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
agcReleasePathPatterns,
|
||||
buildRelease,
|
||||
buildTauriBuildArguments,
|
||||
collectRecentReleaseCommits,
|
||||
collectReleaseCommits,
|
||||
compareVersions,
|
||||
@@ -22,11 +24,14 @@ import {
|
||||
createUpdateManifest,
|
||||
formatRecentReleaseNotes,
|
||||
formatReleaseNotes,
|
||||
generateUpdateManifest,
|
||||
nextPatchVersion,
|
||||
resolveManifestPlatformKeys,
|
||||
resolvePreviousReleaseCommit,
|
||||
resolveReleaseChannel,
|
||||
resolveReleaseContext,
|
||||
resolveRemoteHighWaterVersion,
|
||||
runTauriBuild,
|
||||
selectReleaseArtifact,
|
||||
updateManifestUrl,
|
||||
} from './build-release.mjs';
|
||||
@@ -34,6 +39,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)) {
|
||||
@@ -132,9 +152,12 @@ test('channel manifest URL and build-time endpoint follow the channel', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('universal macOS builds publish one artifact under both platform keys', () => {
|
||||
assert.deepEqual(resolveManifestPlatformKeys(universalTarget), [
|
||||
test('macOS manifests only advertise the architecture actually built', () => {
|
||||
assert.throws(() => resolveManifestPlatformKeys(universalTarget), /单架构/);
|
||||
assert.deepEqual(resolveManifestPlatformKeys('aarch64-apple-darwin'), [
|
||||
'darwin-aarch64',
|
||||
]);
|
||||
assert.deepEqual(resolveManifestPlatformKeys('x86_64-apple-darwin'), [
|
||||
'darwin-x86_64',
|
||||
]);
|
||||
assert.deepEqual(resolveManifestPlatformKeys(windowsTarget), [
|
||||
@@ -142,6 +165,218 @@ test('universal macOS builds publish one artifact under both platform keys', ()
|
||||
]);
|
||||
});
|
||||
|
||||
test('release context resolves explicit targets before environment/default and fails closed', () => {
|
||||
for (const args of [
|
||||
['--target', 'aarch64-apple-darwin'],
|
||||
['--target=aarch64-apple-darwin'],
|
||||
['-t', 'aarch64-apple-darwin'],
|
||||
]) {
|
||||
for (const env of [{}, { AGC_BUILD_TARGET: windowsTarget }]) {
|
||||
const context = resolveReleaseContext(args, env);
|
||||
assert.equal(context.target, 'aarch64-apple-darwin');
|
||||
assert.equal(context.channel, 'dev-mac');
|
||||
assert.match(
|
||||
context.bundleRoot.replaceAll('\\', '/'),
|
||||
/target\/aarch64-apple-darwin\/release\/bundle$/,
|
||||
);
|
||||
assert.ok(Object.isFrozen(context));
|
||||
}
|
||||
assert.throws(
|
||||
() => resolveReleaseContext(args, { AGC_UPDATE_CHANNEL: 'dev-win' }),
|
||||
/只能用于 windows/,
|
||||
);
|
||||
}
|
||||
assert.equal(resolveReleaseContext([], {}).target, windowsTarget);
|
||||
assert.equal(
|
||||
resolveReleaseContext([], { AGC_BUILD_TARGET: 'x86_64-apple-darwin' })
|
||||
.channel,
|
||||
'dev-mac',
|
||||
);
|
||||
for (const args of [
|
||||
['--target'],
|
||||
['--target='],
|
||||
['--target', '--no-bundle'],
|
||||
['--target', windowsTarget, '--target=aarch64-apple-darwin'],
|
||||
['--target', universalTarget],
|
||||
['--target', 'unknown'],
|
||||
])
|
||||
assert.throws(() => resolveReleaseContext(args, {}));
|
||||
});
|
||||
|
||||
test('explicit macOS target drives version lookup, Tauri endpoint, artifact and manifest together', async () => {
|
||||
const calls = [];
|
||||
const seenContexts = [];
|
||||
await withStubbedFetch(
|
||||
(url) => {
|
||||
calls.push(url);
|
||||
assert.match(url, /\/dev-mac\/latest\.json$/);
|
||||
return jsonResponse({ version: '0.1.67' });
|
||||
},
|
||||
() =>
|
||||
withEnv(
|
||||
{ AGC_BUILD_TARGET: undefined, AGC_UPDATE_CHANNEL: undefined },
|
||||
() =>
|
||||
buildRelease(['--target', 'aarch64-apple-darwin'], {
|
||||
prepareVersion: async (context) => {
|
||||
seenContexts.push(context);
|
||||
assert.equal(
|
||||
await resolveRemoteHighWaterVersion(context.channel),
|
||||
'0.1.67',
|
||||
);
|
||||
},
|
||||
build: (args, context) => {
|
||||
seenContexts.push(context);
|
||||
runTauriBuild(args, context, {
|
||||
spawn: (_binary, command) => {
|
||||
const configIndex = command.lastIndexOf('--config');
|
||||
const config = JSON.parse(
|
||||
readFileSync(command[configIndex + 1], 'utf8'),
|
||||
);
|
||||
assert.match(
|
||||
config.plugins.updater.endpoints[0],
|
||||
/\/dev-mac\/latest\.json$/,
|
||||
);
|
||||
assert.ok(command.includes('aarch64-apple-darwin'));
|
||||
assert.ok(
|
||||
!command.includes('--features=cocos-editor-execute'),
|
||||
);
|
||||
return { status: 0 };
|
||||
},
|
||||
});
|
||||
},
|
||||
generateManifest: (context) => {
|
||||
seenContexts.push(context);
|
||||
withSignedArtifact('陶泥儿.app.tar.gz', (artifact) => {
|
||||
assert.equal(
|
||||
selectReleaseArtifact(
|
||||
['/tmp/win.exe', artifact, '/tmp/mac.dmg'],
|
||||
context.target,
|
||||
),
|
||||
artifact,
|
||||
);
|
||||
const manifest = createUpdateManifest(artifact, context);
|
||||
assert.deepEqual(Object.keys(manifest.platforms), [
|
||||
'darwin-aarch64',
|
||||
]);
|
||||
assert.match(
|
||||
manifest.platforms['darwin-aarch64'].url,
|
||||
/\/dev-mac\//,
|
||||
);
|
||||
});
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
assert.equal(calls.length, 1, 'Mac 不应读取 Windows 迁移指针');
|
||||
assert.equal(seenContexts.length, 3);
|
||||
assert.ok(seenContexts.every((context) => context === seenContexts[0]));
|
||||
});
|
||||
|
||||
test('real manifest writer uses the resolved bundle root and does not emit Windows artifacts', async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
|
||||
try {
|
||||
const artifact = path.join(root, '陶泥儿.app.tar.gz');
|
||||
writeFileSync(artifact, 'mac package');
|
||||
writeFileSync(`${artifact}.sig`, 'mac signature');
|
||||
writeFileSync(path.join(root, 'windows.exe'), 'wrong platform');
|
||||
const context = {
|
||||
...resolveReleaseContext(['--target=x86_64-apple-darwin'], {}),
|
||||
bundleRoot: root,
|
||||
};
|
||||
const result = await withStubbedFetch(
|
||||
(url) => {
|
||||
assert.match(url, /\/dev-mac\/latest\.json$/);
|
||||
return jsonResponse({}, 404);
|
||||
},
|
||||
() => generateUpdateManifest(context),
|
||||
);
|
||||
assert.equal(result.artifact, artifact);
|
||||
assert.equal(result.manifestPath, path.join(root, 'latest.json'));
|
||||
assert.equal(result.legacyManifestPath, null);
|
||||
assert.deepEqual(Object.keys(result.manifest.platforms), ['darwin-x86_64']);
|
||||
assert.match(result.manifest.platforms['darwin-x86_64'].url, /\/dev-mac\//);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid target or mismatched channel fails before any release side effect', async () => {
|
||||
let touched = false;
|
||||
const sideEffects = {
|
||||
prepareVersion: () => {
|
||||
touched = true;
|
||||
},
|
||||
build: () => {
|
||||
touched = true;
|
||||
},
|
||||
generateManifest: () => {
|
||||
touched = true;
|
||||
},
|
||||
};
|
||||
await assert.rejects(
|
||||
() => buildRelease(['--target', universalTarget], sideEffects),
|
||||
/单架构/,
|
||||
);
|
||||
await withEnv({ AGC_UPDATE_CHANNEL: 'dev-win' }, () =>
|
||||
assert.rejects(
|
||||
() => buildRelease(['--target=aarch64-apple-darwin'], sideEffects),
|
||||
/只能用于 windows/,
|
||||
),
|
||||
);
|
||||
assert.equal(touched, false);
|
||||
});
|
||||
|
||||
test('Windows remains the default and explicit Windows overrides macOS environment', () => {
|
||||
const files = ['/tmp/mac.app.tar.gz', '/tmp/windows.exe', '/tmp/mac.dmg'];
|
||||
for (const context of [
|
||||
resolveReleaseContext([], {}),
|
||||
resolveReleaseContext(['--target', windowsTarget], {
|
||||
AGC_BUILD_TARGET: 'aarch64-apple-darwin',
|
||||
}),
|
||||
]) {
|
||||
assert.equal(context.channel, 'dev-win');
|
||||
assert.equal(
|
||||
selectReleaseArtifact(files, context.target),
|
||||
'/tmp/windows.exe',
|
||||
);
|
||||
runTauriBuild(
|
||||
['--target', windowsTarget, '--config', 'user-config.json'],
|
||||
context,
|
||||
{
|
||||
spawn: (_binary, command) => {
|
||||
assert.ok(command.includes('--features=cocos-editor-execute'));
|
||||
assert.ok(command.includes('user-config.json'));
|
||||
const configIndex = command.lastIndexOf('--config');
|
||||
const config = JSON.parse(
|
||||
readFileSync(command[configIndex + 1], 'utf8'),
|
||||
);
|
||||
assert.match(
|
||||
config.plugins.updater.endpoints[0],
|
||||
/\/dev-win\/latest\.json$/,
|
||||
);
|
||||
return { status: 0 };
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('no-bundle smoke skips version writes and manifest generation', async () => {
|
||||
const steps = [];
|
||||
await buildRelease(['--no-bundle', '--target=aarch64-apple-darwin'], {
|
||||
prepareVersion: () => {
|
||||
steps.push('version');
|
||||
},
|
||||
build: (_args, context) => {
|
||||
steps.push(context.channel);
|
||||
},
|
||||
generateManifest: () => {
|
||||
steps.push('manifest');
|
||||
},
|
||||
});
|
||||
assert.deepEqual(steps, ['dev-mac']);
|
||||
});
|
||||
|
||||
test('channel manifest carries version, platform keys and signature', () => {
|
||||
withSignedArtifact('陶泥儿_0.1.48_x64-setup.exe', (artifact) => {
|
||||
withEnv({ AGC_UPDATE_RELEASE_NOTES: '修复与改进' }, () => {
|
||||
@@ -345,6 +580,7 @@ test('release upload forces overwrite for artifact, signature and channel pointe
|
||||
);
|
||||
assert.match(source, /agc\/\$\{channel\}\/latest\.json/u);
|
||||
assert.match(source, /agc\/latest\.json/u);
|
||||
assert.match(source, /await buildRelease\(process\.argv\.slice\(2\)\)/u);
|
||||
});
|
||||
|
||||
test('release notes list client commits with short sha and bound their size', () => {
|
||||
|
||||
@@ -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(
|
||||
@@ -1720,7 +1757,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 完整性校验失败',
|
||||
]) {
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -12,8 +12,7 @@ if (!/^[a-z0-9][a-z0-9.-]{1,62}$/u.test(bucket) || /[\r\n\0]/u.test(endpoint)) {
|
||||
process.env.AGC_UPDATE_OSS_BASE_URL ||= `https://${bucket}.${endpoint}/agc`;
|
||||
const dryRun = readReleaseDryRun();
|
||||
|
||||
const { generateUpdateManifest, prepareReleaseVersion, runTauriBuild } =
|
||||
await import('./build-release.mjs');
|
||||
const { buildRelease } = await import('./build-release.mjs');
|
||||
|
||||
function runOssutil(args) {
|
||||
const binary = process.env.OSSUTIL_BIN?.trim() || 'ossutil';
|
||||
@@ -51,10 +50,8 @@ function runOssutil(args) {
|
||||
if (result.status !== 0) process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
await prepareReleaseVersion();
|
||||
runTauriBuild([]);
|
||||
const { artifact, channel, legacyManifestPath, manifest, manifestPath } =
|
||||
await generateUpdateManifest();
|
||||
await buildRelease(process.argv.slice(2));
|
||||
const artifactKey = `agc/${channel}/${manifest.version}/${path.basename(artifact)}`;
|
||||
// Jenkins/ossutil 默认会在目标对象已存在时交互询问并按默认值跳过;
|
||||
// 发布清单是固定的 latest 指针,必须显式覆盖,否则流水线会误报成功但远端仍保留旧版本。
|
||||
|
||||
+1
-1
@@ -1745,7 +1745,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.47"
|
||||
version = "0.1.67"
|
||||
dependencies = [
|
||||
"agent-runtime-core",
|
||||
"axum",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.47"
|
||||
version = "0.1.67"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
|
||||
@@ -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<String, std::io::Error> {
|
||||
let file = fs::File::open(path)?;
|
||||
let mut reader = BufReader::new(file);
|
||||
@@ -42,7 +29,15 @@ fn sha256_file(path: &std::path::Path) -> Result<String, std::io::Error> {
|
||||
}
|
||||
|
||||
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::<Vec<_>>();
|
||||
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) {}
|
||||
|
||||
@@ -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<Layout> {
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": "agc-skill-pack.v1",
|
||||
"version": "2026-08-26.23",
|
||||
"version": "2026-08-26.24",
|
||||
"skills": [
|
||||
{
|
||||
"name": "agc-game-production-workflow",
|
||||
@@ -63,7 +63,7 @@
|
||||
"agents/openai.yaml",
|
||||
"references/platform-art-contract.md"
|
||||
],
|
||||
"sha256": "c6329c6a3cbd17a237d042349d7fd8adcf240287ef56d23b49329923e976d534"
|
||||
"sha256": "47ac742d9b88e5d6cd9833484ab212152578e58ae27f7add312fd1d78183385c"
|
||||
},
|
||||
{
|
||||
"name": "agc-web-game-development",
|
||||
|
||||
@@ -19,6 +19,12 @@ image, UI design image, or publication material; use `agc_edit_image` for an
|
||||
edit of an existing registered image; use `taonier_prepare_game_art` only for
|
||||
the complete game-art package and its canonical slices.
|
||||
|
||||
With `agc_generate_image`, `kind="character"` and `kind="art-spritesheet"`
|
||||
generate the subject on a solid-colour background and automatically matte it
|
||||
away afterwards, producing transparent-background results; write the prompt
|
||||
for the subject only, never for a scene. `kind="image"` keeps the rendered
|
||||
frame without extra processing.
|
||||
|
||||
When `agc_generate_image` is used with `kind="art-spritesheet"`, `sliceMode` is
|
||||
required and has no default, so decide it explicitly:
|
||||
|
||||
|
||||
@@ -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、登录状态、用户配置或项目数据。
|
||||
@@ -21,6 +21,7 @@ mod direct_project_history;
|
||||
mod direct_project_turn_history;
|
||||
mod direct_runtime;
|
||||
mod direct_thread_manager;
|
||||
mod direct_thread_wire;
|
||||
mod direct_tool_bridge;
|
||||
mod direct_tool_calls;
|
||||
mod direct_tools_mcp;
|
||||
@@ -40,7 +41,8 @@ use codex_app_server::*;
|
||||
pub(crate) use codex_app_server::{
|
||||
cancel_direct_codex_turn_at,
|
||||
direct_codex_canonical_project_identity_for_commands as direct_codex_canonical_project_identity,
|
||||
direct_game_creator_codex_chat_at, direct_game_creator_home_codex_chat, DirectTurnCancelView,
|
||||
direct_game_creator_codex_chat_at, direct_game_creator_home_codex_chat,
|
||||
direct_thread_id_for_project, DirectTurnCancelView,
|
||||
};
|
||||
use codex_cli::*;
|
||||
pub(crate) use codex_cli::{
|
||||
@@ -55,6 +57,7 @@ pub(crate) use direct_project_history::*;
|
||||
pub(crate) use direct_project_turn_history::*;
|
||||
pub(crate) use direct_runtime::*;
|
||||
pub(crate) use direct_thread_manager::*;
|
||||
pub(crate) use direct_thread_wire::*;
|
||||
pub(crate) use direct_tool_bridge::*;
|
||||
pub(crate) use direct_tool_calls::*;
|
||||
pub(crate) use direct_tools_mcp::*;
|
||||
|
||||
+23
@@ -20,6 +20,29 @@ pub(crate) fn direct_codex_canonical_project_identity(
|
||||
))
|
||||
}
|
||||
|
||||
/// 项目根目录在 Thread Manager 里的线程身份。
|
||||
///
|
||||
/// 订阅入口、回合事件写入和"回合被兜底释放"三处必须算出同一个字符串,否则前端会订阅到
|
||||
/// 一个永不产生事件的空线程。这个字符串**只取决于路径**:能归一就用 canonical 路径,只有
|
||||
/// 归一本身失败(路径不存在 / 不是目录 / 无法安全解析)才退回调用方给的字符串。
|
||||
///
|
||||
/// 这里刻意不读 `.agent/manifest.json`:那次读取是"项目权威身份"(连接池摘要,见
|
||||
/// `direct_codex_canonical_project_identity`)的要求,而线程 id 只是一个路径 key。把
|
||||
/// manifest 的瞬时抖动混进线程 id,会让同一项目在"订阅那一刻"与"跑回合那一刻"算出两个
|
||||
/// 字符串(例如调用方给的是符号链接路径),订阅就绑到一条永远不会有事件的空线程上。
|
||||
pub(crate) fn direct_thread_id_for_project(root: &std::path::Path) -> String {
|
||||
let Ok((canonical_root, _)) = resolve_direct_codex_project_authority(root) else {
|
||||
return root.to_string_lossy().into_owned();
|
||||
};
|
||||
canonical_root
|
||||
.to_str()
|
||||
.and_then(|value| value.strip_prefix(r"\\?\"))
|
||||
.map(std::path::Path::new)
|
||||
.unwrap_or(canonical_root.as_path())
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
pub(super) fn direct_codex_os_path_identity_bytes(path: &std::path::Path) -> Vec<u8> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<PathBuf> {
|
||||
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<PathBuf>, npm_root: &Path) {
|
||||
let vendor_root = npm_root
|
||||
.join("node_modules")
|
||||
@@ -109,52 +101,71 @@ fn game_creator_codex_cli_executable_candidates() -> Vec<PathBuf> {
|
||||
}
|
||||
|
||||
fn game_creator_bundled_resource_dir() -> Option<PathBuf> {
|
||||
let executable = std::env::current_exe().ok()?;
|
||||
game_creator_bundled_resource_dir_for(&executable)
|
||||
}
|
||||
|
||||
fn game_creator_bundled_resource_dir_for(executable: &Path) -> Option<PathBuf> {
|
||||
#[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<PathBuf> {
|
||||
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<String, String> {
|
||||
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::<GameCreatorBundledCodexCliManifest>(&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<String,
|
||||
)
|
||||
})?;
|
||||
let actual = format!("{:x}", Sha256::digest(bytes));
|
||||
if !actual.eq_ignore_ascii_case(manifest.files.get(relative).expect("validated hash")) {
|
||||
if !actual.eq_ignore_ascii_case(manifest.files.get(*relative).expect("validated hash")) {
|
||||
return Err(format!("内置 Codex CLI 完整性校验失败:组件 {relative}"));
|
||||
}
|
||||
}
|
||||
@@ -899,7 +910,7 @@ mod tests {
|
||||
fn codex_cli_candidates_prefer_bundled_sidecar_before_npm_and_path() {
|
||||
let temp = tempfile::tempdir().expect("temp dir");
|
||||
let resources = temp.path().join("resources");
|
||||
let bundled = resources.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH);
|
||||
let bundled = game_creator_bundled_codex_cli_path(Some(&resources)).unwrap();
|
||||
std::fs::create_dir_all(bundled.parent().expect("bundled parent")).expect("bundled dir");
|
||||
let app_data = temp.path().join("app-data");
|
||||
let native = app_data
|
||||
@@ -918,20 +929,19 @@ mod tests {
|
||||
assert_eq!(candidates[1], native);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
#[test]
|
||||
fn bundled_codex_cli_requires_matching_manifest_hash() {
|
||||
let temp = tempfile::tempdir().expect("temp dir");
|
||||
let executable = temp
|
||||
.path()
|
||||
.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH);
|
||||
let executable = game_creator_bundled_codex_cli_path(Some(temp.path())).unwrap();
|
||||
let layout = codex_bundle::for_target(env!("AGC_BUILD_TARGET")).unwrap();
|
||||
std::fs::create_dir_all(executable.parent().expect("sidecar parent")).expect("sidecar dir");
|
||||
let bundle_root = executable
|
||||
.parent()
|
||||
.and_then(Path::parent)
|
||||
.expect("bundle root");
|
||||
let mut hashes = std::collections::BTreeMap::new();
|
||||
for relative in GAME_CREATOR_BUNDLED_CODEX_CLI_REQUIRED_FILES {
|
||||
for relative in layout.files {
|
||||
let path = bundle_root.join(relative);
|
||||
std::fs::create_dir_all(path.parent().expect("component parent"))
|
||||
.expect("component dir");
|
||||
@@ -939,14 +949,14 @@ mod tests {
|
||||
std::fs::write(&path, bytes.as_bytes()).expect("component bytes");
|
||||
hashes.insert(relative, format!("{:x}", Sha256::digest(bytes.as_bytes())));
|
||||
}
|
||||
let files = serde_json::to_string(&hashes).expect("component hashes");
|
||||
std::fs::write(
|
||||
bundle_root.join("manifest.json"),
|
||||
format!(
|
||||
r#"{{"schemaVersion":"genarrative-codex-sidecar.v2","platform":"win32-x64","version":"codex-cli test","files":{files}}}"#
|
||||
),
|
||||
)
|
||||
.expect("sidecar manifest");
|
||||
let manifest = serde_json::json!({
|
||||
"schemaVersion": codex_bundle::SCHEMA,
|
||||
"platform": layout.platform,
|
||||
"version": "codex-cli test",
|
||||
"files": hashes,
|
||||
});
|
||||
let manifest_path = bundle_root.join("manifest.json");
|
||||
std::fs::write(&manifest_path, manifest.to_string()).expect("sidecar manifest");
|
||||
|
||||
assert_eq!(
|
||||
validate_game_creator_bundled_codex_cli(&executable).expect("trusted sidecar"),
|
||||
@@ -956,15 +966,31 @@ mod tests {
|
||||
assert!(validate_game_creator_bundled_codex_cli(&executable)
|
||||
.expect_err("tampered sidecar must be rejected")
|
||||
.contains("完整性校验失败"));
|
||||
std::fs::write(&executable, format!("trusted {}", layout.executable)).unwrap();
|
||||
let mut wrong_platform = manifest.clone();
|
||||
wrong_platform["platform"] = serde_json::json!("wrong-platform");
|
||||
std::fs::write(&manifest_path, wrong_platform.to_string()).unwrap();
|
||||
assert!(validate_game_creator_bundled_codex_cli(&executable)
|
||||
.expect_err("wrong platform must be rejected")
|
||||
.contains("完整性清单不受支持"));
|
||||
std::fs::write(&manifest_path, manifest.to_string()).unwrap();
|
||||
let helper = bundle_root.join(layout.files[1]);
|
||||
std::fs::write(&helper, b"tampered helper").unwrap();
|
||||
assert!(validate_game_creator_bundled_codex_cli(&executable)
|
||||
.expect_err("tampered helper must be rejected")
|
||||
.contains("完整性校验失败"));
|
||||
std::fs::remove_file(&helper).unwrap();
|
||||
assert!(validate_game_creator_bundled_codex_cli(&executable)
|
||||
.expect_err("missing helper must be rejected")
|
||||
.contains("缺少必需组件"));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
#[test]
|
||||
fn bundled_codex_cli_rejects_a_manifest_without_code_mode_host() {
|
||||
let temp = tempfile::tempdir().expect("temp dir");
|
||||
let executable = temp
|
||||
.path()
|
||||
.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH);
|
||||
let executable = game_creator_bundled_codex_cli_path(Some(temp.path())).unwrap();
|
||||
let layout = codex_bundle::for_target(env!("AGC_BUILD_TARGET")).unwrap();
|
||||
std::fs::create_dir_all(executable.parent().expect("sidecar parent")).expect("sidecar dir");
|
||||
let bundle_root = executable
|
||||
.parent()
|
||||
@@ -975,9 +1001,13 @@ mod tests {
|
||||
let hash = format!("{:x}", Sha256::digest(bytes));
|
||||
std::fs::write(
|
||||
bundle_root.join("manifest.json"),
|
||||
format!(
|
||||
r#"{{"schemaVersion":"genarrative-codex-sidecar.v2","platform":"win32-x64","version":"codex-cli test","files":{{"bin/codex.exe":"{hash}"}}}}"#
|
||||
),
|
||||
serde_json::json!({
|
||||
"schemaVersion": codex_bundle::SCHEMA,
|
||||
"platform": layout.platform,
|
||||
"version": "codex-cli test",
|
||||
"files": { layout.executable: hash },
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.expect("sidecar manifest");
|
||||
|
||||
@@ -986,6 +1016,38 @@ mod tests {
|
||||
.contains("完整性清单不受支持"));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_bundle_resources_and_candidates_do_not_require_a_development_path() {
|
||||
let executable = Path::new("/Applications/陶泥儿 测试.app/Contents/MacOS/taonier");
|
||||
let resources = game_creator_bundled_resource_dir_for(executable).unwrap();
|
||||
assert_eq!(
|
||||
resources,
|
||||
Path::new("/Applications/陶泥儿 测试.app/Contents/Resources")
|
||||
);
|
||||
let bundled = game_creator_bundled_codex_cli_path(Some(&resources)).unwrap();
|
||||
let candidates = game_creator_codex_cli_executable_candidates_for(
|
||||
Some(&resources),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
assert_eq!(candidates, vec![bundled, PathBuf::from("codex")]);
|
||||
assert!(
|
||||
game_creator_bundled_resource_dir_for(Path::new("/tmp/target/release/taonier"))
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
game_creator_bundled_resource_dir_for(Path::new("/tmp/Contents/MacOS/taonier"))
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
game_creator_codex_cli_executable_candidates_for(None, None, None, None, None),
|
||||
vec![PathBuf::from("codex")],
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn codex_cli_resolver_finds_current_native_install() {
|
||||
|
||||
@@ -550,6 +550,8 @@ fn extract_mcp_arguments(root: &Path, tool: &str, arguments: &Value) -> Value {
|
||||
"agc_generate_image" => {
|
||||
copy_string(object, "kind", &mut out);
|
||||
copy_string(object, "sliceMode", &mut out);
|
||||
copy_number(object, "sliceCount", &mut out);
|
||||
copy_string(object, "screenColor", &mut out);
|
||||
copy_string(object, "aspectRatio", &mut out);
|
||||
copy_string(object, "imageSize", &mut out);
|
||||
copy_string(object, "assetName", &mut out);
|
||||
@@ -1194,7 +1196,13 @@ mod tests {
|
||||
"item": {
|
||||
"type": "mcpToolCall",
|
||||
"tool": "agc_generate_image",
|
||||
"arguments": { "prompt": prompt, "kind": "icon-spec" }
|
||||
"arguments": {
|
||||
"prompt": prompt,
|
||||
"kind": "art-spritesheet",
|
||||
"sliceMode": "connected-components",
|
||||
"sliceCount": 8,
|
||||
"screenColor": "#CFEFFF"
|
||||
}
|
||||
}
|
||||
}));
|
||||
audit.finish(true);
|
||||
@@ -1205,6 +1213,8 @@ mod tests {
|
||||
let stored = item["arguments"]["prompt"].as_str().expect("prompt");
|
||||
assert_eq!(stored.chars().count(), DIRECT_CODEX_AUDIT_BRIEF_CHARS);
|
||||
assert_eq!(item["arguments"]["promptChars"], json!(5000));
|
||||
assert_eq!(item["arguments"]["sliceCount"], json!(8));
|
||||
assert_eq!(item["arguments"]["screenColor"], json!("#CFEFFF"));
|
||||
assert_eq!(
|
||||
item["arguments"]["promptSha256"],
|
||||
json!(sha256_hex("收".repeat(5000).as_bytes()))
|
||||
|
||||
@@ -5,8 +5,8 @@ mod validation;
|
||||
mod wire;
|
||||
|
||||
pub(crate) use model::{
|
||||
DirectCodexUserContentPart, DirectCodexUserItem, DirectCodexUserMessageEnvelope,
|
||||
DirectCodexUserMessageItem, DirectCodexUserRole, DirectCodexUserRuntimeRegionPart,
|
||||
DirectCodexUserContentPart, DirectCodexUserItem, DirectCodexUserMessageItem,
|
||||
DirectCodexUserRole, DirectCodexUserRuntimeRegionPart,
|
||||
};
|
||||
pub(crate) use validation::validate_direct_codex_user_item;
|
||||
pub(crate) use wire::{
|
||||
|
||||
@@ -61,13 +61,6 @@ pub(crate) struct DirectCodexUserRuntimeRegionPart {
|
||||
pub(crate) resource_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
|
||||
pub(crate) struct DirectCodexUserMessageEnvelope {
|
||||
pub(crate) item: DirectCodexUserItem,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3390,6 +3390,7 @@ async fn generate_direct_taonier_art_asset_at(
|
||||
slice_mode: (asset_kind == "art-spritesheet").then(|| "connected-components".to_string()),
|
||||
grid_x: None,
|
||||
grid_y: None,
|
||||
screen_color: None,
|
||||
};
|
||||
let runtime_context =
|
||||
direct_taonier_art_generation_runtime_context(root, output_path, asset_kind)?;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -2224,12 +2224,48 @@ fn validate_generate_image_slice_declaration(
|
||||
}
|
||||
if slice_mode.is_some() || grid_x.is_some() || grid_y.is_some() || slice_count.is_some() {
|
||||
return Err(format!(
|
||||
"工具参数 sliceMode/gridX/gridY 仅对 kind=art-spritesheet 生效,当前 kind={kind}"
|
||||
"工具参数 sliceMode/gridX/gridY/sliceCount 仅对 kind=art-spritesheet 生效,当前 kind={kind}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 抠图纯色背景只服务 character 与 art-spritesheet 链路;格式校验收口为
|
||||
/// `auto` 或 `#RRGGBB`(服务端另有支持色板,客户端不复制),`auto`/空串归一为
|
||||
/// None(服务端自动决策),hex 统一大写后透传。其它 kind 携带该字段直接拒绝,
|
||||
/// 避免服务端静默忽略造成“已生效”的误解。
|
||||
fn normalize_generate_image_screen_color(
|
||||
arguments: &Value,
|
||||
kind: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
let Some(value) = arguments.get("screenColor") else {
|
||||
return Ok(None);
|
||||
};
|
||||
if value.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
if !matches!(kind, "character" | "art-spritesheet") {
|
||||
return Err(format!(
|
||||
"工具参数 screenColor 仅对 kind=character 和 kind=art-spritesheet 生效,当前 kind={kind}"
|
||||
));
|
||||
}
|
||||
let raw = value
|
||||
.as_str()
|
||||
.ok_or_else(|| "工具参数 screenColor 必须是 auto 或 #RRGGBB".to_string())?
|
||||
.trim();
|
||||
if raw.is_empty() || raw.eq_ignore_ascii_case("auto") {
|
||||
return Ok(None);
|
||||
}
|
||||
let normalized = raw.to_ascii_uppercase();
|
||||
let valid = normalized.len() == 7
|
||||
&& normalized.starts_with('#')
|
||||
&& normalized[1..].chars().all(|c| c.is_ascii_hexdigit());
|
||||
if !valid {
|
||||
return Err("工具参数 screenColor 必须是 auto 或 #RRGGBB".to_string());
|
||||
}
|
||||
Ok(Some(normalized))
|
||||
}
|
||||
|
||||
async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value) -> Value {
|
||||
let result = async {
|
||||
bridge_reject_unknown_fields(
|
||||
@@ -2244,6 +2280,8 @@ async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value)
|
||||
"sliceMode",
|
||||
"gridX",
|
||||
"gridY",
|
||||
"sliceCount",
|
||||
"screenColor",
|
||||
],
|
||||
)?;
|
||||
enforce_project_permission_policy(&state.root, "canvas.asset_generate")?;
|
||||
@@ -2323,13 +2361,25 @@ async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value)
|
||||
{
|
||||
return Err("工具参数 gridX/gridY 必须在 1 到 32 之间".to_string());
|
||||
}
|
||||
let slice_count = arguments
|
||||
.get("sliceCount")
|
||||
.filter(|value| !value.is_null())
|
||||
.map(|value| {
|
||||
value
|
||||
.as_u64()
|
||||
.filter(|count| (1..=256).contains(count))
|
||||
.map(|count| count as usize)
|
||||
.ok_or_else(|| "工具参数 sliceCount 必须是 1 到 256 的整数".to_string())
|
||||
})
|
||||
.transpose()?;
|
||||
validate_generate_image_slice_declaration(
|
||||
kind.as_str(),
|
||||
slice_mode.as_deref(),
|
||||
grid_x,
|
||||
grid_y,
|
||||
None,
|
||||
slice_count,
|
||||
)?;
|
||||
let screen_color = normalize_generate_image_screen_color(arguments, kind.as_str())?;
|
||||
let options = PlatformArtAssetGenerationOptions {
|
||||
output_path,
|
||||
aspect_ratio,
|
||||
@@ -2337,10 +2387,11 @@ async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value)
|
||||
asset_kind: kind.clone(),
|
||||
asset_label: asset_name.clone(),
|
||||
replace_existing: false,
|
||||
slice_count: None,
|
||||
slice_count,
|
||||
slice_mode,
|
||||
grid_x,
|
||||
grid_y,
|
||||
screen_color,
|
||||
};
|
||||
let _generation_guard = state.image_generation_gate.lock().await;
|
||||
let generated = with_direct_editor_api_credentials(
|
||||
@@ -2864,9 +2915,71 @@ mod tests {
|
||||
wrong_kind.contains("仅对 kind=art-spritesheet 生效"),
|
||||
"{wrong_kind}"
|
||||
);
|
||||
let wrong_kind_count =
|
||||
validate_generate_image_slice_declaration("image", None, None, None, Some(8))
|
||||
.expect_err("sliceCount-only violation must be rejected");
|
||||
assert!(
|
||||
wrong_kind_count.contains("sliceCount"),
|
||||
"sliceCount-only violation must name sliceCount: {wrong_kind_count}"
|
||||
);
|
||||
assert!(validate_generate_image_slice_declaration("image", None, None, None, None).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generate_image_screen_color_is_normalized_and_kind_gated() {
|
||||
// 省略与显式 null 等价,且不触发 kind 门禁。
|
||||
assert_eq!(
|
||||
normalize_generate_image_screen_color(&json!({}), "image").expect("omitted"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_generate_image_screen_color(&json!({"screenColor": null}), "image")
|
||||
.expect("null"),
|
||||
None
|
||||
);
|
||||
// auto 家族归一为 None(服务端自动决策),大小写与空白不敏感。
|
||||
for raw in ["auto", "AUTO", " auto ", ""] {
|
||||
assert_eq!(
|
||||
normalize_generate_image_screen_color(&json!({"screenColor": raw}), "character")
|
||||
.expect("auto variants"),
|
||||
None,
|
||||
"{raw}"
|
||||
);
|
||||
}
|
||||
// hex 统一大写透传;色板白名单由服务端权威校验,客户端只守格式。
|
||||
assert_eq!(
|
||||
normalize_generate_image_screen_color(&json!({"screenColor": "#cfefff"}), "character")
|
||||
.expect("lowercase hex"),
|
||||
Some("#CFEFFF".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_generate_image_screen_color(
|
||||
&json!({"screenColor": " #A0BBA0 "}),
|
||||
"art-spritesheet"
|
||||
)
|
||||
.expect("padded hex"),
|
||||
Some("#A0BBA0".to_string())
|
||||
);
|
||||
// 非 auto/非 hex、非字符串一律拒绝。
|
||||
for bad in [json!("green"), json!("#GGGGGG"), json!("#FFF"), json!(12)] {
|
||||
assert!(
|
||||
normalize_generate_image_screen_color(&json!({"screenColor": bad}), "character")
|
||||
.is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
}
|
||||
// 其它 kind 携带该字段直接拒绝,即使取值合法。
|
||||
let gated =
|
||||
normalize_generate_image_screen_color(&json!({"screenColor": "#CFEFFF"}), "image")
|
||||
.expect_err("screenColor must stay scoped to character/art-spritesheet");
|
||||
assert!(gated.contains("kind=character"), "{gated}");
|
||||
assert!(normalize_generate_image_screen_color(
|
||||
&json!({"screenColor": "auto"}),
|
||||
"ui-prototype"
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_background_identity_preserves_default_and_distinguishes_options() {
|
||||
let legacy = "asset-1\0透明图";
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user