Compare commits

..

1 Commits

Author SHA1 Message Date
kdletters b79ee96f7e 补齐容器预览的 AGC Router 密钥说明
- deploy/container/api-server.env.example 增加 AGC 官方 LLM Router 段,列明容器预览必须由 .env.secrets.local 提供的三个密钥
- 【开发运维】Jenkins容器预览部署控制面技术方案 补充预览 secrets 必含密钥与缺失时的失败表现
- 【开发运维】本地开发验证与生产运维 补充容器与 Jenkins 预览路径同样受 Router 启动校验约束
- project-memory pitfalls 补充容器预览缺少 Router 密钥时的排障特征
2026-09-14 19:52:27 +08:00
114 changed files with 1806 additions and 13512 deletions
-1
View File
@@ -164,7 +164,6 @@ module.exports = {
'server-rs/target-*',
'apps/desktop-shell/src-tauri/target',
'apps/ai-game-creator-shell/src/features/ui-editor/types/**',
'apps/ai-game-creator-shell/src/features/project-workspace/generated/**',
'target',
'src/main.tsx',
'src/App.tsx',
@@ -113,11 +113,6 @@ const allowedUncalledTauriCommands = [
'chat_with_game_creator_agent',
'check_ui_editor_font_glyph_coverage',
'create_ui_design_resource',
// 图片类生成的同步变体:GUI 已改为 `start_local_project_asset_generation` + 项目内任务账本
// (提交即返回、后台生成)。这条命令**没有生产调用方**,只有 Rust 集成测试
// `src/tests/project.rs`)与 `commands.rs` 单测在调;待后续批次删除,或改为转调
// `start_local_project_asset_generation`。
'generate_local_project_asset',
'open_game_creator_launcher_window',
'open_game_creator_workspace_window',
'read_direct_project_conversation',
@@ -9,10 +9,6 @@ import {
const agcDevHost = '127.0.0.1';
const legacyAgcDevPort = 3080;
const agcVitePortEnvKey = 'GENARRATIVE_AGC_VITE_PORT';
const agcAdminWebHost = '127.0.0.1';
const legacyAgcAdminWebPort = 3102;
// 与 scripts/dev.mjs 的后台 Web 端口配置保持同一环境变量名。
const agcAdminWebPortEnvKey = 'ADMIN_WEB_PORT';
function readConfiguredAgcDevPort(env = process.env) {
const rawPort = String(env[agcVitePortEnvKey] ?? '').trim();
@@ -103,100 +99,13 @@ function withAgcDevEndpointEnv(endpoint, env = process.env) {
};
}
function readConfiguredAgcAdminWebPort(env = process.env) {
const rawPort = String(env[agcAdminWebPortEnvKey] ?? '').trim();
if (!rawPort) {
return null;
}
const port = normalizePort(rawPort, -1);
if (port < 1024) {
throw new Error(`${agcAdminWebPortEnvKey} 必须是 1024-65535 的有效端口`);
}
return port;
}
function createAgcAdminWebEndpoint(port, portRange = null) {
const origin = `http://${agcAdminWebHost}:${port}`;
return {
host: agcAdminWebHost,
port,
origin,
basePath: '/admin/',
url: `${origin}/admin/`,
portRange,
};
}
// AGC 开发态的后台 Web 与 `npm run dev` 的后台 Vite 共用同一套优先端口约定:
// Linux 取当前用户端口段的 `start + 3` 槽位,非 Linux 保留 `3102` 兼容首选并允许统一漂移。
async function resolveAgcAdminWebEndpoint({
env = process.env,
platform = process.platform,
strictConfigured = false,
reservedPorts = [],
reservePortRange = reserveLinuxDevPortRange,
findPort = findAvailablePort,
} = {}) {
const configuredPort = readConfiguredAgcAdminWebPort(env);
let portRange = null;
let preferredPort = configuredPort ?? legacyAgcAdminWebPort;
if (platform === 'linux') {
const allocation = await reservePortRange({ env });
if (!allocation?.range) {
throw new Error('无法取得当前 Linux 用户的 dev 端口段');
}
portRange = allocation.range;
const mappedAdminWebPort = mapDevPortsToPortRange(portRange)?.adminWebPort;
if (!Number.isInteger(mappedAdminWebPort)) {
throw new Error(
`当前 Linux dev 端口段 ${portRange.label} 缺少后台 Web 槽位;请先迁移为至少 6 个端口且不与其它用户重叠的端口段`,
);
}
preferredPort = configuredPort ?? mappedAdminWebPort;
}
const reservedPortSet = new Set(
reservedPorts.filter((value) => Number.isInteger(value) && value > 0),
);
const port = await findPort({
host: agcAdminWebHost,
preferredPort,
portRange,
reservedPorts: reservedPortSet,
strict: strictConfigured && configuredPort != null,
});
console.log(
formatPortDecision({
name: 'ai-game-creator-shell-admin-web',
host: agcAdminWebHost,
preferredPort,
resolvedPort: port,
}),
);
if (portRange) {
console.log(
`[ai-game-creator-shell] admin-web port-range: ${portRange.label}`,
);
}
return createAgcAdminWebEndpoint(port, portRange);
}
export {
agcAdminWebHost,
agcAdminWebPortEnvKey,
agcDevHost,
agcVitePortEnvKey,
createAgcAdminWebEndpoint,
createAgcDevEndpoint,
legacyAgcAdminWebPort,
legacyAgcDevPort,
readAgcDevEndpoint,
readConfiguredAgcAdminWebPort,
readConfiguredAgcDevPort,
resolveAgcAdminWebEndpoint,
resolveAgcDevEndpoint,
withAgcDevEndpointEnv,
};
@@ -14,14 +14,12 @@ import {
import {
agcVitePortEnvKey,
readAgcDevEndpoint,
resolveAgcAdminWebEndpoint,
resolveAgcDevEndpoint,
withAgcDevEndpointEnv,
} from './dev-port.mjs';
const appRoot = fileURLToPath(new URL('..', import.meta.url));
const repoRoot = resolve(appRoot, '../..');
const adminWebDir = resolve(repoRoot, 'apps/admin-web');
const devStackStatePath = resolve(repoRoot, '.app/dev-stack.json');
const apiServerExePath = resolve(
repoRoot,
@@ -34,8 +32,6 @@ const backendSpacetimeDataDir = resolve(
repoRoot,
'server-rs/.spacetimedb/ai-game-creator/data',
);
// 后台 Web 默认跟随 AGC 一起起来,便于联调后台页面;`AGC_DEV_ADMIN_WEB=0` 可关闭。
const agcDevAdminWebEnvKey = 'AGC_DEV_ADMIN_WEB';
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const childLifecycles = new WeakMap();
@@ -204,122 +200,36 @@ function urlPort(url) {
}
}
// 端口归属探测脚本。历史实现用 `Get-NetTCPConnection` 取监听进程,而它底层走
// WMI:实测单端口单次 11.2 秒、再叠加每个 PID 的 `Get-CimInstance` 3.3 秒,
// 一轮探测约 43 秒,直接把"配套后端就绪"等待拖到分钟级。改用原生
// `netstat -ano`(约 30 毫秒)取端口 -> PID,再用 .NET `Process` 读进程名和
// 可执行文件路径(毫秒级);只有核对 SpacetimeDB `--data-dir` 归属时才按 PID
// 取命令行,并允许调用方把已知命令行传进来复用。
const windowsPortOwnerProbeCommand = [
'$ErrorActionPreference = "SilentlyContinue"',
'$queriedPorts = @()',
'foreach ($raw in ($env:GENARRATIVE_QUERY_PORTS -split ",")) {',
' if ($raw -match "^\\d+$") { $queriedPorts += [int]$raw }',
'}',
'$knownCommandLines = @{}',
'if ($env:GENARRATIVE_KNOWN_COMMAND_LINES) {',
' try {',
' foreach ($property in (ConvertFrom-Json $env:GENARRATIVE_KNOWN_COMMAND_LINES).PSObject.Properties) {',
' $knownCommandLines[[int]$property.Name] = [string]$property.Value',
' }',
' } catch { }',
'}',
'$listenerPidByPort = @{}',
'foreach ($line in (netstat -ano -p tcp)) {',
' $fields = @($line -split "\\s+" | Where-Object { $_ })',
' if ($fields.Count -lt 4) { continue }',
' if ($fields[0] -ne "TCP") { continue }',
' # A listening socket always has foreign address 0.0.0.0:0 / [::]:0, which',
' # is locale-independent unlike the localized netstat State column.',
' if ($fields[2] -notmatch ":0$") { continue }',
' $localPort = [int]($fields[1].Split(":")[-1])',
' if ($queriedPorts -notcontains $localPort) { continue }',
' # The PID is the last column; do not hardcode its index.',
' if ($fields[-1] -notmatch "^\\d+$") { continue }',
' $listenerPidByPort[$localPort] = [int]$fields[-1]',
'}',
'$result = @()',
'foreach ($port in ($listenerPidByPort.Keys | Sort-Object)) {',
' $processId = $listenerPidByPort[$port]',
' $name = $null',
' $executablePath = $null',
' $commandLine = $null',
' try {',
' $process = [System.Diagnostics.Process]::GetProcessById($processId)',
' $name = $process.ProcessName + ".exe"',
' try { $executablePath = $process.MainModule.FileName } catch { }',
' } catch { }',
' if ($knownCommandLines.ContainsKey($processId)) {',
' $commandLine = $knownCommandLines[$processId]',
' } elseif (($name -like "spacetime*") -or (-not $executablePath)) {',
' try { $commandLine = (Get-CimInstance Win32_Process -Filter ("ProcessId=" + $processId)).CommandLine } catch { }',
' }',
' $result += [pscustomobject]@{ port = [int]$port; processId = $processId; name = $name; executablePath = $executablePath; commandLine = $commandLine }',
'}',
'ConvertTo-Json -InputObject @($result) -Compress',
].join('\n');
// 进程命令行在进程生命周期内不变,但 PID 会被系统复用;按 PID 记 TTL 缓存,
// 让"等配套后端就绪"的轮询只在首个周期付出 WMI 成本。TTL 取 5 分钟:本轮实测
// 这台机器上首次 WMI 调用约 18 秒(热调用 3.3 秒),而 PID 在 5 分钟内被复用
// 成另一个运行本工作树 data dir 的 SpacetimeDB 才能造成误判,概率可忽略。
// 默认实现才缓存,注入实现(测试)与显式 env 始终重新读取。
const WINDOWS_COMMAND_LINE_CACHE_TTL_MS = 300_000;
const windowsPortOwnerCommandLineCache = new Map();
function resolveCommandLineCache({ spawnImpl, env }) {
return spawnImpl === spawnSync && env === process.env
? windowsPortOwnerCommandLineCache
: new Map();
}
// 读取端口当前真正的监听进程身份。返回 null 表示探测本身不可用(例如系统缺少
// netstat),此时调用方必须退化为旧行为,不能让本地启动直接失败。
// 读取端口当前真正的监听进程身份。返回 null 表示探测本身不可用(例如缺少
// Get-NetTCPConnection),此时调用方必须退化为旧行为,不能让本地启动直接失败。
function readWindowsPortOwnerIdentities(
ports,
{
spawnImpl = spawnSync,
env = process.env,
now = Date.now,
commandLineTtlMs = WINDOWS_COMMAND_LINE_CACHE_TTL_MS,
commandLineCache = resolveCommandLineCache({ spawnImpl, env }),
} = {},
{ spawnImpl = spawnSync, env = process.env } = {},
) {
const uniquePorts = [...new Set(ports.filter((port) => port > 0))];
if (uniquePorts.length === 0) {
return null;
}
const knownCommandLines = {};
for (const [processId, record] of [...commandLineCache]) {
if (record && now() - record.at < commandLineTtlMs) {
knownCommandLines[processId] = record.commandLine;
} else {
commandLineCache.delete(processId);
}
}
const childEnv = {
...env,
GENARRATIVE_QUERY_PORTS: uniquePorts.join(','),
};
if (Object.keys(knownCommandLines).length > 0) {
childEnv.GENARRATIVE_KNOWN_COMMAND_LINES =
JSON.stringify(knownCommandLines);
}
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',
windowsPortOwnerProbeCommand,
],
['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command],
{
encoding: 'utf8',
env: childEnv,
env: { ...env, GENARRATIVE_QUERY_PORTS: uniquePorts.join(',') },
maxBuffer: 8 * 1024 * 1024,
},
);
@@ -330,22 +240,9 @@ function readWindowsPortOwnerIdentities(
const owners = new Map();
for (const entry of parseWindowsProcessSnapshot(result.stdout)) {
const port = Number(entry?.port);
if (!Number.isInteger(port) || port <= 0) {
continue;
if (Number.isInteger(port) && port > 0) {
owners.set(port, entry);
}
const processId = Number(entry?.processId);
if (
Number.isInteger(processId) &&
processId > 0 &&
typeof entry?.commandLine === 'string' &&
entry.commandLine
) {
commandLineCache.set(processId, {
commandLine: entry.commandLine,
at: now(),
});
}
owners.set(port, entry);
}
return owners;
}
@@ -982,102 +879,10 @@ async function startVite(apiTarget, endpoint = readAgcDevEndpoint()) {
);
}
function readAdminWebEnabled(env = process.env) {
return String(env[agcDevAdminWebEnvKey] ?? '').trim() !== '0';
}
// 后台 Web 与 AGC Vite 一样直接由本启动器持有,不经过 `dev.mjs admin-web`
// 后者会整体重写 `.app/dev-stack.json`,把本次配套后端的状态覆盖掉。
function startAdminWeb(
apiUrl,
endpoint,
{ env = process.env, spawnImpl = spawnChild } = {},
) {
return spawnImpl(
npm,
[
'--prefix',
'../..',
'exec',
'vite',
'--',
'--host',
endpoint.host,
'--port',
String(endpoint.port),
'--strictPort',
],
{
cwd: adminWebDir,
env: {
...env,
ADMIN_API_TARGET: apiUrl,
GENARRATIVE_API_TARGET: apiUrl,
GENARRATIVE_API_PORT: String(urlPort(apiUrl) || 8082),
ADMIN_WEB_BASE: endpoint.basePath,
},
},
);
}
function formatStartupSummary({
frontendUrl = '',
apiUrl = '',
adminWebUrl = '',
spacetimeUrl = '',
bgfilterWorkerUrl = '',
} = {}) {
const segments = [
['前端', frontendUrl],
['后端', apiUrl],
['后台', adminWebUrl],
['数据库', spacetimeUrl],
['bgfilter-worker', bgfilterWorkerUrl],
]
.filter(([, value]) => Boolean(value))
.map(([label, value]) => `${label} ${value}`);
return `[ai-game-creator-shell] 启动汇总: ${segments.join(' | ')}`;
}
// 后台 Web 是可选联调服务:端口解析或启动失败只告警,不能阻断 AGC 客户端与配套后端。
async function ensureAdminWeb({
apiUrl,
reservedPorts = [],
env = process.env,
enabled = readAdminWebEnabled(env),
resolveEndpoint = resolveAgcAdminWebEndpoint,
spawnAdminWeb = startAdminWeb,
waitForExit = waitForChildTermination,
warn = (message) => console.warn(message),
} = {}) {
if (!enabled) {
return { endpoint: null, child: null };
}
try {
const endpoint = await resolveEndpoint({ env, reservedPorts });
const child = spawnAdminWeb(apiUrl, endpoint, { env });
waitForExit(child).then((failure) => {
warn(
`[ai-game-creator-shell] 后台 Web 已退出(${formatChildFailure(failure)}),AGC 继续运行。`,
);
});
return { endpoint, child };
} catch (error) {
warn(
`[ai-game-creator-shell] 后台 Web 未能启动(${
error instanceof Error ? error.message : String(error)
}),AGC 继续运行。`,
);
return { endpoint: null, child: null };
}
}
async function main() {
let backendChild = null;
let startedBackend = false;
let viteChild = null;
let adminWebChild = null;
let shutdownSignal = '';
const signalHandlers = new Map();
@@ -1100,7 +905,6 @@ async function main() {
const handler = () => {
shutdownSignal = signal;
stopChild(viteChild, signal);
stopChild(adminWebChild, signal);
stopChild(backendChild, signal);
// 立刻清扫,避免外层 taskkill /F 抢在 finally 之前把本进程杀掉。
sweepStartedBackend();
@@ -1133,25 +937,6 @@ async function main() {
throw new Error(`启动期收到 ${shutdownSignal},已停止前端服务`);
}
const adminWeb = await ensureAdminWeb({
apiUrl: backend.targets.apiUrl,
// AGC Vite 端口尚未监听,必须显式保留,避免被后台 Web 抢先占用。
reservedPorts: [endpoint.port],
});
adminWebChild = adminWeb.child;
if (shutdownSignal) {
throw new Error(`启动期收到 ${shutdownSignal},已停止后台 Web`);
}
console.log(
formatStartupSummary({
frontendUrl: endpoint.url,
apiUrl: backend.targets.apiUrl,
adminWebUrl: adminWeb.endpoint?.url ?? '',
spacetimeUrl: backend.targets.spacetimeUrl,
bgfilterWorkerUrl: backend.targets.bgfilterWorkerUrl,
}),
);
const children = [backendChild, viteChild].filter(Boolean);
if (children.length === 0) {
return 0;
@@ -1161,12 +946,10 @@ async function main() {
children.map((child) => waitForChildTermination(child)),
);
stopChild(viteChild);
stopChild(adminWebChild);
stopChild(backendChild);
return failure.type === 'error' || failure.signal ? 1 : (failure.code ?? 0);
} catch (error) {
stopChild(viteChild);
stopChild(adminWebChild);
stopChild(backendChild);
console.error(
`[ai-game-creator-shell] ${error instanceof Error ? error.message : String(error)}`,
@@ -1175,7 +958,6 @@ async function main() {
} finally {
await Promise.all([
terminateChildTree(viteChild),
terminateChildTree(adminWebChild),
terminateChildTree(backendChild),
]);
sweepStartedBackend();
@@ -1193,12 +975,9 @@ function isDirectModuleExecution() {
}
export {
agcDevAdminWebEnvKey,
ensureAdminWeb,
ensureBackend,
formatChildFailure,
formatOwnerLabel,
formatStartupSummary,
isAiGameCreatorServer,
isBackendReady,
isDirectModuleExecution,
@@ -1206,7 +985,6 @@ export {
isWorktreeApiServerOwner,
isWorktreeSpacetimeOwner,
preflightExistingVite,
readAdminWebEnabled,
readBackendServiceFailure,
readChildFailure,
readExistingViteServer,
@@ -1215,7 +993,6 @@ export {
resolveBackendTargetsFromState,
runWindowsTaskkill,
spawnChild,
startAdminWeb,
stopChild,
terminateChildTree,
verifyAgcBackendOwnership,
@@ -16,7 +16,7 @@ mod design_runtime;
mod design_tools;
mod direct_codex_attachments;
mod direct_codex_audit;
mod direct_codex_user_item;
mod direct_codex_references;
mod direct_project_history;
mod direct_project_turn_history;
mod direct_runtime;
@@ -44,7 +44,7 @@ pub(crate) use codex_provider_proxy::*;
pub(crate) use design_runtime::*;
pub(crate) use direct_codex_attachments::*;
pub(crate) use direct_codex_audit::*;
pub(crate) use direct_codex_user_item::*;
pub(crate) use direct_codex_references::*;
pub(crate) use direct_project_history::*;
pub(crate) use direct_project_turn_history::*;
pub(crate) use direct_runtime::*;
@@ -10,11 +10,6 @@ use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufR
use tokio::sync::{mpsc, oneshot, Mutex, Notify};
use uuid::Uuid;
mod direct_project_history_wire;
use direct_project_history_wire::build_direct_project_history_injection_params;
mod direct_project_identity;
use direct_project_identity::*;
const GAME_CREATOR_CODEX_APP_SERVER_PROVIDER_ID: &str = "genarrative_agc";
const GAME_CREATOR_CODEX_APP_SERVER_API_KEY_ENV: &str = "GENARRATIVE_AGC_CODEX_API_KEY";
const GAME_CREATOR_CODEX_APP_SERVER_REMOTE_CONTROL_DISABLED_ENV: &str =
@@ -2625,7 +2620,6 @@ impl CodexAppServerConnection {
request,
None,
None,
None,
on_agent_message_delta,
direct_observer,
audit,
@@ -2640,7 +2634,6 @@ impl CodexAppServerConnection {
request: LlmRunRequest,
direct_history_root: Option<&std::path::Path>,
direct_client_turn_id: Option<&str>,
direct_user_item: Option<&serde_json::Value>,
mut on_agent_message_delta: Option<&mut (dyn FnMut(&platform_llm::LlmStreamDelta) + Send)>,
mut direct_observer: Option<&mut (dyn FnMut(DirectCodexTurnObservation) + Send)>,
mut audit: Option<&mut DirectCodexTurnAudit>,
@@ -2656,19 +2649,12 @@ impl CodexAppServerConnection {
));
}
if let Some(client_turn_id) = direct_client_turn_id {
let user_item = match direct_user_item {
Some(item) => {
direct_codex_user_item_to_response_item(history_root, item)
.map_err(platform_llm::LlmError::InvalidRequest)?;
item.clone()
}
None => direct_project_local_message_item(
"user",
current_prompt,
Some(&format!("direct-codex:{client_turn_id}:user")),
)
.map_err(platform_llm::LlmError::InvalidRequest)?,
};
let user_item = direct_project_local_message_item(
"user",
current_prompt,
Some(&format!("direct-codex:{client_turn_id}:user")),
)
.map_err(platform_llm::LlmError::InvalidRequest)?;
append_direct_project_user_message_at(history_root, &user_item)
.map_err(platform_llm::LlmError::InvalidRequest)?;
}
@@ -2678,14 +2664,24 @@ impl CodexAppServerConnection {
let thread_id = thread_lease.thread_id.clone();
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
if thread_created {
let params =
match build_direct_project_history_injection_params(history_root, &thread_id) {
Ok(params) => params,
Err(error) => {
self.release_thread(snapshot, &thread_id).await;
return Err(error);
}
};
let items = match read_direct_project_history_items_at(history_root) {
Ok(items) => items,
Err(error) => {
self.release_thread(snapshot, &thread_id).await;
return Err(platform_llm::LlmError::InvalidRequest(error));
}
};
let params = serde_json::json!({"threadId": thread_id.clone(), "items": items});
let payload_bytes = serde_json::to_vec(&params)
.map(|bytes| bytes.len().saturating_add(1))
.unwrap_or(usize::MAX);
// 注入前的前置校验:失败关闭并指名 itemId 与字节数,**不截断、不摘要、不改写**。
if let Some(error) =
direct_project_history_injection_oversize_error(&params, payload_bytes)
{
self.release_thread(snapshot, &thread_id).await;
return Err(platform_llm::LlmError::InvalidRequest(error));
}
if let Err(error) = self.request("thread/inject_items", params).await {
self.release_thread(snapshot, &thread_id).await;
return Err(platform_llm::LlmError::Transport(error));
@@ -2833,8 +2829,6 @@ impl CodexAppServerConnection {
callback(&platform_llm::LlmStreamDelta {
accumulated_text: streamed_text.clone(),
delta_text: delta,
accumulated_reasoning: String::new(),
reasoning_delta: String::new(),
finish_reason: None,
});
}
@@ -3139,7 +3133,6 @@ fn parse_game_creator_codex_app_server_text(
} else {
String::new()
},
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: Some(thread_id.to_string()),
usage: None,
@@ -3716,7 +3709,6 @@ pub(crate) async fn direct_game_creator_codex_chat_at(
None,
None,
None,
None,
)
.await
}
@@ -3734,11 +3726,56 @@ pub(crate) async fn direct_game_creator_codex_chat_at_with_observer(
None,
Some(observer),
None,
None,
)
.await
}
fn direct_codex_canonical_project_identity(
root: &std::path::Path,
) -> Result<(std::path::PathBuf, String), String> {
let (canonical_root, _) = resolve_direct_codex_project_authority(root)?;
let manifest = read_manifest(&canonical_root.join(".agent/manifest.json"))
.map_err(|error| format!("读取 DirectProject 权威项目身份失败:{error}"))?;
let manifest_project_id = manifest.project_id.trim();
if manifest_project_id.is_empty() || manifest_project_id.chars().count() > 256 {
return Err("DirectProject manifest.projectId 不满足身份边界".to_string());
}
let path_identity = direct_codex_os_path_identity_bytes(&canonical_root);
Ok((
canonical_root,
direct_codex_project_identity_digest(&path_identity, manifest_project_id.as_bytes()),
))
}
fn direct_codex_os_path_identity_bytes(path: &std::path::Path) -> Vec<u8> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
return path.as_os_str().as_bytes().to_vec();
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let mut bytes = Vec::new();
for unit in path.as_os_str().encode_wide() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
return bytes;
}
#[cfg(not(any(unix, windows)))]
path.as_os_str().to_string_lossy().as_bytes().to_vec()
}
fn direct_codex_project_identity_digest(path_identity: &[u8], project_id: &[u8]) -> String {
let mut digest = Sha256::new();
digest.update(b"genarrative-direct-project-identity.v1\0");
digest.update((path_identity.len() as u64).to_le_bytes());
digest.update(path_identity);
digest.update((project_id.len() as u64).to_le_bytes());
digest.update(project_id);
format!("{:x}", digest.finalize())
}
pub(crate) async fn direct_game_creator_codex_chat_at_with_optional_observer(
root: &std::path::Path,
system_prompt: String,
@@ -3746,7 +3783,6 @@ pub(crate) async fn direct_game_creator_codex_chat_at_with_optional_observer(
client_turn_id: Option<&str>,
observer: Option<&mut (dyn FnMut(DirectCodexTurnObservation) + Send)>,
audit: Option<&mut DirectCodexTurnAudit>,
direct_user_item: Option<serde_json::Value>,
) -> Result<String, String> {
// Resolve project authority before deriving the pool/thread identity. A
// caller may hold a stable symlink path whose target changes between
@@ -3810,7 +3846,6 @@ pub(crate) async fn direct_game_creator_codex_chat_at_with_optional_observer(
request,
Some(&codex_root),
effective_client_turn_id,
direct_user_item.as_ref(),
None,
observer,
audit,
@@ -1,32 +0,0 @@
//! DirectProject 历史注入载荷的单一构造 seam。
//!
//! 历史读取与大小前置校验集中在这里;调用方只负责线程生命周期与 RPC 传输。
use super::super::*;
use super::direct_project_history_injection_oversize_error;
use serde_json::Value;
use std::path::Path;
pub(super) fn build_direct_project_history_injection_params(
history_root: &Path,
thread_id: &str,
) -> Result<Value, platform_llm::LlmError> {
let canonical_items = read_direct_project_history_items_at(history_root)
.map_err(platform_llm::LlmError::InvalidRequest)?;
let items = canonical_items
.iter()
.map(|item| {
direct_codex_user_item_to_response_item(history_root, item)
.map_err(platform_llm::LlmError::InvalidRequest)
})
.collect::<Result<Vec<_>, _>>()?;
let params = serde_json::json!({"threadId": thread_id, "items": items});
let payload_bytes = serde_json::to_vec(&params)
.map(|bytes| bytes.len().saturating_add(1))
.unwrap_or(usize::MAX);
// 注入前的前置校验:失败关闭并指名 itemId 与字节数,**不截断、不摘要、不改写**。
if let Some(error) = direct_project_history_injection_oversize_error(&params, payload_bytes) {
return Err(platform_llm::LlmError::InvalidRequest(error));
}
Ok(params)
}
@@ -1,50 +0,0 @@
//! DirectProject 线程池身份的 canonical 解析与摘要。
use super::super::*;
use sha2::{Digest, Sha256};
pub(super) fn direct_codex_canonical_project_identity(
root: &std::path::Path,
) -> Result<(std::path::PathBuf, String), String> {
let (canonical_root, _) = resolve_direct_codex_project_authority(root)?;
let manifest = read_manifest(&canonical_root.join(".agent/manifest.json"))
.map_err(|error| format!("读取 DirectProject 权威项目身份失败:{error}"))?;
let manifest_project_id = manifest.project_id.trim();
if manifest_project_id.is_empty() || manifest_project_id.chars().count() > 256 {
return Err("DirectProject manifest.projectId 不满足身份边界".to_string());
}
let path_identity = direct_codex_os_path_identity_bytes(&canonical_root);
Ok((
canonical_root,
direct_codex_project_identity_digest(&path_identity, manifest_project_id.as_bytes()),
))
}
fn direct_codex_os_path_identity_bytes(path: &std::path::Path) -> Vec<u8> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
return path.as_os_str().as_bytes().to_vec();
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let mut bytes = Vec::new();
for unit in path.as_os_str().encode_wide() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
return bytes;
}
#[cfg(not(any(unix, windows)))]
path.as_os_str().to_string_lossy().as_bytes().to_vec()
}
fn direct_codex_project_identity_digest(path_identity: &[u8], project_id: &[u8]) -> String {
let mut digest = Sha256::new();
digest.update(b"genarrative-direct-project-identity.v1\0");
digest.update((path_identity.len() as u64).to_le_bytes());
digest.update(path_identity);
digest.update((project_id.len() as u64).to_le_bytes());
digest.update(project_id);
format!("{:x}", digest.finalize())
}
@@ -589,7 +589,6 @@ fn parse_game_creator_codex_cli_response(
} else {
String::new()
},
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id,
usage,
@@ -49,18 +49,6 @@ pub(crate) struct DesignView {
messages: Vec<DesignMessage>,
running: bool,
can_retry: bool,
#[serde(skip_serializing_if = "Option::is_none")]
reasoning_text: Option<String>,
reasoning_entries: Vec<DesignReasoningEntry>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DesignReasoningEntry {
id: String,
text: String,
#[serde(skip_serializing_if = "Option::is_none")]
message_id: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
@@ -77,7 +65,6 @@ pub(crate) struct DesignEvent {
}
fn design_view(session: &DesignSession, running: bool) -> DesignView {
let reasoning_entries = persisted_design_reasoning_entries(session);
DesignView {
session: DesignSessionSummary {
session_id: session.session_id.clone(),
@@ -95,124 +82,9 @@ fn design_view(session: &DesignSession, running: bool) -> DesignView {
&& session.turn.as_ref().is_some_and(|turn| turn.pending)
&& session.pending_approval.is_none()
&& session.pending_clarification.is_none(),
reasoning_text: reasoning_entries.last().map(|entry| entry.text.clone()),
reasoning_entries,
}
}
fn reasoning_text_from_history_item(item: &Value) -> Option<String> {
if item.get("type").and_then(Value::as_str) != Some("reasoning") {
return None;
}
let mut text = String::new();
if let Some(summary) = item.get("summary").and_then(Value::as_array) {
for part in summary {
if let Some(value) = part.get("text").and_then(Value::as_str) {
text.push_str(value.trim());
}
}
}
if let Some(content) = item.get("content").and_then(Value::as_array) {
for part in content {
let part_type = part.get("type").and_then(Value::as_str).unwrap_or_default();
if matches!(
part_type,
"reasoning" | "reasoning_content" | "reasoning_text" | "analysis" | "thinking"
) {
if let Some(value) = part.get("text").and_then(Value::as_str) {
text.push_str(value.trim());
}
}
}
}
(!text.trim().is_empty()).then_some(text)
}
fn persisted_design_reasoning_entries(session: &DesignSession) -> Vec<DesignReasoningEntry> {
// Responses history contains tool-only provider responses. Their reasoning is
// followed by function calls and only the next provider response may contain
// visible assistant text, so pairing on the next `message` item makes the
// earlier reasoning look like an orphan and moves it to the bottom of the UI.
// Both persisted streams retain user-turn boundaries; pair reasoning and
// visible assistant messages by their response order within each turn.
let mut assistant_groups: Vec<Vec<String>> = vec![Vec::new()];
for message in &session.messages {
if message.role == "user" {
assistant_groups.push(Vec::new());
} else if message.role == "assistant" {
assistant_groups
.last_mut()
.expect("assistant group always exists")
.push(message.id.clone());
}
}
let mut entries = Vec::new();
let mut group_index = 0;
let mut assistant_index = 0;
let mut sequence = 0_u64;
let mut current_reasoning = Vec::new();
let mut pending_reasoning = Vec::new();
let mut saw_response_output = false;
for item in &session.history {
if item.get("role").and_then(Value::as_str) == Some("user") {
if !pending_reasoning.is_empty() || !current_reasoning.is_empty() {
pending_reasoning.append(&mut current_reasoning);
}
group_index += 1;
assistant_index = 0;
saw_response_output = false;
continue;
}
if item.get("type").and_then(Value::as_str) == Some("reasoning") {
if saw_response_output {
pending_reasoning.append(&mut current_reasoning);
saw_response_output = false;
}
if let Some(text) = reasoning_text_from_history_item(item) {
sequence += 1;
current_reasoning.push(DesignReasoningEntry {
id: item
.get("id")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("reasoning-{sequence}")),
text,
message_id: None,
});
}
continue;
}
if item.get("role").and_then(Value::as_str) == Some("assistant")
|| item.get("type").and_then(Value::as_str) == Some("message")
{
pending_reasoning.extend(current_reasoning.drain(..));
let assistant_id = assistant_groups
.get(group_index)
.and_then(|ids| ids.get(assistant_index))
.cloned();
assistant_index += 1;
for mut entry in pending_reasoning.drain(..) {
entry.message_id = assistant_id.clone();
entries.push(entry);
}
saw_response_output = false;
} else if item.get("type").is_some() {
saw_response_output = true;
}
}
pending_reasoning.append(&mut current_reasoning);
let fallback_id = assistant_groups
.get(group_index)
.and_then(|ids| ids.last())
.cloned();
for mut entry in pending_reasoning {
entry.message_id = fallback_id.clone();
entries.push(entry);
}
entries
}
fn design_event(
root: &Path,
turn_id: &str,
@@ -232,17 +104,6 @@ fn design_event(
}
}
fn design_reasoning_event(
root: &Path,
turn_id: &str,
id: Option<&str>,
reasoning: String,
) -> DesignEvent {
let mut event = design_event(root, turn_id, "reasoning", id, None, None);
event.reasoning_text = Some(reasoning);
event
}
fn design_project_id(root: &Path) -> Result<String, String> {
validate_project_root(root)?;
Ok(read_existing_manifest_for_project(root)?.project_id)
@@ -601,7 +462,6 @@ fn build_design_request(
.with_tool_choice(platform_llm::LlmToolChoice::Auto)
.with_web_search(false);
apply_game_creator_llm_reasoning_effort(request, llm)
.map(|request| request.with_reasoning_capture(true))
}
// 调试队列只接收副本,写盘慢或失败时丢弃,不参与会话恢复。
@@ -688,15 +548,8 @@ async fn request_design_provider(
Some(String::new()),
None,
));
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
let result = if llm.stream {
let mut stream_sequence = 0_u64;
let mut emitted_reasoning = String::new();
client
.stream_run(request.clone(), |delta| {
stream_sequence = stream_sequence.saturating_add(1);
@@ -712,33 +565,18 @@ async fn request_design_provider(
"model": llm.model,
"deltaChars": delta.delta_text.chars().count(),
"accumulatedChars": delta.accumulated_text.chars().count(),
"reasoningDeltaChars": delta.reasoning_delta.chars().count(),
"reasoningAccumulatedChars": delta.accumulated_reasoning.chars().count(),
"deltaText": delta.delta_text,
"finishReason": delta.finish_reason,
}),
);
if !delta.delta_text.is_empty() || delta.finish_reason.is_some() {
emit(design_event(
root,
&turn_id,
"text",
Some(&message_id),
Some(delta.accumulated_text.clone()),
None,
));
}
if !delta.reasoning_delta.is_empty()
|| delta.accumulated_reasoning != emitted_reasoning
{
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
delta.accumulated_reasoning.clone(),
));
emitted_reasoning = delta.accumulated_reasoning.clone();
}
emit(design_event(
root,
&turn_id,
"text",
Some(&message_id),
Some(delta.accumulated_text.clone()),
None,
));
})
.await
} else {
@@ -746,14 +584,6 @@ async fn request_design_provider(
};
match result {
Ok(response) => {
if !response.reasoning.is_empty() {
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
response.reasoning.clone(),
));
}
design_debug(
root,
"response",
@@ -776,12 +606,6 @@ async fn request_design_provider(
|| game_creator_agent_runtime_transient_provider_error_kind(&error, false)
.is_none()
{
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
return Err(detail);
}
tokio::time::sleep(Duration::from_millis(
@@ -830,24 +654,8 @@ async fn request_scripted_design_provider(
Some(String::new()),
None,
));
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
match fake_provider::take() {
Some(Ok(response)) => {
if !response.reasoning.is_empty() {
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
response.reasoning.clone(),
));
}
return Ok(response);
}
Some(Ok(response)) => return Ok(response),
Some(Err(error)) => {
let detail = redact_agent_runtime_error(
root,
@@ -858,24 +666,10 @@ async fn request_scripted_design_provider(
|| game_creator_agent_runtime_transient_provider_error_kind(&error, false)
.is_none()
{
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
return Err(detail);
}
}
None => {
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
return Err("假 Provider 脚本耗尽".into());
}
None => return Err("假 Provider 脚本耗尽".into()),
}
}
unreachable!()
@@ -1146,9 +940,7 @@ pub(crate) fn set_design_agent_runtime_mode(
"design.runtime-mode",
)?;
if active_runtime.trim() == "game" {
if crate::assets::register_design_artifacts_at(root)? {
advance_agent_runtime_project_revision_locked(root)?;
}
crate::assets::register_design_artifacts_at(root)?;
}
write_design_runtime_mode(root, active_runtime.trim())
}
@@ -1384,38 +1176,6 @@ mod tests {
let error = ensure_design_runtime_active(root).expect_err("game mode must reject design");
assert!(error.contains("游戏运行态"));
}
#[test]
fn switching_to_game_pairs_design_artifact_registration_with_revision() {
let temporary = tempfile::tempdir().expect("create runtime mode root");
let root = temporary.path();
crate::project::init_local_game_project_at(root, "design-switch-test", "策划切换")
.expect("init project");
fs::create_dir_all(root.join("design_artifacts/project")).expect("create artifacts");
fs::write(root.join("design_artifacts/project/design.md"), "设计内容")
.expect("write artifact");
let before = read_game_creator_agent_runtime_project_revision(root)
.expect("read initial revision")
.revision;
assert_eq!(
set_design_agent_runtime_mode(root.to_string_lossy().into_owned(), "game".to_string(),)
.expect("switch to game")
.active_runtime,
"game"
);
let after = read_game_creator_agent_runtime_project_revision(root)
.expect("read committed revision")
.revision;
assert_eq!(after, before + 1);
set_design_agent_runtime_mode(root.to_string_lossy().into_owned(), "game".to_string())
.expect("repeat switch to game");
let repeated = read_game_creator_agent_runtime_project_revision(root)
.expect("read repeated revision")
.revision;
assert_eq!(repeated, after);
}
use serde_json::json;
use std::fs;
@@ -1525,7 +1285,6 @@ mod tests {
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: "fake-design".into(),
text: text.into(),
reasoning: String::new(),
finish_reason: Some(if calls.is_empty() {
"stop".into()
} else {
@@ -1586,110 +1345,6 @@ mod tests {
.clone()
}
#[test]
fn design_request_enables_reasoning_capture_only_for_design_runtime() {
let session = new_design_session("project", "quality");
let request = build_design_request(&session, &pack(), &GameCreatorLlmConfig::default())
.expect("design request");
assert!(request.capture_reasoning);
}
#[test]
fn persisted_reasoning_follows_response_order_across_tool_only_responses() {
let mut session = new_design_session("project", "quality");
session.messages = vec![
DesignMessage {
id: "turn:user".into(),
role: "user".into(),
text: "需求".into(),
},
DesignMessage {
id: "call-1:tool".into(),
role: "tool".into(),
text: "读取资源".into(),
},
DesignMessage {
id: "turn:response:0".into(),
role: "assistant".into(),
text: "给出方案".into(),
},
];
session.history = vec![
json!({"role":"user", "content":"需求"}),
json!({"type":"reasoning", "id":"r1", "content":[{"type":"reasoning_text", "text":"第一段思考"}]}),
json!({"type":"function_call", "call_id":"call-1", "name":"read_resource", "arguments":"{}"}),
json!({"type":"reasoning", "id":"r2", "content":[{"type":"reasoning_text", "text":"第二段思考"}]}),
json!({"type":"message", "role":"assistant", "content":[{"type":"output_text", "text":"给出方案"}]}),
];
let entries = persisted_design_reasoning_entries(&session);
assert_eq!(
entries
.iter()
.map(|entry| (entry.id.as_str(), entry.message_id.as_deref()))
.collect::<Vec<_>>(),
vec![
("r1", Some("turn:response:0")),
("r2", Some("turn:response:0")),
]
);
}
#[tokio::test(flavor = "current_thread")]
async fn scripted_design_provider_emits_reasoning_without_persisting_it() {
let (_temp, root, _resources) = init_design_project();
let mut session = new_design_session("design-fake", "quality");
begin_design_turn(&mut session, "turn-reasoning");
let mut response = fake_response("reasoning", "正文", Vec::new());
response.reasoning = "先分析需求,再组织方案。".into();
let _fake = fake_provider::install(vec![Ok(response)], 0);
let mut events = Vec::new();
let response =
request_scripted_design_provider(&root, &mut session, &mut |event| events.push(event))
.await
.expect("scripted provider");
let reasoning_events = events
.iter()
.filter_map(|event| event.reasoning_text.as_deref())
.collect::<Vec<_>>();
assert_eq!(reasoning_events, vec!["", "先分析需求,再组织方案。"]);
assert_eq!(response.text, "正文");
assert!(session.history.is_empty());
}
#[tokio::test(flavor = "current_thread")]
async fn scripted_design_provider_retry_clears_previous_reasoning_attempt() {
let (_temp, root, _resources) = init_design_project();
let mut session = new_design_session("design-fake", "quality");
begin_design_turn(&mut session, "turn-reasoning-retry");
let mut response = fake_response("reasoning-retry", "重试后的正文", Vec::new());
response.reasoning = "重试后的推理".into();
let _fake = fake_provider::install(
vec![
Err(platform_llm::LlmError::Upstream {
status_code: 503,
message: "busy".into(),
}),
Ok(response),
],
1,
);
let mut events = Vec::new();
let response =
request_scripted_design_provider(&root, &mut session, &mut |event| events.push(event))
.await
.expect("scripted retry provider");
let reasoning_events = events
.iter()
.filter_map(|event| event.reasoning_text.as_deref())
.collect::<Vec<_>>();
assert_eq!(reasoning_events, vec!["", "", "重试后的推理"]);
assert_eq!(response.text, "重试后的正文");
assert!(session.history.is_empty());
}
#[tokio::test(flavor = "current_thread")]
async fn fake_provider_walks_five_phases_and_enters_consultant() {
let (_temp, root, resources) = init_design_project();
@@ -0,0 +1,382 @@
use super::*;
pub(crate) const MAX_DIRECT_CODEX_REFERENCES: usize = 32;
const MAX_DIRECT_CODEX_REFERENCE_ID_CHARS: usize = 200;
const MAX_DIRECT_CODEX_REFERENCE_LABEL_CHARS: usize = 160;
const MAX_DIRECT_CODEX_REFERENCE_SOURCE_CHARS: usize = 32;
const MAX_DIRECT_CODEX_REFERENCE_ELEMENT_CHARS: usize = 80;
const MAX_DIRECT_CODEX_REFERENCE_TEXT_CHARS: usize = 240;
const DIRECT_CODEX_REFERENCE_HEADER: &str =
"[本轮用户引用素材:以下均为当前项目已确认的安全引用。请使用稳定资源 ID 和项目相对路径读取,不要读取或输出其它路径。]";
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
pub(crate) enum DirectCodexTurnReference {
#[serde(rename = "resource")]
Resource(DirectCodexResourceReference),
#[serde(rename = "runtime-region")]
RuntimeRegion(DirectCodexRuntimeRegionReference),
}
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DirectCodexResourceReference {
pub(crate) resource_id: String,
#[serde(default)]
pub(crate) label: Option<String>,
#[serde(default)]
pub(crate) source: Option<String>,
}
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DirectCodexRuntimeRegionReference {
#[serde(default)]
pub(crate) label: Option<String>,
#[serde(default)]
pub(crate) run_id: Option<String>,
#[serde(default)]
pub(crate) version_id: Option<String>,
#[serde(default)]
pub(crate) element_tag: Option<String>,
#[serde(default)]
pub(crate) element_role: Option<String>,
#[serde(default)]
pub(crate) text: Option<String>,
#[serde(default)]
pub(crate) width: Option<f64>,
#[serde(default)]
pub(crate) height: Option<f64>,
#[serde(default)]
pub(crate) resource_ids: Vec<String>,
}
fn sanitize_reference_text(value: &str, max_chars: usize) -> Option<String> {
let sanitized = value
.trim()
.chars()
.filter(|character| !character.is_control())
.take(max_chars)
.collect::<String>();
if sanitized.is_empty() {
None
} else {
Some(sanitized)
}
}
fn sanitize_reference_label(value: Option<&str>) -> Option<String> {
value.and_then(|value| sanitize_reference_text(value, MAX_DIRECT_CODEX_REFERENCE_LABEL_CHARS))
}
fn sanitize_reference_source(value: Option<&str>) -> Option<String> {
let value = sanitize_reference_text(value?, MAX_DIRECT_CODEX_REFERENCE_SOURCE_CHARS)?;
if value
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.'))
{
Some(value)
} else {
None
}
}
fn sanitize_reference_element(value: Option<&str>) -> Option<String> {
let value = sanitize_reference_text(value?, MAX_DIRECT_CODEX_REFERENCE_ELEMENT_CHARS)?;
if value
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.'))
{
Some(value)
} else {
None
}
}
fn sanitize_reference_dimension(value: Option<f64>) -> Option<u32> {
value
.filter(|value| value.is_finite() && *value > 0.0)
.map(|value| value.round().clamp(1.0, 100_000.0) as u32)
}
fn asset_display_label(asset: &GameCreationAppAssetManifestEntry) -> String {
let basename = asset
.local_path
.rsplit(['/', '\\'])
.next()
.unwrap_or(&asset.id);
let without_extension = basename
.rsplit_once('.')
.map(|(name, _)| name)
.unwrap_or(basename)
.trim();
if without_extension.is_empty() {
asset.id.clone()
} else {
without_extension
.chars()
.filter(|character| !character.is_control())
.take(MAX_DIRECT_CODEX_REFERENCE_LABEL_CHARS)
.collect()
}
}
fn validate_resource_reference_id(value: &str) -> Result<String, String> {
let resource_id = value.trim();
if resource_id.is_empty()
|| resource_id.chars().count() > MAX_DIRECT_CODEX_REFERENCE_ID_CHARS
|| resource_id.chars().any(char::is_control)
{
return Err("引用的素材 ID 无效,请移除后重新选择".to_string());
}
Ok(resource_id.to_string())
}
fn render_resource_reference_line(
manifest: &GameCreationAppManifest,
reference: &DirectCodexResourceReference,
) -> Result<String, String> {
let resource_id = validate_resource_reference_id(&reference.resource_id)?;
let asset = manifest
.assets
.iter()
.find(|asset| asset.id == resource_id)
.ok_or_else(|| "引用的素材已不存在,请移除后重新选择".to_string())?;
let local_path = sanitize_attachment_local_path(&asset.local_path)
.ok_or_else(|| "引用的素材路径无效,请移除后重新选择".to_string())?;
let label = sanitize_reference_label(reference.label.as_deref())
.unwrap_or_else(|| asset_display_label(asset));
let source = sanitize_reference_source(reference.source.as_deref())
.unwrap_or_else(|| "unknown".to_string());
Ok(format!(
"- 素材 ID{resource_id};名称:{label};类型:{};媒体类型:{};项目路径:{local_path};来源:{source}",
asset.kind, asset.media_type
))
}
fn render_runtime_region_reference_line(
manifest: &GameCreationAppManifest,
reference: &DirectCodexRuntimeRegionReference,
) -> Result<String, String> {
let label = sanitize_reference_label(reference.label.as_deref())
.unwrap_or_else(|| "运行画面区域".to_string());
let run_id = sanitize_reference_source(reference.run_id.as_deref());
let version_id = sanitize_reference_source(reference.version_id.as_deref());
let element_tag = sanitize_reference_element(reference.element_tag.as_deref());
let element_role = sanitize_reference_element(reference.element_role.as_deref());
let text = reference
.text
.as_deref()
.and_then(|value| sanitize_reference_text(value, MAX_DIRECT_CODEX_REFERENCE_TEXT_CHARS));
let width = sanitize_reference_dimension(reference.width);
let height = sanitize_reference_dimension(reference.height);
// `resourceIds` 是本模块唯一由客户端直接给出、且自身还是一条列表的字段:条数不设界时,
// 每个 id 都要扫一遍 manifestO(assets)),注入提示词的 `关联素材 ID:…` 行也会跟着无界
// 变长(最终只被 32 MiB 写入护栏拦下,变成一条和原因无关的连接级错误)。这里按模块的
// 失败关闭口径直接拒绝超限,而不是静默丢掉用户选中的关联。
if reference.resource_ids.len() > MAX_DIRECT_CODEX_REFERENCES {
return Err(format!(
"运行画面区域一次最多关联 {MAX_DIRECT_CODEX_REFERENCES} 个素材,请重新点选"
));
}
let mut related_resource_ids = Vec::new();
for resource_id in &reference.resource_ids {
let resource_id = validate_resource_reference_id(resource_id)?;
if !manifest.assets.iter().any(|asset| asset.id == resource_id) {
return Err("运行画面引用的素材已变化,请重新点选".to_string());
}
// 去重:同一个 id 在注入提示词里重复出现没有信息量,只是把行撑长。
// 条数已按上限收口,所以这里的逐项比较不会退化成大面积二次扫描。
if !related_resource_ids.contains(&resource_id) {
related_resource_ids.push(resource_id);
}
}
let mut parts = vec![format!("名称:{label}")];
if let Some(run_id) = run_id {
parts.push(format!("运行标识:{run_id}"));
}
if let Some(version_id) = version_id {
parts.push(format!("版本标识:{version_id}"));
}
if let Some(element_tag) = element_tag {
parts.push(format!("元素:{element_tag}"));
}
if let Some(element_role) = element_role {
parts.push(format!("角色:{element_role}"));
}
if let Some(text) = text {
parts.push(format!("文本摘要:{text}"));
}
if let (Some(width), Some(height)) = (width, height) {
parts.push(format!("尺寸:{width}x{height}"));
}
if !related_resource_ids.is_empty() {
parts.push(format!("关联素材 ID{}", related_resource_ids.join(",")));
}
Ok(format!("- 运行画面区域:{}", parts.join("")))
}
pub(crate) fn render_direct_codex_references_section(
root: &Path,
references: &[DirectCodexTurnReference],
) -> Result<Option<String>, String> {
if references.is_empty() {
return Ok(None);
}
if references.len() > MAX_DIRECT_CODEX_REFERENCES {
return Err(format!("一次最多引用 {MAX_DIRECT_CODEX_REFERENCES} 个素材"));
}
let manifest = read_manifest_for_project(root)?;
let mut lines = Vec::with_capacity(references.len());
for reference in references {
lines.push(match reference {
DirectCodexTurnReference::Resource(reference) => {
render_resource_reference_line(&manifest, reference)?
}
DirectCodexTurnReference::RuntimeRegion(reference) => {
render_runtime_region_reference_line(&manifest, reference)?
}
});
}
Ok(Some(
std::iter::once(DIRECT_CODEX_REFERENCE_HEADER.to_string())
.chain(lines)
.collect::<Vec<_>>()
.join("\n"),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture_project() -> tempfile::TempDir {
let directory = tempfile::tempdir().expect("temp project");
let root = directory.path();
std::fs::create_dir_all(root.join(".agent")).expect("create agent dir");
let mut manifest = new_game_creation_app_manifest("project-1", "测试项目");
manifest.assets.push(GameCreationAppAssetManifestEntry {
id: "asset-hero".to_string(),
kind: "character".to_string(),
media_type: "image/png".to_string(),
local_path: "assets/hero.png".to_string(),
source: GameCreationAppAssetSource {
kind: GameCreationAppAssetSourceKind::Uploaded,
canvas_project_id: None,
resource_id: None,
asset_object_id: None,
task_id: None,
prompt: None,
model: None,
generation_route: None,
generation_kind: None,
reference_resource_ids: Vec::new(),
},
image_sequence_frames: None,
image_sequence_duration_ms: None,
category: game_creation_app_asset_category_for_kind("character"),
tags: Vec::new(),
});
write_manifest(&root.join(".agent/manifest.json"), &manifest).expect("write manifest");
directory
}
#[test]
fn resource_reference_uses_manifest_identity_and_never_accepts_client_paths() {
let project = fixture_project();
let reference: DirectCodexTurnReference = serde_json::from_str(
r#"{"type":"resource","resourceId":"asset-hero","label":"主角","source":"asset-picker","localPath":"C:\\secret.png"}"#,
)
.expect("reference json");
let section = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&reference),
)
.expect("render")
.expect("section");
assert!(section.contains("素材 IDasset-hero"));
assert!(section.contains("名称:主角"));
assert!(section.contains("项目路径:assets/hero.png"));
assert!(!section.contains("C:\\secret.png"));
}
#[test]
fn deleted_resource_fails_closed() {
let project = fixture_project();
let reference: DirectCodexTurnReference = serde_json::from_str(
r#"{"type":"resource","resourceId":"asset-missing","label":"不存在"}"#,
)
.expect("reference json");
let error = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&reference),
)
.expect_err("missing resource");
assert_eq!(error, "引用的素材已不存在,请移除后重新选择");
}
#[test]
fn runtime_region_keeps_only_safe_summary_and_existing_resource_ids() {
let project = fixture_project();
let reference: DirectCodexTurnReference = serde_json::from_str(
r#"{"type":"runtime-region","label":"开始按钮","runId":"run-1","elementTag":"button","elementRole":"button","text":"开始游戏","width":120.4,"height":40.2,"resourceIds":["asset-hero"],"html":"<button onclick=secret>"}"#,
)
.expect("reference json");
let section = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&reference),
)
.expect("render")
.expect("section");
assert!(section.contains("运行画面区域:名称:开始按钮"));
assert!(section.contains("文本摘要:开始游戏"));
assert!(section.contains("尺寸:120x40"));
assert!(section.contains("关联素材 IDasset-hero"));
assert!(!section.contains("onclick"));
assert!(!section.contains("secret"));
}
#[test]
fn runtime_region_dedupes_and_bounds_related_resource_ids() {
let project = fixture_project();
// 同一个 id 重复出现只应产生一条关联。
let duplicated: DirectCodexTurnReference = serde_json::from_str(
r#"{"type":"runtime-region","label":"开始按钮","resourceIds":["asset-hero","asset-hero"," asset-hero "],"text":"开始游戏"}"#,
)
.expect("reference json");
let section = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&duplicated),
)
.expect("render")
.expect("section");
assert!(
section.contains("关联素材 IDasset-hero\n")
|| section.trim_end().ends_with("关联素材 IDasset-hero"),
"{section}"
);
assert!(
!section.contains("asset-hero,"),
"重复 id 不得在注入提示词里重复出现:{section}"
);
// 超出上限直接失败关闭:不能按对方给的长度注入提示词。
let oversized_ids = (0..MAX_DIRECT_CODEX_REFERENCES + 1)
.map(|_| "\"asset-hero\"".to_string())
.collect::<Vec<_>>()
.join(",");
let oversized: DirectCodexTurnReference = serde_json::from_str(&format!(
r#"{{"type":"runtime-region","label":"开始按钮","resourceIds":[{oversized_ids}]}}"#
))
.expect("reference json");
let error = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&oversized),
)
.expect_err("oversized resource id list must fail closed");
assert!(error.contains("最多关联"), "{error}");
}
}
@@ -1,15 +0,0 @@
//! DirectProject user input 的 canonical Response item 深模块。
mod model;
mod validation;
mod wire;
pub(crate) use model::{
DirectCodexUserContentPart, DirectCodexUserItem, DirectCodexUserMessageItem,
DirectCodexUserRole, DirectCodexUserRuntimeRegionPart,
};
pub(crate) use validation::validate_direct_codex_user_item;
pub(crate) use wire::{
direct_codex_user_item_to_prompt, direct_codex_user_item_to_prompt_with_attachments,
direct_codex_user_item_to_response_item, direct_codex_user_item_to_wire_input,
};
@@ -1,118 +0,0 @@
use serde::{Deserialize, Serialize};
use ts_rs::TS;
/// DirectProject 本轮 user input 的唯一结构化入口。
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(tag = "type", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) enum DirectCodexUserItem {
#[serde(rename = "message")]
Message(DirectCodexUserMessageItem),
}
#[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 DirectCodexUserMessageItem {
pub(crate) role: DirectCodexUserRole,
pub(crate) content: Vec<DirectCodexUserContentPart>,
pub(crate) id: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) enum DirectCodexUserRole {
User,
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(tag = "type", rename_all_fields = "camelCase", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) enum DirectCodexUserContentPart {
#[serde(rename = "input_text")]
InputText { text: String },
#[serde(rename = "agc_resource_reference")]
AgcResourceReference { resource_id: String },
#[serde(rename = "agc_runtime_region_reference")]
AgcRuntimeRegionReference(DirectCodexUserRuntimeRegionPart),
}
#[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 DirectCodexUserRuntimeRegionPart {
pub(crate) label: String,
#[serde(default)]
pub(crate) run_id: Option<String>,
#[serde(default)]
pub(crate) version_id: Option<String>,
#[serde(default)]
pub(crate) element_tag: Option<String>,
#[serde(default)]
pub(crate) element_role: Option<String>,
#[serde(default)]
pub(crate) text: Option<String>,
#[serde(default)]
pub(crate) width: Option<f64>,
#[serde(default)]
pub(crate) height: Option<f64>,
#[serde(default)]
pub(crate) resource_ids: Vec<String>,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn resource_reference_serializes_with_only_camel_case_resource_id() {
let item = DirectCodexUserItem::Message(DirectCodexUserMessageItem {
role: DirectCodexUserRole::User,
content: vec![DirectCodexUserContentPart::AgcResourceReference {
resource_id: "asset-hero".to_string(),
}],
id: "turn-1".to_string(),
});
assert_eq!(
serde_json::to_value(item).expect("serialize user item"),
json!({
"type": "message",
"role": "user",
"content": [{
"type": "agc_resource_reference",
"resourceId": "asset-hero"
}],
"id": "turn-1"
})
);
}
#[test]
fn resource_reference_rejects_extra_identity_fields() {
let error = serde_json::from_value::<DirectCodexUserItem>(json!({
"type": "message",
"role": "user",
"content": [{
"type": "agc_resource_reference",
"resourceId": "asset-hero",
"label": "主角"
}],
"id": "turn-1"
}))
.expect_err("label must not be accepted on resource reference");
assert!(error.to_string().contains("unknown field"), "{error}");
}
#[test]
fn unknown_content_part_fails_closed() {
serde_json::from_value::<DirectCodexUserItem>(json!({
"type": "message",
"role": "user",
"content": [{"type": "future_part", "value": "x"}],
"id": "turn-1"
}))
.expect_err("unknown content part must fail closed");
}
}
@@ -1,96 +0,0 @@
use super::model::{
DirectCodexUserContentPart, DirectCodexUserItem, DirectCodexUserRole,
DirectCodexUserRuntimeRegionPart,
};
use crate::agent::{
read_manifest_for_project, sanitize_attachment_local_path, GameCreationAppManifest,
};
use std::path::Path;
pub(crate) const MAX_DIRECT_CODEX_REFERENCES: usize = 32;
pub(crate) fn validate_direct_codex_user_item(
root: &Path,
item: &DirectCodexUserItem,
) -> Result<GameCreationAppManifest, String> {
validate_direct_codex_user_item_with_empty_content(root, item, false)
}
pub(crate) fn validate_direct_codex_user_item_with_empty_content(
root: &Path,
item: &DirectCodexUserItem,
allow_empty_content: bool,
) -> Result<GameCreationAppManifest, String> {
let DirectCodexUserItem::Message(message) = item;
if !matches!(message.role, DirectCodexUserRole::User) {
return Err("DirectProject 只接受 user message item".to_string());
}
if message.id.trim().is_empty() {
return Err("DirectProject user item 缺少稳定 id".to_string());
}
if message.content.is_empty() && !allow_empty_content {
return Err("DirectProject user item content 不能为空".to_string());
}
let manifest = read_manifest_for_project(root)?;
let mut reference_count = 0usize;
for part in &message.content {
match part {
DirectCodexUserContentPart::InputText { text } => {
if text.trim().is_empty() {
return Err("DirectProject input_text 不能为空".to_string());
}
}
DirectCodexUserContentPart::AgcResourceReference { resource_id } => {
reference_count = reference_count.saturating_add(1);
validate_resource_id_and_manifest(&manifest, resource_id)?;
}
DirectCodexUserContentPart::AgcRuntimeRegionReference(reference) => {
reference_count = reference_count.saturating_add(1);
validate_runtime_region_reference(&manifest, reference)?;
}
}
}
if reference_count > MAX_DIRECT_CODEX_REFERENCES {
return Err(format!("一次最多引用 {MAX_DIRECT_CODEX_REFERENCES} 个素材"));
}
Ok(manifest)
}
pub(crate) fn validate_resource_id_and_manifest(
manifest: &GameCreationAppManifest,
resource_id: &str,
) -> Result<(), String> {
let resource_id = resource_id.trim();
if resource_id.is_empty()
|| resource_id.chars().count() > 200
|| resource_id.chars().any(char::is_control)
{
return Err("引用的素材 ID 无效,请移除后重新选择".to_string());
}
let asset = manifest
.assets
.iter()
.find(|asset| asset.id == resource_id)
.ok_or_else(|| "引用的素材已不存在,请移除后重新选择".to_string())?;
sanitize_attachment_local_path(&asset.local_path)
.ok_or_else(|| "引用的素材路径无效,请移除后重新选择".to_string())?;
Ok(())
}
fn validate_runtime_region_reference(
manifest: &GameCreationAppManifest,
reference: &DirectCodexUserRuntimeRegionPart,
) -> Result<(), String> {
if reference.label.trim().is_empty() {
return Err("运行画面区域缺少名称".to_string());
}
if reference.resource_ids.len() > MAX_DIRECT_CODEX_REFERENCES {
return Err(format!(
"运行画面区域一次最多关联 {MAX_DIRECT_CODEX_REFERENCES} 个素材"
));
}
for resource_id in &reference.resource_ids {
validate_resource_id_and_manifest(manifest, resource_id)?;
}
Ok(())
}
@@ -1,226 +0,0 @@
use super::model::{DirectCodexUserContentPart, DirectCodexUserItem};
use super::validation::{
validate_direct_codex_user_item, validate_direct_codex_user_item_with_empty_content,
};
use crate::agent::sanitize_attachment_local_path;
use serde_json::Value;
use std::path::Path;
/// 将历史中的 canonical user item 投影为 Codex `response_item` message。
/// 非 user message 的标准 Response item 原样返回;未知形状直接失败。
pub(crate) fn direct_codex_user_item_to_response_item(
root: &Path,
item: &Value,
) -> Result<Value, String> {
let is_user_message = item.get("type").and_then(Value::as_str) == Some("message")
&& item.get("role").and_then(Value::as_str) == Some("user");
if !is_user_message {
if item.get("type").and_then(Value::as_str).is_some() {
return Ok(item.clone());
}
return Err("DirectProject 历史 item 缺少 type,无法投影为 Codex item".to_string());
}
let canonical: DirectCodexUserItem = serde_json::from_value(item.clone())
.map_err(|error| format!("DirectProject user item 无法转换为 Codex item{error}"))?;
let content = direct_codex_user_item_to_response_content(root, &canonical)?;
let mut projected = serde_json::json!({
"type": "message",
"role": "user",
"content": content,
});
if let Some(id) = item.get("id").and_then(Value::as_str) {
projected["id"] = Value::String(id.to_string());
}
Ok(projected)
}
fn direct_codex_user_item_to_response_content(
root: &Path,
item: &DirectCodexUserItem,
) -> Result<Vec<Value>, String> {
let Value::Array(input) = direct_codex_user_item_to_wire_input(root, item)? else {
return Err("DirectProject user item wire content 不是数组".to_string());
};
input
.into_iter()
.map(|part| {
let text = part
.get("text")
.and_then(Value::as_str)
.ok_or_else(|| "DirectProject user item wire part 缺少 text".to_string())?;
Ok(serde_json::json!({ "type": "input_text", "text": text }))
})
.collect()
}
/// 将 canonical user item 转为 app-server `turn/start.input` 可接受的文本数组。
/// AGC 私有 part 只在这里投影为安全摘要,canonical item 本身不被修改。
pub(crate) fn direct_codex_user_item_to_wire_input(
root: &Path,
item: &DirectCodexUserItem,
) -> Result<Value, String> {
direct_codex_user_item_to_wire_input_with_empty_content(root, item, false)
}
fn direct_codex_user_item_to_wire_input_with_empty_content(
root: &Path,
item: &DirectCodexUserItem,
allow_empty_content: bool,
) -> Result<Value, String> {
let manifest = if allow_empty_content {
validate_direct_codex_user_item_with_empty_content(root, item, true)?
} else {
validate_direct_codex_user_item(root, item)?
};
let DirectCodexUserItem::Message(message) = item;
let mut input = Vec::with_capacity(message.content.len());
for part in &message.content {
let text = match part {
DirectCodexUserContentPart::InputText { text } => text.clone(),
DirectCodexUserContentPart::AgcResourceReference { resource_id } => {
let asset = manifest
.assets
.iter()
.find(|asset| asset.id == resource_id.trim())
.ok_or_else(|| "引用的素材已不存在,请移除后重新选择".to_string())?;
let path = sanitize_attachment_local_path(&asset.local_path)
.ok_or_else(|| "引用的素材路径无效,请移除后重新选择".to_string())?;
format!(
"[素材引用 resourceId={};项目路径={path}]",
resource_id.trim()
)
}
DirectCodexUserContentPart::AgcRuntimeRegionReference(reference) => {
let resources = reference
.resource_ids
.iter()
.map(|id| id.trim())
.collect::<Vec<_>>()
.join(",");
let mut summary = format!("[运行画面区域:名称={} ", reference.label.trim());
if let Some(run_id) = reference.run_id.as_deref() {
summary.push_str(&format!("运行标识={} ", run_id.trim()));
}
if let Some(role) = reference.element_role.as_deref() {
summary.push_str(&format!("角色={} ", role.trim()));
}
if let Some(text) = reference.text.as_deref() {
summary.push_str(&format!("文本={} ", text.trim()));
}
if !resources.is_empty() {
summary.push_str(&format!("关联素材={resources}"));
}
summary.push(']');
summary
}
};
input.push(serde_json::json!({ "type": "text", "text": text }));
}
Ok(Value::Array(input))
}
pub(crate) fn direct_codex_user_item_to_prompt(
root: &Path,
item: &DirectCodexUserItem,
) -> Result<String, String> {
let wire = direct_codex_user_item_to_wire_input(root, item)?;
wire.as_array()
.ok_or_else(|| "DirectProject user item wire input 不是数组".to_string())
.map(|parts| {
parts
.iter()
.filter_map(|part| part.get("text").and_then(Value::as_str))
.collect::<String>()
})
.and_then(|prompt| {
if prompt.trim().is_empty() {
Err("DirectProject user item 不能转换为空 prompt".to_string())
} else {
Ok(prompt)
}
})
}
pub(crate) fn direct_codex_user_item_to_prompt_with_attachments(
root: &Path,
item: &DirectCodexUserItem,
) -> Result<String, String> {
let wire = direct_codex_user_item_to_wire_input_with_empty_content(root, item, true)?;
wire.as_array()
.ok_or_else(|| "DirectProject user item wire input 不是数组".to_string())
.map(|parts| {
parts
.iter()
.filter_map(|part| part.get("text").and_then(Value::as_str))
.collect::<String>()
})
}
#[cfg(test)]
mod tests {
use super::super::model::{
DirectCodexUserItem, DirectCodexUserMessageItem, DirectCodexUserRole,
};
use super::{
direct_codex_user_item_to_prompt_with_attachments, direct_codex_user_item_to_response_item,
};
use serde_json::json;
use std::path::Path;
#[test]
fn standard_response_item_passes_through_without_agc_private_parts() {
let item = json!({
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "完成"}]
});
assert_eq!(
direct_codex_user_item_to_response_item(Path::new("/unused"), &item)
.expect("assistant response item should pass through"),
item
);
}
#[test]
fn response_item_projection_uses_input_text_not_turn_input_text() {
let root = tempfile::tempdir().expect("temp project");
crate::init_local_game_project_at(root.path(), "wire-test", "wire 投影测试")
.expect("init project");
let item = json!({
"type": "message",
"role": "user",
"id": "turn-1:user",
"content": [{"type": "input_text", "text": "你好"}]
});
let projected = direct_codex_user_item_to_response_item(root.path(), &item)
.expect("user response item should project");
assert_eq!(projected["content"][0]["type"], "input_text");
assert_ne!(projected["content"][0]["type"], "text");
}
#[test]
fn history_item_without_type_fails_closed() {
let error = direct_codex_user_item_to_response_item(
Path::new("/unused"),
&json!({"role": "assistant"}),
)
.expect_err("history item without type must fail");
assert!(error.contains("缺少 type"), "{error}");
}
#[test]
fn attachment_only_user_item_projects_to_an_empty_text_sidecar_prompt() {
let root = tempfile::tempdir().expect("temp project");
crate::init_local_game_project_at(root.path(), "attachment-only", "attachment-only");
let item = DirectCodexUserItem::Message(DirectCodexUserMessageItem {
role: DirectCodexUserRole::User,
content: vec![],
id: "turn-attachment-only:user".to_string(),
});
assert_eq!(
direct_codex_user_item_to_prompt_with_attachments(root.path(), &item)
.expect("empty canonical text is valid before attachment sidecar rendering"),
""
);
}
}
@@ -17,6 +17,9 @@ const DIRECT_PROJECT_HISTORY_SCAN_PROBE_FINISHED: usize = 1;
/// 写入侧与读取侧共用同一个信封类型:`project.jsonl` 由项目主对话与 DirectProject 共享,
/// 这个值一旦只在写入侧改动,读取侧就会把对方的行当成坏行,整份历史立刻读不出来。
pub(crate) const DIRECT_PROJECT_HISTORY_RECORD_TYPE: &str = "response_item";
/// 格式切换到 `response_item`#282)之前,DirectProject 主对话通过通用对话写入器
/// 落到同一份 `project.jsonl`,行形状是 `PersistedLocalConversationMessageRecord`。
const DIRECT_PROJECT_HISTORY_LEGACY_SCHEMA_VERSION: &str = "game-creator-conversation.v1";
const DIRECT_PROJECT_INTERNAL_CONTEXT_KINDS: &[&str] = &[
"host_skills.instructions",
"permissions.instructions",
@@ -177,22 +180,79 @@ fn direct_project_history_item_from_line(
Ok(Some(item))
}
/// 只接受 `response_item` 行信封;其它历史格式不提供迁移或 fallback,直接失败关闭。
/// 只接受两种行信封:`response_item`,以及白名单化的 legacy 行。返回 `None` 表示行已
/// 被识别、但不该进入 Codex 上下文(legacy 的 `tool` 行)。
/// 其余任何形状(含换了 `schemaVersion`、带 `type` 却不是 `response_item`、role 不在
/// legacy 写入器自己的角色集合内、content 不是非空字符串)都判定为损坏并失败关闭。
fn direct_project_history_item_from_parsed_line(
path: &Path,
parsed: &Value,
) -> Result<Option<Value>, String> {
if parsed.get("type").and_then(Value::as_str) != Some(DIRECT_PROJECT_HISTORY_RECORD_TYPE) {
return Err(format!(
"DirectProject 历史记录类型无效:{}",
path.display()
));
if parsed.get("type").and_then(Value::as_str) == Some(DIRECT_PROJECT_HISTORY_RECORD_TYPE) {
return parsed
.get("payload")
.cloned()
.map(Some)
.ok_or_else(|| format!("DirectProject 历史记录缺少 payload{}", path.display()));
}
parsed
.get("payload")
.cloned()
.map(Some)
.ok_or_else(|| format!("DirectProject 历史记录缺少 payload{}", path.display()))
direct_project_legacy_row(parsed)
.map(|row| row.message_item())
.ok_or_else(|| format!("DirectProject 历史记录类型无效:{}", path.display()))
}
/// 白名单化 legacy 行的投影结果。
enum DirectProjectLegacyRow {
/// user/assistant 行:投影成 message item 进入历史。
Message(Value),
/// 已识别但不可注入的行(`tool`):与 developer/system item 同样处理,不进 Codex
/// 上下文。legacy 行不是 Responses item`tool` 行无法还原成真正的工具 item,
/// 注入会造出假的工具消息;聊天投影本来也只展示 user/assistant。
NotChat,
}
impl DirectProjectLegacyRow {
fn message_item(self) -> Option<Value> {
match self {
DirectProjectLegacyRow::Message(item) => Some(item),
DirectProjectLegacyRow::NotChat => None,
}
}
}
/// 格式切换前的 legacy 行投影。存量用户项目的历史文件全是这种行,读取时投影成与
/// `direct_project_local_message_item` 同形状的 message item`role` 与 `content`
/// 原样保留(不 trim、不改写、不合并),未知字段忽略。
///
/// 角色白名单取的是 legacy 写入器自己的角色集合,也就是
/// `project/conversation.rs` 里 `matches!(role, "user" | "assistant" | "tool")` 这一
/// 条校验,所以「legacy 写入器能写出的行」被完整覆盖,不会有第三种角色漏进来;
/// 白名单之外的角色(手改文件、未来写入器)仍按损坏失败关闭。
fn direct_project_legacy_row(parsed: &Value) -> Option<DirectProjectLegacyRow> {
let object = parsed.as_object()?;
if object.contains_key("type")
|| object.get("schemaVersion").and_then(Value::as_str)
!= Some(DIRECT_PROJECT_HISTORY_LEGACY_SCHEMA_VERSION)
{
return None;
}
let role = object.get("role").and_then(Value::as_str)?;
if !matches!(role, "user" | "assistant" | "tool") {
return None;
}
let content = object.get("content").and_then(Value::as_str)?;
if content.is_empty() {
return None;
}
if role == "tool" {
return Some(DirectProjectLegacyRow::NotChat);
}
let message_id = object
.get("messageId")
.and_then(Value::as_str)
.filter(|message_id| !message_id.is_empty());
Some(DirectProjectLegacyRow::Message(
direct_project_message_item(role, content, message_id),
))
}
/// 测试专用探针:在"锁外幂等回扫"这一段的两端回调。
@@ -452,8 +512,8 @@ pub(crate) fn direct_project_local_message_item(
))
}
/// 本地补写与 Codex response item 共用同一种 Responses message item 形状;本地补写额外做
/// trim 校验,历史读取只接受 response_item envelope
/// 本地补写与 legacy 投影共用同一种 Responses message item 形状,两者的区别只在
/// 是否对入参做 trim 校验:本地补写走上面的校验,legacy 行按文件内容逐字节投影
fn direct_project_message_item(role: &str, content: &str, message_id: Option<&str>) -> Value {
let mut item = serde_json::json!({
"type": "message",
@@ -566,7 +626,7 @@ mod tests {
fn init_history_project(name: &str) -> tempfile::TempDir {
let root = tempfile::tempdir().expect("temp project");
crate::init_local_game_project_at(root.path(), name, "Response item 历史测试")
crate::init_local_game_project_at(root.path(), name, "历史格式兼容测试")
.expect("init project");
root
}
@@ -577,8 +637,9 @@ mod tests {
std::fs::write(&path, format!("{}\n", lines.join("\n"))).expect("write history fixture");
}
const LEGACY_USER_ROW: &str = r#"{"schemaVersion":"game-creator-conversation.v1","role":"user","content":"请创建菜单","agentId":null,"messageId":"direct-codex:turn-0001:user","updatedAt":1757000000}"#;
const LEGACY_ASSISTANT_ROW: &str = r#"{"schemaVersion":"game-creator-conversation.v1","role":"assistant","content":"已完成 第一行\n第二行 ","agentId":null,"updatedAt":1757000001}"#;
const RESPONSE_ITEM_ROW: &str = r#"{"type":"response_item","payload":{"type":"message","role":"user","id":"codex-item-2","content":[{"type":"input_text","text":"再加一个按钮"}]}}"#;
const RESPONSE_ASSISTANT_ROW: &str = r#"{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"已完成"}]}}"#;
/// 判据:争用类失败会被"有界退避重试"真的吃掉,最终把条目落一行。
///
@@ -587,7 +648,7 @@ mod tests {
#[test]
fn contention_failure_is_retried_with_bounded_backoff() {
let root = init_history_project("contention-retry");
write_history_lines(root.path(), &[RESPONSE_ITEM_ROW]);
write_history_lines(root.path(), &[LEGACY_USER_ROW]);
let marker = root
.path()
.join(".agent/runtime/test-fail-next-direct-project-history-append");
@@ -619,7 +680,7 @@ mod tests {
#[test]
fn contention_failure_beyond_the_backoff_budget_fails_closed() {
let root = init_history_project("contention-bounded");
write_history_lines(root.path(), &[RESPONSE_ITEM_ROW]);
write_history_lines(root.path(), &[LEGACY_USER_ROW]);
let marker = root
.path()
.join(".agent/runtime/test-fail-next-direct-project-history-append");
@@ -662,7 +723,7 @@ mod tests {
write_history_lines(
root.path(),
&[
RESPONSE_ITEM_ROW,
LEGACY_USER_ROW,
r#"{"schemaVersion":"game-creator"#,
RESPONSE_ITEM_ROW,
],
@@ -700,7 +761,7 @@ mod tests {
let root = init_history_project("scan-outside-lock");
write_history_lines(
root.path(),
&[RESPONSE_ITEM_ROW, RESPONSE_ITEM_ROW, RESPONSE_ASSISTANT_ROW],
&[LEGACY_USER_ROW, RESPONSE_ITEM_ROW, LEGACY_ASSISTANT_ROW],
);
let path = history_path(root.path());
let fired = Arc::new(AtomicBool::new(false));
@@ -744,7 +805,7 @@ mod tests {
#[test]
fn concurrent_append_after_the_out_of_lock_scan_still_prevents_a_duplicate_row() {
let root = init_history_project("scan-stale-state");
write_history_lines(root.path(), &[RESPONSE_ITEM_ROW]);
write_history_lines(root.path(), &[LEGACY_USER_ROW]);
let path = history_path(root.path());
let item = json!({
"type": "message",
@@ -784,7 +845,7 @@ mod tests {
#[test]
fn conflicting_item_id_still_fails_closed_with_the_scan_outside_the_lock() {
let root = init_history_project("id-conflict-outside-lock");
write_history_lines(root.path(), &[RESPONSE_ITEM_ROW]);
write_history_lines(root.path(), &[LEGACY_USER_ROW]);
append_direct_project_history_item_at(
root.path(),
&json!({
@@ -972,13 +1033,97 @@ mod tests {
}
#[test]
fn non_response_item_history_fails_closed() {
fn legacy_conversation_rows_project_into_responses_message_items() {
let root = init_history_project("legacy-projection");
write_history_lines(root.path(), &[LEGACY_USER_ROW, LEGACY_ASSISTANT_ROW]);
let items = read_direct_project_history_items_at(root.path()).expect("read legacy history");
assert_eq!(
items,
vec![
json!({
"type": "message",
"role": "user",
"id": "direct-codex:turn-0001:user",
"content": [{"type": "input_text", "text": "请创建菜单"}],
}),
json!({
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "已完成 第一行\n第二行 "}],
}),
]
);
let chat = read_direct_project_chat_history_at(root.path()).expect("read legacy chat");
assert_eq!(chat.messages.len(), 2);
assert_eq!(chat.messages[0].role, "user");
assert_eq!(chat.messages[0].content, "请创建菜单");
assert_eq!(
chat.messages[0].message_id.as_deref(),
Some("direct-codex:turn-0001:user")
);
assert_eq!(chat.messages[1].role, "assistant");
assert_eq!(chat.messages[1].content, "已完成 第一行\n第二行 ");
assert_eq!(chat.messages[1].message_id, None);
}
#[test]
fn mixed_legacy_and_response_item_history_reads_in_file_order() {
let root = init_history_project("mixed-history");
write_history_lines(
root.path(),
&[LEGACY_USER_ROW, RESPONSE_ITEM_ROW, LEGACY_ASSISTANT_ROW],
);
let items = read_direct_project_history_items_at(root.path()).expect("read mixed history");
assert_eq!(
items
.iter()
.map(|item| item.get("id").and_then(Value::as_str))
.collect::<Vec<_>>(),
vec![
Some("direct-codex:turn-0001:user"),
Some("codex-item-2"),
None
]
);
assert_eq!(
items[1],
json!({
"type": "message",
"role": "user",
"id": "codex-item-2",
"content": [{"type": "input_text", "text": "再加一个按钮"}],
})
);
assert_eq!(
items[2]["content"][0]["text"],
json!("已完成 第一行\n第二行 ")
);
let chat = read_direct_project_chat_history_at(root.path()).expect("read mixed chat");
assert_eq!(
chat.messages
.iter()
.map(|message| (message.role.as_str(), message.content.as_str()))
.collect::<Vec<_>>(),
vec![
("user", "请创建菜单"),
("user", "再加一个按钮"),
("assistant", "已完成 第一行\n第二行 "),
]
);
}
#[test]
fn legacy_compat_keeps_unrecognized_rows_failing_closed() {
let unrecognized_rows = [
// 带 type 却不是 response_item
r#"{"type":"message","role":"user","content":[{"type":"input_text","text":"x"}]}"#,
// schema 不提供 fallback
// schemaVersion 不在白名单里
r#"{"schemaVersion":"game-creator-conversation.v2","role":"user","content":"x","agentId":null,"updatedAt":1}"#,
// 旧 schema 的其它角色也拒绝
// legacy 写入器角色集合之外的角色
r#"{"schemaVersion":"game-creator-conversation.v1","role":"system","content":"x","agentId":null,"updatedAt":1}"#,
r#"{"schemaVersion":"game-creator-conversation.v1","role":"developer","content":"x","agentId":null,"updatedAt":1}"#,
// content 不是字符串
@@ -1014,4 +1159,61 @@ mod tests {
.expect_err("broken json must fail closed");
assert!(error.starts_with("解析 DirectProject 历史失败"), "{error}");
}
#[test]
fn legacy_tool_row_is_recognized_but_stays_out_of_the_codex_context() {
let root = init_history_project("legacy-tool-row");
write_history_lines(
root.path(),
&[
LEGACY_USER_ROW,
r#"{"schemaVersion":"game-creator-conversation.v1","role":"tool","content":"{\"ok\":true}","agentId":null,"updatedAt":1757000002}"#,
LEGACY_ASSISTANT_ROW,
],
);
let items = read_direct_project_history_items_at(root.path()).expect("read history");
assert_eq!(
items
.iter()
.map(|item| item["role"].as_str().unwrap_or_default())
.collect::<Vec<_>>(),
vec!["user", "assistant"]
);
let chat = read_direct_project_chat_history_at(root.path()).expect("read chat");
assert_eq!(
chat.messages
.iter()
.map(|message| message.role.as_str())
.collect::<Vec<_>>(),
vec!["user", "assistant"]
);
}
#[test]
fn generic_writer_rows_are_covered_by_the_legacy_whitelist() {
let root = init_history_project("generic-writer-shape");
crate::append_local_conversation_message_at(
root.path(),
None,
crate::LocalConversationMessage {
role: "user".to_string(),
content: "通用写入器写的旧格式回合".to_string(),
agent_id: None,
},
)
.expect("append legacy row through the generic writer");
let items =
read_direct_project_history_items_at(root.path()).expect("read generic writer row");
assert_eq!(
items,
vec![json!({
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "通用写入器写的旧格式回合"}],
})]
);
}
}
@@ -6,9 +6,6 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
mod user_input;
pub(crate) use user_input::chat_with_game_creator_direct_codex;
const MAX_DIRECT_SYSTEM_PROMPT_CHARS: usize = 16 * 1024;
const MIN_DIRECT_CLIENT_TURN_ID_CHARS: usize = 6;
const MAX_DIRECT_CLIENT_TURN_ID_CHARS: usize = 160;
@@ -4058,7 +4055,6 @@ pub(crate) async fn run_direct_game_creator_turn_at_with_creation_type(
creation_type,
None,
None,
None,
)
.await
}
@@ -4069,7 +4065,6 @@ async fn run_direct_game_creator_turn_at_with_creation_type_and_emitter(
creation_type: Option<&str>,
turn_emitter: Option<&DirectGameCreatorTurnUpdateEmitter>,
audit: Option<&mut DirectCodexTurnAudit>,
direct_user_item: Option<serde_json::Value>,
) -> Result<String, String> {
if !root.is_absolute() || !root.is_dir() {
return Err("当前项目目录不存在或不是绝对路径".to_string());
@@ -4085,15 +4080,7 @@ async fn run_direct_game_creator_turn_at_with_creation_type_and_emitter(
if let Some(emitter) = turn_emitter {
emitter.emit("accepted", Some("request-accepted"), None);
}
match run_direct_game_creator_turn_inner(
root,
prompt,
creation_type,
turn_emitter,
audit,
direct_user_item,
)
.await
match run_direct_game_creator_turn_inner(root, prompt, creation_type, turn_emitter, audit).await
{
Ok(reply) => Ok(reply),
Err(failure) => {
@@ -4112,7 +4099,6 @@ async fn run_direct_game_creator_turn_inner(
creation_type: Option<&str>,
turn_emitter: Option<&DirectGameCreatorTurnUpdateEmitter>,
audit: Option<&mut DirectCodexTurnAudit>,
direct_user_item: Option<serde_json::Value>,
) -> Result<String, DirectCodexTurnFailure> {
emit_direct_game_creator_progress(root, "codex.turn", "陶泥儿正在处理这条消息");
if let Some(emitter) = turn_emitter {
@@ -4166,7 +4152,6 @@ async fn run_direct_game_creator_turn_inner(
Some(&client_turn_id),
Some(&mut observer),
audit,
direct_user_item,
)
.await
} else {
@@ -4177,7 +4162,6 @@ async fn run_direct_game_creator_turn_inner(
None,
None,
audit,
direct_user_item,
)
.await
}
@@ -4469,6 +4453,95 @@ async fn run_direct_game_creator_turn_with_private_editor_credentials(
))
}
fn normalize_direct_client_turn_id(client_turn_id: Option<&str>) -> Result<String, String> {
let Some(client_turn_id) = client_turn_id else {
return Err("Direct 客户端回合缺少稳定 clientTurnId,已拒绝创建可计费生成身份".to_string());
};
let client_turn_id = client_turn_id.trim();
let valid_length = (MIN_DIRECT_CLIENT_TURN_ID_CHARS..=MAX_DIRECT_CLIENT_TURN_ID_CHARS)
.contains(&client_turn_id.len());
let mut bytes = client_turn_id.bytes();
let valid_first = bytes
.next()
.is_some_and(|byte| byte.is_ascii_alphanumeric());
let valid_rest = bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-');
if !valid_length || !valid_first || !valid_rest {
return Err(format!(
"clientTurnId 必须为 {MIN_DIRECT_CLIENT_TURN_ID_CHARS} 到 {MAX_DIRECT_CLIENT_TURN_ID_CHARS} 位 ASCII 字母、数字或连字符,且首位必须为字母或数字"
));
}
Ok(client_turn_id.to_string())
}
#[tauri::command]
pub(crate) async fn chat_with_game_creator_direct_codex(
project_path: String,
prompt: String,
creation_type: Option<String>,
client_turn_id: Option<String>,
attachments: Option<Vec<DirectCodexTurnAttachment>>,
references: Option<Vec<DirectCodexTurnReference>>,
) -> Result<String, String> {
let root = Path::new(project_path.trim());
let turn_id = normalize_direct_client_turn_id(client_turn_id.as_deref())?;
let _active_invocation = DirectTaonierActiveInvocationGuard::enter(root, &turn_id)?;
recover_direct_taonier_regeneration_workflow_at(root).map_err(|error| {
redact_agent_runtime_error(root, &format!("恢复上一轮陶泥儿整包事务失败:{error}"), 500)
})?;
let turn_emitter = DirectGameCreatorTurnUpdateEmitter::new(root, turn_id.clone());
let mut audit = DirectCodexTurnAudit::start(
root,
&turn_id,
&prompt,
attachments.as_deref().unwrap_or_default(),
);
let attachments = attachments.unwrap_or_default();
let references = references.unwrap_or_default();
let mut user_prompt = match render_direct_codex_user_prompt(&prompt, &attachments) {
Ok(prompt) => prompt,
Err(_) if !references.is_empty() && prompt.trim().is_empty() => String::new(),
Err(error) => {
audit.finish(false);
return Err(error);
}
};
if let Some(reference_section) = match render_direct_codex_references_section(root, &references)
{
Ok(section) => section,
Err(error) => {
audit.finish(false);
return Err(error);
}
} {
if !user_prompt.trim().is_empty() {
user_prompt.push_str("\n\n");
}
user_prompt.push_str(&reference_section);
}
if user_prompt.trim().is_empty() {
audit.finish(false);
return Err("聊天内容不能为空".to_string());
}
let reply = match run_direct_game_creator_turn_at_with_creation_type_and_emitter(
root,
&user_prompt,
creation_type.as_deref(),
Some(&turn_emitter),
Some(&mut audit),
)
.await
{
Ok(reply) => reply,
Err(error) => {
audit.finish(false);
return Err(error);
}
};
audit.finish(true);
turn_emitter.emit("completed", Some("none"), Some(reply.clone()));
Ok(reply)
}
#[tauri::command]
pub(crate) async fn chat_with_game_creator_home_direct_codex(
prompt: String,
@@ -1,86 +0,0 @@
//! DirectProject 用户输入命令适配器。
//!
//! Tauri 只在这里接收前端 item,校验与 canonical→prompt 投影交给 user-item
//! 深模块,回合编排仍由父模块负责。
use super::*;
fn normalize_direct_client_turn_id(client_turn_id: Option<&str>) -> Result<String, String> {
let Some(client_turn_id) = client_turn_id else {
return Err("Direct 客户端回合缺少稳定 clientTurnId,已拒绝创建可计费生成身份".to_string());
};
let client_turn_id = client_turn_id.trim();
let valid_length = (MIN_DIRECT_CLIENT_TURN_ID_CHARS..=MAX_DIRECT_CLIENT_TURN_ID_CHARS)
.contains(&client_turn_id.len());
let mut bytes = client_turn_id.bytes();
let valid_first = bytes
.next()
.is_some_and(|byte| byte.is_ascii_alphanumeric());
let valid_rest = bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-');
if !valid_length || !valid_first || !valid_rest {
return Err(format!(
"clientTurnId 必须为 {MIN_DIRECT_CLIENT_TURN_ID_CHARS}{MAX_DIRECT_CLIENT_TURN_ID_CHARS} 位 ASCII 字母、数字或连字符,且首位必须为字母或数字"
));
}
Ok(client_turn_id.to_string())
}
#[tauri::command]
pub(crate) async fn chat_with_game_creator_direct_codex(
project_path: String,
prompt: String,
user_item: DirectCodexUserItem,
creation_type: Option<String>,
client_turn_id: Option<String>,
attachments: Option<Vec<DirectCodexTurnAttachment>>,
) -> Result<String, String> {
let root = Path::new(project_path.trim());
let turn_id = normalize_direct_client_turn_id(client_turn_id.as_deref())?;
let _active_invocation = DirectTaonierActiveInvocationGuard::enter(root, &turn_id)?;
recover_direct_taonier_regeneration_workflow_at(root).map_err(|error| {
redact_agent_runtime_error(root, &format!("恢复上一轮陶泥儿整包事务失败:{error}"), 500)
})?;
let turn_emitter = DirectGameCreatorTurnUpdateEmitter::new(root, turn_id.clone());
let mut audit = DirectCodexTurnAudit::start(
root,
&turn_id,
&prompt,
attachments.as_deref().unwrap_or_default(),
);
let attachments = attachments.unwrap_or_default();
let user_prompt = if attachments.is_empty() {
direct_codex_user_item_to_prompt(root, &user_item)
} else {
direct_codex_user_item_to_prompt_with_attachments(root, &user_item)
}
.map_err(|error| {
audit.finish(false);
error
})?;
let user_prompt =
render_direct_codex_user_prompt(&user_prompt, &attachments).map_err(|error| {
audit.finish(false);
error
})?;
let canonical_user_item =
Some(serde_json::to_value(user_item).map_err(|error| error.to_string())?);
let reply = match run_direct_game_creator_turn_at_with_creation_type_and_emitter(
root,
&user_prompt,
creation_type.as_deref(),
Some(&turn_emitter),
Some(&mut audit),
canonical_user_item,
)
.await
{
Ok(reply) => reply,
Err(error) => {
audit.finish(false);
return Err(error);
}
};
audit.finish(true);
turn_emitter.emit("completed", Some("none"), Some(reply.clone()));
Ok(reply)
}
File diff suppressed because it is too large Load Diff
@@ -1074,102 +1074,6 @@ pub(in crate::agent) fn remove_platform_art_generation_runtime_state_at(
}
}
/// 一次性兼容:升级前 standalone 槽身份只由 `{outputPath, requireSlices}` 派生,
/// 同一项目所有图片类生成共用一个槽;升级后槽身份按精确动作派生,路径随之变化。
///
/// 若旧槽路径上的账本仍然属于本次精确动作(`agentId` 与 `actionFingerprint` 都与
/// 当前上下文一致),就在项目写锁内把它迁移到新身份路径:保留原 `idempotencyKey`
/// 与 `operationId`,避免同一精确动作在升级后二次 POST 计费。旧账本属于其他动作时
/// 原样保留(不迁移、不删除、不阻塞),由对应动作自己的请求迁移。
///
/// 返回 `Ok(false)` 表示没有需要迁移的旧账本。任何身份无法安全解释的情形都失败关闭。
pub(super) fn adopt_legacy_standalone_platform_art_generation_runtime_state_at(
root: &Path,
context: &PlatformArtGenerationRuntimeContext,
legacy_run_id: &str,
) -> Result<bool, String> {
if !is_standalone_platform_art_generation_runtime_context(context)
|| legacy_run_id == context.run_id
|| !is_lowercase_sha256(legacy_run_id.strip_prefix("slot-").unwrap_or_default())
{
return Ok(false);
}
// 与账本创建互斥:迁移必须在同一把项目写锁内完成,否则两个调用可能同时把同一份
// 旧账本迁移到新路径,或与新建账本互相覆盖。
let _claim_lock = acquire_game_creator_agent_runtime_project_write_lock_with_wait(
root,
"canvas.asset_generate.runtime.claim",
)?;
if game_creator_agent_runtime_external_generation_exists(
root,
&context.agent_id,
&context.run_id,
) {
// 新身份账本已经存在:旧账本不属于本次动作的权威状态,保持两边各自的身份。
return Ok(false);
}
let legacy_relative_path =
platform_art_generation_runtime_relative_path(&context.agent_id, legacy_run_id);
let Some(legacy_state) =
read_agent_runtime_json_sidecar_with_max_bytes::<PlatformArtGenerationRuntimeState>(
root,
&legacy_relative_path,
"External Editor 生成账本",
PLATFORM_ART_GENERATION_RUNTIME_MAX_BYTES,
)?
else {
return Ok(false);
};
if legacy_state.agent_id != context.agent_id
|| legacy_state.run_id != legacy_run_id
|| legacy_state.action_fingerprint != context.action_fingerprint
{
// 旧槽里是另一个精确动作的账本:它仍归那个动作所有,本次调用不得消费、改写或删除它。
return Ok(false);
}
let legacy_identity = format!("{}:{legacy_run_id}", context.agent_id);
let legacy_context = PlatformArtGenerationRuntimeContext {
task_id: legacy_identity.clone(),
session_id: legacy_identity.clone(),
run_id: legacy_run_id.to_string(),
action_id: legacy_identity,
..context.clone()
};
let Some(mut migrated) = read_platform_art_generation_runtime_state(root, &legacy_context)?
else {
return Ok(false);
};
migrated.run_id = context.run_id.clone();
migrated.task_id = context.task_id.clone();
migrated.session_id = context.session_id.clone();
migrated.action_id = context.action_id.clone();
migrated.updated_at = unix_timestamp();
write_platform_art_generation_runtime_state(root, &migrated)?;
remove_platform_art_generation_runtime_state_at(root, &context.agent_id, legacy_run_id)?;
Ok(true)
}
#[cfg(test)]
pub(super) fn platform_art_generation_runtime_operation_id_for_test(
state: &PlatformArtGenerationRuntimeState,
) -> Option<&str> {
state.operation_id.as_deref()
}
#[cfg(test)]
pub(super) fn platform_art_generation_runtime_run_id_for_test(
state: &PlatformArtGenerationRuntimeState,
) -> &str {
&state.run_id
}
#[cfg(test)]
pub(super) fn platform_art_generation_runtime_action_fingerprint_for_test(
state: &PlatformArtGenerationRuntimeState,
) -> &str {
&state.action_fingerprint
}
#[cfg(test)]
pub(crate) fn write_platform_art_generation_runtime_accepted_for_test(
root: &Path,
@@ -409,8 +409,6 @@ where
(self.on_delta)(&platform_llm::LlmStreamDelta {
accumulated_text,
delta_text,
accumulated_reasoning: String::new(),
reasoning_delta: String::new(),
finish_reason,
});
}
@@ -501,7 +499,6 @@ mod tests {
provider: LlmProvider::OpenAiCompatible,
model: "interaction-test".to_string(),
text: text.to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: Some("interaction-response".to_string()),
usage: None,
@@ -115,7 +115,6 @@ fn persist_tool_plan_handoff_repair_chain(
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: llm.model.clone(),
text: text.to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: None,
usage: None,
@@ -147,8 +146,6 @@ fn stream_delta(delta_text: &str, accumulated_text: &str) -> platform_llm::LlmSt
platform_llm::LlmStreamDelta {
accumulated_text: accumulated_text.to_string(),
delta_text: delta_text.to_string(),
accumulated_reasoning: String::new(),
reasoning_delta: String::new(),
finish_reason: None,
}
}
@@ -1006,7 +1003,6 @@ async fn provider_handoff_identity_drift_closes_lifecycle_without_leaking_respon
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: old_llm.model.clone(),
text: private_response.to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: None,
usage: None,
@@ -1120,7 +1116,6 @@ async fn tool_plan_handoff_identity_drift_closes_entire_repair_chain_before_remo
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: old_llm.model.clone(),
text: text.to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: None,
usage: None,
@@ -1307,7 +1302,6 @@ async fn tool_plan_capacity_gate_runs_before_provider_lifecycle_and_network() {
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: llm.model.clone(),
text: format!("capacity response {loop_iteration}"),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: None,
usage: None,
@@ -1442,7 +1436,6 @@ async fn tool_plan_handoff_durable_control_closes_entire_repair_chain_before_rem
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: llm.model.clone(),
text: text.to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: None,
usage: None,
@@ -1559,7 +1552,6 @@ fn provider_recovery_cleanup_closes_tool_plan_lifecycle_before_removing_handoff(
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: llm.model.clone(),
text: "cleanup handoff".to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: None,
usage: None,
@@ -1631,7 +1623,6 @@ fn runtime_resume_scans_and_cleans_terminal_tool_plan_handoff() {
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: llm.model.clone(),
text: "terminal handoff".to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: None,
usage: None,
@@ -1727,7 +1718,6 @@ async fn provider_handoff_retry_conflict_preserves_both_sidecars_for_reconciliat
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: llm.model.clone(),
text: "已成功但尚未消费的回复".to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: None,
usage: None,
@@ -798,7 +798,6 @@ mod provider_reconciliation_diagnostic_tests {
let response = platform_llm::LlmRunResponse {
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: "test-model".to_string(),
reasoning: String::new(),
text: "C:\\private\\response".to_string(),
finish_reason: Some("completed".to_string()),
response_id: Some("response-1".to_string()),
File diff suppressed because it is too large Load Diff
@@ -604,10 +604,10 @@ pub(crate) fn register_local_asset_at(
register_local_asset_entry(root, local_path, kind, media_type, id_prefix, source)
}
pub(crate) fn register_design_artifacts_at(root: &Path) -> Result<bool, String> {
pub(crate) fn register_design_artifacts_at(root: &Path) -> Result<usize, String> {
let design_root = root.join("design_artifacts");
if !design_root.exists() {
return Ok(false);
return Ok(0);
}
let mut files = Vec::new();
let mut directories = vec![design_root];
@@ -630,7 +630,7 @@ pub(crate) fn register_design_artifacts_at(root: &Path) -> Result<bool, String>
}
}
files.sort();
let mut changed = false;
let mut registered = 0;
for path in files {
let relative = path
.strip_prefix(root)
@@ -644,7 +644,7 @@ pub(crate) fn register_design_artifacts_at(root: &Path) -> Result<bool, String>
Some("yaml" | "yml") => "text/yaml",
_ => "application/octet-stream",
};
let (_, asset_changed) = register_local_asset_entry_with_change(
register_local_asset_at(
root,
&relative,
"document",
@@ -663,9 +663,9 @@ pub(crate) fn register_design_artifacts_at(root: &Path) -> Result<bool, String>
reference_resource_ids: Vec::new(),
},
)?;
changed |= asset_changed;
registered += 1;
}
Ok(changed)
Ok(registered)
}
pub(crate) fn import_canvas_asset_at(
@@ -1876,18 +1876,6 @@ pub(crate) fn register_local_asset_entry(
id_prefix: &str,
source: GameCreationAppAssetSource,
) -> Result<UploadLocalAssetResult, String> {
register_local_asset_entry_with_change(root, local_path, kind, media_type, id_prefix, source)
.map(|(result, _)| result)
}
fn register_local_asset_entry_with_change(
root: &Path,
local_path: &str,
kind: &str,
media_type: &str,
id_prefix: &str,
source: GameCreationAppAssetSource,
) -> Result<(UploadLocalAssetResult, bool), String> {
let normalized_path = normalize_relative_path(local_path)?;
let absolute_path = resolve_local_project_path(root, &normalized_path)?;
let manifest_path = root.join(".agent/manifest.json");
@@ -1900,7 +1888,7 @@ fn register_local_asset_entry_with_change(
let mut source_for_record = source.clone();
source_for_record.prompt = None;
let (id, record_type, changed) = mutate_manifest_at(root, |manifest| {
let (id, record_type) = mutate_manifest_at(root, |manifest| {
if let Some(existing) = manifest
.assets
.iter_mut()
@@ -1910,16 +1898,13 @@ fn register_local_asset_entry_with_change(
// 而陈旧的非 unclassified 值会被读侧无条件信任(自愈只在落盘值是 unclassified
// 时才触发),于是这个资产永远停在错误栏目。
// kind 没变时刻意不动 category——落盘分类是权威值,同 kind 重登记不得抹掉它。
let changed = existing.kind != kind
|| existing.media_type != media_type
|| existing.source != source;
if existing.kind != kind {
existing.kind = kind.to_string();
existing.category = game_creation_app_asset_category_for_kind(kind);
}
existing.media_type = media_type.to_string();
existing.source = source;
Ok((existing.id.clone(), "asset.update", changed))
Ok((existing.id.clone(), "asset.update"))
} else {
let id = format!(
"{id_prefix}-{}-{}",
@@ -1937,7 +1922,7 @@ fn register_local_asset_entry_with_change(
tags: Vec::new(),
source,
});
Ok((id, "asset.register", true))
Ok((id, "asset.register"))
}
})?;
append_agent_db_record(
@@ -1952,15 +1937,12 @@ fn register_local_asset_entry_with_change(
}),
)?;
Ok((
UploadLocalAssetResult {
id,
local_path: normalized_path.clone(),
absolute_path: absolute_path.to_string_lossy().into_owned(),
manifest_path: manifest_path.to_string_lossy().into_owned(),
},
changed,
))
Ok(UploadLocalAssetResult {
id,
local_path: normalized_path.clone(),
absolute_path: absolute_path.to_string_lossy().into_owned(),
manifest_path: manifest_path.to_string_lossy().into_owned(),
})
}
#[derive(Clone, Debug, Deserialize)]
@@ -2155,27 +2137,6 @@ mod tests {
use super::*;
use std::io::{Read, Write};
#[test]
fn design_artifact_registration_reports_only_real_manifest_changes() {
let temporary = tempfile::tempdir().expect("tempdir");
let root = temporary.path();
crate::project::init_local_game_project_at(root, "design-artifact-test", "策划产物登记")
.expect("init project");
fs::create_dir_all(root.join("design_artifacts/project")).expect("create artifacts");
fs::write(root.join("design_artifacts/project/design.md"), "设计内容")
.expect("write artifact");
assert!(register_design_artifacts_at(root).expect("register first time"));
assert_eq!(
read_existing_manifest_for_project(root)
.unwrap()
.assets
.len(),
1
);
assert!(!register_design_artifacts_at(root).expect("register idempotently"));
}
/// 画板导出推断出的 kind 必须已经是 canonical 值。
///
/// 这个值会被原样写进 manifest 并据以派生落盘 `category`;一旦写出非 canonical 值

Some files were not shown because too many files have changed in this diff Show More