From f31c1d456516fe3790262c93b53a0fa6bff20eed Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:12:18 +0800 Subject: [PATCH] Fix Codex 0.172 native team recovery and accounting --- apps/web/agentActions.ts | 24 ++++- scripts/codex-backend/README.md | 6 ++ scripts/codex-backend/agent-control.patch | 20 +++- scripts/mathematics/checkWestlakeProtocol.ts | 12 ++- scripts/test-codex-backend-delivery.ts | 93 +++++++++++++---- scripts/test-codex-backend.ts | 66 +++++++++++- src/runtime/codexSession.ts | 64 ++++++++---- src/runtime/formalizationRelay.ts | 42 +++++--- src/runtime/researchHarness.ts | 29 +++++- src/runtime/westlake.ts | 2 + src/solver/agentTeam.ts | 80 ++++++++++---- src/solver/agentTeamContext.ts | 1 + src/solver/agentTeamNative.ts | 69 ++++++++----- src/solver/proofWriter.ts | 8 ++ src/solver/research.ts | 30 ++++-- src/solver/run.ts | 24 +++-- tests/agentTeamNativeControl.test.ts | 82 +++++++++++++++ tests/agentTeamNativeLifecycle.test.ts | 103 ++++++++++++++++++- tests/agentTeamTransportFallback.test.ts | 40 ++++++- tests/codexSessionAgentControl.test.ts | 56 +++++++++- tests/codexSessionNativeMailbox.test.ts | 40 +++++-- tests/formalizationRelay.test.ts | 18 +++- tests/skillSolver.test.ts | 31 ++++++ tests/webAgentActions.test.ts | 14 +++ tests/webProviderFixture.test.ts | 4 +- tests/workflowHarness.test.ts | 21 +++- 26 files changed, 831 insertions(+), 148 deletions(-) diff --git a/apps/web/agentActions.ts b/apps/web/agentActions.ts index d29f3645..6d64968b 100644 --- a/apps/web/agentActions.ts +++ b/apps/web/agentActions.ts @@ -63,7 +63,15 @@ export function createAgentPathMask(context: AgentActionContext) { const statuses: Record = { inProgress: 'running', completed: 'done', failed: 'failed', declined: 'declined' }; // Streaming items start empty; only those that run for a while are worth a "running" row. -const startedKinds = new Set(['commandExecution', 'webSearch', 'mcpToolCall', 'dynamicToolCall', 'reasoning', 'agentMessage']); +const startedKinds = new Set(['commandExecution', 'webSearch', 'mcpToolCall', 'dynamicToolCall', 'reasoning', 'agentMessage', 'collabAgentToolCall']); +const collaborationTools = new Map([ + ['spawnAgent', 'spawn_agent'], ['sendInput', 'send_input'], ['resumeAgent', 'resume_agent'], ['wait', 'wait_agent'], + ['closeAgent', 'close_agent'], ['sendMessage', 'send_message'], ['followupTask', 'followup_task'], + ['interruptAgent', 'interrupt_agent'], ['listAgents', 'list_agents'], +]); +const subAgentActivities = new Map([ + ['started', 'agent_started'], ['interacted', 'agent_contacted'], ['interrupted', 'agent_interrupted'], ['completed', 'agent_turn_completed'], +]); /** The last JSON object a command printed; the Agent's tools end with their result on one line. */ function lastJson(output: string): Item | undefined { @@ -295,6 +303,20 @@ export function sanitizeAgentItem(phase: 'started' | 'completed', item: Item, co return { ...base, kind: 'tool', status: status(failed ? 'failed' : 'done'), tool: clip(server ? `${server}.${name}` : name, 200).text, ...(args && args !== '{}' && args !== 'null' ? { arguments: args } : {}), ...(count(item.durationMs) !== undefined ? { durationMs: count(item.durationMs) } : {}) }; } + case 'collabAgentToolCall': { + const tool = collaborationTools.get(string(item.tool) ?? ''); + if (!tool) return; + // Native thread ids and raw tool prompts are unnecessary for displaying the action. + return { ...base, kind: 'tool', tool: 'collaboration.' + tool, + status: item.status === 'interrupted' ? 'failed' : status('done') }; + } + case 'subAgentActivity': { + const activity = subAgentActivities.get(string(item.kind) ?? ''), agent = string(item.agentPath); + if (!activity) return; + // This is a lifecycle observation, with proof acceptance reported separately by Lean. + return { ...base, kind: 'tool', tool: 'collaboration.' + activity, status: 'done', + ...(agent ? { arguments: clip(shown(agent), limits.arguments).text } : {}) }; + } case 'imageView': return { ...base, kind: 'tool', status: 'done', tool: 'view_image', arguments: clip(mask(string(item.path) ?? '').text, limits.arguments).text }; case 'contextCompaction': return { ...base, kind: 'compaction', status: 'done' }; // User messages and hook prompts are the host's instructions to the Agent, not something the Agent did. diff --git a/scripts/codex-backend/README.md b/scripts/codex-backend/README.md index 1e16249e..87652c44 100644 --- a/scripts/codex-backend/README.md +++ b/scripts/codex-backend/README.md @@ -71,6 +71,12 @@ not call a paid model or alter a running mathematical solve. Mathematical nominations, source freezing, Lean checks and adoption remain host operations; a native final answer does not create a proof delivery. +Pass `--team-capacity` to exercise eight writers with seven simultaneous member +requests. Pass `--large-fork` to verify that an oversized full-history fork +returns a tool error and Lead can retry with `fork_turns: "none"`. Pass +`--web-provider` to exercise proof delivery through the generated Web provider +profile, including metered requests before and after Lead cold resume. + The built runtime link installs this backend for new local CLI team runs. The Web worker Dockerfile builds the same pinned source on Debian Bookworm and installs a separate binary at `/opt/theoremos-codex-backend/codex`. diff --git a/scripts/codex-backend/agent-control.patch b/scripts/codex-backend/agent-control.patch index 39b01066..46db0540 100644 --- a/scripts/codex-backend/agent-control.patch +++ b/scripts/codex-backend/agent-control.patch @@ -589,10 +589,10 @@ index 7c9cded4..1dada718 100644 if let Some(token_usage_turn_id) = token_usage_turn_id { diff --git a/codex-rs/app-server/src/theoremos_agent_control.rs b/codex-rs/app-server/src/theoremos_agent_control.rs new file mode 100644 -index 00000000..dcad9fc4 +index 00000000..7917d178 --- /dev/null +++ b/codex-rs/app-server/src/theoremos_agent_control.rs -@@ -0,0 +1,860 @@ +@@ -0,0 +1,876 @@ +//! Opt-in stdio transport for the native AgentControl execution contract. +//! The model still invokes upstream collaboration handlers. The trusted host owns +//! isolated runtimes and durable membership; it is never a dynamic-tool facade. @@ -934,6 +934,22 @@ index 00000000..dcad9fc4 + let params = TheoremosAgentControlRequestParams { + value: json!({"version":1,"sessionId":self.session_id,"threadId":self.thread_id,"operationId":uuid::Uuid::now_v7().to_string(),"operation":operation,"payload":payload}), + }; ++ if operation == "spawn" { ++ // Match the host's stdio frame limit, reserving space for the ++ // request envelope and the maximum-width integer request ID. ++ const HOST_FRAME_BYTES: usize = 8 * 1024 * 1024; ++ const WIRE_OVERHEAD: usize = ++ br#"{"id":-9223372036854775808,"method":"theoremos/agentControl/request","params":}"# ++ .len(); ++ if serde_json::to_vec(¶ms).map_err(decode_error)?.len() + WIRE_OVERHEAD ++ > HOST_FRAME_BYTES ++ { ++ return Err(CodexErr::InvalidRequest( ++ "Native spawn exceeds the 8 MiB transport limit. Retry with fork_turns=none and a short assignment." ++ .into(), ++ )); ++ } ++ } + let (request_id, receiver) = bridge + .outgoing + .send_request(ServerRequestPayload::TheoremosAgentControlRequest(params)) diff --git a/scripts/mathematics/checkWestlakeProtocol.ts b/scripts/mathematics/checkWestlakeProtocol.ts index a86b225a..a8519419 100644 --- a/scripts/mathematics/checkWestlakeProtocol.ts +++ b/scripts/mathematics/checkWestlakeProtocol.ts @@ -227,7 +227,7 @@ async function checkScenario(executable: string, scenario: Scenario): Promise { incompleteSignals++; }, requestGate, onActivity: value => activities.push(`${value.event}:${value.itemType ?? ''}`) }); - assert.equal(session.usageSource, limited ? 'upstream-requests' : undefined, 'native_usage_source_mismatch'); + assert.equal(session.usageSource, limited ? 'upstream-requests' : 'native-thread-totals', 'native_usage_source_mismatch'); deadline = setTimeout(() => { void session?.close(); }, 45_000); const status = await session.run('Run the local protocol check and report its completion marker.', 'westlake-offline-protocol-check', workspace, () => {}); @@ -246,12 +246,16 @@ async function checkScenario(executable: string, scenario: Scenario): Promise(); - const result: Json = { status: 'running', paidModelCalls: 0 }; + const responseIds = new Map(), concurrentWriters = new Set(); + const writerPaths = ['/root', '/root/proof_writer', '/root/proof_observer']; + const result: Json = { status: 'running', paidModelCalls: 0, providerProfile: input.webProvider ? 'web' : 'cli' }; + const apiKey = 'synthetic-offline-key'; + const webRequest: WorkerInput = { id: 'offline-native-proof-delivery', + provider: { id: 'sub2api', name: 'Fixture gateway', baseUrl: 'http://host.docker.internal:8080/v1' }, + input: { apiKey, providerId: 'sub2api', model: 'deepseek-flash', effort: 'high', + task: 'Prove the frozen original using one checked child helper.', source: '', + workers: 1, coordination: 'independent', maxTurns: 0, maxRunSeconds: 0, + researchMode: 'skill', nativeTeamCapacity: writerPaths.length } }; const controller = new AbortController(); const signal = AbortSignal.any([input.signal, controller.signal]); const originalFetch = globalThis.fetch; const leadProcesses: HarnessProcessIdentity[] = []; + const webActions: WebAgentActionBody[] = []; let state: SolverRunState | undefined, sequence = 0; const quote = (value: string) => "'" + value.replace(/'/gu, "'\\''") + "'"; const call = (id: string, name: string, args: Json, namespace?: string) => ({ @@ -87,13 +100,17 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe const server = createServer(async (request, response) => { try { assert.equal(request.url, '/v1/responses'); + assert.equal(request.headers.authorization, 'Bearer ' + apiKey); const chunks: Buffer[] = []; for await (const chunk of request) chunks.push(Buffer.from(chunk)); const body = JSON.parse(Buffer.concat(chunks).toString()); admitResponsesRequest(body, 'deepseek-flash', 'high'); requests.push(body); + const expectedWriter = JSON.parse(body.client_metadata['x-codex-turn-metadata']).agent_name as string; + assert.ok(writerPaths.includes(expectedWriter), 'Native request must identify its writer.'); const text = body.input.filter((item: Json) => ['message', 'agent_message'].includes(item.type)) .flatMap((item: Json) => item.content ?? []).map((part: Json) => part.text ?? part.encrypted_content ?? '').join('\n'); const receipts = new Set(body.input.filter((item: Json) => item.type === 'function_call_output').map((item: Json) => item.call_id)); const childRequest = text.includes('Current native task instructions'); + assert.equal(childRequest, expectedWriter !== '/root'); const declarations = [...(body.tools ?? []), ...body.input.filter((item: Json) => item.type === 'additional_tools') .flatMap((item: Json) => item.tools)].flatMap((tool: Json) => tool.type === 'namespace' ? tool.tools : [tool]); const host = declarations.find((tool: Json) => tool.name === 'theoremos_team'); @@ -105,8 +122,21 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe 'Native host operations must stay limited to proof delivery, route management and inspection.'); assert.equal(body.tool_choice, 'auto', 'The host must not impose a collaboration decision.'); if (!childRequest && JSON.stringify(body.input).includes(finding)) result.nativeFindingReceived = true; + const overlap = expectedWriter === '/root' ? receipts.has('proof_spawn_observer') && !receipts.has('proof_draft') + : !responseIds.has(expectedWriter); + if (overlap) { + concurrentWriters.add(expectedWriter); + if (concurrentWriters.size === writerPaths.length) { + const records = [state!, ...state!.agentTeam!.workers]; + assert.deepEqual(records.map(record => record.requestUsageAccounting?.pendingRequests), [1, 1, 1], + 'The real Lead and both native members must be in flight through the relay at the same time.'); + result.simultaneousWriters = [...concurrentWriters].sort(); + } + if (!await until(() => concurrentWriters.size === writerPaths.length, response)) return; + } let items: Json[]; - if (childRequest) { + if (expectedWriter === '/root/proof_observer') items = [message('Read only review complete.')]; + else if (childRequest) { assert.deepEqual(state!.agentTeam!.workers[0]!.tasks[0]!.profileEvidence?.loaded, ['prover']); assert.match(text, /### Lean Prover/u, 'The corrected specialty must reach the actual writer request.'); for (const contradictoryHint of ['All agents share the same directory', @@ -141,6 +171,8 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe items = [call('proof_spawn', 'spawn_agent', { task_name: 'proof_writer', fork_turns: 'none', message: 'Profiles: prover\nProve an independent NativeProof.helper (n : Nat) : n + 0 = n in your owned file. Lead consumes it in NativeProof.original. Report the first useful result and submit the helper; leave the original target unfinished.' }, 'collaboration')]; } + else if (!receipts.has('proof_spawn_observer')) items = [call('proof_spawn_observer', 'spawn_agent', { + task_name: 'proof_observer', fork_turns: 'none', message: 'Inspect the frozen original independently. Return an advisory review without editing any files.' }, 'collaboration')]; else if (!receipts.has('proof_draft')) items = [call('proof_draft', 'exec_command', { login: false, cmd: 'printf %s ' + quote(consumerDraft) + ' > generated/problem/Submission.lean && printf %s ' + quote('The first conjunct calls the agreed helper. Lead owns the remaining conjunct.\n') + ' > RESEARCH.md' })]; @@ -174,6 +206,8 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe else items = [message('Original proof is saved.')]; const base = { id: 'resp_proof_' + ++sequence, object: 'response', created_at: 1, model: 'deepseek-flash', status: 'in_progress', output: [] }; + const ids = responseIds.get(expectedWriter) ?? []; + ids.push(base.id); responseIds.set(expectedWriter, ids); const emit = (value: Json) => response.write('event: ' + value.type + '\ndata: ' + JSON.stringify(value) + '\n\n'); response.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' }); emit({ type: 'response.created', response: base }); @@ -201,12 +235,13 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe }); try { await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - // Keep the production sub2api profile and request gate. Only its upstream + // Keep the production provider profile and request gate. Only its upstream // network destination is replaced; no request can reach a real provider. const endpoint = `http://127.0.0.1:${(server.address() as any).port}/v1/responses`; globalThis.fetch = (async (resource, options) => { const url = typeof resource === 'string' ? resource : resource instanceof URL ? resource.href : resource.url; - assert.equal(url, SUB2API_PROVIDER.baseUrl + '/responses', 'Only the fixed production relay endpoint may be requested.'); + assert.equal(url, (input.webProvider ? webRequest.provider.baseUrl : SUB2API_PROVIDER.baseUrl) + '/responses', + 'Only the fixed production relay endpoint may be requested.'); result.relayRequests = (result.relayRequests ?? 0) + 1; return originalFetch(endpoint, options); }) as typeof fetch; @@ -220,21 +255,25 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe state = { schema: 'deepscientist.math.solver.v1', runId: 'offline-native-proof-delivery', phase: 'prepared', problem, worktree, model: 'deepseek-flash', effort: 'high', turns: 0, taskDigest: mathDigest('proof-fixture'), buildDigest: 'fixture', environmentDigest: mathDigest('native-proof-delivery'), evaluatorDigest: 'fixture', researchMode: 'skill', - researchSkillWorkflow: 'full', researchSkill: identity, researchDelegation: { mode: 'team', maxAgents: 2 }, + researchSkillWorkflow: 'full', researchSkill: identity, researchDelegation: { mode: 'team', maxAgents: writerPaths.length }, agentTeam: { schema: 'theorem-os.agent-team.v1', transport: 'native-agent-control', workers: [], events: [], deliveries: [], adoptions: [], operations: [] } }; - const profile = path.join(directory, 'profile'); prepareSub2apiProfile(profile, state.model, state.effort); + const profile = path.join(directory, 'profile'); + if (input.webProvider) prepareWebProviderProfile(profile, webRequest); + else prepareSub2apiProfile(profile, state.model, state.effort); const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); assert.ok(fs.existsSync(path.join(toolchain, 'bin/lean')), 'Native delivery acceptance requires Lean 4.33.0.'); const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, ELAN_HOME: path.join(os.homedir(), '.elan'), LEAN_PATH: '', LEAN_SYSROOT: '', NO_PROXY: '127.0.0.1,localhost', - SUB2API_WESTLAKE_API_KEY: 'synthetic-offline-key', DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', + ...(!input.webProvider && { SUB2API_WESTLAKE_API_KEY: apiKey }), DEEPSCIENTIST_MATH_SANDBOX_BACKEND: 'bwrap', DEEPSCIENTIST_MATH_ENV_FILE: path.join(directory, 'missing.env') }; + const modules = input.webProvider ? webSolverModules(webRequest, { sink: action => webActions.push(action), + hidden: [directory], solverRunId: () => state?.runId }) : directSolverModules; const winner = await runResearchWorkers({ state, root: runtime, buildFile, taskText: 'Prove NativeProof.original by consuming one independently checked child declaration.', - executable: input.executable, profile, modules: { ...directSolverModules, M1: { ...directSolverModules.M1, + executable: input.executable, profile, modules: { ...modules, M1: { ...modules.M1, open: async options => { - const session = await directSolverModules.M1.open(options); + const session = await modules.M1.open(options); if (options.workspace === worktree && session.processIdentity) { const previous = leadProcesses.at(-1); if (previous) assert.equal(confirmHarnessProcessStopped(previous).status, 'stopped', 'Previous Lead writer must stop before reopening.'); @@ -251,15 +290,33 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe writeMathJsonDurable(path.join(input.output, 'state.json'), state); }, emit: (event, details) => { events.push({ event, ...details }); } }); assert.equal(result.providerFailure, undefined); + if (input.webProvider) { + const toolActions = webActions.filter(action => action.kind === 'tool' && action.tool?.startsWith('collaboration.')); + assert.ok(toolActions.some(action => action.tool === 'collaboration.wait_agent' && action.status === 'running')); + assert.ok(toolActions.some(action => action.tool === 'collaboration.agent_started' && + action.arguments === '/root/proof_writer')); + result.webCollaborationActions = toolActions.length; + } assert.ok(result.childContextsChecked > 0); assert.equal(result.relayRequests, requests.length, 'Every upstream fixture request must cross the production relay.'); - const accounting = [state, ...state.agentTeam!.workers].map(record => record.requestUsageAccounting!); - for (const record of accounting) { - assert.ok(record, 'Each native writer must report production request accounting.'); - assert.equal(record.incomplete, false); assert.equal(record.pendingRequests, 0); - assert.equal(record.reportedRequests, record.startedRequests); - } - assert.equal(accounting.reduce((total, record) => total + record.reportedRequests, 0), requests.length); + const writerRecords = [state, ...state.agentTeam!.workers]; + assert.deepEqual(result.simultaneousWriters, [...writerPaths].sort()); + result.writerAccounting = writerRecords.map(record => { + const accounting = record.requestUsageAccounting!; + assert.ok(accounting, 'Each native writer must report production request accounting.'); + assert.equal(accounting.incomplete, false); assert.equal(accounting.pendingRequests, 0); + assert.equal(accounting.reportedRequests, accounting.startedRequests); + const writerPath = 'native' in record ? record.native!.agentPath : '/root'; + const taskId = 'tasks' in record ? record.tasks[0]!.id : undefined; + const threadId = 'native' in record ? record.native!.threadId : state!.agentTeam!.nativeControl!.rootThreadId; + const receipts = accounting.receipts!; + assert.deepEqual(receipts.map(receipt => receipt.providerRequestId).sort(), responseIds.get(writerPath)!.sort()); + assert.ok(receipts.every(receipt => receipt.threadId === threadId && receipt.taskId === taskId && receipt.status === 'reported')); + return { writer: writerPath, threadId, taskId, reportedRequests: accounting.reportedRequests }; + }); + assert.equal(result.writerAccounting.reduce((total: number, record: Json) => total + record.reportedRequests, 0), requests.length); + assert.equal(state.tokenBudget?.status, 'unlimited'); + assert.equal(state.tokenBudget?.reportedTotalTokens, requests.length * 12); assert.equal(winner?.check.passed, true, 'The original must pass independent production M2 checking.'); assert.equal(winner.check.verification.status, 'kernel_verified'); assert.deepEqual(winner.check.verification.results.map(item => item.theoremName), ['NativeProof.original']); @@ -300,7 +357,7 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe result.leadWriterProcesses = leadProcesses; result.originalCheck = { passed: winner.check.passed, status: winner.check.verification.status, commit: winner.check.commit, declarations: winner.check.verification.results.map(item => item.theoremName) }; - result.checks = ['production-relay', 'minimal-native-host-operations', 'native-role-context', 'pinned-skill-read', + result.checks = ['production-relay', 'simultaneous-writer-request-accounting', 'minimal-native-host-operations', 'native-role-context', 'pinned-skill-read', 'native-spawn', 'native-source-write', 'native-finding-message', 'native-wait', 'submit', 'writer-stop', 'adopted-host-mail', 'independent-helper-check', 'inspect', 'adopt', 'native-source-consumption', 'independent-original-check', 'final-s3-check', 'final-uses-one-of-two-adopted-declarations']; diff --git a/scripts/test-codex-backend.ts b/scripts/test-codex-backend.ts index 5eaf0a6d..3285d3e5 100644 --- a/scripts/test-codex-backend.ts +++ b/scripts/test-codex-backend.ts @@ -28,6 +28,8 @@ import { verifyNativeProofDelivery } from './test-codex-backend-delivery'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const flag = (name: string) => { const index = process.argv.indexOf(name); return index < 0 ? undefined : process.argv[index + 1]; }; const capacityTest = process.argv.includes('--team-capacity'); +const largeForkTest = process.argv.includes('--large-fork'); +assert.ok(!capacityTest || !largeForkTest, 'Select only one fixture mode.'); const maxAgents = capacityTest ? 8 : 3; const requestedExecutable = flag('--executable') ?? process.env.THEOREMOS_TEST_CODEX_EXECUTABLE ?? path.join(root, 'out/codex-backend/codex'); if (!fs.existsSync(requestedExecutable)) throw new Error('Native backend acceptance requires a real Codex binary. ' + @@ -61,6 +63,28 @@ const call = (id: string, name: string, args: unknown, namespace?: string) => ({ }); const nativeCall = (id: string, name: string, args: unknown) => call(id, name, args, 'collaboration'); +async function largeForkResponse(body: Record, text: string, mode: string) { + if (mode.includes('You are a member')) { + assert.match(text, /LARGE_FORK_FRESH_WORKER/u); + assert.doesNotMatch(text, /LARGE_FORK_HISTORY/u); + return [message('Fresh worker completed.')]; + } + if (!text.includes('LARGE_FORK_ACTION')) return [message('Stored a disposable history segment.')]; + const receipts = new Map(body.input.filter((item: any) => item.type === 'function_call_output') + .map((item: any) => [item.call_id, item.output])); + if (!receipts.has('oversized_fork')) return [nativeCall('oversized_fork', 'spawn_agent', { + task_name: 'large_fork', fork_turns: 'all', message: 'Try an oversized history transfer.' })]; + const rejection = receipts.get('oversized_fork')!; + assert.match(rejection, /exceeds the 8 MiB transport limit.*fork_turns=none/u); + if (!receipts.has('fresh_after_oversized_fork')) return [nativeCall('fresh_after_oversized_fork', 'spawn_agent', { + task_name: 'large_fork', fork_turns: 'none', message: 'LARGE_FORK_FRESH_WORKER Continue this disposable fixture.' })]; + assert.equal(JSON.parse(receipts.get('fresh_after_oversized_fork')!).task_name, '/root/large_fork'); + await until(() => !team!.hasActiveWorkers); + observations.largeFork = { rejection, leadThreadId: lead!.threadId, + workerStatus: state.agentTeam!.workers[0]?.tasks.at(-1)?.status }; + return [message('Lead finished after recovering from the oversized fork.')]; +} + const pendingMembers = new Set(); let releaseMembers = false; async function capacityResponse(body: Record, text: string, mode: string) { @@ -138,7 +162,7 @@ const server = createServer(async (request, response) => { // Exercise the production relay's contract against actual native requests, // including child message history. A permissive fixture server hid this boundary. admitResponsesRequest(body, 'deepseek-flash', 'high'); - requests.push(body); + requests.push(largeForkTest ? { bytes: chunks.reduce((total, chunk) => total + chunk.length, 0) } : body); const text = body.input.filter((item: any) => ['message', 'agent_message'].includes(item.type)) .flatMap((item: any) => item.content ?? []).map((part: any) => part.text ?? part.encrypted_content ?? '').join('\n'); let items: any[]; @@ -150,6 +174,7 @@ const server = createServer(async (request, response) => { 'The current native mode must honor the explicitly requested team.'); assert.equal(body.tool_choice, 'auto', 'Native collaboration must remain a model choice.'); if (capacityTest) return sendResponse(response, await capacityResponse(body, text, mode)); + if (largeForkTest) return sendResponse(response, await largeForkResponse(body, text, mode)); if (member) { assert.match(mode, /You are a member of an explicitly requested flat team\./u); assert.match(mode, /Do not spawn sub-agents or dispatch, redirect or interrupt other members\./u); @@ -210,7 +235,17 @@ const server = createServer(async (request, response) => { } else { // Resume and full-history forks retain prior tool calls. Advance the scripted // workflow only after the original tool's actual receipt is in history. - const receipts = new Set(body.input.filter((item: any) => item.type === 'function_call_output').map((item: any) => item.call_id)); + const receipts = new Map(body.input.filter((item: any) => item.type === 'function_call_output') + .map((item: any) => [item.call_id, item.output])); + if (!receipts.has('spawn_wrong_effort')) return sendResponse(response, [nativeCall('spawn_wrong_effort', 'spawn_agent', { + task_name: 'expert', message: 'This assignment should be rejected before a writer opens.', + fork_turns: 'none', reasoning_effort: 'low', + })]); + assert.match(receipts.get('spawn_wrong_effort')!, /math_team_native_run_config_frozen/u); + if (!receipts.has('spawn_fresh')) { + assert.equal(state.agentTeam!.workers.length, 0, 'Changing the frozen effort must not reserve a worker.'); + assert.equal(processes.size, 1, 'Changing the frozen effort must not open a writer.'); + } const stages = ['spawn_fresh', 'queue_idle', 'followup', 'spawn_fork', 'native_list', 'interrupt_idle', 'followup_interrupt', 'native_wait', 'followup_busy', 'followup_effective', 'interrupt_active']; let step = 0; while (receipts.has(stages[step])) step++; @@ -293,6 +328,18 @@ try { config.model_provider = 'offline_native_backend'; config.model_providers = { offline_native_backend: { ...config.model_providers.sub2api, base_url: `http://127.0.0.1:${(server.address() as any).port}/v1`, env_key: 'OFFLINE_NATIVE_BACKEND_KEY' } }; + if (largeForkTest) { + // Each user-message notification stays under the stdio frame limit. The + // scripted provider accepts their combined history without auto-compacting. + const window = 8_000_000; + config.model_context_window = window; + config.model_auto_compact_token_limit = window; + const catalogFile = path.resolve(profile, config.model_catalog_json); + const catalog = JSON.parse(fs.readFileSync(catalogFile, 'utf8')); + for (const model of catalog.models) Object.assign(model, { context_window: window, max_context_window: window }); + fs.chmodSync(catalogFile, 0o600); + fs.writeFileSync(catalogFile, JSON.stringify(catalog)); + } fs.chmodSync(configFile, 0o600); fs.writeFileSync(configFile, stringify(config)); const toolchain = path.join(os.homedir(), '.elan/toolchains/leanprover--lean4---v4.33.0'); const environment = { PATH: `${toolchain}/bin:${path.dirname(process.execPath)}:/usr/bin:/bin`, @@ -357,16 +404,25 @@ try { instructions: agentTeamInstructions({ id: 'lead', role: 'lead' }, maxAgents, 'native-agent-control'), signal: controller.signal, onUsage: () => {} }); team.setLeadSession(lead); state.writerProcess = lead.processIdentity; save(); - observations.rootStatus = await lead.run('NATIVE_ROOT_TEST Execute the scripted disposable backend fixture.', 'root-task', worktree, () => {}); + if (largeForkTest) for (const index of [1, 2, 3, 4]) { + const text = `LARGE_FORK_HISTORY ${index} ` + '界'.repeat(800_000); + assert.equal(await lead.run(text, 'history-' + index, worktree, () => {}), 'completed'); + } + observations.rootStatus = await lead.run(largeForkTest ? 'LARGE_FORK_ACTION' : + 'NATIVE_ROOT_TEST Execute the scripted disposable backend fixture.', 'root-task', worktree, () => {}); assert.equal(observations.rootStatus, 'completed'); if (capacityTest) { assert.ok(observations.capacity, 'must reach the full team and observe the failed overflow spawn'); assert.ok(state.agentTeam!.workers.every(w => w.tasks.at(-1)?.status === 'completed')); observations.loopbackRequests = requests.length; + } else if (largeForkTest) { + assert.equal(observations.largeFork?.workerStatus, 'completed'); + assert.equal(state.agentTeam!.workers.length, 1, 'The oversized fork must not reserve a worker.'); + assert.equal(events.filter(event => event.event === 'native_host_callback' && event.operation === 'spawn').length, 1); } else checkLifecycle(worktree, problem.projectRelative); await team.close(); await lead.close(); team = undefined; lead = undefined; - if (!capacityTest) observations.proofDelivery = await verifyNativeProofDelivery({ repository: root, executable, - output: path.join(output, 'proof-delivery'), signal: controller.signal }); + if (!capacityTest && !largeForkTest) observations.proofDelivery = await verifyNativeProofDelivery({ repository: root, executable, + output: path.join(output, 'proof-delivery'), signal: controller.signal, webProvider: process.argv.includes('--web-provider') }); observations.status = 'passed'; } catch (error) { observations.status = 'failed'; observations.error = error instanceof Error ? { message: error.message, stack: error.stack } : String(error); diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index b89e0206..0b721d39 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -8,7 +8,7 @@ import { parse as parseToml, stringify as stringifyToml } from 'smol-toml'; import { mathProofEnvironmentWorkerEnvironment } from '../math/mathProofEnvironment'; import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; import { startChatCompletionsBridge } from './chatCompletionsBridge'; -import { WESTLAKE_PROVIDER, validateWestlakeModel } from './westlake'; +import { WESTLAKE_NATIVE_TEAM_UNSUPPORTED, WESTLAKE_PROVIDER, validateWestlakeModel } from './westlake'; import { SUB2API_PROVIDER } from './sub2api'; import type { ModelRequestGate } from './modelRequest'; import { prepareFormalizationSandbox } from './formalizationSandbox'; @@ -304,12 +304,16 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise const frozenConfig = fs.existsSync(configFile) ? fs.readFileSync(configFile, 'utf8') : undefined; const profileConfig = frozenConfig === undefined ? {} : parseToml(frozenConfig); const providerId = typeof profileConfig.model_provider === 'string' ? profileConfig.model_provider : undefined; + if (providerId === WESTLAKE_PROVIDER.id && options.nativeAgentControl) + throw new Error(WESTLAKE_NATIVE_TEAM_UNSUPPORTED); const providers = profileConfig.model_providers; const selectedProvider = providerId && providers && typeof providers === 'object' && !Array.isArray(providers) ? (providers as Record)[providerId] : undefined; const provider = selectedProvider && typeof selectedProvider === 'object' && !Array.isArray(selectedProvider) ? selectedProvider as Json : undefined; - const useResponsesRelay = providerId === SUB2API_PROVIDER.id && !options.readIsolation && Boolean(options.requestGate); + const webNativeTeam = providerId === 'web_provider' && Boolean(options.nativeAgentControl); + const useResponsesRelay = (providerId === SUB2API_PROVIDER.id || webNativeTeam) && + !options.readIsolation && Boolean(options.requestGate); if (options.delegation && (!skills.length || !useResponsesRelay)) throw new Error('math_native_delegation_requires_skill_and_metered_relay'); if (options.delegation) validateNativeDelegation(options.delegation); @@ -438,7 +442,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise model: options.model, effort: options.effort, env: options.environment, signal: options.signal, requestGate, onUsageIncomplete: options.onUsageIncomplete }); environment = Object.fromEntries(Object.entries(environment ?? process.env) - .filter(([name]) => !name.startsWith(SUB2API_PROVIDER.apiKeyEnvironment))); + .filter(([name]) => name !== envKey && !name.startsWith(SUB2API_PROVIDER.apiKeyEnvironment))); environment[RELAY_CAPABILITY_ENV] = responsesRelay.apiKey; } if (providerId === WESTLAKE_PROVIDER.id) { @@ -449,6 +453,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise .filter(([name]) => !name.startsWith('WESTLAKEHPC_API_KEY'))); environment[WESTLAKE_PROVIDER.apiKeyEnvironment] = bridge.apiKey; } + const usesRequestReceipts = Boolean((bridge || responsesRelay || isolated) && options.requestGate); const providerSettings: Json = isolated ? { model_provider: isolated.providerId, [`model_providers.${isolated.providerId}.base_url`]: isolated.providerBaseUrl, @@ -525,7 +530,8 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise let turnHasOutput = false; const earlyOutputTurns = new Set(); let completion: { resolve: (turn: Json) => void; reject: (error: Error) => void } | undefined; - let compacting: { resolve: () => void; reject: (error: Error) => void } | undefined; + let compacting: { resolve: (turn?: Json) => void; reject: (error: Error) => void; + turnId?: string; installed?: boolean } | undefined; const earlyCompletions = new Map(); const completedMessages = new Map(); let lastCompletedResponse: Readonly<{ turnId: string; text: string }> | undefined; @@ -730,8 +736,14 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise } investigations?.observe(method, params); if (threadId !== undefined && params.threadId !== undefined && params.threadId !== threadId) return; - if (method === 'thread/compacted' || method === 'item/completed' && object(params.item).type === 'contextCompaction') - compacting?.resolve(); + if (compacting && method === 'turn/started') { + const { id } = object(params.turn); + if (typeof id === 'string') compacting.turnId ??= id; + } + if (compacting && (method === 'thread/compacted' || method === 'item/completed' && object(params.item).type === 'contextCompaction')) { + if (!nativeControl) compacting.resolve(); + else if (method === 'item/completed' && params.turnId === compacting.turnId) compacting.installed = true; + } if (method === 'item/started' || method === 'item/completed') { const item = object(params.item); if (isTurnOutputItem(item)) recordTurnOutput(params.turnId); @@ -782,10 +794,15 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise } if (method === 'turn/completed') { const turn = object(params.turn); - if (compacting && (turn.status === 'failed' || turn.status === 'interrupted')) - compacting.reject(new Error('math_codex_compaction_' + turn.status)); if (typeof turn.id !== 'string' || typeof turn.status !== 'string' || !['completed', 'interrupted', 'failed'].includes(turn.status)) return; + if (compacting && (!compacting.turnId || turn.id === compacting.turnId)) { + if (turn.status !== 'completed') compacting.reject(new Error('math_codex_compaction_' + turn.status)); + else if (nativeControl) { + if (compacting.installed) compacting.resolve(turn); + else compacting.reject(new Error('math_codex_compaction_missing_summary')); + } + } if (turn.id === activeTurn && completion) completion.resolve(turn); else if (completion && !activeTurn) { if (earlyCompletions.size >= 32) earlyCompletions.delete(earlyCompletions.keys().next().value!); @@ -826,7 +843,8 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise 'features.shell_snapshot': false, 'shell_environment_policy.experimental_use_profile': false, ...(bridge || responsesRelay || isolated ? { ...(!nativeControl ? { 'features.multi_agent': false, 'features.multi_agent_v2': false } : {}), - 'features.goals': false, 'features.view_image': false } : {}), + 'features.goals': false, 'features.view_image': false, + ...(responsesRelay ? { web_search: 'disabled' } : {}) } : {}), // Native role files cannot narrow inherited writer permissions; profiles cannot enable children implicitly. ...(!nativeControl && (options.skills?.length || options.tools) ? { 'features.multi_agent': false, 'features.multi_agent_v2': false, 'agents.enabled': false, 'features.goals': false } : {}), @@ -853,8 +871,12 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise ...object(capturedBootstrap.hostOverrides ?? {}), developerInstructions: settings.developerInstructions, ...(tools ? { dynamicTools: tools.definitions } : {}), } } : undefined; + // Codex restores history internally. Echoing it can exceed the stdio frame limit. + // Keep the historical usage notification for direct providers with an active budget gate. + const metadataOnlyResume = nativeControl && (usesRequestReceipts || !options.requestGate); const threadSettings = { - ...settings, ...(options.threadId ? { threadId: options.threadId } : {}), + ...settings, + ...(options.threadId ? { threadId: options.threadId, ...(metadataOnlyResume ? { excludeTurns: true } : {}) } : {}), ...(!options.threadId && (options.delegation || tools?.definitions.length) ? { dynamicTools: [ ...(options.delegation ? [nativeInvestigationTool(options.delegation.maxAgents)] : []), ...(tools?.definitions ?? []), ] } : {}), @@ -867,8 +889,6 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise if (bootstrap && (threadId !== bootstrap.threadId || object(result.agentControl).sessionId !== bootstrap.sessionId || object(object(result.agentControl).agent).threadId !== threadId)) throw new Error('math_native_agent_control_child_binding_mismatch'); - if (nativeControl) await nativeControl.bind(result.agentControl ?? - await rpc.request('theoremos/agentControl/snapshot', { threadId })); if (options.threadId && threadId !== options.threadId) throw new Error('math_codex_session_binding_mismatch'); if (result.model !== options.model || result.reasoningEffort !== options.effort || result.approvalPolicy !== 'never') throw new Error('math_codex_session_binding_mismatch'); @@ -900,6 +920,8 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise assertMathAgentSkillsCurrent(skills); } options.signal?.throwIfAborted(); + if (nativeControl) await nativeControl.bind(result.agentControl ?? + await rpc.request('theoremos/agentControl/snapshot', { threadId })); let skillsDispatched = false; return { threadId, @@ -907,7 +929,7 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise nativeConfiguration, ...(isolated ? { isolationReceipt: isolated.receipt } : processLaunch ? { isolationReceipt: processLaunch.isolationReceipt } : {}), ...(processIdentity ? { processIdentity } : {}), - usageSource: (bridge || responsesRelay || isolated) && options.requestGate ? 'upstream-requests' as const : 'native-thread-totals' as const, + usageSource: usesRequestReceipts ? 'upstream-requests' as const : 'native-thread-totals' as const, advisoryNotifications: 'native-history', ...(nativeControl ? { nativeAgentControl: nativeControl.connection } : {}), get lastError() { return lastError; }, @@ -918,15 +940,18 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise options.signal?.throwIfAborted(); if (closing || transportFailure) throw transportFailure ?? new Error('math_codex_transport_closed:closing'); if (completion || activeTurn || compacting) throw new Error('math_codex_turn_already_running'); - const done = new Promise((resolve, reject) => { compacting = { resolve, reject }; }); - turnSettled = false; turnStopping = false; requestTurn++; + const done = new Promise((resolve, reject) => { compacting = { resolve, reject }; }); + turnSettled = false; turnStopping = false; turnCheckpointReached = false; requestTurn++; const cancel = scheduleMathTimeout(() => { compacting?.reject(new Error('math_codex_compaction_timeout')); void closeSession(); }, options.turnTimeoutMs ?? 120_000); const stop = () => compacting?.reject(new Error('math_codex_compaction_closed')); options.signal?.addEventListener('abort', stop, { once: true }); - try { await Promise.all([rpc.request('thread/compact/start', { threadId }), done]); } + try { + const [, turn] = await Promise.all([rpc.request('thread/compact/start', { threadId }), done]); + if (turn && nativeControl) await nativeControl.waitTurnSettled(String(turn.id), turn.status); + } catch (error) { await closeSession(); options.signal?.throwIfAborted(); throw error; } finally { cancel?.(); options.signal?.removeEventListener('abort', stop); @@ -1207,10 +1232,11 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise }, }; } catch (error) { - await closeSession(); - options.signal?.throwIfAborted(); + const closeResult = await closeSession().then(() => ({ ok: true } as const), cause => ({ ok: false, cause } as const)); if (nativeControl && processLaunch && await rpc.confirmStopped().then(receipt => receipt.status !== 'stopped')) - throw new Error('math_codex_startup_shutdown_unconfirmed'); + throw new Error('math_codex_startup_shutdown_unconfirmed', { cause: error }); + if (closeResult.ok === false) throw closeResult.cause; + options.signal?.throwIfAborted(); throw error; } } diff --git a/src/runtime/formalizationRelay.ts b/src/runtime/formalizationRelay.ts index 44249a23..0e880de3 100644 --- a/src/runtime/formalizationRelay.ts +++ b/src/runtime/formalizationRelay.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'; import { once } from 'node:events'; import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; -import type { AddressInfo } from 'node:net'; +import { isIP, type AddressInfo } from 'node:net'; import { parse as parseToml } from 'smol-toml'; import { z } from 'zod'; import { createParser } from 'eventsource-parser'; @@ -22,25 +22,29 @@ const MAX_CREDENTIAL_BYTES = 8192; const MAX_ACTIVE_REQUESTS = 8; const MAX_USAGE_EVENT_BYTES = 2 * 1024 * 1024; -/** Native metadata/header spellings vary by Codex version. Conflicting or invalid - * identities remain unattributed; provider usage is still accounted for once. */ +/** Older Codex versions use a session ID as the thread ID. Current teams share + * a root session while each member has a distinct thread. */ function nativeRequestThread(body: Record, request: IncomingMessage): string | undefined { const metadata = body.client_metadata && typeof body.client_metadata === 'object' && !Array.isArray(body.client_metadata) ? body.client_metadata as Record : {}; - const values: unknown[] = [metadata.session_id, request.headers.session_id, request.headers['session-id'], - request.headers['thread-id'], request.headers['x-codex-thread-id']].filter(value => value !== undefined && value !== null); + const sessions: unknown[] = [metadata.session_id, request.headers.session_id, request.headers['session-id']]; + const threads: unknown[] = [metadata.thread_id, request.headers['thread-id'], request.headers['x-codex-thread-id']]; for (const raw of [metadata['x-codex-turn-metadata'], request.headers['x-codex-turn-metadata']]) { if (raw === undefined) continue; if (typeof raw !== 'string' || raw.length > 16_384) return; try { const parsed: unknown = JSON.parse(raw); - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && 'thread_id' in parsed) - values.push(parsed.thread_id); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + if ('session_id' in parsed) sessions.push(parsed.session_id); + if ('thread_id' in parsed) threads.push(parsed.thread_id); + } } catch { return; } } - if (!values.length || values.some(value => typeof value !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/u.test(value)) || - new Set(values).size !== 1) return; - return values[0] as string; + const unique = (values: unknown[]) => new Set(values.filter(value => value !== undefined && value !== null)); + const sessionIds = unique(sessions), threadIds = unique(threads); + if (sessionIds.size > 1 || threadIds.size > 1 || [...sessionIds, ...threadIds].some(value => + typeof value !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/u.test(value))) return; + return [...threadIds, ...sessionIds][0] as string | undefined; } /** Observe the existing Responses wire stream without changing its bytes or accepting model claims. */ @@ -161,7 +165,7 @@ const selectedTool = z.object({ type: z.enum(['function', 'custom']), name: tool const statelessResponsesRequest = z.object({ model: z.string(), input: z.union([z.string(), z.array(inlineInputItem)]), instructions: z.string().nullable().optional(), stream: z.boolean().optional(), store: z.literal(false), - reasoning: z.object({ effort: z.enum(['low', 'high', 'max']), + reasoning: z.object({ effort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']), summary: z.enum(['auto', 'concise', 'detailed', 'none']).nullable().optional(), context: z.literal('all_turns').optional() }).strict(), tools: z.array(z.union([clientTool, inlineTool])).optional(), @@ -238,7 +242,7 @@ export type NativeRelayProtocol = Readonly<{ observe: (streaming: boolean) => ReturnType; }>; -function readProfile(directory: string, model: string): Profile { +function readProfile(directory: string, model: string, loopback: boolean): Profile { try { if (!path.isAbsolute(directory)) throw new Error(); const file = path.join(directory, 'config.toml'), stat = fs.statSync(file); @@ -253,7 +257,11 @@ function readProfile(directory: string, model: string): Profile { provider.env_http_headers !== undefined || provider.query_params !== undefined) throw new Error(); if (providerId === 'web_provider') { const url = new URL(provider.base_url); - if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || + const [first, second] = url.hostname.split('.').map(Number); + const privateIPv4 = isIP(url.hostname) === 4 && + (first === 10 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168); + const internalHttp = loopback && url.protocol === 'http:' && (url.hostname === 'host.docker.internal' || privateIPv4); + if (url.protocol !== 'https:' && !internalHttp || url.username || url.password || url.search || url.hash || provider.env_key !== 'THEOREMOS_PROVIDER_API_KEY' || provider.auth !== undefined || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/u.test(model)) throw new Error(); return { providerId, endpoint: url.href.replace(/\/$/u, '') + '/responses', envKey: provider.env_key }; @@ -340,9 +348,12 @@ export async function startFormalizationRelay(input: { requestGate?: ModelRequestGate; onUsageIncomplete?: () => void; native?: NativeRelayProtocol; }): Promise { + const loopback = input.transport === 'loopback-http'; const profile: Profile = input.native ? { providerId: 'web_provider', endpoint: input.native.endpoint, envKey: input.native.envKey } - : readProfile(input.profile, input.model); - if (!(input.native ? ['none', 'low', 'medium', 'high', 'xhigh', 'max'] : ['low', 'high', 'max']).includes(input.effort)) + : readProfile(input.profile, input.model, loopback); + const efforts = input.native ? ['none', 'low', 'medium', 'high', 'xhigh', 'max'] : + loopback && profile.providerId === 'web_provider' ? ['low', 'medium', 'high', 'xhigh', 'max'] : ['low', 'high', 'max']; + if (!efforts.includes(input.effort)) throw new Error('formalization_relay_effort_invalid'); if (input.timeoutMs !== undefined && (!Number.isSafeInteger(input.timeoutMs) || input.timeoutMs <= 0)) throw new Error('formalization_relay_timeout_invalid'); @@ -350,7 +361,6 @@ export async function startFormalizationRelay(input: { if (idleMs !== undefined && (input.native || !Number.isSafeInteger(idleMs) || idleMs <= 0 || idleMs > 2_147_483_647)) throw new Error('formalization_relay_idle_timeout_invalid'); input.signal?.throwIfAborted(); - const loopback = input.transport === 'loopback-http'; const socketPath = !loopback && input.socketPath ? path.resolve(input.socketPath) : undefined; if (!loopback) { if (!socketPath) throw new Error('formalization_relay_socket_invalid'); diff --git a/src/runtime/researchHarness.ts b/src/runtime/researchHarness.ts index d8bf134e..fe409702 100644 --- a/src/runtime/researchHarness.ts +++ b/src/runtime/researchHarness.ts @@ -1,6 +1,7 @@ import fs from 'node:fs'; import path from 'node:path'; -import { mathDigest, canonicalMathJson } from '../math/mathRuntimeIo'; +import { createHash } from 'node:crypto'; +import { mathDigest, canonicalMathJson, mathFileIdentity } from '../math/mathRuntimeIo'; import { assertMathCanonicalPath } from '../math/paths'; import type { MathAgentHarnessId } from './agentSession'; import { createCodexMathSession } from './codexSession'; @@ -20,6 +21,30 @@ export type ResearchHarnessIdentity = { }; const secretKey = /API[_-]?KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|PRIVATE[_-]?KEY/iu; + +const executableDigests = new Map(); + +function executableDigest(file: string): string { + const fd = fs.openSync(file, 'r'); + try { + const start = fs.fstatSync(fd, { bigint: true }); + if (!start.isFile()) throw new Error('math_harness_identity_changed'); + // Match both the inode and change time so replacement and same-size rewrites invalidate the digest. + const stamp = mathFileIdentity(start); + const cached = executableDigests.get(file); + if (cached?.stamp === stamp) return cached.digest; + const hash = createHash('sha256'); + const buffer = Buffer.allocUnsafe(1024 * 1024); + let bytes: number; + while ((bytes = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, bytes)); + if (mathFileIdentity(fs.fstatSync(fd, { bigint: true })) !== stamp || + mathFileIdentity(fs.statSync(file, { bigint: true })) !== stamp) throw new Error('math_harness_identity_changed'); + const digest = hash.digest('hex'); + executableDigests.set(file, { stamp, digest }); + return digest; + } finally { fs.closeSync(fd); } +} + /** Native OpenCode expands these references after reading OPENCODE_CONFIG_CONTENT. */ function openCodeEnvironmentReferences(profile: string, model?: string): string[] { const configured = JSON.parse(fs.readFileSync(path.join(profile, 'opencode.json'), 'utf8')) as { provider?: Record }; @@ -65,7 +90,7 @@ export function bindResearchHarness(id: ResearchHarnessIdentity['id'], command: }); const endpoints = cli ? cli.inheritEnvironment.filter(key => key !== cli.sealedRole?.provider.apiKeyEnvironment && !secretKey.test(key)) : id === 'codex' ? [] : id === 'claude-code' ? ['ANTHROPIC_BASE_URL'] : [...new Set(['OPENAI_BASE_URL', 'ANTHROPIC_BASE_URL', ...openCodeEnvironmentReferences(profile, model).filter(key => !secretKey.test(key))])]; - return { id, executable: binary, executableDigest: mathDigest(fs.readFileSync(binary)), profile, + return { id, executable: binary, executableDigest: executableDigest(binary), profile, configurationDigest: mathDigest(canonicalMathJson({ configuration, endpoints: Object.fromEntries(endpoints.map(key => [key, environment[key] ?? null])), ...(cli?.sealedRole?.runtime ? { sealedRuntime: sealedRuntimeIdentity(binary, environment, cli.sealedRole.runtime) } : {}) })) }; diff --git a/src/runtime/westlake.ts b/src/runtime/westlake.ts index 99ea0437..bdea5a4e 100644 --- a/src/runtime/westlake.ts +++ b/src/runtime/westlake.ts @@ -7,6 +7,8 @@ export const WESTLAKE_PROVIDER = { defaultModel: 'deepseek-flash', defaultEffort: 'max', } as const; +export const WESTLAKE_NATIVE_TEAM_UNSUPPORTED = 'math_westlake_native_team_unsupported'; + export function validateWestlakeModel(model: string, effort: string): void { if (model !== WESTLAKE_PROVIDER.defaultModel) throw new Error('Westlake requires --model deepseek-flash'); if (!['low', 'high', 'max'].includes(effort)) throw new Error('Westlake requires --effort low, high or max'); diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index 7c988c32..c7ca5469 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -18,7 +18,7 @@ import { DeclarationArtifactCheckError, DeclarationSubmissionError } from './dec import { hasDeterministicLeanFailure } from './proofReuse'; import { solverSourceDigest } from './modules/evidence'; import { writeOwnedDeclarationIndex } from './declarationIndex'; -import { stopProofWriter } from './proofWriter'; +import { recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter'; import { prepareTacticBatteryFailureCacheRoot } from './tacticBatteryFailureCache'; import { ResearchUsage } from './researchUsage'; import { aggregateUsage, buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget'; @@ -373,6 +373,11 @@ export class AgentResearchTeam { return pending; } + private assertNativeDispatchOpen(signal: AbortSignal) { + if (this.stopping || this.input.signal.aborted) throw new Error('math_team_dispatch_stopped'); + signal.throwIfAborted(); + } + private async waitNativeStart(worker: AgentTeamWorker, signal: AbortSignal, provisional = false): Promise { const pending = this.nativeStarts.get(worker.id)!; const abort = () => { @@ -389,11 +394,18 @@ export class AgentResearchTeam { }; signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort(); + // A skipped launch has no worker finalizer to settle this promise. + if (!this.live.has(worker.id)) pending.reject(new Error('math_team_dispatch_stopped')); try { return await pending.promise; } finally { signal.removeEventListener('abort', abort); this.nativeStarts.delete(worker.id); } } private async spawnNative(request: NativeTeamSpawn, signal: AbortSignal): Promise { + this.assertNativeDispatchOpen(signal); + const { model, effort } = this.input.state; + const config = request.bootstrap.config as Record; + if (config.model !== model || config.reasoningEffort !== effort) + throw new NativeAgentControlInputError('math_team_native_run_config_frozen: Retry spawn_agent with the same task_name and omit model and reasoning_effort to inherit the run configuration (' + model + ', ' + effort + ').'); const { message, routeId } = nativeTaskRoute(request.message); this.assertRouteAvailable(routeId); if (this.occupiedAgentSlots() >= this.input.maxAgents - 1) @@ -416,12 +428,13 @@ export class AgentResearchTeam { worker.exposures = parentExposures.filter(item => item.kind === 'adopted' || spawnHistory === 'parent-history' && item.kind === 'inspected' && !adopted.has(item.deliveryId)) .map(item => ({ ...item, kind: item.kind === 'adopted' ? 'adopted' : 'possible-via-parent' })); - this.archive.workers.push(worker); this.nativeStart(worker); this.changed(); + this.archive.workers.push(worker); this.nativeStart(worker); this.enqueue(worker, task); return this.waitNativeStart(worker, signal, true); } private async followupNative(worker: AgentTeamWorker, initialInput: Record, signal: AbortSignal): Promise { + this.assertNativeDispatchOpen(signal); const { message, routeId } = nativeTaskRoute(nativeTeamAssignmentMessage(initialInput.input as Record)); this.assertRouteAvailable(routeId); if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); @@ -447,38 +460,44 @@ export class AgentResearchTeam { content: [{ type: 'input_text', text: profiles.section.text }] }] } : {}) }); if (result.accepted !== true || typeof result.submissionId !== 'string') throw new Error('math_team_native_input_not_accepted'); if (task.cancelRequested) throw new Error('math_team_task_not_running'); - this.saveNativeFollowup(task, message, profiles?.evidence ?? task.profileEvidence); + this.updateNativeFollowup(task, message, profiles?.evidence ?? task.profileEvidence); const accepted = this.nativeControl!.accepted(worker, active.session, worker.native!.turnId!); return { ...accepted, submissionId: result.submissionId }; } if (active) await active.task; await this.closeNativeIdle(worker); + this.assertNativeDispatchOpen(signal); + if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id); if ((worker.status as string) === 'stopped') throw new Error('math_team_agent_stopped'); this.assertRouteAvailable(routeId); - worker.native!.initialInput = initialInput; - this.nativeStart(worker); const saved = worker.tasks.toReversed().find(task => ['paused', 'interrupted', 'queued'].includes(task.status) && !task.cancelRequested && !task.deliveryId && (routeId === undefined || routeId === task.routeId)); + // There is one captured input per native writer. Do not replace it while + // a different queued task still needs it. + if (worker.tasks.some(task => task.status === 'queued' && task !== saved)) + throw new NativeAgentControlInputError('math_team_native_assignment_queued: Continue the queued route before assigning different work to this member.'); if (saved) { this.assertRouteAvailable(saved.routeId); - this.saveNativeFollowup(saved, message, profiles?.evidence); + this.updateNativeFollowup(saved, message, profiles?.evidence); saved.pauseRequested = undefined; saved.status = 'queued'; saved.error = undefined; - this.launch(worker); - } else { - this.enqueue(worker, this.newTask(message, profiles?.evidence, { routeId })); - } + } else worker.tasks.push(this.newTask(message, profiles?.evidence, { routeId })); + worker.native!.initialInput = initialInput; + this.changed(); + this.nativeStart(worker); + this.launch(worker); return this.waitNativeStart(worker, signal); } /** Native input is the instruction source; retain it for isolated-workspace resume. */ - private saveNativeFollowup(task: AgentTeamTask, message: string, evidence?: AgentTeamTask['profileEvidence']) { + private updateNativeFollowup(task: AgentTeamTask, message: string, evidence?: AgentTeamTask['profileEvidence']) { + const selected = agentTeamProfileSelection(message), inherited = agentTeamProfileSelection(task.message); + const nextMessage = selected.length || !inherited.length ? message : 'Profiles: ' + inherited.join(', ') + '\n' + message; + const nextEvidence = evidence ?? resolveAgentTeamProfiles(this.input.leadAccess.researchSkill!, nextMessage, this.expertCards).evidence; (task.objectiveHistory ??= []).push({ revision: task.objectiveRevision ?? 1, message: task.message, workKind: task.workKind, at: Date.now(), reason: 'Native followup.', profileEvidence: task.profileEvidence }); - const selected = agentTeamProfileSelection(message), inherited = agentTeamProfileSelection(task.message); - task.message = selected.length || !inherited.length ? message : 'Profiles: ' + inherited.join(', ') + '\n' + message; + task.message = nextMessage; task.objectiveRevision = (task.objectiveRevision ?? 1) + 1; - task.profileEvidence = evidence ?? resolveAgentTeamProfiles(this.input.leadAccess.researchSkill!, task.message, this.expertCards).evidence; - this.changed(); + task.profileEvidence = nextEvidence; } private async interruptNative(worker: AgentTeamWorker) { @@ -522,7 +541,10 @@ export class AgentResearchTeam { git(state.worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir'])], isolatedWorkspaceParent: path.dirname(worker.worktree), isolateProcess: true, instructions: context.instructions, signal: this.input.signal, - onUsage: () => { throw new Error('math_team_native_idle_usage'); } }); + onUsage: () => { throw new Error('math_team_native_idle_usage'); } }).catch(error => { + recordUnconfirmedWriterStartup(worker, error, () => this.changed()); + throw error; + }); this.nativeIdle.set(worker.id, session); if (worker.native && session.nativeConfiguration) worker.native.runtimeConfiguration = session.nativeConfiguration; worker.writerProcess = session.processIdentity; this.changed(); @@ -963,7 +985,9 @@ export class AgentResearchTeam { if (worker.pendingDelivery) await this.finishDelivery(worker); await this.flushAdoptions(worker.id); while (!this.stopping && !abort.signal.aborted && worker.status !== 'stopped') { - if (worker.tasks.some(task => task.status === 'paused')) break; + // A native followup chooses and supplies input for one particular task. + // A parked draft on another route does not block that dispatch. + if (!worker.native && worker.tasks.some(task => task.status === 'paused')) break; const task = worker.tasks.find(item => item.status === 'queued'); if (!task) break; const admission = agentTeamChildAdmission(this.budgetInput(task), 'turn'); @@ -982,7 +1006,15 @@ export class AgentResearchTeam { this.event(worker.id, 'lead', 'failed', worker.error); } }).finally(() => { - this.nativeStarts.get(worker.id)?.reject(new Error(worker.error ?? 'math_team_native_start_failed')); + const pending = this.nativeStarts.get(worker.id); + const firstTask = worker.tasks[0]; + if (pending && !pending.accepted && worker.native && !worker.native.submissionId && !worker.writerStopUnconfirmed && + (worker.status === 'failed' || firstTask.status === 'failed')) { + worker.status = 'stopped'; worker.activity = 'idle'; + firstTask.status = 'failed'; firstTask.error ??= worker.error ?? 'math_team_native_start_failed'; + firstTask.finishedAt ??= Date.now(); + } + pending?.reject(new Error(worker.error ?? 'math_team_native_start_failed')); this.live.delete(worker.id); this.changed(); // Per-task interruption consumes this controller. Reuse the member only after runTask has // confirmed shutdown and saved its draft; a global stop or quarantine must never relaunch it. @@ -1145,6 +1177,7 @@ export class AgentResearchTeam { } catch (error) { outcome = signal.aborted || error instanceof Error && error.message === 'math_team_dispatch_stopped' ? 'interrupted' : 'failed'; task.error = error instanceof Error ? error.message : 'math_team_worker_failed'; + if (recordUnconfirmedWriterStartup(worker, error, () => this.changed())) throw error; if (error instanceof LeanEnvironmentHealthCheckError) this.input.emit('lean_environment_unavailable', { workerId: worker.id, health: error.health }); } finally { @@ -1162,7 +1195,7 @@ export class AgentResearchTeam { this.nativeControl?.writerStopped(worker.id); worker.writerProcess = undefined; } - writerStopped = true; + writerStopped = !worker.writerStopUnconfirmed; } finally { if (started) usage.finish(completed); else if (reserved) { state.turns--; worker.turns--; } @@ -1447,6 +1480,15 @@ export class AgentResearchTeam { worker.writerProcess = undefined; if (worker.native) this.nativeControl?.writerStopped(worker.id, 'recovery-process-check'); await this.prepare(worker); + const queued = worker.tasks.filter(task => task.status === 'queued'); + if (worker.native && queued.length > 1) { + // Older checkpoints could accept another queue entry after a blocked + // followup. Only its last input was saved, so require explicit reassignment. + for (const task of queued) { + task.status = 'interrupted'; task.finishedAt = Date.now(); + this.event(worker.id, 'lead', 'interrupted', 'Assign this saved task explicitly to continue; its queued native input could not be recovered.', { taskId: task.id }); + } + } for (const task of worker.tasks.filter(item => item.status === 'running')) { task.status = task.cancelRequested ? 'cancelled' : task.pauseRequested ? 'paused' : 'interrupted'; if (task.status === 'paused') task.pausedAt = Date.now(); else task.finishedAt = Date.now(); diff --git a/src/solver/agentTeamContext.ts b/src/solver/agentTeamContext.ts index f2c8b9b8..7df0831f 100644 --- a/src/solver/agentTeamContext.ts +++ b/src/solver/agentTeamContext.ts @@ -67,6 +67,7 @@ function nativeAgentTeamInstructions(role: AgentTeamRole, maxAgents: number): st `At most ${maxAgents} agents including you may be available. ` + 'As soon as you identify a proof step you can advance, work on it in your Lean files. Keep writing the consuming argument or another unassigned gap while members work. ' + 'If portfolio scouting produced no report, use native spawn_agent for concrete independent gaps found in the frozen statement. ' + + 'Omit model and reasoning_effort when calling spawn_agent so members inherit the frozen run configuration. ' + 'If several goals share a mathematical foundation, assign and check its small Lean interfaces before dispatching the consuming goals. ' + 'Tag route-specific native spawn and followup objectives with Route: ROUTE_ID as the first line. Use theoremos_team retire_route with the obstruction and evidence refs to stop a refuted route. ' + 'Idle members still occupy their places. Use native followup_task to reuse a member for another gap or specialty; interrupt_agent stops its turn and preserves its place and work. ' + diff --git a/src/solver/agentTeamNative.ts b/src/solver/agentTeamNative.ts index f9596cbe..a06ff56d 100644 --- a/src/solver/agentTeamNative.ts +++ b/src/solver/agentTeamNative.ts @@ -53,7 +53,7 @@ export function nativeTeamAssignmentMessage(input: Json): string { /** One host-owned native tree; Rust retains the actual local mailbox/watch implementation. */ export class AgentTeamNativeControl { - private readonly connections = new Map(); + private readonly connections = new Map(); private readonly pending = new Map; digest: string }>(); private readonly flushing = new Map>(); private readonly ordered = new Map>(); @@ -71,22 +71,31 @@ export class AgentTeamNativeControl { ...(worker?.native ? { bootstrap: worker.native.bootstrap, initialInput: worker.native.initialInput } : {}), request: (request, connection, context) => this.request(actor, request, connection, context.signal), disconnected: connection => { - for (const [threadId, active] of this.connections) if (active === connection) { - this.connections.delete(threadId); - for (const mail of this.archive.nativeControl?.mailbox ?? []) - if (mail.threadId === threadId && mail.status === 'accepted') mail.status = 'uncertain'; + for (const [threadId, active] of this.connections) if (active.connection === connection) { + this.detach(threadId); + this.save(); } - this.save(); }, bound: async connection => { const threadId = actor === 'lead' ? this.archive.nativeControl?.rootThreadId : this.worker(actor).native!.threadId; - if (!threadId || this.connections.get(threadId) !== connection) throw new Error('math_team_native_caller_changed'); - this.refresh(threadId, connection); this.save(); + const active = threadId && this.connections.get(threadId); + if (!threadId || !active || active.connection !== connection) throw new Error('math_team_native_caller_changed'); + if (!connection.info) throw new Error('math_team_native_start_identity_changed'); + this.refresh(threadId, connection); + active.bound = true; + this.save(); await this.flush(threadId); + if (this.connection(threadId) !== connection) throw new Error('math_team_native_caller_changed'); }, }; } + private detach(threadId: string) { + this.connections.delete(threadId); + for (const mail of this.archive.nativeControl?.mailbox ?? []) + if (mail.threadId === threadId && mail.status === 'accepted') mail.status = 'uncertain'; + } + private worker(id: string) { const worker = this.archive.workers.find(item => item.id === id); if (!worker?.native) throw new Error('math_team_native_member_unknown'); @@ -149,6 +158,7 @@ export class AgentTeamNativeControl { accepted(worker: AgentTeamWorker, session: { nativeAgentControl?: NativeAgentControlConnection }, turnId: string): NativeTeamAcceptedChild { const native = worker.native!, connection = session.nativeAgentControl; if (!connection) throw new Error('math_team_native_backend_required'); + if (this.connection(native.threadId) !== connection) throw new Error('math_team_native_child_not_bound'); this.refresh(native.threadId, connection); if (!native.agent || !native.configSnapshot) throw new Error('math_team_native_child_not_bound'); native.turnId = turnId; native.submissionId = turnId; @@ -158,7 +168,10 @@ export class AgentTeamNativeControl { return { agent: native.agent, configSnapshot: native.configSnapshot, submissionId: turnId }; } - connection(threadId: string) { return this.connections.get(threadId); } + connection(threadId: string) { + const active = this.connections.get(threadId); + return active?.bound ? active.connection : undefined; + } /** A confirmed stopped process is distinct from a native turn completion or a proof delivery. */ writerStopped(actor: string, source: 'writer-stop' | 'recovery-process-check' = 'writer-stop') { @@ -204,30 +217,27 @@ export class AgentTeamNativeControl { private async flush(threadId: string): Promise { const prior = this.flushing.get(threadId); if (prior) { await prior; return this.flush(threadId); } - const connection = this.connections.get(threadId), state = this.archive.nativeControl; - if (!connection || !state) return; + const state = this.archive.nativeControl; + if (!this.connection(threadId) || !state) return; const queued = state.mailbox.filter(item => item.threadId === threadId && item.status === 'queued'); if (!queued.length) return; const apply = (async () => { try { - const sequence = await this.update(threadId, { mailbox: queued.map(({ id, author, recipient, message, communication }) => ({ id, author, recipient, + await this.update(threadId, { mailbox: queued.map(({ id, author, recipient, message, communication }) => ({ id, author, recipient, ...(communication ? { communication } : { message }) })) }, queued); - for (const item of queued) item.sequence = sequence; - for (const item of queued) item.status = 'accepted'; } catch { - // The runtime may have accepted before its response was lost; never replay automatically. - for (const item of queued) item.status = 'uncertain'; - } finally { this.save(); } + // update() marks mail uncertain at handoff. A disconnect before handoff leaves it queued for the next bind. + } })(); this.flushing.set(threadId, apply); try { await apply; } finally { this.flushing.delete(threadId); } } private async update(threadId: string, fields: Json, - mail: NonNullable['mailbox'] = []): Promise { + mail: NonNullable['mailbox'] = []): Promise { const previous = this.updates.get(threadId) ?? Promise.resolve(); const apply = previous.catch(() => {}).then(async () => { - const state = this.archive.nativeControl!, connection = this.connections.get(threadId); + const state = this.archive.nativeControl!, connection = this.connection(threadId); if (!connection) throw new Error('math_team_native_runtime_unloaded'); const sequence = ++state.sequence; // Persist uncertain ownership before handing off bytes: a crash cannot replay an accepted update. @@ -235,16 +245,17 @@ export class AgentTeamNativeControl { this.save(); const response = await connection.update({ sessionId: state.sessionId, threadId, sequence, ...fields }); if (response.acceptedSequence !== sequence) throw new Error('math_team_native_mailbox_ack_changed'); - if (this.connections.get(threadId) !== connection) throw new Error('math_team_native_runtime_unloaded'); - return sequence; + if (this.connection(threadId) !== connection) throw new Error('math_team_native_runtime_unloaded'); + for (const item of mail) item.status = 'accepted'; + if (mail.length) this.save(); }); this.updates.set(threadId, apply); - try { return await apply; } + try { await apply; } finally { if (this.updates.get(threadId) === apply) this.updates.delete(threadId); } } private snapshot(threadId: string): Json { - const state = this.archive.nativeControl!, connection = this.connections.get(threadId); + const state = this.archive.nativeControl!, connection = this.connection(threadId); if (connection) this.refresh(threadId, connection); const native = threadId === state.rootThreadId ? undefined : this.workerByThread(threadId).native!; const agent = native ? native.agent : state.rootAgent; @@ -273,12 +284,17 @@ export class AgentTeamNativeControl { return Promise.reject(new Error('math_team_native_attach_identity_changed')); sessionId = native.sessionId; } - this.connections.set(threadId, connection); this.save(); + const active = this.connections.get(threadId); + if (active?.connection !== connection) { + if (active) this.detach(threadId); + this.connections.set(threadId, { connection, bound: false }); + } + this.save(); return Promise.resolve({ result: { sessionId } }); } const expected = actor === 'lead' ? this.archive.nativeControl?.rootThreadId : this.worker(actor).native!.threadId; if (!expected || request.threadId !== expected || request.sessionId !== this.archive.nativeControl?.sessionId || - this.connections.get(expected) !== connection) + this.connections.get(expected)?.connection !== connection) return Promise.reject(new Error('math_team_native_caller_changed')); if (payload.caller !== undefined && payload.caller !== expected) return Promise.reject(new Error('math_team_native_caller_changed')); @@ -405,7 +421,8 @@ export class AgentTeamNativeControl { case 'recordUsage': return {}; // Provider request receipts own accounting; no second charge or quota. case 'configUpdate': { leadOnly(); - for (const threadId of this.connections.keys()) await this.update(threadId, { serviceTier: payload.serviceTier ?? null }); + for (const threadId of this.connections.keys()) + if (this.connection(threadId)) await this.update(threadId, { serviceTier: payload.serviceTier ?? null }); this.save(); return {}; } default: throw new Error('math_team_native_operation_unknown:' + request.operation); diff --git a/src/solver/proofWriter.ts b/src/solver/proofWriter.ts index 5e4b392c..1559c956 100644 --- a/src/solver/proofWriter.ts +++ b/src/solver/proofWriter.ts @@ -1,6 +1,14 @@ import type { MathAgentSession } from '../runtime/agentSession'; import type { SolverRunState } from './archive'; +/** Opening can fail before the caller has a session to stop. */ +export function recordUnconfirmedWriterStartup(record: Pick, error: unknown, save: () => void): boolean { + if (!(error instanceof Error) || error.message !== 'math_codex_startup_shutdown_unconfirmed') return false; + record.writerStopUnconfirmed = { at: Date.now(), reason: error.message }; + save(); + return true; +} + /** Confirm that every writer has stopped before any caller freezes proof sources. */ export async function stopProofWriter(input: { session: MathAgentSession; diff --git a/src/solver/research.ts b/src/solver/research.ts index f156dd6c..309bb6c5 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -49,7 +49,7 @@ import { committedResearchNotesDigest, researchHandoffNotesDigest } from './rese import { SingleSolverProofHandoff } from './singleSolverProofHandoff'; import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/agentSkills'; import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext'; -import { stopProofWriter } from './proofWriter'; +import { recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter'; import { createSkillProofLifecycle } from './skillProofLifecycle'; import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; import { materializeResearchToolHelp } from './researchToolHelp'; @@ -260,6 +260,7 @@ export async function runResearchWorkers(input: { let sessionInstructions: string | undefined; let closing: Promise | undefined; let retries = 0; + let nativeContextRecovery: 'pending' | 'attempted' | undefined; let lastCheck: ProofCheck | undefined; research.error = undefined; const access = input.access.get(worker.id)!; @@ -1220,6 +1221,7 @@ export async function runResearchWorkers(input: { team?.setLeadSession(session); if (team && session.processIdentity) { state.writerProcess = session.processIdentity; save(); } } catch (error) { + if (recordUnconfirmedWriterStartup(research, error, save)) throw error; signal.throwIfAborted(); // M1.open disposes failed launches before rejecting. Rebuild Lead's // instructions for host tools before reserving the same turn again. @@ -1275,6 +1277,10 @@ export async function runResearchWorkers(input: { overflow.maxOptionalContextBytes = 0; if (turnContext?.fresh && !overflow.failedFreshContextDigests.includes(turnContext.digest)) overflow.failedFreshContextDigests.push(turnContext.digest); + if (team?.nativeAgentControlEnabled && research.threadId && team.archive.nativeControl?.rootThreadId === research.threadId) { + if (nativeContextRecovery === 'attempted') throw new Error('math_model_context_capacity_blocked'); + nativeContextRecovery = 'pending'; + } await rotateSession('context'); retries = 0; emit('worker_context_recovering', { reason: research.lastFailure.reason, @@ -1299,8 +1305,7 @@ export async function runResearchWorkers(input: { return; } retries = retry.attempt; - // A transient upstream failure does not invalidate the saved native thread. Retry it - // once after closing the failed writer; a repeated failure still gets a fresh thread. + // Close failed writers before retrying. A bound native team must reopen its existing root. if (research.threadId && (retry.reason === 'math_model_tool_failed' || retry.reason === 'math_model_request_failed' && retries === 2 || retries === 1 && ['math_model_request_timeout', 'math_codex_transport_closed'].includes(retry.reason))) @@ -1319,6 +1324,13 @@ export async function runResearchWorkers(input: { } const previous = research.threadId; await close(); + if (previous && team?.nativeAgentControlEnabled && team.archive.nativeControl?.rootThreadId === previous) { + // Child lineage, mailbox ownership and the host's usage baseline all bind this thread ID. + sessionHasHistory = false; compactedUsageVersion = -1; + save(); + emit('context_reconnecting', { threadId: previous, turns: research.turns, reason }); + return; + } if (previous) research.previousThreadIds = [...(research.previousThreadIds ?? []), previous]; research.threadId = undefined; research.lastInputTokens = undefined; research.contextCheckpoint = undefined; research.contextCheckpointBaseline = undefined; sessionHasHistory = false; compactedUsageVersion = -1; @@ -1326,11 +1338,13 @@ export async function runResearchWorkers(input: { emit('context_restarted', { previousThreadId: previous, turns: research.turns, reason }); }; const maintainContext = async (assignment?: CooperativeAction): Promise<'unchanged' | 'compacted' | 'rotated'> => { - if (skillMode || !research.threadId || !session || !sessionHasHistory) return 'unchanged'; + const recoverNative = nativeContextRecovery === 'pending'; + if (skillMode && !recoverNative || !research.threadId || !session || !sessionHasHistory) return 'unchanged'; const threadId = research.threadId, lastInputTokens = Math.max(session.lastInputTokens ?? 0, research.lastInputTokens ?? 0); const notesDigest = currentCheckpointNotesDigest(); - if (lastInputTokens < 96_000 && !notesDigest) return 'unchanged'; - if (session.compact && (compactedUsageVersion !== contextUsageVersion || notesDigest)) { + if (!recoverNative && lastInputTokens < 96_000 && !notesDigest) return 'unchanged'; + if (recoverNative) nativeContextRecovery = 'attempted'; + if (session.compact && (recoverNative || compactedUsageVersion !== contextUsageVersion || notesDigest)) { const startedAt = Date.now(); if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); emit('context_compaction_requested', { threadId, lastInputTokens }); @@ -1346,9 +1360,11 @@ export async function runResearchWorkers(input: { } catch (error) { signal.throwIfAborted(); emit('context_compaction_failed', { threadId, reason: failureDetail(error) }); + if (recoverNative) throw new Error('math_model_context_capacity_blocked', { cause: error }); } finally { explicitCompaction = false; usage.finishMaintenance(); } await rotateSession('context'); return 'rotated'; } + if (recoverNative) throw new Error('math_model_context_capacity_blocked'); if (session.compact) return 'unchanged'; // Wait for a new usage observation before another native maintenance request. if (!cooperation || !assignment || notesDigest) { if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest }); @@ -1760,7 +1776,7 @@ export async function runResearchWorkers(input: { research.candidate = candidate; const turn = cooperation && assignment && candidate.status === 'interrupted' ? 'checkpoint' : candidate.status; if (!['completed', 'failed', 'checkpoint'].includes(turn)) break; - if (turn !== 'failed') retries = 0; + if (turn !== 'failed') { retries = 0; nativeContextRecovery = undefined; } if (turn === 'checkpoint') emit('turn_checkpoint', { turn: research.turns, ...(team?.leadCompletionCheckpoint ? { reason: 'math_team_completion_checkpoint' } : team?.leadAdoptionCheckpoint ? { reason: 'math_team_adoption_checkpoint' } : diff --git a/src/solver/run.ts b/src/solver/run.ts index 137c8628..0eb86253 100644 --- a/src/solver/run.ts +++ b/src/solver/run.ts @@ -34,7 +34,7 @@ import { solverProofIsCurrent } from './modules/evidence'; import { checkCodexProviderConnectivity } from '../runtime/codexConnectivity'; import { aggregateUsage, buildTokenBudget } from './usageBudget'; import { selectedDeepSeekProfile } from '../runtime/deepseek'; -import { selectedWestlakeProfile } from '../runtime/westlake'; +import { WESTLAKE_NATIVE_TEAM_UNSUPPORTED, selectedWestlakeProfile } from '../runtime/westlake'; import { selectedSub2apiProfile } from '../runtime/sub2api'; import { copyKnowledgeSnapshot } from './theoremKnowledgeStore'; import { readAuthorizedKnowledgeCatalog } from './theoremKnowledgeAuthorization'; @@ -106,7 +106,7 @@ export async function runSolver(args: string[], root: string, customModules?: So console.log(`Usage: theorem-os run --workspace DIR --task-file FILE --output FILE --build-manifest FILE [--receipt-file FILE] [--resume] [--method direct] [--scheduler plan|critical-path|continuation] [--module-plan FILE] [--coordination cooperative|independent] [--workers 1..${MAX_RESEARCH_WORKERS}] [--plan-approval] [--model MODEL --effort LEVEL] [--max-run-seconds N --max-turns N --max-turn-seconds N] [--max-total-tokens N] [--prepare-timeout-seconds N] [--proof-timeout-seconds N] [--evaluator-command CMD --evaluator-timeout-seconds N] [--proof-environment-cache-dir DIR] [--startup-only] [--check-statement]\n--module-plan loads the shared research-module plan JSON; use --scheduler plan.\nUse 0 for --prepare-timeout-seconds, --max-run-seconds, --max-turns, --max-turn-seconds, --proof-timeout-seconds or --evaluator-timeout-seconds to disable that limit. All time, turn and token limits default to 0 (unlimited). With an explicit proof-check timeout, an expired check saves a resumable checkpoint and the identical candidate gets more time on its next check.\n--max-total-tokens defaults to 0 (unlimited). A finite value stops new model turns after provider-reported consumption reaches it; in-flight turns finish and may exceed it. Resume retains cumulative usage and the saved allowance unless explicitly changed.`); console.log('--knowledge-base FILE attaches an immutable saved-theorem catalog. Resume requires the same catalog digest. Historical knowledge never grants proof acceptance.'); console.log('--portfolio-exploration enables parallel route scouting before proof work. Use --portfolio-seconds N (default 1800) to bound it, or --skip-portfolio to bypass a pending stage.'); - console.log('--agent-team N selects one Codex Lead and a team of 2..8 agents including Lead. New teams start with native collaboration tools and can retry a failed initial native startup with host tools. Omit the preset to retain ordinary solver dispatch.'); + console.log('--agent-team N selects one Codex Lead and a team of 2..8 agents including Lead. New teams start with native collaboration tools and can retry a failed initial native startup with host tools. The direct Westlake Chat profile uses host tools. Omit the preset to retain ordinary solver dispatch.'); console.log('New proof runs default to --effort high. Resume retains the saved effort when --effort is omitted; an explicit effort must match the frozen run.'); console.log('Accepted proofs automatically generate audited explanations of every original target. --explanation-language zh|en selects the language (default zh; resume keeps the previous language). --no-explanations skips generation. The result.explanations field records progress and artifact/proof.md paths. Explanation failures preserve proof acceptance and exit code; --resume retries them without solving again. Explanation time and tokens are separate from solving limits.'); console.log('--library-catalog FILE --library-catalog-sha256 DIGEST enables agent search/get/request against one pinned release. Installation requests end this frozen run for host-controlled continuation.'); @@ -167,8 +167,6 @@ export async function runSolver(args: string[], root: string, customModules?: So throw new Error('invalid --skill-preferred-profiles: requires --skill-delegation team'); if (values['skill-expert-cards-file'] !== undefined && delegationMode !== 'team') throw new Error('invalid --skill-expert-cards-file: requires --skill-delegation team'); - // A saved team without this discriminator retains its original transport. - const nativeTeamRun = delegationMode === 'team' && (!values.resume || savedConfiguration?.agentTeam?.transport === 'native-agent-control'); if (skillMode) { if (!specified('workers')) values.workers = String(savedConfiguration?.workerCount ?? (specified('coordination') && values.coordination === 'cooperative' ? 4 : 1)); @@ -301,6 +299,13 @@ export async function runSolver(args: string[], root: string, customModules?: So const profile = profileArgument ? fs.realpathSync(profileArgument) : process.env.CODEX_HOME || path.join(os.homedir(), '.config/deepscientist/math-sol-codex'); const cli = harness.id === 'cli' ? readCliConfiguration(profile) : undefined; + const resumedState = values.resume ? readSolverRunState(stateFile) : undefined; + const codexWestlake = harness.id === 'codex' ? selectedWestlakeProfile(profile) : undefined; + // The legacy Chat bridge does not carry native collaboration namespaces or attributed messages. + const newWestlakeTeam = delegationMode === 'team' && !values.resume && Boolean(codexWestlake); + // Historical runs keep the transport frozen by their existing checkpoint. + const nativeTeamRun = delegationMode === 'team' && (resumedState + ? resumedState.agentTeam?.transport === 'native-agent-control' : !newWestlakeTeam); const sourceEnvironment = { ...process.env }; // Explicit CLI-only inputs, including unusually named credentials, never enter host Lean. for (const key of cli?.inheritEnvironment ?? []) delete sourceEnvironment[key]; @@ -312,18 +317,17 @@ export async function runSolver(args: string[], root: string, customModules?: So cli?.executable ?? (harness.id === 'codex' ? process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE || 'codex' : harness.id === 'claude-code' ? 'claude' : 'opencode')); // Historical Codex checkpoints retain their existing binding; explicit new flags opt into full launch identity. const pinHarness = harness.id !== 'codex' || specified('harness-executable') || specified('harness-profile') || - Boolean(savedConfiguration?.agentHarness) || nativeTeamRun; + Boolean(savedConfiguration?.agentHarness) || nativeTeamRun || newWestlakeTeam; const agentHarness = pinHarness ? bindResearchHarness(harness.id, executable, profile, process.env, values.model) : undefined; const harnessEnvironment = harness.id === 'codex' ? undefined : researchHarnessEnvironment(harness.id, process.env, { profile, model: values.model! }); const assertHarnessCurrent = agentHarness ? () => assertResearchHarnessCurrent(agentHarness, harnessEnvironment ?? {}, values.model) : undefined; const sub2apiProfile = modules.M1.open === directSolverModules.M1.open ? selectedSub2apiProfile(profile) : undefined; - const westlakeProfile = modules.M1.open === directSolverModules.M1.open && !sub2apiProfile ? selectedWestlakeProfile(profile) : undefined; + const westlakeProfile = modules.M1.open === directSolverModules.M1.open ? codexWestlake : undefined; const providerProfile = modules.M1.open === directSolverModules.M1.open ? selectedDeepSeekProfile(profile) ?? sub2apiProfile ?? westlakeProfile : undefined; const knowledge = values['knowledge-base'] ? readAuthorizedKnowledgeCatalog(values['knowledge-base'], workspace, values['receipt-file'] || path.join(workspace, 'active-problem.json')) : undefined; - const resumedState = values.resume ? readSolverRunState(stateFile) : undefined; const portfolio = configurePortfolioExploration(resumedState?.portfolioExploration, { enable: values['portfolio-exploration'], skip: values['skip-portfolio'], durationMs: portfolioSeconds === undefined ? undefined : portfolioSeconds * 1000, @@ -451,6 +455,9 @@ export async function runSolver(args: string[], root: string, customModules?: So return result.status === 'evaluated_passed' ? 0 : 2; } } + if (codexWestlake && nativeTeamRun) + throw new Error(WESTLAKE_NATIVE_TEAM_UNSUPPORTED + + ': create a new team run with your saved artifacts. Direct Westlake uses host tools for new runs.'); } else { if (fs.existsSync(stateFile) || fs.existsSync(output)) throw new Error('math_run_exists_use_resume'); if (git(workspace, ['status', '--porcelain', '--untracked-files=no'])) throw new Error('math_workspace_has_uncommitted_sources'); @@ -461,7 +468,8 @@ export async function runSolver(args: string[], root: string, customModules?: So agentSessionPlan: plannedSession, ...(researchSkill ? { researchMode: 'skill', researchSkill, researchSkillWorkflow: 'full' } : {}), ...(commonResearchSkill ? { commonResearchSkill } : {}), ...(researchDelegation ? { researchDelegation } : {}), - ...(nativeTeamRun ? { agentTeam: { schema: 'theorem-os.agent-team.v1' as const, transport: 'native-agent-control' as const, + ...(nativeTeamRun || newWestlakeTeam ? { agentTeam: { schema: 'theorem-os.agent-team.v1' as const, + transport: nativeTeamRun ? 'native-agent-control' as const : 'host-tools' as const, workers: [], events: [], deliveries: [], adoptions: [], operations: [] } } : {}), ...(continuation ? { continuationDigest: continuation.digest } : {}), worktree: path.join(directory, 'worktree'), phase: 'prepared', turns: 0, dispatchCounts: {}, workerCount, diff --git a/tests/agentTeamNativeControl.test.ts b/tests/agentTeamNativeControl.test.ts index cc9aab0f..56f97947 100644 --- a/tests/agentTeamNativeControl.test.ts +++ b/tests/agentTeamNativeControl.test.ts @@ -43,6 +43,7 @@ async function fixture() { { signal: new AbortController().signal }); }; await call('attach', { threadId: ROOT, sessionId: ROOT }); + await control.options('lead').bound!(root); return { archive, lifecycle, save, control, root, call, accepted }; } @@ -90,6 +91,7 @@ describe('native AgentControl mathematical-team host routing', () => { expect((await f.call('list', payload, 'lead', f.root, 'same-read')).result).toMatchObject({ agents: [{ threadId: ROOT }] }); const child = connection(CHILD, '/root/analyst'); await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); + await f.control.options('analyst').bound!(child); f.save.mockClear(); expect((await f.call('list', payload, 'lead', f.root, 'same-read')).result).toMatchObject({ agents: [{ threadId: ROOT }, { threadId: CHILD }], @@ -116,6 +118,52 @@ describe('native AgentControl mathematical-team host routing', () => { expect(child.update).toHaveBeenCalledTimes(1); }); + it('keeps a reconnecting child unloaded and retains mail if its startup fails before binding', async () => { + const f = await fixture(), provisional = { ...connection(CHILD, '/root/analyst'), info: undefined }; + await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', provisional); + expect(await f.call('list', { caller: ROOT, pathPrefix: '/root/analyst' })).toEqual({ result: { agents: [] } }); + const target = { kind: 'reference', reference: '/root/analyst' }; + expect(await f.call('resolve', { caller: ROOT, target })).toEqual({ result: { threadId: CHILD } }); + const sent = await f.call('send', { caller: ROOT, target, + input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'Use the checked dependency.' } } }); + expect(sent.result).toMatchObject({ threadId: CHILD, submissionId: expect.any(String) }); + expect(provisional.update).not.toHaveBeenCalled(); + expect(f.archive.nativeControl!.mailbox[0].status).toBe('queued'); + await f.control.options('analyst').disconnected!(provisional); + const child = connection(CHILD, '/root/analyst'); + await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); + expect(child.update).not.toHaveBeenCalled(); + await f.control.options('analyst').bound!(child); + expect(child.update).toHaveBeenCalledTimes(1); + expect(f.archive.nativeControl!.mailbox[0].status).toBe('accepted'); + expect((await f.call('list', { caller: ROOT, pathPrefix: '/root/analyst' })).result).toMatchObject({ agents: [{ threadId: CHILD }] }); + }); + + it('leaves delivery uncertain when an in-flight update is acknowledged by the replaced connection', async () => { + const f = await fixture(), child = connection(CHILD, '/root/analyst'); + await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); + await f.control.options('analyst').bound!(child); + await f.control.advisory(null, 'analyst', 'Already forwarded to the old connection.'); + expect(f.archive.nativeControl!.mailbox[0].status).toBe('accepted'); + const updating = deferred(), release = deferred(); + vi.mocked(child.update).mockImplementationOnce(async request => { + updating.resolve(); await release.promise; + return { acceptedSequence: request.sequence }; + }); + const sent = f.call('send', { caller: ROOT, target: { kind: 'id', threadId: CHILD }, + input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'Do not replay an unconfirmed delivery.' } } }); + await updating.promise; + const replacement = connection(CHILD, '/root/analyst'); + await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', replacement); + await f.control.options('analyst').disconnected!(child); + release.resolve(); + await f.control.options('analyst').bound!(replacement); + await sent; + expect(child.update).toHaveBeenCalledTimes(2); + expect(replacement.update).not.toHaveBeenCalled(); + expect(f.archive.nativeControl!.mailbox.map(mail => mail.status)).toEqual(['uncertain', 'uncertain']); + }); + it('preserves native sender identity and enforces the flat Lead dispatch authority', async () => { const f = await fixture(), child = connection(CHILD, '/root/analyst'); await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); @@ -142,6 +190,7 @@ describe('native AgentControl mathematical-team host routing', () => { it('delivers host adoption and failure observations without looking up a nonexistent host worker', async () => { const f = await fixture(), child = connection(CHILD, '/root/analyst'); await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); + await f.control.options('analyst').bound!(child); await f.control.advisory(null, 'lead', 'Checked declarations were integrated.'); await f.control.advisory(null, 'analyst', 'The dependency is ready.'); expect(f.archive.nativeControl!.mailbox).toMatchObject([ @@ -238,6 +287,7 @@ describe('native AgentControl mathematical-team host routing', () => { operationId: 'cold-attach', operation: 'attach', payload: { threadId: CHILD, sessionId: CHILD } }, child, { signal: new AbortController().signal }); expect(response).toEqual({ result: { sessionId: ROOT } }); + await f.control.options('analyst').bound!(child); vi.mocked(child.update).mockRejectedValueOnce(new Error('response-lost-after-native-acceptance')); await f.call('send', { caller: ROOT, target: { kind: 'id', threadId: CHILD }, input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'No false read receipt.' } } }); @@ -247,6 +297,38 @@ describe('native AgentControl mathematical-team host routing', () => { expect(f.lifecycle.followup).not.toHaveBeenCalled(); }); + it('retries queued mail on reattach if the recipient disconnected before the update could send it', async () => { + const f = await fixture(), child = connection(CHILD, '/root/analyst'); + await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', child); + await f.control.options('analyst').bound!(child); + const updating = deferred(), release = deferred(); + vi.mocked(child.update).mockImplementationOnce(async request => { + updating.resolve(); await release.promise; + return { acceptedSequence: request.sequence }; + }); + const configUpdate = f.call('configUpdate', { serviceTier: 'priority' }).catch(error => (error as Error).message); + await updating.promise; + const send = f.call('send', { caller: ROOT, target: { kind: 'id', threadId: CHILD }, + input: { kind: 'message', mode: 'queueOnly', message: { kind: 'plaintext', text: 'A dependency is ready.' } } }); + await expect.poll(() => f.archive.nativeControl!.mailbox.length).toBe(1); + await f.control.options('analyst').disconnected!(child); + release.resolve(); + await configUpdate; + await send; + const [mail] = f.archive.nativeControl!.mailbox; + expect(mail).toMatchObject({ status: 'queued' }); + expect(mail.sequence).toBeUndefined(); + expect(child.update).toHaveBeenCalledTimes(1); + + const resumed = connection(CHILD, '/root/analyst'); + await f.call('attach', { threadId: CHILD, sessionId: ROOT }, 'analyst', resumed); + await f.control.options('analyst').bound!(resumed); + expect(resumed.update).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + mailbox: [expect.objectContaining({ id: mail.id, message: { kind: 'plaintext', text: 'A dependency is ready.' } })], + })); + expect(mail.status).toBe('accepted'); + }); + it('returns one spawn receipt for the same operation and rejects a reused path for another assignment', async () => { const f = await fixture(); const payload = { caller: ROOT, source: { subagent: { thread_spawn: { parent_thread_id: ROOT, agent_path: '/root/prover' } } }, diff --git a/tests/agentTeamNativeLifecycle.test.ts b/tests/agentTeamNativeLifecycle.test.ts index f0fab64c..75e52ccd 100644 --- a/tests/agentTeamNativeLifecycle.test.ts +++ b/tests/agentTeamNativeLifecycle.test.ts @@ -126,9 +126,11 @@ function fixture({ earlyCompletion = false, beforeOpen }: { earlyCompletion?: bo const spawn = async (name: string, message = 'Profiles: D006, prover\nInvestigate a complementary helper.', signal?: AbortSignal, messageKind: 'plaintext' | 'encrypted' = 'plaintext', initialHistory?: unknown) => { await native('attach', { threadId: ROOT, sessionId: ROOT }); + await rootOptions.bound?.(rootConnection); const source = { subagent: { thread_spawn: { parent_thread_id: ROOT, agent_path: '/root/' + name, depth: 1 } } }; return native('spawn', { caller: ROOT, source, - bootstrap: { version: 1, sessionId: ROOT, threadId: null, source, config: { cwd: state.worktree }, + bootstrap: { version: 1, sessionId: ROOT, threadId: null, source, + config: { cwd: state.worktree, model: state.model, reasoningEffort: state.effort }, ...(initialHistory === undefined ? {} : { initialHistory }) }, input: { kind: 'message', mode: 'triggerTurn', message: { kind: messageKind, text: message } }, startOptions: { parentTurnId: 'root-turn' } }, crypto.randomUUID(), signal); }; @@ -141,7 +143,10 @@ afterEach(async () => { for (const f of fixtures.splice(0)) { f.controller.abort(); for (const session of f.sessions) { session.outcome.resolve('interrupted'); session.stopGate.resolve(); } - await f.team.close(); fs.rmSync(f.directory, { recursive: true, force: true }); + await f.team.close().catch(error => { + if (!f.state.agentTeam!.workers.some(worker => worker.writerStopUnconfirmed)) throw error; + }); + fs.rmSync(f.directory, { recursive: true, force: true }); } }); @@ -285,6 +290,59 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => expect(worker.tasks[0].status).toBe('cancelled'); expect(worker.writerStopUnconfirmed).toBeUndefined(); }); + it('rejects a late spawn when the run has stopped before a worker is scheduled', async () => { + const f = fixture(); + f.controller.abort(new Error('run-stopped')); + const spawn = f.spawn('analyst').then(() => 'accepted', error => (error as Error).message); + const nextTick = new Promise(resolve => setImmediate(() => resolve('still pending'))); + expect(await Promise.race([spawn, nextTick])).toBe('math_team_dispatch_stopped'); + expect(f.state.agentTeam!.workers).toEqual([]); + expect(f.sessions).toEqual([]); + }); + + it('releases the failed startup seat for other native assignments', async () => { + let opens = 0; + const f = fixture({ beforeOpen: async () => { if (++opens === 1) throw new Error('worker-start-failed'); } }); + await expect(f.spawn('broken')).rejects.toThrow(); + await f.spawn('analyst'); + await expect(f.spawn('prover')).resolves.toMatchObject({ result: { agent: { metadata: { agentPath: '/root/prover' } } } }); + expect(f.state.agentTeam!.workers[0]).toMatchObject({ status: 'stopped', tasks: [{ status: 'failed', error: 'worker-start-failed' }] }); + }); + + it('holds the seat and the workspace when a failed startup could not confirm writer shutdown', async () => { + let opens = 0; + const f = fixture({ beforeOpen: async () => { + if (++opens === 1) throw new Error('math_codex_startup_shutdown_unconfirmed'); + } }); + await expect(f.spawn('broken')).rejects.toThrow(); + const worker = f.state.agentTeam!.workers[0]; + expect(worker.writerStopUnconfirmed).toMatchObject({ reason: 'math_codex_startup_shutdown_unconfirmed' }); + expect(worker.tasks[0].researchArtifactId).toBeUndefined(); + expect(readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0].writerStopUnconfirmed) + .toEqual(worker.writerStopUnconfirmed); + await f.spawn('analyst'); + await expect(f.spawn('prover')).rejects.toThrow('math_team_capacity_exceeded'); + await expect(f.team.restore()).rejects.toThrow('math_writer_stop_unconfirmed:broken'); + }); + + it('rejects a followup when the run stops while the previous writer is being closed', async () => { + const f = fixture(); + await f.spawn('analyst'); + const worker = f.state.agentTeam!.workers[0]!, session = f.sessions[0]!; + await session.complete(false); + await expect.poll(() => worker.activity).toBe('stopping'); + const followup = f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue the work.' } } }) + .then(() => 'accepted', error => (error as Error).message); + await new Promise(resolve => setImmediate(resolve)); + f.controller.abort(new Error('run-stopped')); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + const nextTick = new Promise(resolve => setImmediate(() => resolve('still pending'))); + expect(await Promise.race([followup, nextTick])).toBe('math_team_dispatch_stopped'); + expect(worker.tasks).toHaveLength(1); + expect(f.sessions).toHaveLength(1); + }); + it('keeps a child accepted by the host when its initiating request is subsequently cancelled', async () => { const f = fixture(), caller = new AbortController(); await f.spawn('analyst', undefined, caller.signal); @@ -387,6 +445,47 @@ describe('native AgentControl preserves the mathematical team lifecycle', () => expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toContain('saved dependency'); }); + it('can reuse a yielded worker for a different route and return to its original task', async () => { + const f = fixture(); await f.spawn('analyst', 'Route: initial\nInvestigate the first approach.'); + const worker = f.state.agentTeam!.workers[0], original = worker.tasks[0]; + expect(await f.tool({ operation: 'yield', reason: 'Awaiting a dependency.' }, worker.id)).toMatchObject({ status: 'pending-writer-stop' }); + await f.sessions[0].complete(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + const followup = (text: string) => f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } } }); + await followup('Route: other\nCheck an independent approach while the first waits.'); + expect(worker.tasks).toHaveLength(2); + expect(original.status).toBe('paused'); + expect(worker.tasks[1]).toMatchObject({ routeId: 'other', status: 'running' }); + expect(f.sessions[1].message).toContain('Check an independent approach'); + await f.sessions[1].complete(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + await followup('Route: initial\nThe dependency is ready. Continue the original approach.'); + expect(worker.tasks).toHaveLength(2); + expect(original).toMatchObject({ status: 'running', objectiveRevision: 2 }); + expect(f.sessions[2].message).toContain('Continue the original approach'); + }); + + it('holds legacy queued routes for reassignment when the checkpoint has only one native input', async () => { + const f = fixture(); await f.spawn('analyst', 'Route: initial\nInvestigate the first approach.'); + const worker = f.state.agentTeam!.workers[0]; + await f.sessions[0].complete(); + await expect.poll(() => f.team.hasActiveWorkers).toBe(false); + const earlier = { id: 'queued-earlier', message: 'First queued approach.', status: 'queued' as const, routeId: 'earlier' }; + const latest = { id: 'queued-latest', message: 'Last queued approach.', status: 'queued' as const, routeId: 'latest' }; + worker.tasks.push(earlier, latest); + worker.native!.initialInput = { author: '/root', input: { kind: 'message', mode: 'triggerTurn', + message: { kind: 'plaintext', text: 'Route: latest\nLast queued approach.' } } }; + await f.team.restore(); + expect(worker.tasks.slice(-2).map(task => task.status)).toEqual(['interrupted', 'interrupted']); + expect(f.team.hasActiveWorkers).toBe(false); + expect(f.sessions).toHaveLength(1); + await f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, + input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Route: earlier\nContinue the saved earlier approach.' } } }); + expect(worker.tasks.find(task => task.id === earlier.id)?.status).toBe('running'); + expect(f.sessions[1].message).toContain('Continue the saved earlier approach'); + }); + it('returns the pre-interruption observation and retains the member, task and draft for continuation', async () => { const f = fixture(); await f.spawn('analyst'); const worker = f.state.agentTeam!.workers[0], task = worker.tasks[0]; diff --git a/tests/agentTeamTransportFallback.test.ts b/tests/agentTeamTransportFallback.test.ts index 6502e2aa..fbbdb595 100644 --- a/tests/agentTeamTransportFallback.test.ts +++ b/tests/agentTeamTransportFallback.test.ts @@ -16,7 +16,7 @@ const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); function fixture(open: (options: MathAgentOptions, signal: AbortController) => Promise, - previous?: { turns: number; threadId: string }) { + previous?: { turns: number; threadId: string }, maxTurns = (previous?.turns ?? 0) + 1) { const { problem, workspace, directory } = localExample('agent-team-transport-'); roots.push(directory); const root = path.resolve('.'); @@ -41,9 +41,12 @@ function fixture(open: (options: MathAgentOptions, signal: AbortController) => P const run = () => runResearchWorkers({ state, workers: [worker], access: new Map([[worker.id, { environment: {}, researchSkill, retrievalRoot: directory }]]), modules: { ...directSolverModules, M1: { ...directSolverModules.M1, open: start }, - M2: { ...directSolverModules.M2, check } }, root, buildFile: path.join(directory, 'build.json'), + M2: { ...directSolverModules.M2, check }, M3: { ...directSolverModules.M3, retry: (...args) => { + const retry = directSolverModules.M3.retry(...args); + return retry && { ...retry, delayMs: 0 }; + } } }, root, buildFile: path.join(directory, 'build.json'), taskText: 'Prove the frozen targets.', executable: 'offline', profile: 'offline', signal: controller.signal, - deadline: Infinity, maxTurns: (previous?.turns ?? 0) + 1, maxTurnMs: Infinity, maxTotalTokens: 0, + deadline: Infinity, maxTurns, maxTurnMs: Infinity, maxTotalTokens: 0, save: () => writeSolverRunState(stateFile, state), emit }); return { run, state, stateFile, start, emit, controller }; } @@ -103,3 +106,34 @@ describe('AgentResearchTeam startup transport fallback', () => { expect(f.emit.mock.calls.map(([event]) => event)).not.toContain('team_transport_fallback'); }); }); + +describe('native Lead recovery', () => { + it.each(['transport exit', 'context overflow'] as const)('reopens the same team root after %s', async failure => { + const threadId = 'native-lead'; + const sequence: string[] = []; + const compact = vi.fn(async () => { sequence.push('compact'); }); + const f = fixture(async options => { + const reopening = f.start.mock.calls.length > 1; + expect(options.nativeAgentControl).toBeDefined(); + expect(options.threadId).toBe(reopening ? threadId : undefined); + if (!reopening) f.state.agentTeam!.nativeControl = { sessionId: threadId, rootThreadId: threadId, sequence: 0, mailbox: [] }; + let lastError: string | undefined; + return { threadId, compact, get lastError() { return lastError; }, + close: async () => { sequence.push('close'); }, interrupt: async () => {}, + stopForFreeze: async () => ({ status: 'stopped' }), + run: async (_message, _id, _workspace, started) => { + sequence.push(reopening ? 'retry' : 'first'); + started(reopening ? 'native-turn-2' : 'native-turn-1'); + if (reopening) return 'completed'; + lastError = failure === 'transport exit' + ? 'math_codex_transport_closed:process_exit:code=9:signal=none' : 'math_model_context_window_exceeded'; + throw new Error(lastError); + } }; + }, undefined, 2); + await f.run(); + expect(sequence).toEqual(failure === 'transport exit' + ? ['first', 'close', 'retry', 'close'] : ['first', 'close', 'compact', 'retry', 'close']); + expect(readSolverRunState(f.stateFile)).toMatchObject({ threadId, turns: 2, + agentTeam: { nativeControl: { sessionId: threadId, rootThreadId: threadId } } }); + }); +}); diff --git a/tests/codexSessionAgentControl.test.ts b/tests/codexSessionAgentControl.test.ts index 58b0bbb8..6c3bbeb7 100644 --- a/tests/codexSessionAgentControl.test.ts +++ b/tests/codexSessionAgentControl.test.ts @@ -7,6 +7,7 @@ import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSes import type { NativeAgentControlOptions } from '../src/runtime/nativeAgentControl'; import { nativeAgentControlModelCatalog } from '../src/runtime/nativeAgentControl'; import { readMathAgentSkill } from '../src/runtime/agentSkills'; +import { deferred } from './helpers/async'; const fixture = String.raw` const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'); @@ -21,7 +22,9 @@ readline.createInterface({input:process.stdin}).on('line', line => { const reply = result => send({id:call.id,result}); if (call.id === 'attach') { fs.writeFileSync(path.join(directory,'attach.json'), JSON.stringify(call)); - return send({id:start.id,result:{thread:{id:threadId},model:settings.model,approvalPolicy:'never', + const turns = process.env.LONG_RESUME_HISTORY && !settings.excludeTurns + ? [{id:'old-turn', items:[{type:'agentMessage', text:'x'.repeat(8 * 1024 * 1024)}]}] : []; + return send({id:start.id,result:{thread:{id:threadId,turns},model:settings.model,approvalPolicy:'never', reasoningEffort:settings.config.model_reasoning_effort, activePermissionProfile:start.params.bootstrap ? null : {id:'math-worker'}, agentControl:{sessionId:'root-id',agent:{threadId},configSnapshot:{model:settings.model, @@ -40,6 +43,16 @@ readline.createInterface({input:process.stdin}).on('line', line => { return reply({thread:{id:threadId},model:settings.model,approvalPolicy:'never', reasoningEffort:settings.config.model_reasoning_effort,activePermissionProfile:{id:'math-worker'}}); } + if (call.method === 'thread/compact/start') { + const turn = { id:'compact-turn',status:'inProgress' }; + host('admitTurn','compact-admit',{turnId:turn.id}); + send({method:'turn/started',params:{threadId,turn}}); + send({method:'item/completed',params:{threadId,turnId:turn.id,item:{id:'summary',type:'contextCompaction'}}}); + send({method:'turn/completed',params:{threadId,turn:{...turn,status:'completed'}}}); + host('turnFinished','compact-finished',{outcome:{threadId,turnId:turn.id,status:{completed:null}}}); + host('releaseTurn','compact-release',{turnId:turn.id}); + return reply({}); + } if (['turn/start','theoremos/agentControl/input'].includes(call.method)) { const turn = {id:'native-turn-'+ ++counter,status:'inProgress'}; const native = process.env.THEOREMOS_HOST_AGENT_CONTROL === '1'; @@ -168,15 +181,18 @@ describe('native AgentControl stdio integration without model calls', () => { }); it('requires the native child to report its actual restricted permission intersection', async () => { + const bound = vi.fn(); await expect(createCodexMathSession({ ...options, environment: { ...options.environment, BAD_CHILD_PERMISSIONS: '1' }, - nativeAgentControl: { ...host, bootstrap: { version: 1, sessionId: 'root-id', threadId: 'child-id' } }, + nativeAgentControl: { ...host, bound, bootstrap: { version: 1, sessionId: 'root-id', threadId: 'child-id' } }, })).rejects.toThrow('math_codex_sandbox_profile_mismatch'); + expect(bound).not.toHaveBeenCalled(); expect(calls().some(call => call.method === 'theoremos/agentControl/input')).toBe(false); }); it('registers the captured child identity before cold resume without replaying fork history', async () => { const bootstrap = { version: 1, sessionId: 'root-id', threadId: 'saved-child', initialHistory: 'parent-fork' }; - session = await createCodexMathSession({ ...options, threadId: 'saved-child', nativeAgentControl: { + session = await createCodexMathSession({ ...options, threadId: 'saved-child', + environment: { ...options.environment, LONG_RESUME_HISTORY: '1' }, nativeAgentControl: { ...host, bootstrap, initialInput: { author: '/root', input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Continue the saved child.' } }, startOptions: {} }, } }); @@ -188,6 +204,40 @@ describe('native AgentControl stdio integration without model calls', () => { expect(await session.run('Current source and feedback.', 'task', directory, () => {})).toBe('completed'); }); + it('resumes the Lead when the stored history exceeds the stdio frame limit', async () => { + session = await createCodexMathSession({ ...options, threadId: 'root-id', nativeAgentControl: host, + environment: { ...options.environment, LONG_RESUME_HISTORY: '1' } }); + expect(session.threadId).toBe('root-id'); + expect(await session.run('Continue the saved proof.', 'task', directory, () => {})).toBe('completed'); + }); + + it('keeps resume usage replay for a direct provider with a budget gate', async () => { + session = await createCodexMathSession({ ...options, threadId: 'root-id', nativeAgentControl: host, + requestGate: () => ({ allowed: true, settle: () => {} }) }); + const resume = calls().find(call => call.method === 'thread/resume').params; + expect(resume.excludeTurns).toBeUndefined(); + expect(session.usageSource).toBe('native-thread-totals'); + }); + + it('keeps native compaction open until the completed maintenance turn releases the writer', async () => { + const release = deferred(), reachedRelease = deferred(); + session = await createCodexMathSession({ ...options, nativeAgentControl: { request: async request => { + if (request.operation === 'releaseTurn' && request.payload.turnId === 'compact-turn') { + reachedRelease.resolve(); + await release.promise; + } + return { result: { admitted: request.operation === 'admitTurn' } }; + } } }); + let settled = false; + const compact = session.compact!().then(() => { settled = true; }); + try { + await reachedRelease.promise; + expect(settled).toBe(false); + await expect(session.run('Too early.', 'task', directory, () => {})).rejects.toThrow('math_codex_turn_already_running'); + } finally { release.resolve(); await compact; } + expect(await session.run('Use the compacted context.', 'task', directory, () => {})).toBe('completed'); + }); + it('does not activate a backend through inherited process environment', async () => { session = await createCodexMathSession({ ...options, environment: { ...options.environment, THEOREMOS_HOST_AGENT_CONTROL: '1' } }); expect(session.nativeAgentControl).toBeUndefined(); diff --git a/tests/codexSessionNativeMailbox.test.ts b/tests/codexSessionNativeMailbox.test.ts index 64a5f036..ff63e758 100644 --- a/tests/codexSessionNativeMailbox.test.ts +++ b/tests/codexSessionNativeMailbox.test.ts @@ -4,6 +4,8 @@ import { spawnSync } from 'node:child_process'; import { createServer, type Server, type ServerResponse } from 'node:http'; import type { AddressInfo } from 'node:net'; import { afterEach, describe, expect, it, vi } from 'vitest'; +import { prepareWebProviderProfile, webSolverModules } from '../apps/web/worker'; +import type { WorkerInput } from '../apps/web/shared'; import { createCodexMathSession } from '../src/runtime/codexSession'; import type { MathAgentSession } from '../src/runtime/agentSession'; import { readMathAgentSkill } from '../src/runtime/agentSkills'; @@ -12,7 +14,7 @@ import type { ModelRequestReceipt } from '../src/runtime/modelRequest'; import { deferred } from './helpers/async'; type Json = Record; -const executable = process.env.THEOREMOS_TEST_CODEX_EXECUTABLE ?? 'codex'; +const executable = process.env.THEOREMOS_TEST_CODEX_EXECUTABLE ?? path.resolve('out/codex-backend/codex'); const nativeAvailable = spawnSync(executable, ['--version'], { env: { PATH: process.env.PATH }, timeout: 5000, stdio: 'ignore' }).status === 0; const temporaryRoot = process.env.TMPDIR ?? '/data/lzh/default-storage/tmp'; @@ -34,12 +36,19 @@ describe.skipIf(!nativeAvailable)('native AgentControl mailbox through the produ directory = undefined; }); - it('retains a tool and final usage after mail arrives during a reasoning item, and explicitly loads only the pinned skill', async () => { + it.each(['CLI', 'Web'])('retains a tool and final usage after mail in a %s research session', async client => { fs.mkdirSync(temporaryRoot, { recursive: true }); directory = fs.realpathSync(fs.mkdtempSync(path.join(temporaryRoot, 'native-mailbox-relay-'))); const workspace = path.join(directory, 'work'), profile = path.join(directory, 'profile'); fs.mkdirSync(workspace); - prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); + const apiKey = 'synthetic-fixture-key'; + const webRequest: WorkerInput = { id: 'fixture', provider: { id: 'sub2api', name: 'Fixture gateway', + baseUrl: 'http://host.docker.internal:8080/v1' }, input: { apiKey, providerId: 'sub2api', model: 'deepseek-flash', effort: 'high', + task: 'Offline fixture.', source: '', workers: 1, coordination: 'independent', maxTurns: 0, maxRunSeconds: 0, + researchMode: 'skill', nativeTeamCapacity: 2 } }; + const web = client === 'Web'; + if (web) prepareWebProviderProfile(profile, webRequest); + else prepareSub2apiProfile(profile, 'deepseek-flash', 'high'); const pinnedDirectory = path.join(workspace, '.agents', 'skills', 'pinned-mailbox-fixture'); fs.mkdirSync(pinnedDirectory, { recursive: true }); const pinnedFile = path.join(pinnedDirectory, 'SKILL.md'); @@ -56,6 +65,7 @@ describe.skipIf(!nativeAvailable)('native AgentControl mailbox through the produ server = createServer(async (request, response) => { activeResponses.add(response); response.once('close', () => activeResponses.delete(response)); try { + expect(request.headers.authorization).toBe(`Bearer ${apiKey}`); const bytes: Buffer[] = []; for await (const chunk of request) bytes.push(Buffer.from(chunk)); const body = JSON.parse(Buffer.concat(bytes).toString('utf8')); requests.push(body); const index = requests.length; @@ -94,7 +104,7 @@ describe.skipIf(!nativeAvailable)('native AgentControl mailbox through the produ }); await new Promise(resolve => server!.listen(0, '127.0.0.1', resolve)); const originalFetch = globalThis.fetch; - const upstream = SUB2API_PROVIDER.baseUrl + '/responses'; + const upstream = (web ? webRequest.provider.baseUrl : SUB2API_PROVIDER.baseUrl) + '/responses'; // The production relay still parses, admits, streams and accounts for the // request. Only its fixed upstream endpoint is redirected to this fixture. vi.stubGlobal('fetch', ((input: string | URL | Request, init?: RequestInit) => { @@ -102,19 +112,21 @@ describe.skipIf(!nativeAvailable)('native AgentControl mailbox through the produ return originalFetch(`http://127.0.0.1:${(server!.address() as AddressInfo).port}/v1/responses`, init); }) as typeof fetch); - session = await createCodexMathSession({ executable, profile, workspace, model: 'deepseek-flash', effort: 'high', + const open = web ? webSolverModules(webRequest).M1.open : createCodexMathSession; + session = await open({ executable, profile, workspace, model: 'deepseek-flash', effort: 'high', instructions: 'Execute the disposable transport fixture. Follow the pinned skill.', skills: [readMathAgentSkill(pinnedFile)], - environment: { PATH: process.env.PATH, SUB2API_WESTLAKE_API_KEY: 'synthetic-fixture-key', NO_PROXY: '127.0.0.1,localhost' }, + environment: { PATH: process.env.PATH, ...(!web && { SUB2API_WESTLAKE_API_KEY: apiKey }), NO_PROXY: '127.0.0.1,localhost' }, requestGate: () => ({ allowed: true, settle: receipt => receipts.push(receipt) }), onUsage: () => {}, onItem: (phase, item) => { observedItems.push({ phase, type: item.type, id: item.id }); }, nativeAgentControl: { request: async request => ({ result: request.operation === 'attach' ? { sessionId: request.sessionId } : request.operation === 'admitTurn' ? { admitted: true } : {} }) }, }); + expect(session.usageSource).toBe('upstream-requests'); const running = session.run('Exercise the mailbox fixture.', 'fixture-turn', workspace, () => {}); - // Attach a rejection observer while the fixture controls the response stream. - void running.catch(() => {}); - const response = await firstResponse.promise; + const response = await Promise.race([firstResponse.promise, running.then(status => { + throw new Error(`fixture ended before its first upstream request (${status}): ${session!.lastError ?? 'no error'}`); + })]); const info = session.nativeAgentControl!.info!; await session.nativeAgentControl!.update({ sessionId: info.sessionId, threadId: session.threadId, sequence: 1, mailbox: [{ id: 'fixture-mail', author: '/root/peer', recipient: '/root', @@ -139,5 +151,15 @@ describe.skipIf(!nativeAvailable)('native AgentControl mailbox through the produ expect(receipts.every(receipt => receipt.complete && receipt.usage?.totalTokens === 12)).toBe(true); expect(JSON.stringify(requests[0].input)).toContain(pinnedMarker); expect(JSON.stringify(requests[0].input)).not.toContain('unrelated-catalog-fixture'); + + if (web) { + const threadId = session.threadId; + await session.compact!(); + expect(session.threadId).toBe(threadId); + expect(requests).toHaveLength(3); + expect(receipts).toHaveLength(3); + expect(await session.run('Continue after compaction.', 'after-compaction', workspace, () => {})).toBe('completed'); + expect(requests).toHaveLength(4); + } }, 45_000); }); diff --git a/tests/formalizationRelay.test.ts b/tests/formalizationRelay.test.ts index f83693e0..80bf1f85 100644 --- a/tests/formalizationRelay.test.ts +++ b/tests/formalizationRelay.test.ts @@ -212,6 +212,21 @@ describe('host credential relay for isolated formalization roles', () => { expect(gate.mock.calls[2][0]).not.toHaveProperty('threadId'); }); + it('attributes a Codex 0.172 worker to its thread within the shared root session', async () => { + vi.stubGlobal('fetch', vi.fn(async () => fakeResponse())); + const gate = vi.fn((_identity?: Parameters[0]) => ({ allowed: true as const, settle: () => {} })); + const relay = await start({ transport: 'loopback-http', requestGate: gate }); + const turnMetadata = JSON.stringify({ session_id: 'root-session', thread_id: 'worker-thread', parent_thread_id: 'root-session' }); + const request = { ...nativeTeamRequest, client_metadata: { session_id: 'root-session', thread_id: 'worker-thread', + 'x-codex-turn-metadata': turnMetadata } }; + expect((await send(relay, { body: JSON.stringify(request), headers: { 'session-id': 'root-session', + 'thread-id': 'worker-thread', 'x-codex-turn-metadata': turnMetadata } })).status).toBe(200); + expect(gate.mock.calls[0][0]?.threadId).toBe('worker-thread'); + expect((await send(relay, { body: JSON.stringify({ ...request, client_metadata: { ...request.client_metadata, + 'x-codex-turn-metadata': JSON.stringify({ thread_id: 'another-worker' }) } }) })).status).toBe(200); + expect(gate.mock.calls[1][0]).not.toHaveProperty('threadId'); + }); + it.each(['session-id', 'thread-id', 'session_id', 'x-codex-thread-id'])('attributes the native %s header', async header => { vi.stubGlobal('fetch', vi.fn(async () => fakeResponse())); const gate = vi.fn((_identity?: Parameters[0]) => ({ allowed: true as const, settle: () => {} })); @@ -222,7 +237,8 @@ describe('host credential relay for isolated formalization roles', () => { }); it.each([ - { 'thread-id': 'child-one', 'session-id': 'child-two' }, + { 'thread-id': 'child-one', 'x-codex-thread-id': 'child-two' }, + { 'session-id': 'root-one', 'session_id': 'root-two' }, { 'thread-id': 'child-one', 'x-codex-turn-metadata': JSON.stringify({ thread_id: 'child-two' }) }, { 'x-codex-turn-metadata': 'invalid-json' }, ])('keeps inconsistent native identities unattributed while accounting for the request: %j', async headers => { diff --git a/tests/skillSolver.test.ts b/tests/skillSolver.test.ts index 496db34c..04826ce7 100644 --- a/tests/skillSolver.test.ts +++ b/tests/skillSolver.test.ts @@ -11,6 +11,7 @@ import { runSolver } from '../src/solver/run'; import { assertSolverSources, git } from '../src/solver/problem'; import { localExample } from './helpers/solver'; import { researchHarness } from '../src/runtime/researchHarness'; +import { prepareWestlakeProfile } from '../src/runtime/westlake'; vi.mock('../src/math/mathBuildManifest', async original => ({ ...await original(), readMathBuildManifest: vi.fn(), @@ -44,6 +45,7 @@ describe('opt-in skill research CLI and pinned identity', () => { vi.stubEnv('DEEPSCIENTIST_MATH_ENV_FILE', path.join(example.directory, 'empty.env')); vi.stubEnv('DEEPSCIENTIST_MATH_PANTOGRAPH_MANIFEST', undefined); vi.stubEnv('DEEPSCIENTIST_MATH_PANTOGRAPH_SHA256', undefined); + vi.stubEnv('THEOREMOS_CODEX_BACKEND_EXECUTABLE', process.execPath); vi.spyOn(console, 'log').mockImplementation(() => {}); open.mockClear(); }); @@ -202,6 +204,35 @@ describe('opt-in skill research CLI and pinned identity', () => { expect(open).not.toHaveBeenCalled(); }); + it('freezes the direct Westlake Chat team with host tools and preserves that on resume', async () => { + const profile = path.join(example.directory, 'westlake-profile'); + prepareWestlakeProfile(profile, 'deepseek-flash', 'high'); + vi.stubEnv('DEEPSCIENTIST_MATH_CODEX_EXECUTABLE', process.execPath); + vi.stubEnv('THEOREMOS_CODEX_BACKEND_EXECUTABLE', path.join(example.directory, 'missing-native-backend')); + expect(await runSolver([...args, '--agent-team', '3', '--harness-profile', profile], root, modules)).toBe(0); + const saved = state(); + expect(saved).toMatchObject({ agentTeam: { transport: 'host-tools' }, agentHarness: { executable: fs.realpathSync(process.execPath) }, + researchDelegation: { mode: 'team', maxAgents: 3 }, turns: 0 }); + expect(await runSolver([...args, '--resume'], root, modules)).toBe(0); + expect(state()).toMatchObject({ runId: saved.runId, agentTeam: { transport: 'host-tools' }, turns: 0 }); + expect(open).not.toHaveBeenCalled(); + }); + + it('rejects an unfinished Westlake run with a frozen native team without changing its checkpoint', async () => { + const profile = path.join(example.directory, 'westlake-profile'); + prepareWestlakeProfile(profile, 'deepseek-flash', 'high'); + expect(await runSolver([...args, '--agent-team', '3', '--harness-profile', profile, '--codex', process.execPath], root, modules)).toBe(0); + const saved = state(); + saved.agentTeam!.transport = 'native-agent-control'; + const stateFile = output + '.runtime/state.json'; + writeSolverRunState(stateFile, saved); + const original = fs.readFileSync(stateFile); + expect(await runSolver([...args, '--resume'], root, modules)).toBe(1); + rejected('math_westlake_native_team_unsupported: create a new team run with your saved artifacts. Direct Westlake uses host tools for new runs.'); + expect(fs.readFileSync(stateFile)).toEqual(original); + expect(open).not.toHaveBeenCalled(); + }); + it('freezes optional profiles without filling seats and preserves them on resume', async () => { const team = [...args, '--research-mode', 'skill', '--skill-delegation', 'team', '--skill-max-agents', '8']; expect(await runSolver([...team, '--skill-preferred-profiles', ' engineer,elementary-number-theory,D011 '], root, modules)).toBe(0); diff --git a/tests/webAgentActions.test.ts b/tests/webAgentActions.test.ts index c7cb2cd8..fdcd5442 100644 --- a/tests/webAgentActions.test.ts +++ b/tests/webAgentActions.test.ts @@ -36,6 +36,20 @@ const libraryCommand = (operation: string, result: unknown, extra: Record { + test('keeps native waiting and member activity visible without exporting raw prompts or thread ids', () => { + const wait = { id: 'wait', type: 'collabAgentToolCall', tool: 'wait', status: 'inProgress', + senderThreadId: 'private-thread', prompt: `private ${key}` }; + const started = sanitizeAgentItem('started', wait, context); + const interrupted = sanitizeAgentItem('completed', { ...wait, status: 'interrupted' }, context); + expect(started).toEqual({ workerId: 'engineer', itemId: 'wait', phase: 'started', + kind: 'tool', tool: 'collaboration.wait_agent', status: 'running' }); + expect(interrupted).toEqual({ ...started, phase: 'completed', status: 'failed' }); + const member = done({ type: 'subAgentActivity', kind: 'completed', agentPath: '/root/specialist', agentThreadId: 'private-thread' }); + expect(member).toEqual({ workerId: 'engineer', itemId: 'item-1', phase: 'completed', + kind: 'tool', tool: 'collaboration.agent_turn_completed', status: 'done', arguments: '/root/specialist' }); + expect([started, interrupted, member].every(isWebAgentActionBody)).toBe(true); + }); + test('retains the matching Lean source and native recipient identity, but keeps stale diagnostics detached', async () => { const root = temporaryDirectory('web-check-probe-'); try { diff --git a/tests/webProviderFixture.test.ts b/tests/webProviderFixture.test.ts index 61f71a77..35df5c24 100644 --- a/tests/webProviderFixture.test.ts +++ b/tests/webProviderFixture.test.ts @@ -54,7 +54,7 @@ describe('web BYOK provider configuration and offline app-server fixture', () => expect(source).toContain('by rfl'); expect(source).toContain('by exact Nat.zero_add n'); expect(source).not.toContain('sorry'); - const checks = JSON.parse(fs.readFileSync(path.join(root, 'profile/web-fixture-checks.json'), 'utf8')); + const checks = JSON.parse(fs.readFileSync(path.join(root, 'profile/runtime/web-fixture-checks.json'), 'utf8')); expect(checks).toEqual({ apiKeyFromEnvironment: true, keyAbsentFromConfig: true, shellKeyExcluded: true, responsesProvider: true, privateProfile: true }); expect(activity).toHaveBeenCalledWith({ event: 'item_started', itemType: 'commandExecution' }); @@ -119,7 +119,7 @@ describe('web BYOK provider configuration and offline app-server fixture', () => it('refuses to start without an injected BYOK credential', async () => { await expect(createCodexMathSession({ ...options(), environment: { ...process.env, THEOREMOS_PROVIDER_API_KEY: '' } })).rejects.toThrow('math_model_api_key_missing:THEOREMOS_PROVIDER_API_KEY'); - expect(fs.existsSync(path.join(root, 'profile/web-fixture-checks.json'))).toBe(false); + expect(fs.existsSync(path.join(root, 'profile/runtime/web-fixture-checks.json'))).toBe(false); }); it('refuses a profile that persisted the API key', async () => { diff --git a/tests/workflowHarness.test.ts b/tests/workflowHarness.test.ts index e6fbbb74..575eecdf 100644 --- a/tests/workflowHarness.test.ts +++ b/tests/workflowHarness.test.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { temporaryDirectory } from './helpers/files'; -import { bindResearchHarness } from '../src/runtime/researchHarness'; +import { assertResearchHarnessCurrent, bindResearchHarness } from '../src/runtime/researchHarness'; import type { MathAgentOptions, MathAgentSession } from '../src/runtime/agentSession'; import { canonicalMathJson, mathDigest } from '../src/math/mathRuntimeIo'; import { formalizationModelConfigurationDigest, formalizationModelConfigurationSchema } from '../src/math/formalizationWorkflow'; @@ -87,6 +87,25 @@ describe('complete workflow harness selection', () => { .toThrow('math_workflow_harness_binding_mismatch'); }); + it.each(['rewrite', 'replacement'])('rejects an executable %s with the same size and modification time', mode => { + const { config } = fixture(); + const { executable, profile } = config; + const first = Buffer.alloc(2 * 1024 * 1024 + 27, 0x61); + const changed = Buffer.from(first); changed[changed.length - 1] = 0x62; + const mtime = new Date('2024-01-01T00:00:00Z'); + fs.writeFileSync(executable, first); + fs.utimesSync(executable, mtime, mtime); + const identity = bindResearchHarness('codex', executable, profile); + expect(identity.executableDigest).toBe(mathDigest(first)); + expect(() => assertResearchHarnessCurrent(identity, process.env)).not.toThrow(); + + const target = mode === 'rewrite' ? executable : executable + '.next'; + fs.writeFileSync(target, changed, { mode: 0o700 }); + fs.utimesSync(target, mtime, mtime); + if (target !== executable) fs.renameSync(target, executable); + expect(() => assertResearchHarnessCurrent(identity, process.env)).toThrow('math_harness_identity_changed'); + }); + it('retains legacy Codex profile observations alongside explicit harness identity', () => { const f = fixture(); const catalog = path.join(f.config.profile, 'models.json'); fs.writeFileSync(catalog, '{"model":"first"}');