Repository navigation
Expand file tree
/
Copy pathworker.ts
More file actions
754 lines (738 loc) · 31 KB
/
Copy pathworker.ts
File metadata and controls
754 lines (738 loc) · 31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { stringify as stringifyToml } from 'smol-toml';
import { isNativeToolBundle } from '../../src/solver/researchToolGuide';
import { prepareWebProblem } from './formalizationSeed';
import { classifyWebError, classifyWebResult } from './failure';
import { getLeanTaskEnvironment, type LeanTaskEnvironment } from '../../src/math/leanTaskEnvironment';
import { PANTOGRAPH_DIGEST_ENV, PANTOGRAPH_MANIFEST_ENV } from '../../src/math/pantographSession';
import { mathDigest, readMathJson, readMathText } from '../../src/math/mathRuntimeIo';
import { assertMathBuildAgentTools, readMathBuildManifest } from '../../src/math/mathBuildManifest';
import { isMathPathWithin } from '../../src/math/paths';
import { sub2apiModelCatalog } from '../../src/runtime/sub2api';
import { configurableRuntimeModules, type RuntimeSolverModules } from '../../src/solver/modules/runtime';
import { solverModuleConfiguration } from '../../src/solver/modules/moduleIdentity';
import { readSolverProblem } from '../../src/solver/problem';
import { runSolver } from '../../src/solver/run';
import { readKnowledgeCatalog } from '../../src/solver/theoremKnowledgeStore';
import { createWebProgressForwarder } from './progress';
import { withoutCheckMarkers } from './report';
import {
retiredResearchCoordinationCode,
webArtifactMaxBytes,
webPreparationSeconds,
type WebAgentActionBody,
type WebArtifact,
type WorkerInput,
} from './shared';
import { createAgentActionStream, sanitizeAgentItem } from './agentActions';
import { createWebWorkerBridge, freezeWebKnowledge, writeWebActiveRun } from './workerBridge';
import { webByokModuleIdentity } from './webModuleIdentity';
import { webAgentLibraryAccess } from './frozenLibrary';
import { runWebLibraryResearch } from './libraryResearch';
import { retiredWebRunInputError, webResearchArguments } from './researchMode';
import { webProofMessageSink } from './proofJournal';
import { createWebHostDisconnectWatchdog, webWorkerShutdownMs } from './workerDisconnect';
import { webHarnessResearchError } from './harness';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
type WebWorkerState = {
worktree: string;
check?: { passed: boolean; verification?: { status?: string; results?: Record<string, unknown>[] } };
};
function readCandidateSource(directory: string, file: string): string | undefined {
let descriptor: number | undefined;
try {
if (!file.startsWith(directory + path.sep)) return;
const segments = path.relative(directory, file).split(path.sep);
let current = directory;
for (const [index, segment] of segments.entries()) {
current = path.join(current, segment);
const info = fs.lstatSync(current);
if (info.isSymbolicLink() || (index < segments.length - 1 && !info.isDirectory())) return;
}
if (fs.realpathSync(file) !== file) return;
descriptor = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
const before = fs.fstatSync(descriptor);
if (!before.isFile() || before.nlink !== 1 || before.size < 1 || before.size > webArtifactMaxBytes) return;
// Resolve the opened inode on Linux as well as the path, so directory swaps cannot escape the run.
const openedPath = () =>
process.platform === 'linux' ? fs.realpathSync(`/proc/self/fd/${descriptor}`) : fs.realpathSync(file);
if (openedPath() !== file) return;
const buffer = Buffer.alloc(webArtifactMaxBytes + 1);
let bytes = 0;
while (bytes < buffer.length) {
const count = fs.readSync(descriptor, buffer, bytes, buffer.length - bytes, null);
if (!count) break;
bytes += count;
}
const after = fs.fstatSync(descriptor),
currentInfo = fs.lstatSync(file);
if (
bytes > webArtifactMaxBytes ||
bytes !== before.size ||
after.size !== before.size ||
after.mtimeMs !== before.mtimeMs ||
after.ctimeMs !== before.ctimeMs ||
currentInfo.isSymbolicLink() ||
currentInfo.ino !== after.ino ||
currentInfo.dev !== after.dev ||
fs.realpathSync(file) !== file ||
openedPath() !== file
)
return;
return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, bytes));
} catch {
return undefined;
} finally {
if (descriptor !== undefined) fs.closeSync(descriptor);
}
}
export function createWebArtifactSampler(options: {
directory: string;
output: string;
source: string;
apiKey: string;
onArtifact(artifact: WebArtifact): void;
}) {
const directory = fs.realpathSync(options.directory);
const file = path.join(`${options.output}.runtime`, 'worktree', 'generated/problem/Submission.lean');
let lastSource = options.source;
let latest: WebArtifact | undefined;
return {
get latest() {
return latest;
},
sample() {
const candidate = readCandidateSource(directory, file);
if (candidate === undefined || candidate === lastSource) return;
const source = options.apiKey ? candidate.replaceAll(options.apiKey, '[REDACTED]') : candidate;
if (Buffer.byteLength(source) > webArtifactMaxBytes) return;
lastSource = candidate;
latest = { source, workerId: 'solver', capturedAt: new Date().toISOString(), status: 'candidate' };
options.onArtifact(latest);
},
};
}
export function readWebResultProof(options: {
directory: string;
workspace: string;
status: unknown;
state?: WebWorkerState;
artifact?: WebArtifact;
}): string {
const accepted = options.status === 'evaluated_passed';
if (!accepted && !options.state?.check?.passed && options.artifact) return options.artifact.source;
if (!options.state) return '';
const tree = accepted ? options.workspace : options.state.worktree;
const file = path.resolve(tree, 'generated/problem/Submission.lean');
if (file.startsWith(options.directory + path.sep)) {
try {
return readMathText(file, webArtifactMaxBytes);
} catch {
/* Rejected or oversized candidates have no downloadable source. */
}
}
return '';
}
/**
* Why a run ended `incomplete` without a failure: its shared turn allowance ran out, its solving budget ran out
* before the abort fired, or no research route was left to run. Settings come from the request the worker ran.
*/
export function webIncompleteReason(
raw: Record<string, unknown>,
input: Pick<WorkerInput['input'], 'maxTurns' | 'maxRunSeconds'>,
) {
if (raw.status !== 'incomplete' || raw.reason) return;
if (input.maxTurns > 0 && typeof raw.turns === 'number' && raw.turns >= input.maxTurns)
return 'math_turn_limit_reached';
const elapsed = raw.solveExecutionMs ?? raw.solveWallMs;
if (input.maxRunSeconds > 0 && typeof elapsed === 'number' && elapsed >= input.maxRunSeconds * 1_000)
return 'math_run_stopped';
return 'math_research_routes_exhausted';
}
type ProviderInput = Pick<WorkerInput, 'provider'> & { input: Pick<WorkerInput['input'], 'model' | 'effort'> };
export function webProviderConfig(input: ProviderInput, modelCatalog?: string): string {
return stringifyToml({
model: input.input.model,
model_provider: 'web_provider',
model_reasoning_effort: input.input.effort,
...(modelCatalog
? {
model_catalog_json: modelCatalog,
features: { multi_agent: false, multi_agent_v2: false, goals: false, view_image: false },
}
: {}),
approval_policy: 'never',
sandbox_mode: 'workspace-write',
model_providers: {
web_provider: {
name: input.provider.name,
base_url: input.provider.baseUrl,
wire_api: 'responses',
env_key: 'THEOREMOS_PROVIDER_API_KEY',
requires_openai_auth: false,
request_max_retries: 0,
stream_max_retries: 0,
stream_idle_timeout_ms: 60_000,
},
},
shell_environment_policy: { inherit: 'all', exclude: ['THEOREMOS_PROVIDER_API_KEY'] },
history: { persistence: 'none' },
analytics: { enabled: false },
});
}
export function prepareWebProviderProfile(profile: string, request: ProviderInput): void {
fs.mkdirSync(profile, { mode: 0o700 });
const modelCatalog = request.provider.id === 'sub2api' ? path.join(profile, 'models.json') : undefined;
if (modelCatalog) fs.writeFileSync(modelCatalog, JSON.stringify(sub2apiModelCatalog()), { mode: 0o600, flag: 'wx' });
fs.writeFileSync(path.join(profile, 'config.toml'), webProviderConfig(request, modelCatalog), {
mode: 0o600,
flag: 'wx',
});
}
/**
* Writes the version a run continues from beside the task as the solver's continuation input: the file is an advisory
* attachment every Agent can read, recorded but not replayed here; the task file and the problem stay the original's.
* Returns the manifest to pass as --continuation-manifest.
*/
export function writeWebContinuation(
directory: string,
continuation: NonNullable<WorkerInput['continuation']>,
identity: { taskFile: string; workspace: string; receiptFile: string },
): string {
const content = Buffer.from(continuation.source, 'utf8'),
file = path.join(directory, 'continuation-previous.lean');
fs.writeFileSync(file, content, { mode: 0o600, flag: 'wx' });
const manifest = {
schema: 'theorem-os.continuation-input.v1',
taskDigest: mathDigest(fs.readFileSync(identity.taskFile, 'utf8')),
problemReceiptDigest: readSolverProblem(identity.workspace, identity.receiptFile).receiptDigest,
attachments: [
{
id: 'previous-version',
kind: 'proof-source',
path: path.basename(file),
bytes: content.length,
sha256: mathDigest(content),
provenance: {
source: `${continuation.label} (${continuation.file})`.slice(0, 1000),
evidence: 'recorded-not-replayed',
runId: continuation.runId,
...(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(continuation.commit) ? { commit: continuation.commit } : {}),
},
},
],
};
const manifestFile = path.join(directory, 'continuation-input.json');
fs.writeFileSync(manifestFile, JSON.stringify(manifest), { mode: 0o600, flag: 'wx' });
return manifestFile;
}
/**
* Agent shells in this container cannot read the application or its build state; they run the bundled commands from
* scripts/build-agent-tools.ts instead, which the image installs here.
*/
export const webAgentToolsDefault = '/opt/theoremos-agent-tools/math.mjs';
export const webPantographManifest = '/opt/theoremos-pantograph/manifest.json';
/** Pass only the frozen knowledge projection to the solver, outside all member worktrees. */
export function webExpertCardArguments(
directory: string,
request: Pick<WorkerInput, 'input' | 'researchConfiguration'>,
): string[] {
const cards = request.researchConfiguration?.personalExperts;
if (!request.input.nativeTeamCapacity || !cards?.length) return [];
const file = path.join(directory, 'personal-experts.json');
fs.writeFileSync(file, JSON.stringify(cards), { mode: 0o600, flag: 'wx' });
return ['--skill-expert-cards-file', file];
}
/** Proof search needs the existing sealed Mathlib/FUSE environment. Standard workers have no lease. */
export function configureWebProofSearchEnvironment(
environment: LeanTaskEnvironment,
env: NodeJS.ProcessEnv = process.env,
): void {
if (environment === 'mathlib') env[PANTOGRAPH_MANIFEST_ENV] = webPantographManifest;
else {
delete env[PANTOGRAPH_MANIFEST_ENV];
delete env[PANTOGRAPH_DIGEST_ENV];
}
}
export type WebAgentIsolation = { tools: string; hiddenRoots: readonly string[] };
const webProofProgressInstructions = `Public mathematical progress for the user:
Use public commentary in the problem's language at the start and when the math or approach changes. Briefly share the claim and assumptions, relevant Lean feedback, and next check. Distinguish proposals, local checks, and host acceptance. Keep private reasoning private and continue working after each update.`;
export function webSolverModules(
request: WorkerInput,
actions?: {
sink: (action: WebAgentActionBody) => void;
hidden: readonly string[];
solverRunId?: () => string | undefined;
},
isolation?: WebAgentIsolation,
): RuntimeSolverModules {
const harnessError = webHarnessResearchError(request.provider, request.input);
if (harnessError) throw new Error(harnessError);
const base = configurableRuntimeModules(request.input.modulePlan, request.input.coordination, request.input.workers);
const identity = webByokModuleIdentity(solverModuleConfiguration(base));
let sessions = 0;
return {
...base,
id: identity.id,
...(isolation
? {
M4: {
...base.M4,
tools: isolation.tools,
build: (problem, state, access) => base.M4.build(problem, state, { ...access, tools: isolation.tools }),
},
}
: {}),
M1: {
...base.M1,
version: identity.versions.M1!,
open: options => {
const workerId = options.environment?.DEEPSCIENTIST_MATH_WORKER_ID;
// Each item is sanitized here, inside the container, before it is written to the host.
const context =
actions && workerId
? {
workerId,
worktree: options.workspace,
hidden: actions.hidden,
tool: isolation?.tools ?? path.join(root, 'bin/math.ts'),
apiKey: request.input.apiKey,
solverRunId: actions.solverRunId?.(),
...(options.sharedProofTeam && { nativeRole: 'lead' as const }),
}
: undefined;
// Native item ids are scoped to one session; a restarted session may number its own.
const session = ++sessions;
const stream = context ? createAgentActionStream(actions!.sink) : undefined;
if (stream) {
options.signal?.addEventListener('abort', stream.stop, { once: true });
if (options.signal?.aborted) stream.stop();
}
const show = (phase: 'started' | 'completed', item: Record<string, unknown>, incremental = false) => {
const id = typeof item.id === 'string' ? `${session}:${item.id}` : item.id;
const action = sanitizeAgentItem(phase, { ...item, id }, context!);
if (typeof id === 'string') stream!.write(phase, id, action, incremental);
};
return base.M1.open({
...options,
...(isolation ? { hiddenRoots: [...(options.hiddenRoots ?? []), ...isolation.hiddenRoots] } : {}),
environment: { ...options.environment, THEOREMOS_PROVIDER_API_KEY: request.input.apiKey },
...(context
? {
onItem: (phase, item) => show(phase, item),
onItemUpdate: (item, context) => {
options.onItemUpdate?.(item, context);
show('started', item, true);
},
}
: {}),
}).then(opened => {
if (!stream) return opened;
const run = opened.run,
interrupt = opened.interrupt,
close = opened.close;
opened.run = async (...args) => {
stream.reset();
if (options.signal?.aborted) stream.stop();
args[0] += `\n\n${webProofProgressInstructions}`;
try {
return await run(...args);
} finally {
stream.stop();
}
};
opened.interrupt = async () => {
stream.stop();
await interrupt();
};
opened.close = async () => {
stream.stop();
options.signal?.removeEventListener('abort', stream.stop);
await close();
};
return opened;
});
},
},
};
}
/** Rejections before result publication must reach the worker's error handler. */
export async function runWebProofSolver(
args: string[],
solverRoot: string,
modules?: RuntimeSolverModules,
signal?: AbortSignal,
): Promise<void> {
let rejection: string | undefined;
await runSolver(args, solverRoot, modules, signal, {
onRejected: reason => {
rejection = reason;
},
});
if (rejection !== undefined) throw new Error(rejection);
}
async function main(watchdog: ReturnType<typeof createWebHostDisconnectWatchdog>, controlledStdin: boolean) {
let bytes = 0;
const chunks: Buffer[] = [];
// Legacy callers send a single JSON document to EOF. The runner can keep stdin
// open on compatible images, framing the request with a newline and then sending heartbeats.
const stdin = process.stdin[Symbol.asyncIterator]();
if (controlledStdin) watchdog.heartbeat();
for (;;) {
const { value, done } = await stdin.next();
if (done) break;
const chunk = Buffer.from(value);
const newline = controlledStdin ? chunk.indexOf(10) : -1;
const input = newline === -1 ? chunk : chunk.subarray(0, newline);
bytes += input.length;
if (bytes > 16 * 1024 * 1024) throw new Error('运行输入过大。');
chunks.push(input);
if (newline !== -1) {
watchdog.heartbeat();
void (async () => {
try {
while (!(await stdin.next()).done) watchdog.heartbeat();
} catch {
/* A broken stdin pipe also ends the control stream. */
} finally {
watchdog.disconnect();
}
})();
break;
}
}
const request = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))) as WorkerInput;
const key = request.input.apiKey;
const journalDirectory =
process.env.THEOREMOS_WORKER_JOURNAL && fs.realpathSync(process.env.THEOREMOS_WORKER_JOURNAL);
const write = webProofMessageSink(
process.stdout,
key,
journalDirectory ? { directory: journalDirectory, webRunId: request.id } : undefined,
);
const send: typeof write = (message, frame) =>
write(message, request.observationSourceRefs === true ? frame : undefined);
const retiredInput = retiredWebRunInputError(request.input);
if (retiredInput) {
send({
type: 'error',
message: retiredInput,
failure: { kind: 'protocol', reason: retiredResearchCoordinationCode },
});
process.exitCode = 1;
return;
}
const harnessError = webHarnessResearchError(request.provider, request.input);
if (harnessError) {
send({ type: 'error', message: harnessError });
process.exitCode = 1;
return;
}
const workspaceRoot = process.env.THEOREMOS_WORKER_ROOT || '/work';
const directory = fs.mkdtempSync(path.join(workspaceRoot, 'run-'));
const activeRunFile = path.join(workspaceRoot, 'active-run.json');
const activateRound = (
output: string,
libraryRestart?: Parameters<typeof writeWebActiveRun>[0]['libraryRestart'],
) => {
const active = { webRunId: request.id, directory, output, libraryRestart };
writeWebActiveRun(active, activeRunFile);
return createWebWorkerBridge({ ...active, apiKey: key, onMessage: send });
};
let output = path.join(directory, 'result.json');
let bridge = activateRound(output);
const profile = path.join(directory, 'codex');
prepareWebProviderProfile(profile, request);
fs.mkdirSync(process.env.HOME || '/work/home', { recursive: true, mode: 0o700 });
// Each container owns this profile. No machine profile or authentication file is read.
process.env.CODEX_HOME = profile;
process.env.DEEPSCIENTIST_MATH_ENV_FILE = path.join(directory, 'math.env');
fs.writeFileSync(process.env.DEEPSCIENTIST_MATH_ENV_FILE, '', { mode: 0o400, flag: 'wx' });
const originalLog = console.log;
let artifactSampler: ReturnType<typeof createWebArtifactSampler> | undefined;
let observationTimer: ReturnType<typeof setInterval> | undefined;
let capturePending: Promise<unknown> | undefined;
const capture = async (final = false) => {
if (final) await capturePending;
const stateFile = `${output}.runtime/state.json`;
return (capturePending ??= bridge
.capture({ includeCatalog: final, force: final })
.catch(error => {
// The marker exists during preparation, before the first solver checkpoint is available.
if (fs.existsSync(stateFile) && error instanceof Error && error.message !== 'math_runtime_lease_busy')
send({ type: 'progress', event: 'observation_unavailable', message: `研究观察暂不可用:${error.message}。` });
})
.finally(() => {
capturePending = undefined;
}));
};
let solverRunId: string | undefined;
const forwardProgress = createWebProgressForwarder(send);
console.log = (...args: unknown[]) => {
for (const value of args)
if (typeof value === 'string') {
try {
const event = JSON.parse(value);
if (event.event === 'ready' && typeof event.runId === 'string') solverRunId = event.runId;
forwardProgress(event);
if (
['turn_checkpoint', 'proof_check_started', 'candidate_selected', 'evaluation_started'].includes(event.event)
)
artifactSampler?.sample();
} catch {
/* Unstructured runtime output stays private to this disposable container. */
}
}
};
console.error = () => {};
try {
const researchArguments = webResearchArguments(request.input);
const environment = getLeanTaskEnvironment(request.input.environment ?? 'standard');
configureWebProofSearchEnvironment(environment.id);
const receipt = prepareWebProblem(directory, request);
const buildFile = process.env.THEOREMOS_WORKER_BUILD || '/opt/theoremos-build.json';
const buildIndex = readMathJson(buildFile) as { buildManifestRef: string };
const build = readMathBuildManifest(buildIndex.buildManifestRef, root, path.join(root, 'out/main'), 'source');
const taskFile = receipt.taskFile;
const knowledgeFile = freezeWebKnowledge(directory, request.knowledgeCatalog);
const expertCardArguments = webExpertCardArguments(directory, request);
if (request.input.knowledgeDigest) {
if (!knowledgeFile) throw new Error('math_knowledge_identity_changed');
readKnowledgeCatalog(knowledgeFile, request.input.knowledgeDigest);
}
const continuationFile =
request.continuation &&
writeWebContinuation(directory, request.continuation, {
taskFile,
workspace: receipt.workspaceRoot,
receiptFile: receipt.activeProblemPath,
});
observationTimer = setInterval(() => {
artifactSampler?.sample();
void capture();
}, 1_500);
const buildState = path.dirname(path.dirname(path.dirname(buildIndex.buildManifestRef)));
const tools = process.env.THEOREMOS_WORKER_AGENT_TOOLS || webAgentToolsDefault;
// Without the bundle the shells would need the application itself, so the run stops rather than expose it.
if (!fs.existsSync(tools) || isMathPathWithin(root, fs.realpathSync(tools)))
throw new Error('math_agent_tools_unavailable');
// Native deployments can supply their own dispatcher. The packaged TypeScript copy is bound to this build.
if (!isNativeToolBundle(tools)) {
if ('agentTools' in build && path.basename(tools) !== 'math.mjs') throw new Error('math_agent_tools_unavailable');
assertMathBuildAgentTools(build, path.dirname(path.resolve(tools)));
}
const modules = webSolverModules(
request,
{
sink: action => send({ type: 'action', action }),
solverRunId: () => solverRunId,
// Keep the application, build state, Codex profile and solver state private.
// The proof workspace inside the run directory is shown relative.
hidden: [
root,
buildState,
buildFile,
directory,
activeRunFile,
...(journalDirectory ? [journalDirectory] : []),
],
},
{ tools, hiddenRoots: [root, buildState, ...(journalDirectory ? [journalDirectory] : [])] },
);
const completed = await runWebLibraryResearch({
directory,
request,
seed: receipt,
output,
continuationFile,
libraryCatalog: webAgentLibraryAccess(environment.id),
run: async round => {
watchdog.signal.throwIfAborted();
if (round.previousSolverRunId) {
output = round.output;
solverRunId = undefined;
bridge = activateRound(output, { previousSolverRunId: round.previousSolverRunId, round: round.round });
}
artifactSampler = createWebArtifactSampler({
directory,
output,
source: request.input.source,
apiKey: key,
onArtifact: artifact => send({ type: 'artifact', artifact }),
});
if (round.round)
send({
type: 'progress',
event: 'library_continuation_started',
message: `已装入请求的库依赖,保留原题与研究材料,开始第 ${round.round + 1} 轮。`,
});
await runWebProofSolver(
[
'--workspace',
round.seed.workspaceRoot,
'--task-file',
round.seed.taskFile,
'--output',
output,
'--receipt-file',
round.seed.activeProblemPath,
'--build-manifest',
buildIndex.buildManifestRef,
'--model',
request.input.model,
'--effort',
request.input.effort,
'--no-explanations',
...(request.input.coordination === 'cooperative' ? ['--coordination', 'cooperative'] : []),
'--max-turns',
String(round.limits.maxTurns),
...researchArguments,
...expertCardArguments,
...(request.input.nativeTeamCapacity
? ['--harness-profile', profile]
: request.provider.execution?.executable
? ['--harness-profile', profile, '--harness-executable', request.provider.execution.executable]
: []),
...(round.planApproval ? ['--plan-approval'] : []),
...(knowledgeFile ? ['--knowledge-base', knowledgeFile] : []),
...(round.continuationFile ? ['--continuation-manifest', round.continuationFile] : []),
...(round.libraryCatalog
? [
'--library-catalog',
round.libraryCatalog.file,
'--library-catalog-sha256',
round.libraryCatalog.digest,
]
: []),
// The remaining shared budget follows the run into the new library environment.
'--max-run-seconds',
String(round.limits.maxRunSeconds),
'--max-turn-seconds',
String(round.limits.maxRunSeconds),
...(round.limits.maxTotalTokens ? ['--max-total-tokens', String(round.limits.maxTotalTokens)] : []),
'--prepare-timeout-seconds',
String(
round.limits.maxRunSeconds === 0
? 0
: webPreparationSeconds[environment.id === 'mathlib' ? 'mathlib' : 'standard'],
),
...(round.limits.maxRunSeconds === 0 ? ['--proof-timeout-seconds', '0'] : []),
'--evaluator-timeout-seconds',
round.limits.maxRunSeconds === 0 ? '0' : '120',
],
root,
modules,
watchdog.signal,
);
artifactSampler.sample();
await capture(true);
},
});
clearInterval(observationTimer);
const { raw, state } = completed;
const report = Object.fromEntries(
[
'schema',
'runId',
'problemId',
'status',
'solution_commit',
'solver_ready_receipt_valid',
'completion_signal_valid',
'evaluator',
'turns',
'solveWallMs',
'solveExecutionMs',
'solveWaitingMs',
'usage',
'winningWorker',
'workers',
'teamContributions',
'reason',
'tokenBudget',
'libraryResearch',
'libraryUsage',
]
.filter(field => Object.hasOwn(raw, field))
.map(field => [field, raw[field]]),
);
const disconnected = watchdog.signal.aborted && raw.status !== 'evaluated_passed';
if (disconnected) report.reason = 'math_host_disconnected';
const failure = disconnected ? { kind: 'network', reason: 'math_host_disconnected' } : classifyWebResult(raw);
if (failure) report.failure = failure;
const stopReason = webIncompleteReason(raw, request.input);
if (stopReason) report.stopReason = stopReason;
report.environment = {
id: environment.id,
toolchain: environment.toolchain,
dependencyDigest: environment.dependencyDigest,
...(environment.mathlibRevision ? { mathlibRevision: environment.mathlibRevision } : {}),
};
if (state?.check)
report.candidateCheck = {
passed: state.check.passed,
status: state.check.verification?.status,
results: state.check.verification?.results?.slice(0, 64).map(result =>
Object.fromEntries(
['theoremName', 'status', 'sorryCount', 'admitCount', 'error', 'stdoutPreview', 'stderrPreview']
.filter(field => Object.hasOwn(result, field))
.map(field => {
const value: unknown = result[field as keyof typeof result];
if (typeof value !== 'string') return [field, value];
return [field, (field.endsWith('Preview') ? withoutCheckMarkers(value) : value).slice(0, 2_000)];
})
.filter(([, value]) => value !== ''),
),
),
};
const proof = readWebResultProof({
directory,
workspace: completed.seed.workspaceRoot,
status: raw.status,
state,
artifact: artifactSampler?.latest,
});
send({ type: 'result', result: { status: String(raw.status || 'runtime_error'), proof, report } });
} catch (error) {
clearInterval(observationTimer);
await capture(true);
send({
type: 'error',
message: '运行未能完成。请检查 Lean 原题、模型服务配置与隔离环境。',
failure: watchdog.signal.aborted
? { kind: 'network', reason: 'math_host_disconnected' }
: classifyWebError(error),
});
process.exitCode = 1;
} finally {
clearInterval(observationTimer);
request.input.apiKey = '';
console.log = originalLog;
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const controlledStdin = process.env.THEOREMOS_WORKER_CONTROL === '1';
const graceMs = Number(process.env.THEOREMOS_WORKER_DISCONNECT_GRACE_MS);
let forceExit: ReturnType<typeof setTimeout> | undefined;
const watchdog = createWebHostDisconnectWatchdog(process.stdout, {
...(Number.isSafeInteger(graceMs) && graceMs > 0 && graceMs <= 2_147_483_647 ? { graceMs } : {}),
// The normal abort unwinds the solver and records the latest evidence first.
onAbort: () => {
forceExit = setTimeout(() => process.exit(1), webWorkerShutdownMs);
},
});
main(watchdog, controlledStdin)
.catch(() => {
process.stdout.write(JSON.stringify({ type: 'error', message: '运行输入无效或环境无法初始化。' }) + '\n');
process.exitCode = 1;
})
.finally(() => {
watchdog.stop();
clearTimeout(forceExit);
if (controlledStdin) process.stdin.destroy();
// Journal writes finished above. A stale attach pipe must not keep the worker alive.
if (watchdog.signal.aborted) process.exit(process.exitCode);
});
}