Repository navigation
Expand file tree
/
Copy pathjobs.ts
More file actions
941 lines (938 loc) · 40 KB
/
Copy pathjobs.ts
File metadata and controls
941 lines (938 loc) · 40 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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
import { queueCounts } from './queueCounts';
import { webProviderExecutionDigest, webHarnessResearchError } from './harness';
import crypto from 'node:crypto';
import type { WebConfig } from './config';
import type { WebRunner } from './runner';
import type {
WebEvent,
WebEventDetails,
WebProvider,
WebResult,
WebWorkerProvider,
WebRun,
WebRunInput,
WorkerInput,
WorkerMessage,
} from './shared';
import { webResearchModeError } from './researchMode';
import { normalizeWebTeamPreferences } from './nativeTeamProfiles';
import { personalExpertCardsDigest } from '../../src/solver/personalExperts';
import { isProgressEvent, parseWebFailure, webAgentActionLimits, webLimits, webRunEventLimit } from './shared';
import { recordWebModuleEvent, sanitizeWebEventDetails } from './moduleTelemetry';
import type { WebCommand, WebCommandResult, WebLibraryRestart, WebObservation } from './collaboration';
import { canonicalMathJson, mathDigest } from '../../src/math/mathRuntimeIo';
import { currentResearchModulePlan } from '../../src/solver/modules/policy';
import { WebStorage, type WebCreation } from './storage';
import { WebKnowledgeService } from './knowledgeService';
import { freezeModuleConfiguration } from './moduleRegistry';
import { WebStorageError } from './storage';
import { isAcceptedRun, isStatementReviewed } from './presentation';
import { projectStoredObservationChecks } from './observationChecks';
type Job = {
owner: string;
run: WebRun;
input: WebRunInput;
provider: WebWorkerProvider;
controller: AbortController;
formalization?: WorkerInput['formalization'];
compiledFormalization?: WorkerInput['compiledFormalization'];
researchConfiguration?: WorkerInput['researchConfiguration'];
continuation?: WorkerInput['continuation'];
};
const terminal = (run: WebRun) => ['completed', 'cancelled', 'error'].includes(run.status);
const clean = <T>(value: T, key: string): T =>
JSON.parse(
key ? JSON.stringify(value).replaceAll(JSON.stringify(key).slice(1, -1), '[REDACTED]') : JSON.stringify(value),
);
export class WebJobs {
private jobs = new Map<string, Job>();
private creations = new Map<string, WebCreation & { runId: string }>();
private running = 0;
private closing = false;
private closeError?: unknown;
private commands = new Map<string, { digest: string; promise: Promise<WebCommandResult> }>();
private readonly versionId = crypto.randomUUID();
private revisions = new Map<string, number>();
private listeners = new Map<string, Set<(version: string) => void>>();
private pendingNotifications = new Set<string>();
/** Runs whose action count changed since they were last saved; see actionsChanged. */
private pendingActions = new Map<string, ReturnType<typeof setTimeout>>();
readonly storage: WebStorage;
readonly knowledge: WebKnowledgeService;
private readonly onAccepted?: (owner: string) => void;
private readonly onFinished?: (owner: string, run: WebRun) => void;
private readonly onPlanWaiting?: (owner: string, run: WebRun) => void;
private readonly onProofAccepted?: (
owner: string,
run: WebRun,
credentials: { apiKey: string; provider: WebProvider },
) => void;
private readonly onStatementReview?: (owner: string, run: WebRun) => void;
constructor(
private readonly runner: WebRunner,
private readonly config: Pick<WebConfig, 'concurrency' | 'queueLimit'>,
options: {
storage?: WebStorage;
knowledge?: WebKnowledgeService;
onAccepted?: (owner: string) => void;
onFinished?: (owner: string, run: WebRun) => void;
onPlanWaiting?: (owner: string, run: WebRun) => void;
onProofAccepted?: WebJobs['onProofAccepted'];
onStatementReview?: WebJobs['onStatementReview'];
} = {},
) {
this.onAccepted = options.onAccepted;
this.onFinished = options.onFinished;
this.onPlanWaiting = options.onPlanWaiting;
this.onProofAccepted = options.onProofAccepted;
this.onStatementReview = options.onStatementReview;
this.storage = options.storage ?? new WebStorage();
this.knowledge = options.knowledge ?? new WebKnowledgeService(this.storage);
for (const { owner, run, creation } of this.storage.loadRuns()) {
if (creation) this.creations.set(JSON.stringify([owner, creation.requestId]), { ...creation, runId: run.id });
const provider: WebWorkerProvider = { id: run.providerId, name: run.providerId, baseUrl: '' };
const tail = this.storage.recoverRunTail(owner, run);
const recoveredObservation = tail.observation && this.applyObservation(run, tail.observation);
if (tail.actionCount !== undefined) run.actions = { ...run.actions, count: tail.actionCount };
this.jobs.set(run.id, { owner, run, provider, input: { ...run, apiKey: '' }, controller: new AbortController() });
if (run.result && (!terminal(run) || (run.phase === 'interrupted' && run.result.status === 'evaluated_passed'))) {
if (run.phase === 'interrupted') {
delete run.error;
delete run.failure;
delete run.finishedAt;
}
const last = run.events.at(-1);
this.finishResult(run, run.result, last?.type === 'finished' ? last.at : run.updatedAt);
} else if (!terminal(run)) {
run.status = 'error';
run.phase = 'interrupted';
run.finishedAt = new Date().toISOString();
run.error = '服务已重启;保留最后观测与已有证据。本次运行未恢复执行。';
run.failure = { kind: 'interrupted' };
delete run.queue;
this.event(run, 'interrupted', run.error);
} else {
if (run.phase === 'interrupted' && !run.failure) run.failure = { kind: 'interrupted' };
if (recoveredObservation || tail.actionCount !== undefined) this.persist(run);
}
}
}
queueState() {
const waiting = [...this.jobs.values()].filter(job => job.run.status === 'queued').map(job => job.run.createdAt);
return { running: this.running, waiting };
}
counts() {
return queueCounts(this.queueState());
}
list(owner: string): WebRun[] {
return [...this.jobs.values()]
.filter(job => job.owner === owner)
.map(job => job.run)
.reverse();
}
get(owner: string, id: string): WebRun | undefined {
const job = this.jobs.get(id);
return job?.owner === owner ? job.run : undefined;
}
version(owner: string): string {
const identity = `${this.versionId}/${owner}/${this.revisions.get(owner) ?? 0}`;
return `"${crypto.createHash('sha256').update(identity).digest('hex')}"`;
}
subscribe(owner: string, listener: (version: string) => void): () => void {
let listeners = this.listeners.get(owner);
if (!listeners) this.listeners.set(owner, (listeners = new Set()));
listeners.add(listener);
return () => {
listeners.delete(listener);
if (!listeners.size && this.listeners.get(owner) === listeners) this.listeners.delete(owner);
};
}
private creation(input: WebRunInput, provider: WebWorkerProvider, requestId: string): WebCreation {
const { apiKey: _key, ...visible } = input;
const providerIdentity = {
id: provider.id,
baseUrl: provider.baseUrl,
...(provider.harness || provider.execution ? { executionDigest: webProviderExecutionDigest(provider) } : {}),
};
return {
schema: 'theorem-os.web-creation.v1',
requestId,
digest: crypto
.createHash('sha256')
.update(
canonicalMathJson({
input: { ...visible, environment: input.environment ?? 'standard' },
provider: providerIdentity,
}),
)
.digest('hex'),
};
}
replay(
owner: string,
input: WebRunInput,
provider: WebWorkerProvider,
requestId?: string,
legacyEnvironmentOmitted = false,
): WebRun | undefined {
if (!requestId) return;
if (!/^[A-Za-z0-9_-]{1,128}$/u.test(requestId)) throw new WebStorageError(400, '提交请求标识无效。');
const stored = this.creations.get(JSON.stringify([owner, requestId]));
const previous = stored ?? this.storage.deletedCreation(owner, requestId);
if (!previous) return;
// New submissions have nothing to compare. Hash the full source only for a saved identity.
input = normalizeWebTeamPreferences(input);
const expected = this.creation(input, provider, requestId);
// Older HTTP clients could omit the environment when its default was standard.
// Match that frozen identity only on a replay; new submissions keep the current default.
if (
previous.digest !== expected.digest &&
(!legacyEnvironmentOmitted ||
previous.digest !== this.creation({ ...input, environment: 'standard' }, provider, requestId).digest)
)
throw new WebStorageError(409, '同一提交请求不能使用不同的题目或配置。');
const run = stored && this.get(owner, stored.runId);
if (!run) throw new WebStorageError(410, '这次提交对应的运行已删除,请发起新研究。');
return run;
}
/** The source goes only to the worker; its exact host-resolved identity stays with the visible run. */
create(
owner: string,
input: WebRunInput,
provider: WebWorkerProvider,
continuation?: WorkerInput['continuation'],
requestId?: string,
formalization?: { evidence?: unknown; compiled?: unknown; provenance: NonNullable<WebRun['formalization']> },
researchConfiguration?: WorkerInput['researchConfiguration'],
creationInput: WebRunInput = input,
): WebRun {
input = normalizeWebTeamPreferences(input);
if (input.nativeTeamCapacity !== undefined && input.researchMode === undefined)
input = { ...input, researchMode: 'skill' };
const modeError = webResearchModeError(input);
const harnessError = webHarnessResearchError(provider, input);
if (harnessError) throw new WebStorageError(400, harnessError);
if (modeError) throw new WebStorageError(400, modeError);
const previous = this.replay(owner, creationInput, provider, requestId);
if (previous) return previous;
if (this.closing) throw new Error('服务正在停止,请稍后重试。');
const count = (status: string) => [...this.jobs.values()].filter(job => job.run.status === status).length;
const active = count('running'),
waiting = count('queued');
if (active + waiting >= this.config.queueLimit)
throw new Error(`运行队列已满:${active} 个任务正在运行,${waiting} 个在排队。草稿已保留,请等几分钟后再提交。`);
if (this.list(owner).length >= webLimits.maxRuns)
throw new Error(`已达到 ${webLimits.maxRuns} 条运行记录的上限。请先下载需要的档案,删除已结束的记录后重试。`);
const now = new Date().toISOString();
const knowledgeDigest =
input.knowledgeDigest === undefined
? continuation
? this.get(owner, continuation.runId)?.knowledgeDigest
: this.knowledge.latestReusableCatalog(owner)?.digest
: input.knowledgeDigest;
if (knowledgeDigest && !this.knowledge.getCatalog(owner, knowledgeDigest))
throw new WebStorageError(404, '所选知识目录不存在或不属于当前会话。');
const pinnedInput: WebRunInput = {
...input,
environment: input.environment ?? 'standard',
autoExplain: input.autoExplain ?? true,
explanationLanguage: input.explanationLanguage ?? 'zh',
};
if (researchConfiguration && !input.nativeTeamCapacity) {
const modulePlan = currentResearchModulePlan(researchConfiguration.modulePlan);
if (modulePlan !== researchConfiguration.modulePlan) {
const { digest: _oldDigest, ...configuration } = { ...researchConfiguration, modulePlan };
researchConfiguration = { ...configuration, digest: mathDigest(canonicalMathJson(configuration)) };
}
pinnedInput.modulePlan = structuredClone(modulePlan);
} else if (pinnedInput.modulePlan) pinnedInput.modulePlan = currentResearchModulePlan(pinnedInput.modulePlan);
if (input.researchMode === 'skill') pinnedInput.skillLoading ??= 'native';
if (knowledgeDigest) pinnedInput.knowledgeDigest = knowledgeDigest;
else delete pinnedInput.knowledgeDigest;
const { apiKey, knowledgeDigest: _selectedKnowledgeDigest, ...visible } = pinnedInput;
const environment = input.environment ?? 'standard';
const fields = {
...clean(visible, apiKey),
...(knowledgeDigest !== undefined ? { knowledgeDigest } : {}),
...(formalization ? { formalization: formalization.provenance } : {}),
environment,
};
const run: WebRun = {
...fields,
id: crypto.randomUUID(),
title: (formalization?.provenance.original.trim() || fields.task).split('\n')[0].slice(0, 60) || 'Lean 研究',
status: 'queued',
phase: 'queued',
createdAt: now,
updatedAt: now,
timings: {},
events: [],
modules: {},
};
if (input.continueFrom && continuation)
run.continueFrom = clean(
{
...input.continueFrom,
...(continuation.taskVersion ? { taskVersion: continuation.taskVersion } : {}),
...(continuation.sourceDigest ? { sourceDigest: continuation.sourceDigest } : {}),
...(continuation.environmentDigest ? { environmentDigest: continuation.environmentDigest } : {}),
file: continuation.file,
},
apiKey,
);
if (researchConfiguration) run.researchConfiguration = structuredClone(researchConfiguration);
if (provider.harness || provider.execution) {
run.harness = 'codex';
run.harnessConfigurationDigest = webProviderExecutionDigest(provider);
}
if (input.researchMode !== 'skill' || input.workers > 1 || input.modulePlan)
run.moduleConfiguration = freezeModuleConfiguration(run.modulePlan, run.coordination, run.workers);
const creation = requestId
? this.creation(normalizeWebTeamPreferences(creationInput), provider, requestId)
: undefined;
this.event(run, 'queued', '任务已进入队列');
// Persist the identity and initial run atomically before a worker can be queued.
this.storage.saveRun(owner, run, creation);
if (creation) this.creations.set(JSON.stringify([owner, requestId]), { ...creation, runId: run.id });
this.jobs.set(run.id, {
owner,
input: pinnedInput,
provider: structuredClone(provider),
run,
controller: new AbortController(),
...(researchConfiguration ? { researchConfiguration: structuredClone(researchConfiguration) } : {}),
...(formalization ? { formalization: formalization.evidence } : {}),
...(formalization?.compiled ? { compiledFormalization: formalization.compiled } : {}),
...(continuation ? { continuation } : {}),
});
this.reindex();
queueMicrotask(() => this.pump());
return run;
}
/** Review updates only the Web provenance; the solver's frozen task and Lean receipt never change. */
reviewFormalization(
owner: string,
id: string,
candidateDigest: string,
confirmation: NonNullable<WebRun['formalization']>['confirmation'],
approved?: {
evidenceSha256: string;
confirmedAt: string;
sourceSha256: string;
environment: WebRun['environment'];
},
) {
const job = this.jobs.get(id),
provenance = job?.run.formalization;
if (!job || job.owner !== owner || !provenance || provenance.candidateDigest !== candidateDigest) return;
const reviewed = isStatementReviewed(job.run);
if (confirmation === 'interrupted' && provenance.confirmation !== 'pending') return;
if (approved && !['automatic', 'manual'].includes(confirmation ?? ''))
throw new Error('formalization_binding_changed');
if (
approved &&
(crypto.createHash('sha256').update(job.run.source).digest('hex') !== approved.sourceSha256 ||
job.run.environment !== approved.environment)
)
throw new Error('formalization_binding_changed');
Object.assign(
provenance,
{ confirmation },
approved ? { evidenceSha256: approved.evidenceSha256, confirmedAt: approved.confirmedAt } : {},
);
try {
this.onStatementReview?.(owner, job.run);
} catch {
/* Explanation failures never change proof acceptance. */
}
const message =
confirmation === 'automatic'
? '后台审核通过,已关联同一份固定 Lean 陈述。'
: confirmation === 'rejected'
? '后台审核要求修改陈述,已停止旧候选的证明。'
: confirmation === 'superseded'
? '陈述已更新,旧候选的证明与新版本分开保留。'
: '原题含义审核已停止;现有代码与 Lean 验收结果保留。';
this.event(job.run, 'statement_review_updated', message);
if (!['automatic', 'manual', 'pending'].includes(confirmation ?? '')) this.cancel(owner, id);
if (approved && !reviewed && isAcceptedRun(job.run)) {
this.onAccepted?.(owner);
this.onFinished?.(owner, job.run);
}
}
cancel(owner: string, id: string): WebRun | undefined {
const job = this.jobs.get(id);
if (!job || job.owner !== owner) return undefined;
if (terminal(job.run) || job.run.result?.status === 'evaluated_passed') return job.run;
const queued = job.run.status === 'queued';
try {
job.run.status = 'cancelled';
job.run.phase = 'cancelled';
job.run.finishedAt = new Date().toISOString();
delete job.run.queue;
this.event(job.run, 'cancelled', '运行已取消');
} finally {
job.controller.abort();
job.input.apiKey = '';
delete job.continuation;
delete job.formalization;
delete job.compiledFormalization;
if (queued) this.reindex();
}
return job.run;
}
remove(owner: string, id: string): 'deleted' | 'active' | 'missing' {
const job = this.jobs.get(id);
if (!job || job.owner !== owner) return 'missing';
if (!terminal(job.run)) return 'active';
this.storage.deleteRun(owner, id);
this.jobs.delete(id);
this.changed(owner);
return 'deleted';
}
forget(owner: string) {
let removed = false;
let failure: unknown;
for (const [id, job] of this.jobs)
if (job.owner === owner) {
// Detach before abort: final worker observations must not write a deleted owner's records.
this.jobs.delete(id);
if (!terminal(job.run)) {
job.run.status = 'cancelled';
job.run.phase = 'cancelled';
job.run.finishedAt = new Date().toISOString();
}
job.controller.abort();
job.input.apiKey = '';
delete job.continuation;
delete job.formalization;
delete job.compiledFormalization;
removed = true;
try {
this.storage.deleteRun(owner, id);
} catch (error) {
failure ??= error;
}
}
if (removed) {
this.reindex();
this.changed(owner);
}
if (failure) throw failure;
}
async close() {
this.closing = true;
this.closeError = undefined;
for (const timer of this.pendingActions.values()) clearTimeout(timer);
this.pendingActions.clear();
for (const job of this.jobs.values()) {
try {
this.cancel(job.owner, job.run.id);
} catch (error) {
this.closeError ??= error;
}
}
while (this.running) await new Promise(resolve => setTimeout(resolve, 25));
this.jobs.clear();
this.listeners.clear();
if (this.closeError) throw this.closeError;
}
private persist(run: WebRun) {
const job = this.jobs.get(run.id);
const pending = this.pendingActions.get(run.id);
if (pending) {
clearTimeout(pending);
this.pendingActions.delete(run.id);
}
if (job) {
this.storage.saveRun(job.owner, run);
this.changed(job.owner);
}
}
/**
* An Agent acts several times a second, and each save tells every open page to reload its run list; the action
* itself is already stored, so the run with its new count is saved at most every two seconds, or with its next event.
*/
private actionsChanged(run: WebRun) {
if (this.pendingActions.has(run.id)) return;
const timer = setTimeout(() => {
this.pendingActions.delete(run.id);
const job = this.jobs.get(run.id);
if (job?.run !== run) return;
try {
this.persist(run);
} catch {
run.error = '运行状态未能保存;服务恢复后请重新查看。';
this.changed(job.owner);
}
}, 2_000);
timer.unref?.();
this.pendingActions.set(run.id, timer);
}
private changed(owner: string) {
this.revisions.set(owner, (this.revisions.get(owner) ?? 0) + 1);
if (!this.listeners.has(owner) || this.pendingNotifications.has(owner)) return;
this.pendingNotifications.add(owner);
queueMicrotask(() => {
this.pendingNotifications.delete(owner);
const version = this.version(owner);
for (const listener of this.listeners.get(owner) ?? []) listener(version);
});
}
private libraryRestart(job: Job, message: WebLibraryRestart) {
const current =
job.run.solverAttempt ??
(job.run.observation && {
solverRunId: job.run.observation.solverRunId,
round: 0,
sequence: job.run.observation.sequence,
});
if (
!current ||
current.solverRunId !== message.previousSolverRunId ||
message.solverRunId === message.previousSolverRunId ||
!Number.isSafeInteger(message.round) ||
message.round <= current.round
)
return;
job.run.solverAttempt = { solverRunId: message.solverRunId, round: message.round, sequence: current.sequence };
delete job.run.observation;
this.persist(job.run);
}
private observe(job: Job, observation: WebObservation) {
if (this.applyObservation(job.run, observation)) this.persist(job.run);
}
private applyObservation(run: WebRun, observation: WebObservation) {
const current =
run.solverAttempt ??
(run.observation && {
solverRunId: run.observation.solverRunId,
round: 0,
sequence: run.observation.sequence,
});
if (
observation.webRunId !== run.id ||
observation.snapshot.runId !== observation.solverRunId ||
(current && (current.solverRunId !== observation.solverRunId || current.sequence >= observation.sequence))
)
return;
const configuration = observation.inspection.configuration;
const actualHarness = configuration?.agentHarness,
expectedHarness = run.harness ?? 'codex';
if (
(actualHarness && actualHarness.id !== expectedHarness) ||
(expectedHarness !== 'codex' && !actualHarness) ||
(run.agentHarness && canonicalMathJson(run.agentHarness) !== canonicalMathJson(actualHarness))
)
return;
if ((configuration?.researchMode ?? 'legacy') !== (run.researchMode ?? 'legacy')) return;
if (
(configuration?.researchDelegation?.mode === 'team' ? configuration.researchDelegation.maxAgents : undefined) !==
run.nativeTeamCapacity
)
return;
if (
canonicalMathJson(configuration?.researchDelegation?.preferredProfiles ?? []) !==
canonicalMathJson(run.nativeTeamPreferredProfiles ?? [])
)
return;
const cards = run.researchConfiguration?.personalExperts;
if (
configuration?.researchDelegation?.personalExperts?.digest !==
(cards?.length ? personalExpertCardsDigest(cards) : undefined)
)
return;
if (run.researchMode === 'skill') {
const skill = configuration?.researchSkill,
frozen = run.researchSkill;
if (
!skill ||
skill.loading !== (run.skillLoading ?? 'native') ||
(frozen && (skill.name !== frozen.name || skill.digest !== frozen.digest || skill.loading !== frozen.loading))
)
return;
run.researchSkill = { ...skill };
}
if (actualHarness) run.agentHarness = { ...actualHarness };
const approval = observation.inspection.planApproval;
if (
run.nativeTeamCapacity &&
run.planApproval &&
!run.initialPlanApproval &&
(current?.round ?? 0) === 0 &&
approval?.status === 'approved' &&
approval.approvedId &&
approval.approvedVersion &&
approval.approvedAt !== undefined
)
run.initialPlanApproval = { solverRunId: observation.solverRunId, receipt: approval };
run.solverAttempt = {
solverRunId: observation.solverRunId,
round: current?.round ?? 0,
sequence: observation.sequence,
};
run.observation = projectStoredObservationChecks(observation);
run.updatedAt = observation.observedAt;
return true;
}
guidance(owner: string, runId: string, id: string) {
const run = this.get(owner, runId);
return (
run?.observation?.guidance.find(item => item.id === id) ?? this.storage.getCommand(owner, runId, id)?.guidance
);
}
/** Resolve a saved command against observed host receipts without sending or changing anything. */
commandReceipt(owner: string, runId: string, id: string): WebCommandResult | undefined {
const run = this.get(owner, runId);
if (!run) return;
const stored = this.storage.getCommand(owner, runId, id);
if (!stored) return;
const saved = run.observation ? { ...stored, observation: run.observation } : stored;
const guidance = run.observation?.guidance.find(item => item.id === id);
if (guidance) return { ...saved, status: guidance.status, reason: guidance.reason, guidance };
const edit = run.observation?.inspection.edits.find(item => item.id === id);
if (edit)
return {
...saved,
status: edit.status,
reason: edit.reason,
baseVersion: edit.baseVersion ?? saved.baseVersion,
planVersion: edit.planVersion,
affectedTaskIds: edit.affectedTasks ?? saved.affectedTaskIds,
edit,
};
// An approval is settled once the running solver records it as the approval, or rejects it.
const approval = run.observation?.inspection.planApproval;
const approved = [run.initialPlanApproval?.receipt, approval].find(item => item?.approvedId === id);
if (approved) return { ...saved, status: 'approved', reason: undefined, planVersion: approved.approvedVersion };
const rejected = approval?.rejections.find(item => item.id === id);
if (rejected)
return {
...saved,
status: 'rejected',
reason: rejected.reason,
planVersion: rejected.planVersion ?? saved.planVersion,
};
return saved;
}
async command(
owner: string,
runId: string,
command: Extract<WebCommand, { type: 'plan-approval' }>,
): Promise<WebCommandResult> {
const job = this.jobs.get(runId);
if (!job || job.owner !== owner) throw new Error('运行不存在或不属于当前会话。');
if (command.type !== 'plan-approval' || !job.run.nativeTeamCapacity || !job.run.planApproval)
throw new WebStorageError(409, '此研究安排不支持计划审批。');
const { id } = command.approval;
const key = `${runId}/${id}`;
const digest = crypto.createHash('sha256').update(canonicalMathJson(command)).digest('hex');
const previous = this.commandReceipt(owner, runId, id);
if (previous) {
if (previous.commandDigest !== digest) throw new Error('命令 ID 已用于另一份内容,请使用新的 ID。');
return previous;
}
if (terminal(job.run) || job.run.status !== 'running') throw new Error('仅可干预正在执行且已建立计划的运行。');
if (!this.runner.command) throw new Error('当前运行器未提供人工介入通道。');
const pending = this.commands.get(key);
if (pending) {
if (pending.digest !== digest) throw new Error('命令 ID 已用于另一份内容,请使用新的 ID。');
return pending.promise;
}
// The worker clears its input credential on exit, while an already sent command may still be returning.
const apiKey = job.input.apiKey;
const run = async (): Promise<WebCommandResult> => {
try {
const receipt = clean(await this.runner.command!(runId, command), apiKey);
if (this.jobs.get(runId) !== job) throw new WebStorageError(404, '运行不存在或不属于当前会话。');
if (receipt.id !== id) throw new Error('命令回执身份不匹配。');
if (receipt.observation) this.observe(job, receipt.observation);
if (job.run.observation) receipt.observation = job.run.observation;
this.storage.saveCommand(owner, runId, id, { ...receipt, commandDigest: digest });
if (receipt.status === 'queued') {
try {
this.event(
job.run,
'plan_approval_queued',
'计划批准已提交;运行确认后 Agent 才开始工作,未生效会另行记录。',
);
} catch {
job.run.error = '运行状态未能保存;服务恢复后请重新查看。';
this.changed(owner);
}
}
return this.commandReceipt(owner, runId, id) ?? receipt;
} catch (error) {
// Deleted runs/accounts must stay deleted even when a transport fails after removal.
if (this.jobs.get(runId) !== job) throw new WebStorageError(404, '运行不存在或不属于当前会话。');
const reason = clean(error instanceof Error ? error.message : '命令回执暂不可用。', apiKey);
const receipt = {
id,
status: 'unknown',
reason,
commandDigest: digest,
...(job.run.observation ? { observation: job.run.observation } : {}),
};
this.storage.saveCommand(owner, runId, id, receipt);
return this.commandReceipt(owner, runId, id) ?? receipt;
} finally {
this.commands.delete(key);
}
};
const promise = run();
this.commands.set(key, { digest, promise });
return promise;
}
async archive(owner: string, id: string) {
const job = this.jobs.get(id);
if (!job || job.owner !== owner) throw new Error('运行不存在或不属于当前会话。');
if (!terminal(job.run) && this.runner.command) {
const apiKey = job.input.apiKey;
const capture = clean(await this.runner.command(id, { type: 'capture' }), apiKey);
if (this.jobs.get(id) !== job) throw new WebStorageError(404, '运行不存在或不属于当前会话。');
if (capture.libraryRestart) this.libraryRestart(job, capture.libraryRestart);
if (capture.observation) this.observe(job, capture.observation);
if (capture.catalog) job.run.knowledgeCatalogDigest = this.knowledge.importCatalog(owner, capture.catalog).digest;
}
const archive = this.storage.archiveRun(owner, job.run, job.run.knowledgeCatalogDigest);
job.run.archives ??= [];
if (!job.run.archives.some(item => item.id === archive.id)) job.run.archives.push(archive);
this.persist(job.run);
return archive;
}
private event(run: WebRun, type: string, message: string, rawDetails?: WebEventDetails) {
const sequence = (run.events.at(-1)?.sequence ?? 0) + 1;
run.updatedAt = new Date().toISOString();
const timing =
type === 'preparing'
? 'preparing'
: type === 'solve_started'
? 'solving'
: type === 'evaluation_started'
? 'evaluating'
: undefined;
// Keep phase boundaries even after the bounded activity log has rotated.
if (timing) (run.timings ??= {})[timing] ??= run.updatedAt;
const details = sanitizeWebEventDetails(rawDetails);
if (isProgressEvent(type, details)) run.progressAt = run.updatedAt;
const event: WebEvent = {
sequence,
at: run.updatedAt,
type,
message: message.slice(0, 2_000),
...(details ? { details } : {}),
};
recordWebModuleEvent(run, event);
run.events.push(event);
if (run.events.length > webRunEventLimit) run.events.shift();
this.persist(run);
}
private pump() {
if (this.closing) return;
while (!this.closing && this.running < this.config.concurrency) {
const job = [...this.jobs.values()].find(job => job.run.status === 'queued');
if (!job) break;
this.startWorker(job);
}
this.reindex();
}
private startWorker(job: Job) {
this.running++;
job.run.status = 'running';
job.run.phase = 'preparing';
delete job.run.queue;
void this.execute(job).finally(() => {
this.running--;
this.pump();
});
}
/** Queue positions are global and first-in first-out; only counts are shown, never other owners' runs. */
private reindex() {
const queued = [...this.jobs.values()].filter(job => job.run.status === 'queued');
queued.forEach((job, index) => {
const queue = {
position: index + 1,
ahead: index,
running: this.running,
slots: this.config.concurrency,
};
const previous = job.run.queue;
if (previous && Object.entries(queue).every(([key, value]) => previous[key as keyof typeof queue] === value))
return;
job.run.queue = queue;
this.changed(job.owner);
});
}
private finishResult(run: WebRun, result: WebResult, finishedAt: string, beforeFinished?: () => void) {
run.status = result.status === 'runtime_error' ? 'error' : 'completed';
run.phase = result.status;
run.finishedAt ??= finishedAt;
delete run.queue;
beforeFinished?.();
if (run.events.at(-1)?.type === 'finished') {
this.persist(run);
return;
}
const acceptance = !run.formalization
? '完整原题通过独立 Lean 验收'
: !isStatementReviewed(run)
? '候选 Lean 陈述通过独立验收;原题含义尚未审核通过。'
: run.formalization.confirmation === 'manual'
? 'Lean 陈述通过独立 Lean 验收;原题含义已由你确认。Lean 验收不能替代自然语言原意核对。'
: run.formalization.confirmation === 'automatic'
? 'Lean 陈述通过独立 Lean 验收;原题含义仅经模型审核,未经人工确认。Lean 验收不能替代自然语言原意核对。'
: 'Lean 陈述通过独立 Lean 验收;原题含义未记录确认方式,请核对 Lean 陈述。Lean 验收不能替代自然语言原意核对。';
this.event(run, 'finished', result.status === 'evaluated_passed' ? acceptance : '运行结束,请查看验收状态');
}
private async execute(job: Job) {
const key = job.input.apiKey;
let messageError: unknown;
const handle = (raw: WorkerMessage) => {
if (
messageError ||
this.jobs.get(job.run.id) !== job ||
(terminal(job.run) &&
raw.type !== 'observation' &&
raw.type !== 'catalog' &&
!(job.run.status === 'cancelled' && raw.type === 'library_restart'))
)
return;
try {
const message = clean(raw, key);
if (message.type === 'progress') {
if (message.event === 'library_continuation_started') delete job.run.artifact;
job.run.phase = message.event;
this.event(job.run, message.event, message.message, message.details);
// The solver asks once per run, when its first plan is accepted; the owner may be away from the page.
if (message.event === 'plan_approval_requested')
try {
this.onPlanWaiting?.(job.owner, job.run);
} catch {
/* Telling the owner never changes the run. */
}
} else if (message.type === 'action') {
// Kept apart from the 200-event activity log; past the per-run limit only the count grows.
const tally = (job.run.actions ??= { count: 0 });
if (tally.count >= webAgentActionLimits.perRun) tally.dropped = (tally.dropped ?? 0) + 1;
else {
const sequence = tally.count + 1;
this.storage.saveAction(job.owner, job.run.id, {
...message.action,
sequence,
at: new Date().toISOString(),
});
tally.count = sequence;
}
this.actionsChanged(job.run);
} else if (message.type === 'artifact') {
if (job.run.result) return;
job.run.artifact = message.artifact;
job.run.updatedAt = new Date().toISOString();
this.persist(job.run);
} else if (message.type === 'library_restart') {
this.libraryRestart(job, message);
} else if (message.type === 'observation') {
this.observe(job, message.observation);
} else if (message.type === 'catalog') {
try {
job.run.knowledgeCatalogDigest = this.knowledge.importCatalog(job.owner, message.catalog).digest;
this.persist(job.run);
} catch {
this.event(job.run, 'archive_failed', '本次知识材料未能保存;已有证明验收状态不变。');
}
} else if (message.type === 'result') {
job.run.result = message.result;
const failure = parseWebFailure(message.result.report.failure);
if (failure) job.run.failure = failure;
job.run.phase = message.result.status;
job.run.updatedAt = new Date().toISOString();
this.persist(job.run);
} else if (message.type === 'error') {
job.run.error = message.message;
job.run.failure = message.failure ?? { kind: 'environment' };
job.run.updatedAt = new Date().toISOString();
this.persist(job.run);
}
} catch (error) {
messageError = error;
job.controller.abort();
}
};
try {
this.event(job.run, 'preparing', '正在准备独立运行环境');
// Project provenance remains on the visible run; preserve the input object whose key is cleared on cancellation and completion.
delete job.input.budgetOrigin;
delete job.input.libraryProposalOrigin;
await this.runner.run(
{
id: job.run.id,
input: job.input,
provider: job.provider,
...(job.researchConfiguration ? { researchConfiguration: job.researchConfiguration } : {}),
...(job.formalization ? { formalization: job.formalization } : {}),
...(job.compiledFormalization ? { compiledFormalization: job.compiledFormalization } : {}),
...(job.input.knowledgeDigest
? { knowledgeCatalog: this.knowledge.getCatalog(job.owner, job.input.knowledgeDigest) }
: {}),
...(job.continuation ? { continuation: job.continuation } : {}),
},
handle,
job.controller.signal,
);
if (messageError) throw messageError;
if (!terminal(job.run)) {
if (!job.run.result) throw new Error(job.run.error || '没有收到运行结果。');
const accepted = job.run.result.status === 'evaluated_passed';
this.finishResult(
job.run,
job.run.result,
new Date().toISOString(),
accepted
? () => {
// The explanation queue receives credentials before the solver releases them.
try {
this.onProofAccepted?.(job.owner, job.run, { apiKey: job.input.apiKey, provider: job.provider });
} catch {
this.event(job.run, 'explanation_queue_failed', '证明已验收,自动讲解未能保存;请稍后重试。');
}
}
: undefined,
);
if (accepted && isStatementReviewed(job.run)) this.onAccepted?.(job.owner);
}
} catch (error) {
if (!terminal(job.run)) {
job.run.status = 'error';
job.run.phase = 'error';
const failure = messageError ?? error;
job.run.error = clean(failure instanceof Error ? failure.message : '运行失败。', key);
job.run.failure ??= { kind: 'environment' };
try {
this.event(job.run, 'error', job.run.error);
} catch {
/* The final save retries below, after credentials are released. */
}
}
} finally {
job.input.apiKey = '';
delete job.continuation;
delete job.formalization;
delete job.compiledFormalization;
job.run.finishedAt ??= new Date().toISOString();
try {
this.persist(job.run);
} catch (error) {
if (this.closing) this.closeError ??= error;
else {
job.run.error = '运行状态未能保存;服务恢复后请重新查看。';
job.run.failure ??= { kind: 'environment' };
}
}
try {
this.onFinished?.(job.owner, job.run);
} catch {
/* Telling the owner never changes the run. */
}
}
}
}