Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2043f8c966 | |||
| 65012e89b6 | |||
| 64b9ccfb9d | |||
| fcc3c39dad | |||
| f7a0adc616 | |||
| 57cd81d551 | |||
| 78088e422a | |||
| 65551cd827 |
@@ -16,5 +16,8 @@
|
||||
"maxRetries": 2,
|
||||
"retryBackoffMs": 500
|
||||
},
|
||||
"agentLlm": {}
|
||||
"agentLlm": {},
|
||||
"planning": {
|
||||
"capabilityEnabled": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@genarrative/ai-game-creator-shell",
|
||||
"private": true,
|
||||
"version": "0.1.12",
|
||||
"version": "0.1.19",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node scripts/start-tauri-dev.mjs",
|
||||
@@ -9,6 +9,7 @@
|
||||
"dev-stack": "node scripts/start-dev-stack.mjs",
|
||||
"build": "node scripts/build-release.mjs",
|
||||
"release:upload": "node scripts/release-upload.mjs",
|
||||
"bump-version": "node scripts/bump-version.mjs",
|
||||
"skill-pack:check": "node scripts/check-skill-pack.mjs",
|
||||
"skill-pack:sync": "node scripts/check-skill-pack.mjs --write",
|
||||
"skill-pack:test": "node --test scripts/check-skill-pack.test.mjs",
|
||||
@@ -19,6 +20,8 @@
|
||||
"config": "node scripts/game-creator-config-wizard.mjs",
|
||||
"test:chat": "node scripts/agent-swarm-test-chat.mjs --task \"制作一个可直接试玩的原创植物塔防小游戏:玩家选择并放置原创守卫阻挡敌人,完成波次后可以进入下一关并重新开始。主题、单位名称与视觉语言必须原创,不使用任何现有游戏角色、单位名、Logo 或受保护视觉语言。请自主完成正式产物、静态检查和双视口试玩验证。\" --no-open",
|
||||
"test:chat:manual": "node scripts/agent-swarm-test-chat.mjs",
|
||||
"test:plan": "node scripts/agent-swarm-test-chat.mjs --plan --task \"我想做一款原创横版像素解谜小游戏,主角是一个能操控自己影子的小机器人,影子可以变成平台和开关。请完成立项策划并给出 Fast GDD。主题、角色名与视觉语言必须原创,不使用任何现有游戏角色、名称、Logo 或受保护视觉语言。\"",
|
||||
"test:plan:manual": "node scripts/agent-swarm-test-chat.mjs --plan",
|
||||
"agent-run": "node scripts/run-cli-with-config.mjs --agent-run",
|
||||
"agent-run:smoke": "node scripts/smoke-agent-run-local-provider.mjs",
|
||||
"agent-runtime:real-e2e": "node scripts/agent-runtime-real-e2e.mjs",
|
||||
@@ -51,7 +54,6 @@
|
||||
"focus-trap-react": "^12.0.3",
|
||||
"lexical": "^0.47.0",
|
||||
"lucide-react": "^0.546.0",
|
||||
"phaser": "^4.2.1",
|
||||
"react": "^19.0.0",
|
||||
"react-arborist": "^3.16.0",
|
||||
"react-colorful": "^5.8.0",
|
||||
|
||||
@@ -36,6 +36,8 @@ export const ungeneratedGameEntryMarker =
|
||||
'还没有生成游戏。回到聊天输入创意并确认生成后';
|
||||
export const defaultRealSwarmTestTask =
|
||||
'制作一个可直接试玩的原创植物塔防小游戏:玩家选择并放置原创守卫阻挡敌人,完成波次后可以进入下一关并重新开始。主题、单位名称与视觉语言必须原创,不使用任何现有游戏角色、单位名、Logo 或受保护视觉语言。请自主完成正式产物、静态检查和双视口试玩验证。';
|
||||
export const defaultRealSwarmPlanTask =
|
||||
'我想做一款原创横版像素解谜小游戏,主角是一个能操控自己影子的小机器人,影子可以变成平台和开关。请完成立项策划并给出 Fast GDD。主题、角色名与视觉语言必须原创,不使用任何现有游戏角色、名称、Logo 或受保护视觉语言。';
|
||||
export const swarmTurnReportPrefix = '[turn.report] ';
|
||||
export const swarmTurnReportSchema = 'game-creator-swarm-turn-report.v1';
|
||||
|
||||
@@ -138,10 +140,15 @@ export const usage = `用法:
|
||||
--keep-project 保留自动创建的一次性项目
|
||||
--no-open 手工模式启动预览但不自动打开浏览器
|
||||
--task <需求> 通过 manual 入口非交互提交自定义需求
|
||||
--timeout-minutes <分钟> 设置本次执行期限;自动任务默认 50 分钟,手工模式默认不限时
|
||||
--plan 走「做方案」立项策划入口,不做游戏,不做产物验收和试玩
|
||||
--timeout-minutes <分钟> 设置本次执行期限;自动任务默认 50 分钟,--plan 默认 6 分钟,手工模式默认不限时
|
||||
--dry-run 只检查目录发现和项目准备,不启动 LLM
|
||||
-h, --help 显示帮助
|
||||
`;
|
||||
|
||||
环境变量:
|
||||
AGC_PLAN_GDD_DECISION 审批卡自动应答动作,默认 approve;revise/reject 必须
|
||||
同时用 AGC_PLAN_GDD_COMMENT 给出真实修改意见
|
||||
AGC_PLAN_GDD_COMMENT revise/reject 的意见原文`;
|
||||
|
||||
function readOptionValue(args, index, option) {
|
||||
const value = args[index + 1]?.trim();
|
||||
@@ -170,6 +177,7 @@ export function parseSwarmTestArguments(args) {
|
||||
keepProject: false,
|
||||
openBrowser: true,
|
||||
task: null,
|
||||
plan: false,
|
||||
timeoutMinutes: null,
|
||||
dryRun: false,
|
||||
help: false,
|
||||
@@ -194,6 +202,8 @@ export function parseSwarmTestArguments(args) {
|
||||
if (task.length > 4_000) throw new Error('--task 不能超过 4000 字符');
|
||||
options.task = task;
|
||||
index += 1;
|
||||
} else if (argument === '--plan') {
|
||||
options.plan = true;
|
||||
} else if (argument === '--timeout-minutes') {
|
||||
if (options.timeoutMinutes !== null) {
|
||||
throw new Error('--timeout-minutes 只能指定一次');
|
||||
@@ -212,11 +222,16 @@ export function parseSwarmTestArguments(args) {
|
||||
}
|
||||
|
||||
export function shouldStartPersistentPreview(options) {
|
||||
return !options.task;
|
||||
// 立项策划链路只出 GDD,没有可试玩产物,任何模式都不该起预览。
|
||||
return !options.task && !options.plan;
|
||||
}
|
||||
|
||||
export function resolveSwarmTestTimeoutMs(options) {
|
||||
const minutes = options.timeoutMinutes ?? (options.task ? 50 : null);
|
||||
// 立项策划的设计目标是五分钟出方案,给一分钟余量;再久就是卡住了,早失败
|
||||
// 比让 harness 空等更有用。做游戏那条链路的 50 分钟不变。
|
||||
const planMinutes = options.plan ? 6 : null;
|
||||
const minutes =
|
||||
options.timeoutMinutes ?? planMinutes ?? (options.task ? 50 : null);
|
||||
return minutes === null ? null : minutes * 60_000;
|
||||
}
|
||||
|
||||
@@ -964,12 +979,25 @@ export function swarmAutoPilotShouldCloseInput(output, promptsAfterSubmit) {
|
||||
return swarmAutoPilotSitsAtPrompt(output) && promptsAfterSubmit >= 1;
|
||||
}
|
||||
|
||||
// GDD 审批位不能等 CLI 退出之后再处理:Run 停在这里时状态是 waiting-for-user-input,
|
||||
// 而 swarm CLI 恰好把这个状态算作「本轮还在跑」,turn 永远不 settle,CLI 也就永远
|
||||
// 不退出。所以审批必须在 CLI 还活着的时候并发做完,让 Run 自己继续跑到收束。
|
||||
// 这一句是 PlanGddCompletionBlockerKind::AwaitingApprovalDecision 专有的投影文案,
|
||||
// 另外三个 blocked 子状态都不会打出它;即便认错了,真正的判据也是随后那次
|
||||
// --plan-gdd-status,没有待决定审批时不会有任何写入。
|
||||
const planGddApprovalWaitPattern = /等待 Fast GDD 审批决定/u;
|
||||
|
||||
export function swarmOutputAwaitsPlanGddApproval(line) {
|
||||
return planGddApprovalWaitPattern.test(line);
|
||||
}
|
||||
|
||||
async function runTaskCargo(
|
||||
cliArguments,
|
||||
task,
|
||||
setActiveChild,
|
||||
timeoutMs,
|
||||
autoPilot = false,
|
||||
onPlanGddApprovalWait = null,
|
||||
) {
|
||||
const child = spawnChild(cargoCommand, buildCargoCliArguments(cliArguments), {
|
||||
stdio: ['pipe', 'pipe', 'inherit'],
|
||||
@@ -981,6 +1009,25 @@ async function runTaskCargo(
|
||||
let taskSubmitted = false;
|
||||
let promptsSeen = 0;
|
||||
let sittingAtPrompt = false;
|
||||
let planGddApproval = null;
|
||||
let planGddApprovalError = null;
|
||||
let planGddApprovalStarted = false;
|
||||
let planGddApprovalPromise = null;
|
||||
const startPlanGddApproval = () => {
|
||||
planGddApprovalStarted = true;
|
||||
console.log(
|
||||
`[自动审批] 检测到 Fast GDD 审批位,正在提交 ${resolvePlanGddAutoDecision().action}`,
|
||||
);
|
||||
planGddApprovalPromise = onPlanGddApprovalWait()
|
||||
.then((value) => {
|
||||
planGddApproval = value;
|
||||
})
|
||||
.catch((error) => {
|
||||
planGddApprovalError = error;
|
||||
// 审批没成的话 Run 会一直停在等待位,干等到超时只会把真正的原因埋掉。
|
||||
void terminateChildTree(child).catch(() => {});
|
||||
});
|
||||
};
|
||||
child.stdout.setEncoding('utf8');
|
||||
child.stdout.on('data', (chunk) => {
|
||||
process.stdout.write(chunk);
|
||||
@@ -993,6 +1040,13 @@ async function runTaskCargo(
|
||||
reportLines.push(normalizedLine);
|
||||
settled = true;
|
||||
}
|
||||
if (
|
||||
onPlanGddApprovalWait &&
|
||||
!planGddApprovalStarted &&
|
||||
swarmOutputAwaitsPlanGddApproval(normalizedLine)
|
||||
) {
|
||||
startPlanGddApproval();
|
||||
}
|
||||
}
|
||||
if (!autoPilot || child.stdin.writableEnded) return;
|
||||
const atPrompt = swarmAutoPilotSitsAtPrompt(pendingLine);
|
||||
@@ -1031,9 +1085,12 @@ async function runTaskCargo(
|
||||
if (normalizedPendingLine.startsWith(swarmTurnReportPrefix)) {
|
||||
reportLines.push(normalizedPendingLine);
|
||||
}
|
||||
await planGddApprovalPromise;
|
||||
if (planGddApprovalError) throw planGddApprovalError;
|
||||
return {
|
||||
...result,
|
||||
turnReportOutput: reportLines.join('\n'),
|
||||
planGddApproval,
|
||||
};
|
||||
} finally {
|
||||
setActiveChild(null);
|
||||
@@ -1723,6 +1780,196 @@ export async function validateSwarmProjectArtifacts(projectPath, options) {
|
||||
return inspection;
|
||||
}
|
||||
|
||||
// 这四条路径的权威定义都在 Rust 侧 `planning_storage.rs`(`PLAN_SESSION_PATH`、
|
||||
// `PLAN_GDD_INDEX_PATH`、`PLAN_STORAGE_ROOT`、`PLAN_FAST_GDD_PATH`)。跨语言没有共享
|
||||
// 常量的通道,改路径时要连同 `GddApprovalCard.tsx` 一起动。
|
||||
export const planningOutputPaths = [
|
||||
'.agent/planning/session.json',
|
||||
'.agent/planning/index.json',
|
||||
'.agent/planning/pending.json',
|
||||
'game/fast_gdd.md',
|
||||
];
|
||||
|
||||
export async function inspectPlanningOutputs(projectPath) {
|
||||
const outputs = [];
|
||||
for (const relativePath of planningOutputPaths) {
|
||||
const absolutePath = path.join(projectPath, ...relativePath.split('/'));
|
||||
const metadata = await lstat(absolutePath).catch((error) => {
|
||||
if (error?.code === 'ENOENT') return null;
|
||||
throw error;
|
||||
});
|
||||
outputs.push({
|
||||
path: relativePath,
|
||||
exists: Boolean(metadata?.isFile()),
|
||||
bytes: metadata?.isFile() ? metadata.size : 0,
|
||||
});
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
|
||||
async function reportPlanningOutputs(projectPath) {
|
||||
const outputs = await inspectPlanningOutputs(projectPath);
|
||||
console.log('\n立项策划产物:');
|
||||
for (const output of outputs) {
|
||||
console.log(
|
||||
output.exists
|
||||
? ` [有] ${output.path}(${output.bytes} 字节)`
|
||||
: ` [无] ${output.path}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const planGddApprovalTimeoutMs = 60_000;
|
||||
export const planGddStatusOutputPrefix = 'planGddStateJson=';
|
||||
export const planGddDecisionOutputPrefix = 'planGddDecisionJson=';
|
||||
|
||||
function parsePrefixedJsonLine(output, prefix, label) {
|
||||
const line = output
|
||||
.split('\n')
|
||||
.map((value) => (value.endsWith('\r') ? value.slice(0, -1) : value))
|
||||
.find((value) => value.startsWith(prefix));
|
||||
if (!line) throw new Error(`${label}缺少 ${prefix} 输出`);
|
||||
try {
|
||||
return JSON.parse(line.slice(prefix.length));
|
||||
} catch (error) {
|
||||
throw new Error(`解析${label}失败:${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function parsePlanGddStatusOutput(output) {
|
||||
return parsePrefixedJsonLine(
|
||||
output,
|
||||
planGddStatusOutputPrefix,
|
||||
'Fast GDD 审批状态',
|
||||
);
|
||||
}
|
||||
|
||||
export function parsePlanGddDecisionOutput(output) {
|
||||
return parsePrefixedJsonLine(
|
||||
output,
|
||||
planGddDecisionOutputPrefix,
|
||||
'Fast GDD 审批回执',
|
||||
);
|
||||
}
|
||||
|
||||
// 审批卡是这条链路唯一的人类判据,所以自动应答默认只投 approve,且只在投影确实有
|
||||
// 一张待决定审批时出手。revise/reject 需要一段真实的修改意见,让机器编一段等于把
|
||||
// 判据换成噪声——所以那两条分支只在跑的人自己用 AGC_PLAN_GDD_COMMENT 给出意见时
|
||||
// 才走。手工调 --plan-gdd-decide 也能达到同样效果,但那要求 plan 根 run 仍然活着,
|
||||
// 而它恰好是本进程持有的 CLI 子进程。
|
||||
export function planGddAutoApprovalIsPending(state) {
|
||||
return Boolean(state?.pendingApproval);
|
||||
}
|
||||
|
||||
export function resolvePlanGddAutoDecision(env = process.env) {
|
||||
const action = (env.AGC_PLAN_GDD_DECISION ?? 'approve').trim();
|
||||
if (!['approve', 'revise', 'reject'].includes(action)) {
|
||||
throw new Error('AGC_PLAN_GDD_DECISION 只能是 approve / revise / reject');
|
||||
}
|
||||
const comment = (env.AGC_PLAN_GDD_COMMENT ?? '').trim();
|
||||
if (action === 'approve') return { action, comment: null };
|
||||
if (!comment) {
|
||||
throw new Error(
|
||||
`${action} 必须同时设 AGC_PLAN_GDD_COMMENT 提供真实修改意见`,
|
||||
);
|
||||
}
|
||||
return { action, comment };
|
||||
}
|
||||
|
||||
async function settlePlanGddApproval(
|
||||
projectPath,
|
||||
runtimeConfigPath,
|
||||
setActiveChild,
|
||||
) {
|
||||
const readStatus = async () => {
|
||||
const result = await runCapturedCargo(
|
||||
['--config-dir', runtimeConfigPath, '--plan-gdd-status', projectPath],
|
||||
setActiveChild,
|
||||
{
|
||||
timeoutMs: planGddApprovalTimeoutMs,
|
||||
label: 'Fast GDD 审批状态查询',
|
||||
},
|
||||
);
|
||||
if (result.code !== 0 || result.signal) {
|
||||
throw new Error(
|
||||
`读取 Fast GDD 审批状态失败:${result.stderr.trim() || result.stdout.trim()}`,
|
||||
);
|
||||
}
|
||||
return parsePlanGddStatusOutput(result.stdout);
|
||||
};
|
||||
|
||||
const before = await readStatus();
|
||||
if (!planGddAutoApprovalIsPending(before)) {
|
||||
return { decided: false, state: before };
|
||||
}
|
||||
const { action, comment } = resolvePlanGddAutoDecision();
|
||||
const decision = await runCapturedCargo(
|
||||
[
|
||||
'--config-dir',
|
||||
runtimeConfigPath,
|
||||
'--plan-gdd-decide',
|
||||
projectPath,
|
||||
action,
|
||||
...(comment === null ? [] : ['--stdin']),
|
||||
],
|
||||
setActiveChild,
|
||||
{
|
||||
timeoutMs: planGddApprovalTimeoutMs,
|
||||
label: 'Fast GDD 审批决定',
|
||||
stdin: comment,
|
||||
},
|
||||
);
|
||||
if (decision.code !== 0 || decision.signal) {
|
||||
throw new Error(
|
||||
`提交 Fast GDD 审批决定失败:${decision.stderr.trim() || decision.stdout.trim()}`,
|
||||
);
|
||||
}
|
||||
const receipt = parsePlanGddDecisionOutput(decision.stdout);
|
||||
// 回执落盘和唤醒后台任务是两件事:decide 命令把唤醒失败降级成 recoveryPending,
|
||||
// 于是审批已经生效、Run 却仍停在 waiting-for-user-input。实测就是这样——只有
|
||||
// 补一次 --agent-resume 才会重新起 turn。这是仓库自己给这个状态定义的恢复动作。
|
||||
let recovered = false;
|
||||
if (receipt.recoveryPending) {
|
||||
const resume = await runCapturedCargo(
|
||||
['--config-dir', runtimeConfigPath, '--agent-resume', projectPath],
|
||||
setActiveChild,
|
||||
{
|
||||
timeoutMs: planGddApprovalTimeoutMs,
|
||||
label: 'Fast GDD 审批后恢复后台任务',
|
||||
},
|
||||
);
|
||||
if (resume.code !== 0 || resume.signal) {
|
||||
throw new Error(
|
||||
`审批已提交但恢复后台任务失败:${resume.stderr.trim() || resume.stdout.trim()}`,
|
||||
);
|
||||
}
|
||||
recovered = true;
|
||||
}
|
||||
return { decided: true, receipt, recovered, state: await readStatus() };
|
||||
}
|
||||
|
||||
async function reportPlanGddApproval(approval) {
|
||||
const { state } = approval;
|
||||
console.log('\nFast GDD 审批:');
|
||||
if (!approval.decided) {
|
||||
console.log(` [无待决定审批] 当前投影状态=${state.state}`);
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
` [已决定 ${approval.receipt.decisionRef.action}] outcome=${approval.receipt.outcome} v${approval.receipt.decisionRef.version} 投影状态=${state.state}`,
|
||||
);
|
||||
if (approval.recovered) {
|
||||
console.log(
|
||||
' [已恢复] 审批回执的 recoveryPending 由一次 --agent-resume 收口',
|
||||
);
|
||||
}
|
||||
if (state.session) {
|
||||
console.log(
|
||||
` 澄清轮次=${state.session.clarificationRound} 返工深度=${state.session.repairDepth} phase=${state.session.phase}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function hasConfiguredEditorApiKey(configDir) {
|
||||
let configured = false;
|
||||
for (const fileName of [configFileName, localConfigFileName]) {
|
||||
@@ -1875,7 +2122,13 @@ export async function runSwarmTestChat(options) {
|
||||
const setActiveChild = (child) => {
|
||||
activeChild = child;
|
||||
};
|
||||
// GDD 审批要和 swarm CLI 并发跑,两者不能共用 activeChild 这一个槽位:审批子进程
|
||||
// 结束时的 setActiveChild(null) 会把 CLI 从槽里抹掉,Ctrl-C 就杀不到它了。
|
||||
const concurrentChildren = new Set();
|
||||
const setConcurrentChild = (child) => {
|
||||
if (child) concurrentChildren.add(child);
|
||||
else concurrentChildren.clear();
|
||||
};
|
||||
const stopRequested = () => receivedSignal !== null;
|
||||
const handleSignal = (signal) => {
|
||||
const repeatedSignal = receivedSignal !== null;
|
||||
@@ -1953,10 +2206,11 @@ export async function runSwarmTestChat(options) {
|
||||
);
|
||||
}
|
||||
console.log('LLM 配置已就绪。');
|
||||
const requirementNoun = options.plan ? '立项策划需求' : '游戏需求';
|
||||
console.log(
|
||||
options.task
|
||||
? '已提交一条非交互游戏需求,正在等待 Swarm 自主完成。\n'
|
||||
: '输入一条游戏需求并回车;提交后按 Ctrl+D,让 Swarm 自主完成。\n',
|
||||
? `已提交一条非交互${requirementNoun},正在等待 Swarm 自主完成。\n`
|
||||
: `输入一条${requirementNoun}并回车;提交后按 Ctrl+D,让 Swarm 自主完成。\n`,
|
||||
);
|
||||
|
||||
phase = 'chat';
|
||||
@@ -1966,7 +2220,8 @@ export async function runSwarmTestChat(options) {
|
||||
runtimeConfig.path,
|
||||
'--swarm-chat',
|
||||
'--init',
|
||||
'--autonomous-game-build',
|
||||
// 做方案链路只能跑 standard 档,后端对 plan + autonomous 是硬否决。
|
||||
options.plan ? '--plan' : '--autonomous-game-build',
|
||||
project.path,
|
||||
];
|
||||
let chat;
|
||||
@@ -1979,6 +2234,15 @@ export async function runSwarmTestChat(options) {
|
||||
timeoutDeadline === null
|
||||
? null
|
||||
: Math.max(1, timeoutDeadline - Date.now()),
|
||||
options.plan,
|
||||
options.plan
|
||||
? () =>
|
||||
settlePlanGddApproval(
|
||||
project.path,
|
||||
runtimeConfig.path,
|
||||
setConcurrentChild,
|
||||
)
|
||||
: null,
|
||||
)
|
||||
: await runInteractiveCargo(chatArguments, setActiveChild);
|
||||
} catch (error) {
|
||||
@@ -1994,6 +2258,32 @@ export async function runSwarmTestChat(options) {
|
||||
if (options.task) {
|
||||
turnReport = parseSettledSwarmTurnReport(chat.turnReportOutput);
|
||||
}
|
||||
if (options.plan) {
|
||||
// 立项策划不出游戏产物,正式验收在 GDD 审批卡上;这里只报告落盘情况,
|
||||
// 是否收束已经由 CLI 的退出码判过了。
|
||||
// 自动任务档的审批已经在 CLI 运行期间并发做完了;手工档(人自己敲 Ctrl+D
|
||||
// 退出)没有那次触发,退出后补一次,没有待决定审批时它是只读的。
|
||||
phase = 'plan-approval';
|
||||
const approval =
|
||||
chat.planGddApproval ??
|
||||
(await settlePlanGddApproval(
|
||||
project.path,
|
||||
runtimeConfig.path,
|
||||
setConcurrentChild,
|
||||
));
|
||||
if (receivedSignal) break session;
|
||||
phase = 'plan-report';
|
||||
await reportPlanGddApproval(approval);
|
||||
await reportPlanningOutputs(project.path);
|
||||
phase = 'complete';
|
||||
console.log(
|
||||
approval.decided
|
||||
? '\n立项策划链路已收束:Fast GDD 已批准,策划产物见上方清单。'
|
||||
: '\n立项策划链路已收束:Run 正常结束但没有待决定审批,策划产物见上方清单。',
|
||||
);
|
||||
break session;
|
||||
}
|
||||
phase = 'artifact-validation';
|
||||
const requireEditorImages = await hasConfiguredEditorApiKey(
|
||||
runtimeConfig.path,
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
const defaultReleaseTarget = 'x86_64-pc-windows-msvc';
|
||||
const releaseTarget =
|
||||
process.env.AGC_BUILD_TARGET?.trim() || defaultReleaseTarget;
|
||||
@@ -49,16 +50,23 @@ function parseVersion(value, label) {
|
||||
return value;
|
||||
}
|
||||
|
||||
export function nextPatchVersion(localVersion, remoteVersion) {
|
||||
const local = parseVersion(localVersion, '本地版本');
|
||||
const remote =
|
||||
remoteVersion == null ? null : parseVersion(remoteVersion, 'OSS版本');
|
||||
const base = remote && compareVersions(remote, local) > 0 ? remote : local;
|
||||
const [major, minor, patch] = base.split('.').map(Number);
|
||||
if (patch === Number.MAX_SAFE_INTEGER) {
|
||||
throw new Error(`版本号 patch 已达到上限:${base}`);
|
||||
export function bumpVersion(current, target = 'patch') {
|
||||
const [major, minor, patch] =
|
||||
parseVersion(current, '当前版本').split('.').map(Number);
|
||||
if (target === 'major') return `${major + 1}.0.0`;
|
||||
if (target === 'minor') return `${major}.${minor + 1}.0`;
|
||||
if (target === 'patch' || target == null) {
|
||||
if (patch === Number.MAX_SAFE_INTEGER) {
|
||||
throw new Error(`版本号 patch 已达到上限:${current}`);
|
||||
}
|
||||
return `${major}.${minor}.${patch + 1}`;
|
||||
}
|
||||
return `${major}.${minor}.${patch + 1}`;
|
||||
if (typeof target === 'string' && /^\d+\.\d+\.\d+$/u.test(target)) {
|
||||
return parseVersion(target, '指定版本');
|
||||
}
|
||||
throw new Error(
|
||||
`无法识别的版本目标:${String(target)}(支持 patch / minor / major / 明确的三段版本号)`,
|
||||
);
|
||||
}
|
||||
|
||||
async function readRemoteVersion() {
|
||||
@@ -88,14 +96,52 @@ function replaceVersionLine(source, version, pattern, label) {
|
||||
return source.replace(pattern, `$1${version}$3`);
|
||||
}
|
||||
|
||||
export async function prepareReleaseVersion() {
|
||||
const localVersion = parseVersion(readPackageJson().version, '本地版本');
|
||||
const remoteVersion = await readRemoteVersion();
|
||||
const requestedVersion = process.env.AGC_RELEASE_VERSION?.trim();
|
||||
const nextVersion = requestedVersion
|
||||
? parseVersion(requestedVersion, '指定版本')
|
||||
: nextPatchVersion(localVersion, remoteVersion);
|
||||
const versionFileSources = [
|
||||
{
|
||||
file: packageJsonPath,
|
||||
pattern: /("version"\s*:\s*")([^"]+)(")/u,
|
||||
label: 'package.json',
|
||||
},
|
||||
{
|
||||
file: rootPackageLockPath,
|
||||
pattern: /("apps\/ai-game-creator-shell"\s*:\s*\{\s*\n\s*"name"\s*:\s*"@genarrative\/ai-game-creator-shell"\s*,\s*\n\s*"version"\s*:\s*")([^"]+)(")/u,
|
||||
label: 'package-lock.json',
|
||||
},
|
||||
{
|
||||
file: tauriConfigPath,
|
||||
pattern: /("version"\s*:\s*")([^"]+)(")/u,
|
||||
label: 'tauri.conf.json',
|
||||
},
|
||||
{
|
||||
file: cargoManifestPath,
|
||||
pattern: /(^\[package\][\s\S]*?^version\s*=\s*")([^"]+)(")/mu,
|
||||
label: 'Cargo.toml',
|
||||
},
|
||||
{
|
||||
file: cargoLockPath,
|
||||
pattern: /(^name\s*=\s*"genarrative-ai-game-creator-shell"\s*\nversion\s*=\s*")([^"]+)(")/mu,
|
||||
label: 'Cargo.lock',
|
||||
},
|
||||
];
|
||||
|
||||
export function readLocalVersion() {
|
||||
return parseVersion(readPackageJson().version, '本地版本');
|
||||
}
|
||||
|
||||
export function validateVersionConsistency(expectedVersion) {
|
||||
for (const source of versionFileSources) {
|
||||
const match = fs.readFileSync(source.file, 'utf8').match(source.pattern);
|
||||
const actual = match ? match[2].trim() : '<未找到>';
|
||||
if (actual !== expectedVersion) {
|
||||
throw new Error(
|
||||
`AGC 版本号不一致:${source.label} 应为 ${expectedVersion},实际 ${actual}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function writeVersionFiles(version) {
|
||||
const nextVersion = parseVersion(version, '目标版本');
|
||||
const packageSource = fs.readFileSync(packageJsonPath, 'utf8');
|
||||
fs.writeFileSync(
|
||||
packageJsonPath,
|
||||
@@ -151,14 +197,47 @@ export async function prepareReleaseVersion() {
|
||||
),
|
||||
);
|
||||
|
||||
console.log(
|
||||
requestedVersion
|
||||
? `[ai-game-creator-shell] 使用指定版本 ${nextVersion}(本地 ${localVersion} / OSS ${remoteVersion ?? '不存在'})`
|
||||
: `[ai-game-creator-shell] 版本 ${localVersion} / OSS ${remoteVersion ?? '不存在'} -> ${nextVersion}`,
|
||||
);
|
||||
return nextVersion;
|
||||
}
|
||||
|
||||
export function assertVersionCommitted() {
|
||||
const repoPaths = versionFileSources.map((source) =>
|
||||
path.relative(repoRoot, source.file).replaceAll('\\', '/'),
|
||||
);
|
||||
const changed =
|
||||
spawnSync(
|
||||
'git',
|
||||
['diff', '--quiet', 'HEAD', '--', ...repoPaths],
|
||||
{ cwd: repoRoot },
|
||||
).status === 1;
|
||||
if (changed) {
|
||||
throw new Error(
|
||||
'版本文件相对 HEAD 存在未提交改动,请先提交后再发布:运行 npm --prefix apps/ai-game-creator-shell run bump-version -- --commit',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareReleaseVersion() {
|
||||
const localVersion = readLocalVersion();
|
||||
validateVersionConsistency(localVersion);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 使用仓库版本 ${localVersion}(不再自动递增或自由指定版本)`,
|
||||
);
|
||||
return localVersion;
|
||||
}
|
||||
|
||||
export async function assertVersionNotBelowOss(version) {
|
||||
const remoteVersion = await readRemoteVersion();
|
||||
if (remoteVersion && compareVersions(version, remoteVersion) < 0) {
|
||||
throw new Error(
|
||||
`仓库版本 ${version} 低于线上 OSS 版本 ${remoteVersion}。请先运行 npm --prefix apps/ai-game-creator-shell run bump-version 提升版本后再发布。`,
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 线上 OSS 版本 ${remoteVersion ?? '不存在'},发布版本 ${version}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function runTauriBuild(args = []) {
|
||||
const noBundle = args.includes('--no-bundle');
|
||||
const hasTarget = args.includes('--target');
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
bumpVersion,
|
||||
compareVersions,
|
||||
createUpdateManifest,
|
||||
nextPatchVersion,
|
||||
selectReleaseArtifact,
|
||||
} from './build-release.mjs';
|
||||
|
||||
test('selects an explicit release artifact when configured', () => {
|
||||
const artifactPath = new URL('../package.json', import.meta.url).pathname;
|
||||
const artifactPath = fileURLToPath(
|
||||
new URL('../package.json', import.meta.url),
|
||||
);
|
||||
const previous = process.env.AGC_UPDATE_ARTIFACT;
|
||||
process.env.AGC_UPDATE_ARTIFACT = artifactPath;
|
||||
try {
|
||||
@@ -30,7 +33,7 @@ test('does not select unsupported files', () => {
|
||||
|
||||
test('manifest contains version, download URL and integrity fields', () => {
|
||||
const manifest = createUpdateManifest(
|
||||
new URL('../package.json', import.meta.url).pathname,
|
||||
fileURLToPath(new URL('../package.json', import.meta.url)),
|
||||
);
|
||||
assert.match(manifest.version, /^\d+\.\d+\.\d+$/u);
|
||||
assert.match(
|
||||
@@ -46,7 +49,7 @@ test('manifest preserves multiline release notes', () => {
|
||||
process.env.AGC_UPDATE_RELEASE_NOTES = '第一行\n第二行\r\n第三行';
|
||||
try {
|
||||
const manifest = createUpdateManifest(
|
||||
new URL('../package.json', import.meta.url).pathname,
|
||||
fileURLToPath(new URL('../package.json', import.meta.url)),
|
||||
);
|
||||
assert.equal(manifest.releaseNotes, '第一行\n第二行\r\n第三行');
|
||||
} finally {
|
||||
@@ -55,11 +58,14 @@ test('manifest preserves multiline release notes', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('next release version follows the higher local or OSS version', () => {
|
||||
test('bump version follows the requested target', () => {
|
||||
assert.equal(compareVersions('0.1.15', '0.1.12'), 1);
|
||||
assert.equal(nextPatchVersion('0.1.12', '0.1.15'), '0.1.16');
|
||||
assert.equal(nextPatchVersion('0.1.18', '0.1.15'), '0.1.19');
|
||||
assert.equal(nextPatchVersion('0.1.12', null), '0.1.13');
|
||||
assert.equal(compareVersions('0.1.12', '0.1.12'), 0);
|
||||
assert.equal(bumpVersion('0.1.19', 'patch'), '0.1.20');
|
||||
assert.equal(bumpVersion('0.1.19'), '0.1.20');
|
||||
assert.equal(bumpVersion('0.1.19', 'minor'), '0.2.0');
|
||||
assert.equal(bumpVersion('0.1.19', 'major'), '1.0.0');
|
||||
assert.equal(bumpVersion('0.1.12', '0.1.25'), '0.1.25');
|
||||
});
|
||||
|
||||
test('release upload forces overwrite for versioned artifact and latest pointer', () => {
|
||||
@@ -72,3 +78,12 @@ test('release upload forces overwrite for versioned artifact and latest pointer'
|
||||
2,
|
||||
);
|
||||
});
|
||||
|
||||
test('release upload verifies the version is committed and not below OSS', () => {
|
||||
const source = readFileSync(
|
||||
new URL('./release-upload.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(source, /assertVersionCommitted\(\)/u);
|
||||
assert.match(source, /assertVersionNotBelowOss\(/u);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
|
||||
const {
|
||||
bumpVersion,
|
||||
readLocalVersion,
|
||||
writeVersionFiles,
|
||||
} = await import('./build-release.mjs');
|
||||
|
||||
const versionFiles = [
|
||||
'apps/ai-game-creator-shell/package.json',
|
||||
'package-lock.json',
|
||||
'apps/ai-game-creator-shell/src-tauri/tauri.conf.json',
|
||||
'apps/ai-game-creator-shell/src-tauri/Cargo.toml',
|
||||
'apps/ai-game-creator-shell/src-tauri/Cargo.lock',
|
||||
];
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = argv.slice(2);
|
||||
const explicitIndex = args.indexOf('--version');
|
||||
const explicit = explicitIndex >= 0 ? args[explicitIndex + 1] : null;
|
||||
const target =
|
||||
explicit ??
|
||||
args.find((arg) => arg === 'patch' || arg === 'minor' || arg === 'major') ??
|
||||
'patch';
|
||||
return { target, commit: args.includes('--commit') };
|
||||
}
|
||||
|
||||
function runGit(args) {
|
||||
const result = spawnSync('git', args, { cwd: repoRoot, stdio: 'inherit' });
|
||||
if (result.error) throw result.error;
|
||||
return result.status ?? 1;
|
||||
}
|
||||
|
||||
function hasUncommittedVersionChanges() {
|
||||
return (
|
||||
spawnSync('git', ['diff', '--quiet', '--', ...versionFiles], {
|
||||
cwd: repoRoot,
|
||||
}).status === 1
|
||||
);
|
||||
}
|
||||
|
||||
function otherStagedFiles() {
|
||||
const result = spawnSync(
|
||||
'git',
|
||||
['diff', '--cached', '--name-only'],
|
||||
{ cwd: repoRoot, encoding: 'utf8' },
|
||||
);
|
||||
if (result.status !== 0) {
|
||||
throw new Error('无法读取已暂存文件列表');
|
||||
}
|
||||
const versionSet = new Set(versionFiles);
|
||||
return result.stdout
|
||||
.split('\n')
|
||||
.map((file) => file.trim())
|
||||
.filter(Boolean)
|
||||
.filter((file) => !versionSet.has(file));
|
||||
}
|
||||
|
||||
const { target, commit } = parseArgs(process.argv);
|
||||
|
||||
// 提交前先确认没有其他已暂存改动,避免把无关改动一并提交;若存在则在改动任何文件前中止。
|
||||
if (commit) {
|
||||
const others = otherStagedFiles();
|
||||
if (others.length > 0) {
|
||||
console.error(
|
||||
`[bump-version] 检测到其他已暂存改动,为避免误提交,请先单独处理后再运行 --commit:\n ${others.join('\n ')}`,
|
||||
);
|
||||
console.error(
|
||||
'提示:用 git restore --staged <file> 取消暂存,或先提交这些改动。',
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
const current = readLocalVersion();
|
||||
|
||||
// 若版本文件已带着一次未提交的提升(例如先默认跑过一次),再 --commit 时不再重复递增,直接提交现有改动。
|
||||
const next =
|
||||
commit && hasUncommittedVersionChanges()
|
||||
? current
|
||||
: bumpVersion(current, target);
|
||||
|
||||
writeVersionFiles(next);
|
||||
|
||||
if (!commit) {
|
||||
console.log(
|
||||
`[bump-version] 版本 ${current} -> ${next}(已写入版本文件,未创建提交;如需提交加 --commit)`,
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const addStatus = runGit(['add', ...versionFiles]);
|
||||
if (addStatus !== 0) process.exit(addStatus);
|
||||
|
||||
const hasDiff =
|
||||
spawnSync('git', ['diff', '--cached', '--quiet'], {
|
||||
cwd: repoRoot,
|
||||
}).status === 1;
|
||||
|
||||
if (!hasDiff) {
|
||||
console.log(`[bump-version] 版本未变化(已是 ${current}),未创建提交`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const commitStatus = runGit([
|
||||
'commit',
|
||||
'-m',
|
||||
`提升 AGC 版本至 ${next}`,
|
||||
'-m',
|
||||
`- AGC 客户端版本提升至 ${next}`,
|
||||
'-m',
|
||||
'- 同步更新 package.json、根 package-lock.json、tauri.conf.json、Cargo.toml、Cargo.lock 中的 AGC 包条目',
|
||||
]);
|
||||
if (commitStatus !== 0) process.exit(commitStatus);
|
||||
|
||||
console.log(`[bump-version] 已提交版本 ${next}(本地提交,未推送)`);
|
||||
@@ -107,16 +107,12 @@ const rustSharedContractSource = fs.readFileSync(
|
||||
'utf8',
|
||||
);
|
||||
const allowedUncalledTauriCommands = [
|
||||
'append_direct_project_conversation_message',
|
||||
'chat_with_game_creator_agent',
|
||||
'check_ui_editor_font_glyph_coverage',
|
||||
'create_ui_design_resource',
|
||||
'open_game_creator_launcher_window',
|
||||
'open_game_creator_workspace_window',
|
||||
'read_direct_project_conversation',
|
||||
'stop_local_game_preview_if_matches',
|
||||
'start_game_creator_external_mcp',
|
||||
'stop_game_creator_external_mcp',
|
||||
];
|
||||
const sourceExtensions = new Set([
|
||||
'.json',
|
||||
@@ -1285,9 +1281,6 @@ if (tauriConfig.identifier !== 'world.genarrative.ai-game-creator') {
|
||||
throw new Error('AI game creator shell identifier drifted');
|
||||
}
|
||||
|
||||
const expectedBundledDesignAgentResources = {
|
||||
'design-agent': 'design-agent',
|
||||
};
|
||||
const expectedBundledCodexResources = {
|
||||
'resources/codex/win-x64/bin/codex.exe': 'codex/win-x64/bin/codex.exe',
|
||||
'resources/codex/win-x64/bin/codex-code-mode-host.exe':
|
||||
@@ -1303,33 +1296,16 @@ const expectedBundledCodexResources = {
|
||||
'resources/codex/win-x64/NOTICE.md': 'codex/win-x64/NOTICE.md',
|
||||
'resources/codex/win-x64/manifest.json': 'codex/win-x64/manifest.json',
|
||||
};
|
||||
assert.deepEqual(
|
||||
tauriConfig.bundle?.resources,
|
||||
expectedBundledDesignAgentResources,
|
||||
'AI game creator shell base Tauri config must bundle the design-agent resource pack',
|
||||
);
|
||||
for (const key of Object.keys(tauriConfig.bundle?.resources ?? {})) {
|
||||
if (String(key).includes('codex')) {
|
||||
throw new Error(
|
||||
'AI game creator shell base Tauri config must not require Windows-only Codex resources',
|
||||
);
|
||||
}
|
||||
if (tauriConfig.bundle?.resources !== undefined) {
|
||||
throw new Error(
|
||||
'AI game creator shell base Tauri config must not require Windows-only Codex resources',
|
||||
);
|
||||
}
|
||||
assert.deepEqual(
|
||||
windowsTauriConfig.bundle?.resources,
|
||||
expectedBundledCodexResources,
|
||||
'AI game creator shell Windows Tauri config must bundle the complete pinned Codex resource set',
|
||||
);
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
windowsTauriConfig.bundle?.resources ?? {},
|
||||
'design-agent',
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'design-agent resource pack must not be mixed into the Windows Codex sidecar bundle',
|
||||
);
|
||||
}
|
||||
if (windowsTauriConfig.bundle?.useLocalToolsDir !== true) {
|
||||
throw new Error(
|
||||
'AI game creator shell Windows Tauri config must cache bundling tools in the project target directory',
|
||||
@@ -1725,16 +1701,10 @@ if (
|
||||
runtimeConfigSetupStart === -1 ||
|
||||
runtimeConfigSetupEnd === -1 ||
|
||||
!runtimeConfigSetupSource.includes('sanitize_diagnostic_message(') ||
|
||||
!runtimeConfigSetupSource.includes('setup_log.fail(') ||
|
||||
!runtimeConfigSetupSource.includes('append_bounded_diagnostic_line(') ||
|
||||
!runtimeConfigSetupSource.includes(
|
||||
'startup.appdata.configure.failed details={details}',
|
||||
) ||
|
||||
!tauriHandlerSource.includes('impl StartupLogSlot {') ||
|
||||
!tauriHandlerSource.includes('append_bounded_diagnostic_line(&path, line)') ||
|
||||
!tauriHandlerSource.includes(
|
||||
'self.append(line);\n show_startup_error_dialog(self.path().as_deref());',
|
||||
) ||
|
||||
!tauriHandlerSource.includes('early_startup_log_path(')
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator setup must configure the runtime AppData directory and log sanitized setup failures',
|
||||
|
||||
@@ -9,8 +9,13 @@ 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 { generateUpdateManifest, prepareReleaseVersion, runTauriBuild } =
|
||||
await import('./build-release.mjs');
|
||||
const {
|
||||
assertVersionCommitted,
|
||||
assertVersionNotBelowOss,
|
||||
generateUpdateManifest,
|
||||
prepareReleaseVersion,
|
||||
runTauriBuild,
|
||||
} = await import('./build-release.mjs');
|
||||
|
||||
function runOssutil(args) {
|
||||
const binary = process.env.OSSUTIL_BIN?.trim() || 'ossutil';
|
||||
@@ -36,7 +41,9 @@ function runOssutil(args) {
|
||||
if (result.status !== 0) process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
await prepareReleaseVersion();
|
||||
const releaseVersion = await prepareReleaseVersion();
|
||||
assertVersionCommitted();
|
||||
await assertVersionNotBelowOss(releaseVersion);
|
||||
runTauriBuild([]);
|
||||
const { artifact, manifestPath, manifest } = generateUpdateManifest();
|
||||
const artifactKey = `agc/${manifest.version}/${path.basename(artifact)}`;
|
||||
|
||||
@@ -722,7 +722,7 @@ function runAgent() {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
child.on('error', reject);
|
||||
child.on('close', (code, signal) => {
|
||||
child.on('close', (code) => {
|
||||
const output = `${stdout}${stderr}`;
|
||||
if (previewReadError) {
|
||||
reject(previewReadError);
|
||||
@@ -740,24 +740,13 @@ function runAgent() {
|
||||
previewDom,
|
||||
});
|
||||
} else {
|
||||
reject(
|
||||
new Error(
|
||||
`agent run failed: exitCode=${code}, signal=${signal ?? 'none'}\n` +
|
||||
`stderr tail (last 8000 characters):\n${stderr.slice(-8000)}\n` +
|
||||
`stdout tail (last 4000 characters):\n${stdout.slice(-4000)}`,
|
||||
),
|
||||
);
|
||||
reject(new Error(output || `agent run exited with ${code}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function seedLocalAsset() {
|
||||
await fs.mkdir(path.join(projectRoot, 'game'), { recursive: true });
|
||||
await fs.writeFile(
|
||||
path.join(projectRoot, 'game/index.html'),
|
||||
'<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><body>还没有生成游戏</body></html>',
|
||||
);
|
||||
await fs.mkdir(path.join(projectRoot, 'assets/uploads'), { recursive: true });
|
||||
await fs.mkdir(path.join(projectRoot, '.agent'), { recursive: true });
|
||||
await seedConversationContext();
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
normalizeWindowsPath,
|
||||
parseWindowsProcessSnapshot,
|
||||
stopWindowsProcessTree,
|
||||
stopWindowsWorktreeProcesses,
|
||||
} from '../../../scripts/dev-windows-process.mjs';
|
||||
import {
|
||||
agcVitePortEnvKey,
|
||||
readAgcDevEndpoint,
|
||||
@@ -21,10 +15,6 @@ import {
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = resolve(appRoot, '../..');
|
||||
const devStackStatePath = resolve(repoRoot, '.app/dev-stack.json');
|
||||
const apiServerExePath = resolve(
|
||||
repoRoot,
|
||||
'server-rs/target/debug/api-server.exe',
|
||||
);
|
||||
const defaultApiTarget =
|
||||
process.env.RUST_SERVER_TARGET || 'http://127.0.0.1:8082';
|
||||
const backendDatabase = 'genarrative-game-creator-dev';
|
||||
@@ -137,217 +127,19 @@ function readBackendTargets({ requireAgcBackend = false } = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
function readBackendServiceFailure(
|
||||
state,
|
||||
{
|
||||
expectedDatabase = backendDatabase,
|
||||
expectedSpacetimeDataDir = backendSpacetimeDataDir,
|
||||
} = {},
|
||||
) {
|
||||
const targets = resolveBackendTargetsFromState(state, {
|
||||
requireAgcBackend: true,
|
||||
expectedDatabase,
|
||||
expectedSpacetimeDataDir,
|
||||
});
|
||||
if (!targets.hasMatchingBackend) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const serviceName of ['spacetime', 'api-server', 'bgfilter-worker']) {
|
||||
const service = state?.services?.[serviceName];
|
||||
if (service?.status !== 'failed') {
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
serviceName,
|
||||
failure: service.signal
|
||||
? `signal=${service.signal}`
|
||||
: `code=${service.exitCode ?? 1}`,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function urlPort(url) {
|
||||
try {
|
||||
const port = Number(new URL(url).port);
|
||||
return Number.isInteger(port) && port > 0 ? port : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// 读取端口当前真正的监听进程身份。返回 null 表示探测本身不可用(例如缺少
|
||||
// Get-NetTCPConnection),此时调用方必须退化为旧行为,不能让本地启动直接失败。
|
||||
function readWindowsPortOwnerIdentities(
|
||||
ports,
|
||||
{ spawnImpl = spawnSync, env = process.env } = {},
|
||||
) {
|
||||
const uniquePorts = [...new Set(ports.filter((port) => port > 0))];
|
||||
if (uniquePorts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const command = [
|
||||
'$ErrorActionPreference = "SilentlyContinue"',
|
||||
'$ports = ($env:GENARRATIVE_QUERY_PORTS -split ",") | Where-Object { $_ }',
|
||||
'$result = @()',
|
||||
'foreach ($port in $ports) {',
|
||||
' $connection = Get-NetTCPConnection -State Listen -LocalPort ([int]$port) -ErrorAction SilentlyContinue | Select-Object -First 1',
|
||||
' if (-not $connection) { continue }',
|
||||
' $owner = Get-CimInstance Win32_Process -Filter ("ProcessId=" + $connection.OwningProcess) -ErrorAction SilentlyContinue',
|
||||
' $result += [pscustomobject]@{ port = [int]$port; processId = [int]$connection.OwningProcess; name = $owner.Name; executablePath = $owner.ExecutablePath; commandLine = $owner.CommandLine }',
|
||||
'}',
|
||||
'ConvertTo-Json -InputObject @($result) -Compress',
|
||||
].join('\n');
|
||||
|
||||
const result = spawnImpl(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
env: { ...env, GENARRATIVE_QUERY_PORTS: uniquePorts.join(',') },
|
||||
maxBuffer: 8 * 1024 * 1024,
|
||||
},
|
||||
);
|
||||
if (result?.error || result?.status !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const owners = new Map();
|
||||
for (const entry of parseWindowsProcessSnapshot(result.stdout)) {
|
||||
const port = Number(entry?.port);
|
||||
if (Number.isInteger(port) && port > 0) {
|
||||
owners.set(port, entry);
|
||||
}
|
||||
}
|
||||
return owners;
|
||||
}
|
||||
|
||||
function isWorktreeApiServerOwner(
|
||||
owner,
|
||||
{ expectedExePath = apiServerExePath } = {},
|
||||
) {
|
||||
if (!owner) {
|
||||
return false;
|
||||
}
|
||||
const expected = normalizeWindowsPath(expectedExePath);
|
||||
const actual = normalizeWindowsPath(owner.executablePath);
|
||||
return Boolean(expected) && actual === expected;
|
||||
}
|
||||
|
||||
function isWorktreeSpacetimeOwner(
|
||||
owner,
|
||||
{ expectedDataDir = backendSpacetimeDataDir } = {},
|
||||
) {
|
||||
if (!owner) {
|
||||
return false;
|
||||
}
|
||||
const expected = normalizeWindowsPath(expectedDataDir);
|
||||
if (!expected) {
|
||||
return false;
|
||||
}
|
||||
const name = String(owner.name ?? '').toLowerCase();
|
||||
if (!name.startsWith('spacetime')) {
|
||||
return false;
|
||||
}
|
||||
return normalizeWindowsPath(owner.commandLine).includes(expected);
|
||||
}
|
||||
|
||||
// 端口健康不代表后端属于当前工作树:上个工作树 Ctrl+C 残留的 api-server 仍会
|
||||
// 应答 /healthz。复用前必须证明端口上的进程就是本工作树的可执行文件与数据目录。
|
||||
function verifyAgcBackendOwnership({
|
||||
apiUrl,
|
||||
spacetimeUrl,
|
||||
bgfilterWorkerUrl,
|
||||
platform = process.platform,
|
||||
expectedExePath = apiServerExePath,
|
||||
expectedDataDir = backendSpacetimeDataDir,
|
||||
readPortOwners = readWindowsPortOwnerIdentities,
|
||||
} = {}) {
|
||||
if (platform !== 'win32') {
|
||||
return { ok: true, reason: 'platform-unsupported', owners: new Map() };
|
||||
}
|
||||
|
||||
const ports = [
|
||||
urlPort(apiUrl),
|
||||
urlPort(bgfilterWorkerUrl),
|
||||
urlPort(spacetimeUrl),
|
||||
];
|
||||
const owners = readPortOwners(ports);
|
||||
if (!owners) {
|
||||
return { ok: true, reason: 'owner-probe-unavailable', owners: new Map() };
|
||||
}
|
||||
|
||||
const apiOwner = owners.get(urlPort(apiUrl));
|
||||
if (!isWorktreeApiServerOwner(apiOwner, { expectedExePath })) {
|
||||
return { ok: false, reason: 'api-server-owner-mismatch', owners, apiOwner };
|
||||
}
|
||||
|
||||
const workerOwner = owners.get(urlPort(bgfilterWorkerUrl));
|
||||
if (!isWorktreeApiServerOwner(workerOwner, { expectedExePath })) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'bgfilter-worker-owner-mismatch',
|
||||
owners,
|
||||
workerOwner,
|
||||
};
|
||||
}
|
||||
|
||||
const spacetimeOwner = owners.get(urlPort(spacetimeUrl));
|
||||
if (!isWorktreeSpacetimeOwner(spacetimeOwner, { expectedDataDir })) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'spacetime-owner-mismatch',
|
||||
owners,
|
||||
spacetimeOwner,
|
||||
};
|
||||
}
|
||||
|
||||
return { ok: true, reason: 'owned', owners };
|
||||
}
|
||||
|
||||
function formatOwnerLabel(owner) {
|
||||
if (!owner) {
|
||||
return '未知进程';
|
||||
}
|
||||
const pid = Number(owner.processId);
|
||||
const label = owner.executablePath || owner.commandLine || owner.name || '';
|
||||
return `${Number.isInteger(pid) ? `pid=${pid} ` : ''}${String(label).trim()}`.trim();
|
||||
}
|
||||
|
||||
async function isBackendReady({
|
||||
state = readJson(devStackStatePath),
|
||||
isReady = isHttpReady,
|
||||
verifyOwnership = verifyAgcBackendOwnership,
|
||||
onOwnershipRejected = null,
|
||||
} = {}) {
|
||||
const { apiUrl, spacetimeUrl, bgfilterWorkerUrl, hasMatchingBackend } =
|
||||
resolveBackendTargetsFromState(state, {
|
||||
requireAgcBackend: true,
|
||||
});
|
||||
if (!hasMatchingBackend || !apiUrl || !spacetimeUrl || !bgfilterWorkerUrl) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ownership = await verifyOwnership({
|
||||
apiUrl,
|
||||
spacetimeUrl,
|
||||
bgfilterWorkerUrl,
|
||||
});
|
||||
if (!ownership?.ok) {
|
||||
onOwnershipRejected?.(ownership);
|
||||
return false;
|
||||
}
|
||||
if (ownership.reason === 'owner-probe-unavailable') {
|
||||
console.warn(
|
||||
'[ai-game-creator-shell] 无法读取端口监听进程归属,本次按旧行为复用配套后端。',
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
hasMatchingBackend &&
|
||||
Boolean(apiUrl) &&
|
||||
Boolean(spacetimeUrl) &&
|
||||
Boolean(bgfilterWorkerUrl) &&
|
||||
(await isReady(`${apiUrl}/healthz`)) &&
|
||||
(await isReady(`${spacetimeUrl}/v1/ping`)) &&
|
||||
(await isReady(`${bgfilterWorkerUrl}/readyz`))
|
||||
@@ -660,18 +452,14 @@ async function terminateChildTree(
|
||||
return { stopped: true, forced: false };
|
||||
}
|
||||
const result = await taskkillImpl(child.pid);
|
||||
const taskkillStopped =
|
||||
!result?.timedOut &&
|
||||
!result?.error &&
|
||||
[0, 128].includes(result?.code ?? 0);
|
||||
if (taskkillStopped) {
|
||||
return { stopped: true, forced: true, result };
|
||||
}
|
||||
|
||||
// 包装层(cmd.exe / npm.cmd)先被 Ctrl+C 杀掉时 taskkill 拿不到活着的 PID,
|
||||
// 这里继续按记录下来的根 PID 遍历,尽量收掉更深的后端进程。
|
||||
const treeStopped = stopWindowsProcessTree(child.pid);
|
||||
return { stopped: treeStopped.length > 0, forced: true, result };
|
||||
return {
|
||||
stopped:
|
||||
!result?.timedOut &&
|
||||
!result?.error &&
|
||||
[0, 128].includes(result?.code ?? 0),
|
||||
forced: true,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
const processGroupId = childLifecycles.get(child)?.processGroupId;
|
||||
@@ -717,43 +505,11 @@ async function terminateChildTree(
|
||||
return { stopped, forced: true };
|
||||
}
|
||||
|
||||
async function waitForBackendReady(
|
||||
backendChild,
|
||||
timeoutMs = 600_000,
|
||||
{
|
||||
checkBackendReady = (onOwnershipRejected) =>
|
||||
isBackendReady({ onOwnershipRejected }),
|
||||
readState = () => readJson(devStackStatePath),
|
||||
resolveTargets = readBackendTargets,
|
||||
} = {},
|
||||
) {
|
||||
const initialStateUpdatedAt = readState()?.updatedAt ?? '';
|
||||
async function waitForBackendReady(backendChild, timeoutMs = 600_000) {
|
||||
const startedAt = Date.now();
|
||||
let lastOwnershipReason = '';
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
if (
|
||||
await checkBackendReady((ownership) => {
|
||||
if (ownership.reason === lastOwnershipReason) {
|
||||
return;
|
||||
}
|
||||
lastOwnershipReason = ownership.reason;
|
||||
// 本次自己拉起的后端如果归属校验一直不通过,必须把原因打出来,
|
||||
// 否则只会表现为等待 600 秒后超时。
|
||||
console.warn(
|
||||
`[ai-game-creator-shell] 等待配套后端就绪时归属校验未通过(${ownership.reason}: ${formatOwnerLabel(ownership.apiOwner ?? ownership.spacetimeOwner ?? ownership.workerOwner)})。`,
|
||||
);
|
||||
})
|
||||
) {
|
||||
return resolveTargets();
|
||||
}
|
||||
const state = readState();
|
||||
if ((state?.updatedAt ?? '') !== initialStateUpdatedAt) {
|
||||
const serviceFailure = readBackendServiceFailure(state);
|
||||
if (serviceFailure) {
|
||||
throw new Error(
|
||||
`配套后端启动失败: ${serviceFailure.serviceName} ${serviceFailure.failure}`,
|
||||
);
|
||||
}
|
||||
if (await isBackendReady()) {
|
||||
return readBackendTargets();
|
||||
}
|
||||
const failure = readChildFailure(backendChild);
|
||||
if (failure) {
|
||||
@@ -769,14 +525,7 @@ async function waitForBackendReady(
|
||||
|
||||
async function ensureBackend({
|
||||
onBackendChild = () => {},
|
||||
checkBackendReady = () =>
|
||||
isBackendReady({
|
||||
onOwnershipRejected(ownership) {
|
||||
console.warn(
|
||||
`[ai-game-creator-shell] 端口上的配套后端不属于当前工作树(${ownership.reason}: ${formatOwnerLabel(ownership.apiOwner ?? ownership.spacetimeOwner ?? ownership.workerOwner)}),改为启动本工作树自己的后端。`,
|
||||
);
|
||||
},
|
||||
}),
|
||||
checkBackendReady = isBackendReady,
|
||||
resolveTargets = readBackendTargets,
|
||||
spawnBackend = () =>
|
||||
spawnChild(
|
||||
@@ -856,33 +605,15 @@ async function startVite(apiTarget, endpoint = readAgcDevEndpoint()) {
|
||||
|
||||
async function main() {
|
||||
let backendChild = null;
|
||||
let startedBackend = false;
|
||||
let viteChild = null;
|
||||
let shutdownSignal = '';
|
||||
const signalHandlers = new Map();
|
||||
|
||||
// 只有本次会话真正拉起过配套后端时才做兜底清扫:复用别人后端时不能连带
|
||||
// 杀掉对方的进程。dev.mjs 的清理依赖它的 shell 包装层仍然活着,而 Ctrl+C
|
||||
// 往往先杀掉包装层,所以这里必须按本工作树 api-server.exe 的身份再收一次。
|
||||
const sweepStartedBackend = () => {
|
||||
if (!startedBackend || process.platform !== 'win32') {
|
||||
return;
|
||||
}
|
||||
const stopped = stopWindowsWorktreeProcesses({ apiServerExePath });
|
||||
if (stopped.length > 0) {
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 已清理残留后端进程: ${stopped.join(', ')}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
for (const signal of ['SIGINT', 'SIGTERM']) {
|
||||
const handler = () => {
|
||||
shutdownSignal = signal;
|
||||
stopChild(viteChild, signal);
|
||||
stopChild(backendChild, signal);
|
||||
// 立刻清扫,避免外层 taskkill /F 抢在 finally 之前把本进程杀掉。
|
||||
sweepStartedBackend();
|
||||
};
|
||||
signalHandlers.set(signal, handler);
|
||||
process.on(signal, handler);
|
||||
@@ -901,7 +632,6 @@ async function main() {
|
||||
},
|
||||
});
|
||||
backendChild = backend.backendChild;
|
||||
startedBackend = Boolean(backendChild);
|
||||
if (shutdownSignal) {
|
||||
throw new Error(`启动期收到 ${shutdownSignal},已停止配套后端`);
|
||||
}
|
||||
@@ -935,7 +665,6 @@ async function main() {
|
||||
terminateChildTree(viteChild),
|
||||
terminateChildTree(backendChild),
|
||||
]);
|
||||
sweepStartedBackend();
|
||||
for (const [signal, handler] of signalHandlers) {
|
||||
process.off(signal, handler);
|
||||
}
|
||||
@@ -952,25 +681,19 @@ function isDirectModuleExecution() {
|
||||
export {
|
||||
ensureBackend,
|
||||
formatChildFailure,
|
||||
formatOwnerLabel,
|
||||
isAiGameCreatorServer,
|
||||
isBackendReady,
|
||||
isDirectModuleExecution,
|
||||
isProcessGroupAlive,
|
||||
isWorktreeApiServerOwner,
|
||||
isWorktreeSpacetimeOwner,
|
||||
preflightExistingVite,
|
||||
readBackendServiceFailure,
|
||||
readChildFailure,
|
||||
readExistingViteServer,
|
||||
readLinuxProcessGroupAlive,
|
||||
readWindowsPortOwnerIdentities,
|
||||
resolveBackendTargetsFromState,
|
||||
runWindowsTaskkill,
|
||||
spawnChild,
|
||||
stopChild,
|
||||
terminateChildTree,
|
||||
verifyAgcBackendOwnership,
|
||||
waitForBackendReady,
|
||||
waitForChildTermination,
|
||||
};
|
||||
|
||||
+1
-1
@@ -1703,7 +1703,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.12"
|
||||
version = "0.1.19"
|
||||
dependencies = [
|
||||
"agent-runtime-core",
|
||||
"axum",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.12"
|
||||
version = "0.1.19"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ struct PromptCompositions {
|
||||
/// 而是一份独立的完整清单:plan 根的工具面只有 7 个原生工具,专业组、
|
||||
/// isolated child、任务图与视觉产物合同在这条链路上全部不可执行,逐段
|
||||
/// 减法会把「plan 根到底看到什么」摊在两个函数的四个否定分支里。
|
||||
supervisor_plan: Vec<String>,
|
||||
supervisor_chat: SupervisorChatComposition,
|
||||
}
|
||||
|
||||
@@ -98,6 +99,10 @@ struct ProviderFragments {
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct AgentCatalog {
|
||||
supervisor: AgentGroup,
|
||||
/// 立项策划子 Agent。与 `supervisor` 平级、**不进 `groups`**:`specialist_nodes`
|
||||
/// 只从 `groups[].roles[]` 派生,因此它不参与 `build.rs` 与种子 DAG 的一致性
|
||||
/// 校验,「做游戏」的 16 任务 DAG 一行不动。详见技术方案第 3.1 节。
|
||||
planning: AgentGroup,
|
||||
groups: Vec<AgentGroup>,
|
||||
}
|
||||
|
||||
@@ -226,6 +231,12 @@ pub fn compile_manifest(manifest_path: &Path) -> Result<CompiledPromptBundle, St
|
||||
§ions,
|
||||
&["$base", "$visualContract"],
|
||||
)?;
|
||||
validate_composition(
|
||||
"supervisorPlan",
|
||||
&manifest.compositions.supervisor_plan,
|
||||
§ions,
|
||||
&["$header"],
|
||||
)?;
|
||||
validate_section_reference(
|
||||
&manifest.compositions.supervisor_chat.identity,
|
||||
§ions,
|
||||
@@ -288,6 +299,7 @@ pub fn compile_manifest(manifest_path: &Path) -> Result<CompiledPromptBundle, St
|
||||
.supervisor
|
||||
.roles
|
||||
.iter()
|
||||
.chain(manifest.agent_catalog.planning.roles.iter())
|
||||
.chain(
|
||||
manifest
|
||||
.agent_catalog
|
||||
@@ -336,6 +348,7 @@ pub fn compile_manifest(manifest_path: &Path) -> Result<CompiledPromptBundle, St
|
||||
.runtime
|
||||
.iter()
|
||||
.chain(manifest.compositions.supervisor.iter())
|
||||
.chain(manifest.compositions.supervisor_plan.iter())
|
||||
.filter(|item| !item.starts_with('$'))
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
@@ -408,6 +421,14 @@ fn validate_section_ownership(manifest: &PromptBundleManifest) -> Result<(), Str
|
||||
{
|
||||
register("composition supervisor", section);
|
||||
}
|
||||
for section in manifest
|
||||
.compositions
|
||||
.supervisor_plan
|
||||
.iter()
|
||||
.filter(|section| !section.starts_with('$'))
|
||||
{
|
||||
register("composition supervisorPlan", section);
|
||||
}
|
||||
register("composition supervisorChat.identity", identity);
|
||||
register(
|
||||
"composition supervisorChat.finalReply",
|
||||
@@ -436,9 +457,19 @@ fn validate_section_ownership(manifest: &PromptBundleManifest) -> Result<(), Str
|
||||
"composition supervisor",
|
||||
"composition supervisorChat.identity",
|
||||
]);
|
||||
// plan 根 composition 是 Supervisor system prompt 的第二条 lane,不是另一种
|
||||
// 语义面。它按设计复用 runtime lane 的 `isolatedAgentContract`(`agent.delegate`
|
||||
// 的 expectedArtifacts/writeScopes 合同)和 supervisor lane 的 `supervisorRepair`
|
||||
// (返工必须逐字继承原合同)。除这两个方向外,跨所有者复用仍然是错误。
|
||||
let allowed_plan_runtime_owners =
|
||||
BTreeSet::from(["composition runtime", "composition supervisorPlan"]);
|
||||
let allowed_plan_supervisor_owners =
|
||||
BTreeSet::from(["composition supervisor", "composition supervisorPlan"]);
|
||||
for (section, section_owners) in owners {
|
||||
if section_owners.len() > 1
|
||||
&& !(section == identity && section_owners == allowed_identity_owners)
|
||||
&& section_owners != allowed_plan_runtime_owners
|
||||
&& section_owners != allowed_plan_supervisor_owners
|
||||
{
|
||||
return Err(format!(
|
||||
"Prompt section 跨语义所有者复用:{section} -> {section_owners:?}"
|
||||
@@ -675,11 +706,17 @@ fn validate_agent_catalog(catalog: &AgentCatalog) -> Result<(), String> {
|
||||
if catalog.supervisor.roles.len() != 1 {
|
||||
return Err("agentCatalog.supervisor 必须且只能包含一个 role".to_string());
|
||||
}
|
||||
if catalog.planning.roles.len() != 1 {
|
||||
return Err("agentCatalog.planning 必须且只能包含一个 role".to_string());
|
||||
}
|
||||
if catalog.groups.is_empty() {
|
||||
return Err("agentCatalog.groups 不能为空".to_string());
|
||||
}
|
||||
let mut group_brief_names = BTreeSet::new();
|
||||
for group in std::iter::once(&catalog.supervisor).chain(catalog.groups.iter()) {
|
||||
for group in std::iter::once(&catalog.supervisor)
|
||||
.chain(std::iter::once(&catalog.planning))
|
||||
.chain(catalog.groups.iter())
|
||||
{
|
||||
if !group_brief_names.insert(group.brief_path_name.as_str()) {
|
||||
return Err(format!(
|
||||
"agent group briefPathName 重复:{}",
|
||||
@@ -687,7 +724,10 @@ fn validate_agent_catalog(catalog: &AgentCatalog) -> Result<(), String> {
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut generated_names = BTreeSet::from(["PROJECT_SUPERVISOR".to_string()]);
|
||||
let mut generated_names = BTreeSet::from([
|
||||
"PROJECT_SUPERVISOR".to_string(),
|
||||
"PROJECT_PLANNING".to_string(),
|
||||
]);
|
||||
for group in &catalog.groups {
|
||||
let generated = rust_identifier(&group.id);
|
||||
if !generated
|
||||
@@ -713,6 +753,12 @@ fn validate_agent_catalog(catalog: &AgentCatalog) -> Result<(), String> {
|
||||
&mut task_ids,
|
||||
&mut tool_ids,
|
||||
)?;
|
||||
validate_agent_group(
|
||||
&catalog.planning,
|
||||
&mut group_ids,
|
||||
&mut task_ids,
|
||||
&mut tool_ids,
|
||||
)?;
|
||||
for group in &catalog.groups {
|
||||
validate_agent_group(group, &mut group_ids, &mut task_ids, &mut tool_ids)?;
|
||||
}
|
||||
@@ -874,6 +920,10 @@ fn render_rust(manifest: &PromptBundleManifest, sections: &BTreeMap<String, Stri
|
||||
"RUNTIME_PROMPT_SUPERVISOR_COMPOSITION",
|
||||
&manifest.compositions.supervisor,
|
||||
));
|
||||
output.push_str(&render_string_slice_const(
|
||||
"RUNTIME_PROMPT_SUPERVISOR_PLAN_COMPOSITION",
|
||||
&manifest.compositions.supervisor_plan,
|
||||
));
|
||||
output.push_str(&format!(
|
||||
"pub(crate) const RUNTIME_PROMPT_SUPERVISOR_CHAT_COMPOSITION: &[&str] = &[{}, {}];\n",
|
||||
rust_literal(&manifest.compositions.supervisor_chat.identity),
|
||||
@@ -962,6 +1012,26 @@ fn render_agent_catalog(catalog: &AgentCatalog) -> String {
|
||||
"static PROJECT_SUPERVISOR_AGENT_DEFINITION: AgentGroupDefinition = {};\n",
|
||||
render_group_value(&catalog.supervisor, "&PROJECT_SUPERVISOR_AGENT_ROLES")
|
||||
));
|
||||
let planning_role = &catalog.planning.roles[0];
|
||||
output.push_str(&format!(
|
||||
"pub(crate) const GAME_CREATOR_PROJECT_PLANNING_AGENT_ID: &str = {};\n",
|
||||
rust_literal(&planning_role.task_id)
|
||||
));
|
||||
output.push_str(&format!(
|
||||
"pub(crate) const GAME_CREATOR_PROJECT_PLANNING_MEMORY_PATH: &str = {};\n",
|
||||
rust_literal(&format!(
|
||||
"memory/agents/{}",
|
||||
catalog.planning.brief_path_name
|
||||
))
|
||||
));
|
||||
output.push_str(&render_role_array(
|
||||
"PROJECT_PLANNING_AGENT_ROLES",
|
||||
&catalog.planning.roles,
|
||||
));
|
||||
output.push_str(&format!(
|
||||
"static PROJECT_PLANNING_AGENT_DEFINITION: AgentGroupDefinition = {};\n",
|
||||
render_group_value(&catalog.planning, "&PROJECT_PLANNING_AGENT_ROLES")
|
||||
));
|
||||
for group in &catalog.groups {
|
||||
let roles_name = format!("{}_AGENT_ROLES", rust_identifier(&group.id));
|
||||
output.push_str(&render_role_array(&roles_name, &group.roles));
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
当前阶段:系统架构。明确系统清单、职责边界、依赖和数据归属。
|
||||
@@ -1,6 +0,0 @@
|
||||
共享过程文件(如需维护,请使用这些相对路径):
|
||||
- project/analysis.md
|
||||
- project/决策台账.md
|
||||
- project/dialog.md
|
||||
不要把正式产物写在工作区根目录,也不要等审批失败后再迁移。
|
||||
阶段审批工具:当你判断本阶段必需产物已完成时,必须提交阶段审批。用户批准后 Runtime 自动进入下一阶段;你不能自行切换阶段。
|
||||
@@ -1 +0,0 @@
|
||||
当前阶段:概念设计。明确游戏是什么、不是什么,并形成概念设计产物。
|
||||
@@ -1,4 +0,0 @@
|
||||
顾问阶段不需要继续自主推动项目或主动安排下一步;遵照用户的具体指示行动。
|
||||
根据用户指示回答问题、读取相关文档、修改工作区文件,并说明改动可能影响的已有产物。
|
||||
涉及方向性变化或多个可行方案时,先向用户说明影响并等待用户决定;不要替用户做决定。
|
||||
顾问阶段没有下一层,也不需要提交阶段审批。
|
||||
@@ -1 +0,0 @@
|
||||
当前阶段:项目顾问。五个策划阶段已经完成,后续由用户指示驱动协作。
|
||||
@@ -1,44 +0,0 @@
|
||||
概念阶段定稿时,还必须创建或更新 `project/速览卡.md`。Runtime 只检查该文件是否存在,不检查内容。请使用下面的固定结构,不要加入审批操作说明或独立的决定状态段落:
|
||||
|
||||
# 速览卡:《游戏名》
|
||||
|
||||
## 1. 游戏名称
|
||||
|
||||
## 2. 游戏分类
|
||||
|
||||
## 3. 美术风格
|
||||
- 视觉类型:
|
||||
- 风格关键词:
|
||||
- 色彩与氛围:
|
||||
- MVP 美术边界:
|
||||
|
||||
## 4. 一句话描述
|
||||
|
||||
## 5. 游戏支柱
|
||||
| 支柱 | 玩家感受 | 实现机制 |
|
||||
|---|---|---|
|
||||
|
||||
## 6. 核心循环
|
||||
|
||||
## 7. 目标用户
|
||||
- 核心用户:
|
||||
- 游戏偏好:
|
||||
- 单次游玩时长:
|
||||
- 参考游戏与参考点:
|
||||
|
||||
## 8. 平台事实
|
||||
|
||||
## 9. 最小 MVP 系统
|
||||
| 系统 | 最小功能 | 为什么必须有 | 验证方法 |
|
||||
|---|---|---|---|
|
||||
|
||||
## 10. 给创作者的关键提示
|
||||
- 先做:
|
||||
- 暂时不做:
|
||||
- 这样验证:
|
||||
- 达标再扩展:
|
||||
|
||||
### 待原型验证项
|
||||
- 问题:
|
||||
- 原型:
|
||||
- 观察:
|
||||
@@ -1 +0,0 @@
|
||||
当前阶段:系统文档。逐个完成已确定系统的内部规则、接口和验证标准。
|
||||
@@ -1 +0,0 @@
|
||||
当前阶段:技术文档。完成数据与配表、技术实现、美术圣经和总册。
|
||||
@@ -1 +0,0 @@
|
||||
当前阶段:顶层设计。明确玩家持续游玩的循环、资源流、节奏和系统范围。
|
||||
File diff suppressed because one or more lines are too long
@@ -1,384 +0,0 @@
|
||||
{
|
||||
"version": 1,
|
||||
"resources": [
|
||||
{
|
||||
"path": "skills/concept.md",
|
||||
"id": "skills.concept",
|
||||
"summary": "概念阶段写作规则。",
|
||||
"category": "skills",
|
||||
"title": "概念设计分册",
|
||||
"inject_phases": [
|
||||
"concept"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "skills/top_design.md",
|
||||
"id": "skills.top_design",
|
||||
"summary": "顶层设计阶段写作规则。",
|
||||
"category": "skills",
|
||||
"title": "顶层设计分册",
|
||||
"inject_phases": [
|
||||
"top_design"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "skills/architecture.md",
|
||||
"id": "skills.architecture",
|
||||
"summary": "系统架构阶段写作规则。",
|
||||
"category": "skills",
|
||||
"title": "系统架构分册",
|
||||
"inject_phases": [
|
||||
"architecture"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "skills/systems.md",
|
||||
"id": "skills.systems",
|
||||
"summary": "系统文档阶段写作规则。",
|
||||
"category": "skills",
|
||||
"title": "系统文档分册",
|
||||
"inject_phases": [
|
||||
"systems"
|
||||
]
|
||||
},
|
||||
{
|
||||
"path": "skills/tdd.md",
|
||||
"id": "skills.tdd",
|
||||
"summary": "技术文档阶段写作规则。",
|
||||
"category": "skills",
|
||||
"title": "技术文档分册",
|
||||
"inject_phases": [
|
||||
"tdd"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "templates.analysis",
|
||||
"category": "templates",
|
||||
"title": "analysis",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/analysis.md"
|
||||
},
|
||||
{
|
||||
"id": "templates.architecture",
|
||||
"category": "templates",
|
||||
"title": "architecture",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/architecture.md"
|
||||
},
|
||||
{
|
||||
"id": "templates.concept_design",
|
||||
"category": "templates",
|
||||
"title": "concept-design",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/concept-design.md"
|
||||
},
|
||||
{
|
||||
"id": "templates.stardew_analysis",
|
||||
"category": "templates",
|
||||
"title": "stardew-analysis",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/stardew-analysis.md"
|
||||
},
|
||||
{
|
||||
"id": "templates.tdd_art_bible",
|
||||
"category": "templates",
|
||||
"title": "tdd-art-bible",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/tdd-art-bible.md"
|
||||
},
|
||||
{
|
||||
"id": "templates.tdd_data",
|
||||
"category": "templates",
|
||||
"title": "tdd-data",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/tdd-data.md"
|
||||
},
|
||||
{
|
||||
"id": "templates.tdd_master",
|
||||
"category": "templates",
|
||||
"title": "tdd-master",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/tdd-master.md"
|
||||
},
|
||||
{
|
||||
"id": "templates.tdd_tech",
|
||||
"category": "templates",
|
||||
"title": "tdd-tech",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/tdd-tech.md"
|
||||
},
|
||||
{
|
||||
"id": "templates.top_design",
|
||||
"category": "templates",
|
||||
"title": "top-design",
|
||||
"summary": "策划文档结构模板。",
|
||||
"path": "templates/top-design.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.decision_log",
|
||||
"category": "exemplars",
|
||||
"title": "decision-log",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/decision-log.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.fast_gdd",
|
||||
"category": "exemplars",
|
||||
"title": "fast-gdd",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/fast-gdd.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.overview_card",
|
||||
"category": "exemplars",
|
||||
"title": "overview-card",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/overview-card.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.stardew_architecture",
|
||||
"category": "exemplars",
|
||||
"title": "stardew-architecture",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/stardew-architecture.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.stardew_concept",
|
||||
"category": "exemplars",
|
||||
"title": "stardew-concept",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/stardew-concept.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.stardew_s06_combat",
|
||||
"category": "exemplars",
|
||||
"title": "stardew-s06-combat",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/stardew-s06-combat.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.stardew_tdd_art_bible",
|
||||
"category": "exemplars",
|
||||
"title": "stardew-tdd-art-bible",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/stardew-tdd-art-bible.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.stardew_tdd_data",
|
||||
"category": "exemplars",
|
||||
"title": "stardew-tdd-data",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/stardew-tdd-data.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.stardew_tdd_master",
|
||||
"category": "exemplars",
|
||||
"title": "stardew-tdd-master",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/stardew-tdd-master.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.stardew_tdd_tech",
|
||||
"category": "exemplars",
|
||||
"title": "stardew-tdd-tech",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/stardew-tdd-tech.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.stardew_top_design",
|
||||
"category": "exemplars",
|
||||
"title": "stardew-top-design",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/stardew-top-design.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.tdd_art_bible_SKILL",
|
||||
"category": "exemplars",
|
||||
"title": "tdd-art-bible-SKILL",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/tdd-art-bible-SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.tdd_data_SKILL",
|
||||
"category": "exemplars",
|
||||
"title": "tdd-data-SKILL",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/tdd-data-SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "exemplars.tdd_tech_SKILL",
|
||||
"category": "exemplars",
|
||||
"title": "tdd-tech-SKILL",
|
||||
"summary": "策划文档范例或需求附件。",
|
||||
"path": "exemplars/tdd-tech-SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.核心玩法编排.skill",
|
||||
"category": "system_types",
|
||||
"title": "01_核心玩法编排 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/01_核心玩法编排/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.核心玩法编排.template",
|
||||
"category": "system_types",
|
||||
"title": "01_核心玩法编排 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/01_核心玩法编排/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.时间与日程.skill",
|
||||
"category": "system_types",
|
||||
"title": "02_时间与日程 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/02_时间与日程/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.时间与日程.template",
|
||||
"category": "system_types",
|
||||
"title": "02_时间与日程 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/02_时间与日程/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.生产种植经营.skill",
|
||||
"category": "system_types",
|
||||
"title": "03_生产种植经营 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/03_生产种植经营/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.生产种植经营.template",
|
||||
"category": "system_types",
|
||||
"title": "03_生产种植经营 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/03_生产种植经营/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.地图与探索.skill",
|
||||
"category": "system_types",
|
||||
"title": "04_地图与探索 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/04_地图与探索/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.地图与探索.template",
|
||||
"category": "system_types",
|
||||
"title": "04_地图与探索 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/04_地图与探索/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.采集与支线活动.skill",
|
||||
"category": "system_types",
|
||||
"title": "05_采集与支线活动 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/05_采集与支线活动/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.采集与支线活动.template",
|
||||
"category": "system_types",
|
||||
"title": "05_采集与支线活动 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/05_采集与支线活动/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.战斗与敌人.skill",
|
||||
"category": "system_types",
|
||||
"title": "06_战斗与敌人 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/06_战斗与敌人/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.战斗与敌人.template",
|
||||
"category": "system_types",
|
||||
"title": "06_战斗与敌人 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/06_战斗与敌人/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.物品背包与制作.skill",
|
||||
"category": "system_types",
|
||||
"title": "07_物品背包与制作 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/07_物品背包与制作/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.物品背包与制作.template",
|
||||
"category": "system_types",
|
||||
"title": "07_物品背包与制作 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/07_物品背包与制作/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.成长与技能.skill",
|
||||
"category": "system_types",
|
||||
"title": "08_成长与技能 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/08_成长与技能/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.成长与技能.template",
|
||||
"category": "system_types",
|
||||
"title": "08_成长与技能 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/08_成长与技能/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.NPC关系与任务.skill",
|
||||
"category": "system_types",
|
||||
"title": "09_NPC关系与任务 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/09_NPC关系与任务/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.NPC关系与任务.template",
|
||||
"category": "system_types",
|
||||
"title": "09_NPC关系与任务 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/09_NPC关系与任务/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.经济与商店.skill",
|
||||
"category": "system_types",
|
||||
"title": "10_经济与商店 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/10_经济与商店/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.经济与商店.template",
|
||||
"category": "system_types",
|
||||
"title": "10_经济与商店 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/10_经济与商店/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.事件与节日.skill",
|
||||
"category": "system_types",
|
||||
"title": "11_事件与节日 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/11_事件与节日/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.事件与节日.template",
|
||||
"category": "system_types",
|
||||
"title": "11_事件与节日 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/11_事件与节日/模板.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.UI与文本呈现.skill",
|
||||
"category": "system_types",
|
||||
"title": "12_UI与文本呈现 skill",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/12_UI与文本呈现/SKILL.md"
|
||||
},
|
||||
{
|
||||
"id": "system_types.UI与文本呈现.template",
|
||||
"category": "system_types",
|
||||
"title": "12_UI与文本呈现 template",
|
||||
"summary": "系统类型写法规则或模板。",
|
||||
"path": "modules/system-types/12_UI与文本呈现/模板.md"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
此文档已在需求中声明,但附件内容尚未实现。
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user