@anyswarm/core 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +19 -4
- package/README.md +68 -61
- package/dist/examples/README.md +134 -84
- package/dist/examples/autoresearch/README.md +106 -21
- package/dist/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
- package/dist/examples/autoresearch/config.d.ts +48 -5
- package/dist/examples/autoresearch/config.js +57 -23
- package/dist/examples/autoresearch/demo.d.ts +12 -4
- package/dist/examples/autoresearch/demo.js +65 -22
- package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -2
- package/dist/examples/autoresearch/frontiercs2-config.js +13 -2
- package/dist/examples/autoresearch/frontiercs2.d.ts +18 -1
- package/dist/examples/autoresearch/frontiercs2.js +71 -14
- package/dist/examples/autoresearch/prepare-demo.js +34 -3
- package/dist/examples/autoresearch/prepare.d.ts +105 -53
- package/dist/examples/autoresearch/prepare.js +126 -57
- package/dist/examples/autoresearch/project.d.ts +6 -1
- package/dist/examples/autoresearch/project.js +130 -26
- package/dist/examples/autoresearch/research-service.d.ts +16 -1
- package/dist/examples/autoresearch/research-service.js +84 -44
- package/dist/examples/code/config.d.ts +1 -0
- package/dist/examples/first-harness/AGENTS.md +25 -0
- package/dist/examples/first-harness/README.md +136 -0
- package/dist/examples/first-harness/config.d.ts +9 -8
- package/dist/examples/first-harness/config.js +33 -26
- package/dist/examples/first-harness/eject.json +14 -0
- package/dist/examples/first-harness/handoff.js +3 -3
- package/dist/examples/first-harness/harness.d.ts +14 -18
- package/dist/examples/first-harness/harness.js +102 -77
- package/dist/examples/first-harness/input/README.md +7 -0
- package/dist/examples/first-harness/session.js +2 -1
- package/dist/examples/first-harness/tsconfig.json +2 -1
- package/dist/examples/harness-session/README.md +1 -1
- package/dist/examples/lead-worker/README.md +1 -1
- package/dist/examples/lead-worker/project-config.d.ts +1 -0
- package/dist/examples/messages/README.md +2 -2
- package/dist/examples/notes/README.md +2 -2
- package/dist/examples/notes/config.d.ts +1 -0
- package/dist/examples/parallel-swarm/AGENTS.md +32 -0
- package/dist/examples/parallel-swarm/README.md +136 -0
- package/dist/examples/parallel-swarm/board-service.js +25 -8
- package/dist/examples/parallel-swarm/board.d.ts +31 -1
- package/dist/examples/parallel-swarm/board.js +98 -13
- package/dist/examples/parallel-swarm/config.d.ts +11 -0
- package/dist/examples/parallel-swarm/config.js +39 -0
- package/dist/examples/parallel-swarm/eject.json +5 -0
- package/dist/examples/parallel-swarm/harness.d.ts +26 -20
- package/dist/examples/parallel-swarm/harness.js +77 -76
- package/dist/examples/parallel-swarm/report.d.ts +12 -0
- package/dist/examples/parallel-swarm/report.js +30 -0
- package/dist/examples/peermesh/README.md +1 -1
- package/dist/examples/peermesh/project-config.d.ts +1 -0
- package/dist/examples/services/agent-control/README.md +1 -1
- package/dist/examples/services/mathlib-search/README.md +1 -1
- package/dist/examples/services/mcp-managed/README.md +1 -1
- package/dist/examples/services/persistent-board/README.md +1 -1
- package/dist/examples/subagents/AGENTS.md +35 -0
- package/dist/examples/subagents/README.md +129 -93
- package/dist/examples/subagents/config.d.ts +2 -10
- package/dist/examples/subagents/config.js +8 -15
- package/dist/examples/subagents/eject.json +17 -0
- package/dist/examples/subagents/handoff-config.d.ts +41 -0
- package/dist/examples/subagents/handoff-config.js +13 -0
- package/dist/examples/subagents/model.d.ts +3 -0
- package/dist/examples/subagents/model.js +19 -0
- package/dist/examples/substrate/README.md +12 -6
- package/dist/examples/substrate/config.d.ts +1 -0
- package/dist/examples/substrate/project-config.d.ts +1 -0
- package/dist/examples/taskpool/README.md +1 -1
- package/dist/examples/taskpool/config.d.ts +1 -0
- package/dist/examples/taskpool/deploy/service-hosts/service-authority-snapshot.d.ts +4 -4
- package/dist/scripts/anyswarm-progress.js +36 -5
- package/dist/scripts/build-provenance.json +1 -1
- package/dist/scripts/generate-architecture-coverage.js +1 -1
- package/dist/scripts/generate-architecture-prompts.js +18 -10
- package/dist/scripts/local-environment.d.ts +3 -3
- package/dist/scripts/local-environment.js +6 -1
- package/dist/scripts/local-setup.js +25 -18
- package/dist/scripts/pack-release.js +27 -3
- package/dist/src/core/index.js +1 -1
- package/dist/src/core/sandbox/opensandbox-backend.js +10 -4
- package/dist/src/core/sandbox/sandbox-connection.d.ts +9 -2
- package/dist/src/core/sandbox/sandbox-connection.js +22 -7
- package/dist/src/harness/project-harness.js +3 -2
- package/dist/src/harness/project-rpc-client.js +19 -0
- package/dist/src/harness/typescript-loader.d.ts +2 -0
- package/dist/src/harness/typescript-loader.js +26 -8
- package/dist/src/trace-viewer/command.mjs +6 -3
- package/dist/src/trace-viewer/public/app.js +239 -59
- package/dist/src/trace-viewer/public/index.html +5 -0
- package/dist/src/trace-viewer/public/style.css +22 -0
- package/dist/src/trace-viewer/reader.mjs +242 -26
- package/dist/src/trace-viewer/run-root.d.mts +1 -0
- package/dist/src/trace-viewer/run-root.mjs +7 -0
- package/dist/src/trace-viewer/server.mjs +3 -1
- package/docs/INDEX.md +9 -8
- package/docs/architecture/06-observability-experiments.md +21 -7
- package/docs/architecture/07-run-configuration.md +97 -12
- package/docs/architecture/08-prompts.md +21 -2
- package/docs/architecture/10-service-api-reference.md +12 -5
- package/docs/architecture/12-code-coverage.md +129 -86
- package/docs/architecture/15-core-runtime.md +1 -1
- package/docs/architecture/16-pi-opensandbox-backend.md +2 -0
- package/docs/architecture/17-harness-reporting.md +78 -0
- package/docs/architecture/22-website.md +53 -18
- package/docs/architecture/23-project-harness.md +63 -16
- package/docs/architecture/28-autoresearch.md +16 -22
- package/docs/architecture/prompts/11-first-sdk-harness.md +9 -9
- package/docs/architecture/prompts/16-parallel-swarm.md +46 -13
- package/docs/architecture/prompts/22-autoresearch.md +9 -2
- package/docs/architecture/prompts/source-manifest.json +78 -54
- package/docs/architecture/source-map.json +396 -36
- package/docs/designs/core-harness/06-project-harness.md +1 -1
- package/docs/en/autoresearch.md +41 -0
- package/docs/en/blog/100b-tokens.md +157 -0
- package/docs/en/build-your-harness.md +47 -22
- package/docs/en/changelog.md +22 -1
- package/docs/en/first-harness.md +40 -32
- package/docs/en/harnesses/index.md +23 -23
- package/docs/en/harnesses/subagents.md +8 -29
- package/docs/en/latest.md +26 -5
- package/docs/en/overview.md +22 -22
- package/docs/en/quickstart.md +55 -21
- package/docs/en/reference/api.md +1 -1
- package/docs/en/trace-viewer.md +32 -12
- package/docs/operations/trace-viewer.md +25 -10
- package/docs/workflows/development.md +160 -120
- package/docs/workflows/release-and-docs-versioning.md +207 -55
- package/docs/workflows/release-cli-acceptance.md +124 -47
- package/docs/zh/autoresearch.md +41 -0
- package/docs/zh/blog/100b-tokens.md +102 -0
- package/docs/zh/build-your-harness.md +48 -23
- package/docs/zh/changelog.md +22 -1
- package/docs/zh/first-harness.md +43 -35
- package/docs/zh/harnesses/index.md +23 -23
- package/docs/zh/harnesses/subagents.md +8 -29
- package/docs/zh/latest.md +26 -5
- package/docs/zh/overview.md +23 -23
- package/docs/zh/quickstart.md +51 -21
- package/docs/zh/reference/api.md +1 -1
- package/docs/zh/trace-viewer.md +32 -12
- package/examples/README.md +134 -84
- package/examples/autoresearch/README.md +106 -21
- package/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
- package/examples/autoresearch/config.ts +64 -25
- package/examples/autoresearch/demo.ts +75 -22
- package/examples/autoresearch/frontiercs2-config.ts +13 -2
- package/examples/autoresearch/frontiercs2.ts +64 -11
- package/examples/autoresearch/prepare-demo.ts +32 -3
- package/examples/autoresearch/prepare.ts +134 -60
- package/examples/autoresearch/project.ts +119 -26
- package/examples/autoresearch/research-service.ts +91 -41
- package/examples/first-harness/AGENTS.md +25 -0
- package/examples/first-harness/README.md +136 -0
- package/examples/first-harness/config.ts +41 -27
- package/examples/first-harness/eject.json +14 -0
- package/examples/first-harness/handoff.ts +3 -3
- package/examples/first-harness/harness.ts +104 -72
- package/examples/first-harness/input/README.md +7 -0
- package/examples/first-harness/session.ts +2 -1
- package/examples/first-harness/tsconfig.json +2 -1
- package/examples/harness-session/README.md +1 -1
- package/examples/lead-worker/README.md +1 -1
- package/examples/messages/README.md +2 -2
- package/examples/notes/README.md +2 -2
- package/examples/parallel-swarm/AGENTS.md +32 -0
- package/examples/parallel-swarm/README.md +136 -0
- package/examples/parallel-swarm/board-service.ts +28 -9
- package/examples/parallel-swarm/board.ts +107 -13
- package/examples/parallel-swarm/config.ts +47 -0
- package/examples/parallel-swarm/eject.json +5 -0
- package/examples/parallel-swarm/harness.ts +83 -71
- package/examples/parallel-swarm/report.ts +33 -0
- package/examples/peermesh/README.md +1 -1
- package/examples/services/agent-control/README.md +1 -1
- package/examples/services/mathlib-search/README.md +1 -1
- package/examples/services/mcp-managed/README.md +1 -1
- package/examples/services/persistent-board/README.md +1 -1
- package/examples/subagents/AGENTS.md +35 -0
- package/examples/subagents/README.md +129 -93
- package/examples/subagents/config.ts +8 -15
- package/examples/subagents/eject.json +17 -0
- package/examples/subagents/handoff-config.ts +14 -0
- package/examples/subagents/model.ts +20 -0
- package/examples/substrate/README.md +12 -6
- package/examples/taskpool/README.md +1 -1
- package/npm-shrinkwrap.development.json +9 -2
- package/npm-shrinkwrap.json +9 -2
- package/package.development.json +2 -1
- package/package.json +2 -1
- package/scripts/anyswarm-progress.ts +36 -6
- package/scripts/generate-architecture-coverage.ts +1 -1
- package/scripts/generate-architecture-prompts.ts +21 -10
- package/scripts/local-environment.ts +8 -1
- package/scripts/local-setup.ts +22 -17
- package/scripts/pack-release.ts +24 -3
- package/src/core/index.ts +1 -1
- package/src/core/sandbox/opensandbox-backend.ts +10 -4
- package/src/core/sandbox/sandbox-connection.ts +22 -7
- package/src/harness/project-harness.ts +3 -2
- package/src/harness/project-rpc-client.ts +23 -0
- package/src/harness/typescript-loader.ts +28 -8
- package/src/trace-viewer/command.mjs +6 -3
- package/src/trace-viewer/public/app.js +239 -59
- package/src/trace-viewer/public/index.html +5 -0
- package/src/trace-viewer/public/style.css +22 -0
- package/src/trace-viewer/reader.mjs +242 -26
- package/src/trace-viewer/run-root.d.mts +1 -0
- package/src/trace-viewer/run-root.mjs +7 -0
- package/src/trace-viewer/server.mjs +3 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { availableParallelism, freemem } from 'node:os';
|
|
2
2
|
import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, statfs, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
|
-
import {
|
|
5
|
-
import { bridgeDockerfile, bridgeWorkflow, digest, FrontierRun, frontierRevision, frontierTask, installBridge, judgeImages, pumpkinPin } from './frontiercs2.js';
|
|
4
|
+
import { frontierBudget, frontierHome, modelConfigurationError } from './config.js';
|
|
5
|
+
import { bridgeDockerfile, bridgeWorkflow, digest, FrontierRun, frontierRevision, frontierTask, installBridge, judgeImages, preparePumpkin, pumpkinPin } from './frontiercs2.js';
|
|
6
6
|
import { command, requireSuccess } from './process.js';
|
|
7
7
|
const upstream = 'https://github.com/FrontierCS/FrontierCS-2.git';
|
|
8
8
|
const taskPackage = 'tasks/binary_fuse_filter';
|
|
@@ -10,53 +10,60 @@ const shared = ['fetch', 'lib', 'shared', taskPackage];
|
|
|
10
10
|
const GiB = 1024 ** 3;
|
|
11
11
|
const prepareTimeout = 2_700_000;
|
|
12
12
|
const pinFiles = ['.pumpkinversion', 'PUMPKIN.star', 'pumpkin', ...shared];
|
|
13
|
-
export function resourcePlan(budget) {
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
13
|
+
export function resourcePlan(budget, sandbox) {
|
|
14
|
+
const lifecycle = URL.parse(sandbox.endpoint ?? sandbox.lifecycleBaseUrl ?? 'http://127.0.0.1');
|
|
15
|
+
const localWorkers = lifecycle !== null && ['localhost', '127.0.0.1', '[::1]'].includes(lifecycle.hostname);
|
|
16
|
+
const bridge = { role: 'Pumpkin submission role', count: 1, cpu: 2, memoryGiB: 4, placement: 'controller' };
|
|
17
|
+
const judge = { role: 'Active official judge', count: 1, cpu: 2, memoryGiB: 4, placement: 'controller' };
|
|
18
|
+
const controller = { role: 'Controller, services and headroom', count: 1, cpu: 2, memoryGiB: 2, placement: 'controller' };
|
|
19
|
+
const worker = { role: 'AnySwarm Workers', count: budget.workers, cpu: 2, memoryGiB: 4,
|
|
20
|
+
placement: localWorkers ? 'controller' : 'opensandbox' };
|
|
21
|
+
const totals = (roles) => ({
|
|
22
|
+
roles, cpu: roles.reduce((sum, role) => sum + role.count * role.cpu, 0),
|
|
23
|
+
memoryGiB: roles.reduce((sum, role) => sum + role.count * role.memoryGiB, 0),
|
|
24
|
+
diskGiB: 12, gpu: 0,
|
|
25
|
+
});
|
|
21
26
|
return {
|
|
22
|
-
|
|
23
|
-
|
|
27
|
+
prepare: totals([bridge, judge, controller, { role: 'Image build headroom', count: 1, cpu: 2, memoryGiB: 4, placement: 'controller' }]),
|
|
28
|
+
run: totals([worker, bridge, judge, controller]),
|
|
29
|
+
localWorkers,
|
|
24
30
|
};
|
|
25
31
|
}
|
|
26
|
-
export async function
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return [{ name: 'kimi-k3-config', ok: false, detail: error.message }];
|
|
33
|
-
}
|
|
34
|
-
const config = { name: 'kimi-k3-config', ok: true, detail: 'Configured provider, model ID and fixed Responses URL.' };
|
|
35
|
-
const name = 'kimi-k3-route';
|
|
32
|
+
export async function checkModelRoute(model, executor, signal) {
|
|
33
|
+
const problem = modelConfigurationError(model, executor);
|
|
34
|
+
const config = { name: 'model-config', ok: !problem, detail: problem ?? 'A model, protocol and endpoint are configured.' };
|
|
35
|
+
if (problem)
|
|
36
|
+
return [config];
|
|
37
|
+
const name = 'model-http';
|
|
36
38
|
try {
|
|
37
39
|
const response = await fetch(model.upstream.url, {
|
|
38
40
|
method: 'HEAD', headers: model.upstream.headers, redirect: 'manual',
|
|
39
41
|
signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]),
|
|
40
42
|
});
|
|
41
|
-
const
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
const reachable = response.ok || [405, 501].includes(response.status);
|
|
44
|
+
const headOnly = !(model.provider === 'kimi_proxy' && model.model === 'k3') && [400, 404].includes(response.status);
|
|
45
|
+
const detail = reachable ? `Endpoint responded to HEAD (HTTP ${response.status}).`
|
|
46
|
+
: headOnly ? `Endpoint is reachable; its HEAD probe returned HTTP ${response.status}. Confirm the configured POST route on the first run.`
|
|
47
|
+
: [401, 403].includes(response.status) ? `HEAD denied (HTTP ${response.status}). Check your endpoint token and access policy.`
|
|
48
|
+
: `Unexpected HEAD response (HTTP ${response.status}). Check the configured endpoint and protocol.`;
|
|
49
|
+
return [config, { name, ok: reachable || headOnly, detail }];
|
|
46
50
|
}
|
|
47
51
|
catch {
|
|
48
52
|
signal.throwIfAborted();
|
|
49
|
-
return [config, { name, ok: false, detail: 'Could not reach the
|
|
53
|
+
return [config, { name, ok: false, detail: 'Could not reach the configured model endpoint within 5 seconds. Check its URL, DNS and network access from the controller.' }];
|
|
50
54
|
}
|
|
51
55
|
}
|
|
52
56
|
function paths(home, dockerContext) {
|
|
53
57
|
return { source: join(home, 'bridge'), config: join(home, 'pumpkin.toml'), dockerContext, cache: join(home, 'cache') };
|
|
54
58
|
}
|
|
59
|
+
export const starterPath = (home) => join(home, 'reference', taskPackage, 'repo');
|
|
55
60
|
export async function loadPrepared(home = frontierHome()) {
|
|
56
|
-
const saved =
|
|
61
|
+
const saved = await readFile(join(home, 'prepared.json'), 'utf8')
|
|
62
|
+
.then(raw => JSON.parse(raw))
|
|
63
|
+
.catch(() => { throw new Error('Prepare this state directory first with anyswarm run ./prepare-demo.ts --config ./frontiercs2-config.ts.'); });
|
|
57
64
|
if (saved.version !== 2 || saved.revision !== frontierRevision || saved.pumpkin !== pumpkinPin ||
|
|
58
65
|
!/^[a-zA-Z0-9._-]+$/.test(saved.dockerContext))
|
|
59
|
-
throw new Error('Run anyswarm
|
|
66
|
+
throw new Error('Run anyswarm run ./prepare-demo.ts with the same --config to refresh this demo.');
|
|
60
67
|
const locations = paths(home, saved.dockerContext);
|
|
61
68
|
const reference = join(home, 'reference');
|
|
62
69
|
const [bridgeDigest, sourceDigest] = await Promise.all([treeDigest(locations.source), treeDigest(reference)]);
|
|
@@ -66,14 +73,13 @@ export async function loadPrepared(home = frontierHome()) {
|
|
|
66
73
|
const activeConfig = await readFile(locations.config, 'utf8');
|
|
67
74
|
if (saved.bridgeDigest !== bridgeDigest || saved.sourceDigest !== sourceDigest || activeWorkflow !== bridgeWorkflow(officialWorkflow) ||
|
|
68
75
|
roleDockerfile !== bridgeDockerfile || activeConfig !== pumpkinConfig(saved.dockerContext))
|
|
69
|
-
throw new Error('Prepared FrontierCS-2 materials changed.
|
|
70
|
-
const
|
|
71
|
-
const starter = join(reference, taskPackage, 'repo');
|
|
76
|
+
throw new Error('Prepared FrontierCS-2 materials changed. Run prepare-demo.ts with your configuration to refresh it.');
|
|
77
|
+
const starter = starterPath(home);
|
|
72
78
|
const tracked = requireSuccess(await command('git', ['ls-files', '--', 'README.md', 'include/binaryfusefilter.h'], { cwd: starter, timeoutMs: 5000 }), 'Validate tracked FrontierCS-2 starter');
|
|
73
79
|
if (!tracked.split('\n').includes('README.md') || !tracked.split('\n').includes('include/binaryfusefilter.h')) {
|
|
74
|
-
throw new Error('The pinned Git starter is missing required tracked files.
|
|
80
|
+
throw new Error('The pinned Git starter is missing required tracked files. Run prepare-demo.ts with your configuration to refresh it.');
|
|
75
81
|
}
|
|
76
|
-
return { saved
|
|
82
|
+
return { saved, paths: locations, starter };
|
|
77
83
|
}
|
|
78
84
|
async function treeDigest(root) {
|
|
79
85
|
const hashes = [];
|
|
@@ -101,7 +107,7 @@ async function sourceAt(home, signal) {
|
|
|
101
107
|
const status = await command('git', ['status', '--porcelain', '--untracked-files=no'], { cwd: cached, timeoutMs: 10_000, signal });
|
|
102
108
|
if (head.stdout.trim() === frontierRevision && status.code === 0 && !status.stdout.trim())
|
|
103
109
|
return cached;
|
|
104
|
-
throw new Error('Prepared reference source has local changes. Move it aside and
|
|
110
|
+
throw new Error('Prepared reference source has local changes. Move it aside and run prepare-demo.ts again with your configuration.');
|
|
105
111
|
}
|
|
106
112
|
const temp = await mkdtemp(join(home, 'source-'));
|
|
107
113
|
const git = async (args, timeoutMs) => requireSuccess(await command('git', args, { cwd: temp, timeoutMs, env: { ...process.env, GIT_LFS_SKIP_SMUDGE: '1' }, signal }), 'Prepare pinned FrontierCS-2 source');
|
|
@@ -129,9 +135,15 @@ async function verifyReference(record) {
|
|
|
129
135
|
const train = actions.find(action => action.kind === 'start_call' && action.grant === 'train');
|
|
130
136
|
const final = actions.find(action => action.kind === 'start_final_call');
|
|
131
137
|
const submission = outcome.agents?.find((agent) => agent.role === 'agent')?.submission;
|
|
132
|
-
const returned = (job) => events.
|
|
138
|
+
const returned = (job) => events.find(({ event }) => event?.job === job && event.kind === 'call_returned')?.event.returned;
|
|
139
|
+
const measured = (values, name) => values?.find(row => row.name === name)?.value;
|
|
140
|
+
const trainScore = measured(train && returned(train.job), 'raw_score');
|
|
141
|
+
const finalScore = measured(outcome.verdict?.result?.values, 'score');
|
|
142
|
+
const verdict = measured(outcome.verdict?.result?.values, 'summary');
|
|
133
143
|
if (outcome.state !== 'finished' || outcome.verdict?.kind !== 'returned' || outcome.usage?.model_requests !== 0 ||
|
|
134
|
-
!submission?.finalized ||
|
|
144
|
+
!submission?.finalized || typeof trainScore !== 'number' || !Number.isFinite(trainScore) || trainScore <= 0 ||
|
|
145
|
+
!final || !returned(final.job) || typeof finalScore !== 'number' || !Number.isFinite(finalScore) ||
|
|
146
|
+
typeof verdict !== 'string' || (verdict !== 'strict PASS' && !verdict.startsWith('valid;')) ||
|
|
135
147
|
!final.selections?.some((item) => item.role === 'agent' && item.selection?.digest === submission.payload?.digest)) {
|
|
136
148
|
throw new Error(`The reference record does not establish completed no-model train and final: ${record}`);
|
|
137
149
|
}
|
|
@@ -161,9 +173,10 @@ async function referenceRecord(source, state, home, signal) {
|
|
|
161
173
|
throw new Error(`Pumpkin reference cleanup is pending: ${runs}`);
|
|
162
174
|
}
|
|
163
175
|
}
|
|
164
|
-
export async function prepareFrontier({ signal, progress,
|
|
165
|
-
const
|
|
166
|
-
const
|
|
176
|
+
export async function prepareFrontier({ signal, progress, configuration, checkOnly = false }) {
|
|
177
|
+
const { frontierStateDir: home, executor, image, model, sandbox, connection, preparedWorker } = configuration;
|
|
178
|
+
const budget = frontierBudget(configuration.budget);
|
|
179
|
+
const resources = resourcePlan(budget, sandbox);
|
|
167
180
|
const checks = [];
|
|
168
181
|
const check = (name, ok, detail) => checks.push({ name, ok, detail });
|
|
169
182
|
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
@@ -175,22 +188,54 @@ export async function prepareFrontier({ signal, progress, home = frontierHome()
|
|
|
175
188
|
const result = await command(tool, args, { timeoutMs: 5000, signal }).catch(() => undefined);
|
|
176
189
|
check(tool, result?.code === 0, result?.stdout.trim() || remedy);
|
|
177
190
|
}));
|
|
191
|
+
const installer = await command('/bin/sh', ['-c', 'for tool in sha256sum tar xz flock; do command -v "$tool" >/dev/null || printf "%s " "$tool"; done; command -v curl >/dev/null || command -v wget >/dev/null || printf "curl/wget"'], { timeoutMs: 5000, signal }).catch(() => undefined);
|
|
192
|
+
const missing = installer?.stdout.trim();
|
|
193
|
+
check('pumpkin-tools', installer?.code === 0 && !missing, installer?.code === 0 && !missing
|
|
194
|
+
? 'Found downloader, SHA-256, tar, xz and flock.'
|
|
195
|
+
: `Install curl, ca-certificates, coreutils, tar, xz-utils and util-linux.${missing ? ` Missing: ${missing}.` : ''}`);
|
|
178
196
|
const local = await command('docker', ['context', 'show'], { timeoutMs: 5000, signal }).catch(() => undefined);
|
|
179
197
|
const dockerContext = local?.code === 0 ? local.stdout.trim() : '';
|
|
180
198
|
const validContext = /^[a-zA-Z0-9._-]+$/.test(dockerContext);
|
|
181
199
|
check('docker-cli', validContext, validContext ? dockerContext : 'Install Docker CLI and select a local context.');
|
|
200
|
+
const buildx = validContext ? await command('docker', ['--context', dockerContext, 'buildx', 'version'], { timeoutMs: 5000, signal }).catch(() => undefined) : undefined;
|
|
201
|
+
check('docker-buildx', buildx?.code === 0, buildx?.code === 0 ? buildx.stdout.trim()
|
|
202
|
+
: 'Install the Docker Buildx plugin for your Docker CLI and verify it with docker buildx version.');
|
|
182
203
|
const info = validContext ? await command('docker', ['--context', dockerContext, 'info', '--format',
|
|
183
|
-
'{{.OSType}} {{.Architecture}} {{.NCPU}} {{.MemTotal}}'], { timeoutMs: 8000, signal }).catch(() => undefined) : undefined;
|
|
184
|
-
const [
|
|
204
|
+
'{{.OSType}} {{.Architecture}} {{.NCPU}} {{.MemTotal}}\n{{json .DriverStatus}}'], { timeoutMs: 8000, signal }).catch(() => undefined) : undefined;
|
|
205
|
+
const [platform, driver] = info?.stdout.trim().split('\n', 2) ?? [];
|
|
206
|
+
const [os, arch, cpu, memory] = platform?.split(/\s+/) ?? [];
|
|
185
207
|
check('docker-daemon', info?.code === 0 && os === 'linux' && ['x86_64', 'amd64'].includes(arch), info?.code === 0 ? `${os}/${arch}, ${cpu} CPUs, ${Math.floor(Number(memory) / GiB)} GiB` : 'Start Docker and verify daemon access with docker info.');
|
|
208
|
+
const imageStore = info?.code === 0 && driver?.includes('"io.containerd.snapshotter.v1"');
|
|
209
|
+
check('docker-image-store', !!imageStore, imageStore ? 'Docker uses the containerd image store.'
|
|
210
|
+
: 'Pumpkin requires the containerd image store. Check docker info --format "{{ .DriverStatus }}" and see the Docker setup section of README.md.');
|
|
211
|
+
const availableCpu = Math.min(availableParallelism(), Number(cpu));
|
|
212
|
+
const availableMemory = Math.min(freemem(), Number(memory)) / GiB;
|
|
186
213
|
const disk = await statfs(home);
|
|
214
|
+
const tmp = await statfs(process.env.TMPDIR ?? '/tmp');
|
|
187
215
|
const diskGiB = disk.bavail * disk.bsize / GiB;
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
216
|
+
const tmpGiB = tmp.bavail * tmp.bsize / GiB;
|
|
217
|
+
for (const [phase, plan] of [['prepare', resources.prepare], ['run', resources.run]]) {
|
|
218
|
+
const local = plan.roles.filter(role => role.placement === 'controller');
|
|
219
|
+
const localCpu = local.reduce((sum, role) => sum + role.cpu * role.count, 0);
|
|
220
|
+
const localMemory = local.reduce((sum, role) => sum + role.memoryGiB * role.count, 0);
|
|
221
|
+
check(phase + '-capacity', availableCpu >= localCpu && availableMemory >= localMemory, `Controller needs ${localCpu} vCPU and ${localMemory} GiB available for ${phase}. Observed: ${Number.isFinite(availableCpu) ? availableCpu : 'unknown'} vCPU and ${Number.isFinite(availableMemory) ? Math.floor(availableMemory) : 'unknown'} GiB. For run capacity, reduce budget.workers or use a larger host.`);
|
|
222
|
+
}
|
|
223
|
+
check('storage', diskGiB >= resources.prepare.diskGiB && disk.ffree >= 25_000 && tmp.ffree >= 25_000 && tmpGiB >= 1, `State: ${Math.floor(diskGiB)} GiB, ${disk.ffree} inodes. Temporary storage: ${Math.floor(tmpGiB)} GiB, ${tmp.ffree} inodes. Allow 12 GiB for state, 1 GiB for temporary files and 25000 free inodes on both mounts.`);
|
|
224
|
+
checks.push(...await checkModelRoute(model, executor, signal));
|
|
225
|
+
const placement = typeof executor === 'string' ? executor : executor?.kind;
|
|
226
|
+
check('executor', !!placement && !!image, placement && image
|
|
227
|
+
? `Selected backend: ${placement}; Worker image: ${image}. The first Worker startup checks executor compatibility.`
|
|
228
|
+
: 'Run anyswarm setup --backend pi or --backend codex, or configure executor and its matching image.');
|
|
229
|
+
check('callback', !!(connection.advertiseHost || connection.publicUrl), connection.advertiseHost || connection.publicUrl
|
|
230
|
+
? 'Runtime callback is configured. Use anyswarm doctor --smoke to check guest connectivity.'
|
|
231
|
+
: 'Configure ANYSWARM_ADVERTISE_HOST or ANYSWARM_RUNTIME_PUBLIC_URL for the Worker callback, or run anyswarm setup.');
|
|
232
|
+
const limits = sandbox.resourceLimits;
|
|
233
|
+
check('worker-spec', limits?.cpu === '2' && limits.memory === '4Gi', 'FrontierCS-2 reserves 2 vCPU and 4 GiB per Worker. Keep sandbox.resourceLimits.cpu=2 and memory=4Gi.');
|
|
191
234
|
try {
|
|
192
|
-
const
|
|
193
|
-
|
|
235
|
+
const base = sandbox.endpoint ?? sandbox.lifecycleBaseUrl;
|
|
236
|
+
if (!base)
|
|
237
|
+
throw new Error('Lifecycle endpoint is required');
|
|
238
|
+
const url = base.replace(/\/$/, '') + '/sandboxes?page=1&pageSize=1';
|
|
194
239
|
const deadline = AbortSignal.any([signal, AbortSignal.timeout(8000)]);
|
|
195
240
|
const [authenticated, anonymous] = await Promise.all([
|
|
196
241
|
fetch(url, { redirect: 'error', signal: deadline, headers: { 'OPEN-SANDBOX-API-KEY': sandbox.apiKey ?? '' } }),
|
|
@@ -198,21 +243,35 @@ export async function prepareFrontier({ signal, progress, home = frontierHome()
|
|
|
198
243
|
]);
|
|
199
244
|
const ok = Boolean(sandbox.apiKey && authenticated.ok && [401, 403].includes(anonymous.status) && sandbox.egressMode === 'dns+nft');
|
|
200
245
|
await Promise.all([authenticated.body?.cancel(), anonymous.body?.cancel()]);
|
|
201
|
-
check('opensandbox', ok, ok ? 'Authenticated Lifecycle endpoint
|
|
202
|
-
|
|
203
|
-
check('worker-image', !!worker && worker.code === 0, worker && worker.code === 0 ? worker.stdout.trim() : 'Select the prepared AnySwarm Worker image for this Docker daemon.');
|
|
246
|
+
check('opensandbox', ok, ok ? 'Authenticated Lifecycle endpoint and configured dns+nft egress.'
|
|
247
|
+
: 'Run anyswarm setup and anyswarm doctor. For an existing deployment configure the Lifecycle endpoint, API key and dns+nft egress.');
|
|
204
248
|
}
|
|
205
|
-
catch
|
|
206
|
-
|
|
249
|
+
catch {
|
|
250
|
+
signal.throwIfAborted();
|
|
251
|
+
check('opensandbox', false, 'Could not reach the configured Lifecycle endpoint. Run anyswarm setup or check the existing service with anyswarm doctor.');
|
|
252
|
+
}
|
|
253
|
+
if (resources.localWorkers) {
|
|
254
|
+
const worker = validContext && image && await command('docker', ['--context', dockerContext, 'image', 'inspect', '--format', '{{.Id}}', preparedWorker ?? image], { timeoutMs: 8000, signal }).catch(() => undefined);
|
|
255
|
+
check('worker-image', !!worker && worker.code === 0, worker && worker.code === 0 ? `Docker resolved ${worker.stdout.trim()} for ${image}.`
|
|
256
|
+
: 'Run anyswarm setup to prepare the selected Worker on this Docker daemon, or select its image in the configuration.');
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
check('worker-image', !!image, 'Worker is assigned to the existing OpenSandbox service. Confirm the image is available there with anyswarm doctor --mode existing --smoke.');
|
|
207
260
|
}
|
|
208
|
-
const
|
|
209
|
-
|
|
261
|
+
const savedManifest = await readFile(join(home, 'prepared.json'), 'utf8').then(raw => JSON.parse(raw)).catch(() => undefined);
|
|
262
|
+
check('task-materials', !savedManifest || savedManifest.dockerContext === dockerContext, !savedManifest ? 'The pinned task will be downloaded and checked during prepare.'
|
|
263
|
+
: savedManifest.dockerContext === dockerContext ? 'Prepared manifest found. Prepare verifies its material and image identities before reuse.'
|
|
264
|
+
: 'The state directory belongs to another Docker context. Set ANYSWARM_AUTORESEARCH_STATE_DIR to a fresh directory for this context.');
|
|
265
|
+
const report = { ok: checks.every(row => row.ok), benchmark: frontierRevision, pumpkin: pumpkinPin, budget, resources, checks, home,
|
|
266
|
+
model: { provider: model?.provider || null, id: model?.model || null }, modelInference: 'not-attempted' };
|
|
267
|
+
if (!report.ok || checkOnly)
|
|
210
268
|
return report;
|
|
211
269
|
signal.throwIfAborted();
|
|
212
270
|
const state = paths(home, dockerContext);
|
|
213
271
|
const lock = join(home, 'preparing');
|
|
214
272
|
await mkdir(lock, { mode: 0o700 }).catch(() => { throw new Error('FrontierCS-2 preparation is already active. Inspect the preparing directory before retrying.'); });
|
|
215
273
|
try {
|
|
274
|
+
progress('Checking pinned FrontierCS-2 source and Git LFS material.');
|
|
216
275
|
const source = await sourceAt(home, signal);
|
|
217
276
|
const sourceDigest = await treeDigest(source);
|
|
218
277
|
const current = await loadPrepared(home).catch(() => undefined);
|
|
@@ -226,6 +285,7 @@ export async function prepareFrontier({ signal, progress, home = frontierHome()
|
|
|
226
285
|
return { ...report, ok: true, reused: true, prepared: current.saved };
|
|
227
286
|
}
|
|
228
287
|
await writeFile(state.config, pumpkinConfig(dockerContext), { mode: 0o600 });
|
|
288
|
+
await preparePumpkin(source, state.cache, signal);
|
|
229
289
|
progress('Validating official FrontierCS-2 reference and building pinned judge images.');
|
|
230
290
|
const reference = await referenceRecord(source, state, home, signal);
|
|
231
291
|
await mkdir(state.source, { recursive: true, mode: 0o700 });
|
|
@@ -236,7 +296,7 @@ export async function prepareFrontier({ signal, progress, home = frontierHome()
|
|
|
236
296
|
const bridgeRuns = await mkdtemp(join(home, 'bridge-check-'));
|
|
237
297
|
const bridge = new FrontierRun(state, bridgeRuns);
|
|
238
298
|
try {
|
|
239
|
-
await bridge.start(120, signal, prepareTimeout);
|
|
299
|
+
await bridge.start(120, signal, prepareTimeout, budget.maxEvaluations);
|
|
240
300
|
if (JSON.stringify(bridge.judges) !== JSON.stringify(reference.judges))
|
|
241
301
|
throw new Error('Submission bridge changed the official judge images');
|
|
242
302
|
}
|
|
@@ -245,12 +305,21 @@ export async function prepareFrontier({ signal, progress, home = frontierHome()
|
|
|
245
305
|
throw new Error(`Pumpkin submission role cleanup is pending: ${bridge.record}`);
|
|
246
306
|
}
|
|
247
307
|
const manifest = { version: 2, revision: frontierRevision, pumpkin: pumpkinPin, sourceDigest,
|
|
248
|
-
bridgeDigest: await treeDigest(state.source), bridgeImage: bridge.imageId, dockerContext,
|
|
308
|
+
bridgeDigest: await treeDigest(state.source), bridgeImage: bridge.imageId, dockerContext, referenceRecord: reference.record, judges: reference.judges };
|
|
249
309
|
const pending = join(lock, 'prepared.json');
|
|
250
310
|
await writeFile(pending, JSON.stringify(manifest, null, 2) + '\n', { mode: 0o600 });
|
|
251
311
|
await rename(pending, join(home, 'prepared.json'));
|
|
252
312
|
return { ...report, ok: true, reused: false, prepared: manifest };
|
|
253
313
|
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
signal.throwIfAborted();
|
|
316
|
+
const detail = error instanceof Error ? error.message : 'Preparation failed. Check the pinned task and Docker logs.';
|
|
317
|
+
const remedy = detail.includes("can't be tagged") && detail.includes('No such image')
|
|
318
|
+
? 'Check the selected Docker daemon and Buildx. Try Docker Engine 29 with the official Buildx plugin and the containerd image store, then rerun prepare.\n'
|
|
319
|
+
: '';
|
|
320
|
+
check('prepare-materials', false, remedy + detail);
|
|
321
|
+
return { ...report, ok: false };
|
|
322
|
+
}
|
|
254
323
|
finally {
|
|
255
324
|
await rm(lock, { recursive: true, force: true });
|
|
256
325
|
}
|
|
@@ -11,7 +11,12 @@ declare const _default: {
|
|
|
11
11
|
reason: string;
|
|
12
12
|
result: HarnessJson;
|
|
13
13
|
acceptance: HarnessJson;
|
|
14
|
-
artifacts:
|
|
14
|
+
artifacts: ({
|
|
15
|
+
path: string;
|
|
16
|
+
sha256: string;
|
|
17
|
+
} | {
|
|
18
|
+
path: string;
|
|
19
|
+
})[];
|
|
15
20
|
cleanup: {
|
|
16
21
|
status: "complete" | "pending";
|
|
17
22
|
pending?: HarnessJson | undefined;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createReadStream } from 'node:fs';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
|
|
2
4
|
import { join, resolve } from 'node:path';
|
|
3
5
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
4
6
|
import { createRuntime, createSandbox, getExecutorCapabilities, observeProjectRuntime, ProjectPreflightError, runInput, ServiceRegistry } from '@anyswarm/core';
|
|
5
|
-
import { checkBudget } from './config.js';
|
|
6
|
-
import { appendResearchEvent, candidatePath, createResearch, researchOperations, withDeadline } from './research-service.js';
|
|
7
|
+
import { checkBudget, modelConfigurationError } from './config.js';
|
|
8
|
+
import { appendResearchEvent, candidatePath, createResearch, readFinalEvaluation, researchOperations, withDeadline } from './research-service.js';
|
|
7
9
|
const instructions = `You are one of several equal research peers exploring the same goal. Choose your own concrete direction and coordinate directly with peers.
|
|
8
10
|
Use the following CLI directly in your private project. The host already provides this Service.
|
|
9
11
|
swarm service invoke research board
|
|
@@ -40,6 +42,9 @@ function configuration(value) {
|
|
|
40
42
|
throw new ProjectPreflightError('AUTORESEARCH_CONFIG_INVALID', 'Evaluator timeouts must be positive millisecond values.');
|
|
41
43
|
}
|
|
42
44
|
}
|
|
45
|
+
const problem = modelConfigurationError(config.model, config.executor);
|
|
46
|
+
if (problem)
|
|
47
|
+
throw new ProjectPreflightError('AUTORESEARCH_MODEL_REQUIRED', problem);
|
|
43
48
|
return { ...config, budget: checkBudget(config.budget) };
|
|
44
49
|
}
|
|
45
50
|
export function resolveWorkspace({ cwd, configuration }) {
|
|
@@ -57,6 +62,8 @@ async function modelUsage(directory, peers) {
|
|
|
57
62
|
let outputTokens = 0;
|
|
58
63
|
let attemptsWithUsage = 0;
|
|
59
64
|
const intervals = [];
|
|
65
|
+
const upstreamModels = new Map();
|
|
66
|
+
const requestIntervals = [];
|
|
60
67
|
const summarized = new Map(peers.map(peer => [peer.agentId, { ...peer, dispatched: 0, succeeded: 0 }]));
|
|
61
68
|
for (const id of attempts) {
|
|
62
69
|
const attempt = (file) => readFile(join(trace, id, file), 'utf8').then(text => JSON.parse(text)).catch(() => null);
|
|
@@ -73,6 +80,29 @@ async function modelUsage(directory, peers) {
|
|
|
73
80
|
if (result?.state !== 'completed' || result?.upstreamStatus !== 200)
|
|
74
81
|
continue;
|
|
75
82
|
peer.succeeded++;
|
|
83
|
+
const models = new Set();
|
|
84
|
+
const stream = createReadStream(join(trace, id, 'response.txt'));
|
|
85
|
+
try {
|
|
86
|
+
for await (const line of createInterface({ input: stream, crlfDelay: Infinity })) {
|
|
87
|
+
if (!line.startsWith('data:'))
|
|
88
|
+
continue;
|
|
89
|
+
try {
|
|
90
|
+
const event = JSON.parse(line.slice(5));
|
|
91
|
+
const model = event.type === 'response.completed' ? event.response?.model : event.model;
|
|
92
|
+
if (typeof model === 'string')
|
|
93
|
+
models.add(model.slice(0, 160));
|
|
94
|
+
}
|
|
95
|
+
catch { /* Incomplete or non-JSON SSE fields carry no model identity. */ }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch { /* The gateway can record the attempt even if the upstream bytes are unavailable. */ }
|
|
99
|
+
finally {
|
|
100
|
+
stream.destroy();
|
|
101
|
+
}
|
|
102
|
+
if (models.size === 1) {
|
|
103
|
+
const model = [...models][0];
|
|
104
|
+
upstreamModels.set(model, (upstreamModels.get(model) ?? 0) + 1);
|
|
105
|
+
}
|
|
76
106
|
const start = Date.parse(request.startedAt);
|
|
77
107
|
const end = Date.parse(result.endedAt);
|
|
78
108
|
if (start < end)
|
|
@@ -80,7 +110,12 @@ async function modelUsage(directory, peers) {
|
|
|
80
110
|
}
|
|
81
111
|
const current = new Map();
|
|
82
112
|
let peakConcurrentPeers = 0;
|
|
113
|
+
let lastAt;
|
|
83
114
|
for (const point of intervals.flatMap(({ agentId, start, end }) => [{ agentId, at: start, delta: 1 }, { agentId, at: end, delta: -1 }]).sort((a, b) => a.at - b.at || a.delta - b.delta)) {
|
|
115
|
+
if (lastAt !== undefined && lastAt < point.at && current.size > 1) {
|
|
116
|
+
requestIntervals.push({ from: lastAt, to: point.at, peers: current.size });
|
|
117
|
+
}
|
|
118
|
+
lastAt = point.at;
|
|
84
119
|
const next = (current.get(point.agentId) ?? 0) + point.delta;
|
|
85
120
|
if (next)
|
|
86
121
|
current.set(point.agentId, next);
|
|
@@ -92,6 +127,13 @@ async function modelUsage(directory, peers) {
|
|
|
92
127
|
dispatched: attempts.length, attemptsWithUsage, attemptsWithoutUsage: attempts.length - attemptsWithUsage,
|
|
93
128
|
inputTokens: attemptsWithUsage ? inputTokens : null, outputTokens: attemptsWithUsage ? outputTokens : null,
|
|
94
129
|
peers: [...summarized.values()], peakConcurrentPeers,
|
|
130
|
+
upstreamModels: Object.fromEntries(upstreamModels),
|
|
131
|
+
requestsWithoutUpstreamModel: [...summarized.values()].reduce((sum, peer) => sum + peer.succeeded, 0) -
|
|
132
|
+
[...upstreamModels.values()].reduce((sum, count) => sum + count, 0),
|
|
133
|
+
peerOverlapMs: requestIntervals.reduce((summary, { from, to, peers }) => {
|
|
134
|
+
summary[peers] = (summary[peers] ?? 0) + to - from;
|
|
135
|
+
return summary;
|
|
136
|
+
}, {}),
|
|
95
137
|
};
|
|
96
138
|
}
|
|
97
139
|
const encode = (value) => JSON.parse(JSON.stringify(value));
|
|
@@ -101,6 +143,7 @@ export default {
|
|
|
101
143
|
async run(context) {
|
|
102
144
|
const config = configuration(context.configuration);
|
|
103
145
|
const { budget } = config;
|
|
146
|
+
await config.validateStarter?.(context.initial);
|
|
104
147
|
if (config.requiredFiles?.some(path => !Object.hasOwn(context.initial.files, path))) {
|
|
105
148
|
throw new ProjectPreflightError('AUTORESEARCH_STARTER_INCOMPLETE', 'Project capture missed required starter files. Verify the prepared Git checkout and retry.');
|
|
106
149
|
}
|
|
@@ -111,6 +154,11 @@ export default {
|
|
|
111
154
|
: Promise.resolve('complete');
|
|
112
155
|
const registry = new ServiceRegistry();
|
|
113
156
|
let deadlineAt = 0;
|
|
157
|
+
let workStartedAt = null;
|
|
158
|
+
let workEndedAt = null;
|
|
159
|
+
const startingAt = Date.now();
|
|
160
|
+
let runtimeAttempted = false;
|
|
161
|
+
let initFailure;
|
|
114
162
|
let runtime;
|
|
115
163
|
const peerLabels = Array.from({ length: budget.workers }, (_, index) => `peer-${index + 1}`);
|
|
116
164
|
const profile = { model: 'research', image: config.image, writable: true, services: { research: researchOperations }, addedSystemPrompt: instructions, ...(config.restrictNetwork ? { network: { allow: [] } } : {}) };
|
|
@@ -139,7 +187,7 @@ export default {
|
|
|
139
187
|
}
|
|
140
188
|
}
|
|
141
189
|
const research = createResearch({
|
|
142
|
-
outputDir
|
|
190
|
+
get outputDir() { return join(context.outputDir, runtime.id); }, direction: config.direction, maxEvaluations: budget.maxEvaluations, targetScore: config.targetScore,
|
|
143
191
|
get deadlineAt() { return deadlineAt; }, signal, trainSignal: context.signal, evaluator: config.evaluator, evaluationTimeoutMs: config.evaluationTimeoutMs ?? 190_000,
|
|
144
192
|
stopWork: reason => controller.abort(reason),
|
|
145
193
|
statusChanged: () => {
|
|
@@ -188,6 +236,9 @@ export default {
|
|
|
188
236
|
let final = null;
|
|
189
237
|
let judgeCleanup = 'complete';
|
|
190
238
|
let error = null;
|
|
239
|
+
let finalStartedAt = null;
|
|
240
|
+
let finalEndedAt = null;
|
|
241
|
+
let cleanupStartedAt = null;
|
|
191
242
|
let searchEnd = 'workers-settled';
|
|
192
243
|
let selected;
|
|
193
244
|
try {
|
|
@@ -195,8 +246,7 @@ export default {
|
|
|
195
246
|
const startSignal = AbortSignal.any([context.signal, AbortSignal.timeout(360_000)]);
|
|
196
247
|
await withDeadline(startSignal, () => config.evaluator.start(context.outputDir, startSignal));
|
|
197
248
|
}
|
|
198
|
-
|
|
199
|
-
deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
|
|
249
|
+
runtimeAttempted = true;
|
|
200
250
|
runtime = await createRuntime({
|
|
201
251
|
sandbox: createSandbox(config.sandbox), connection: { ...config.connection, modelGateway: {
|
|
202
252
|
...config.connection.modelGateway,
|
|
@@ -281,6 +331,9 @@ export default {
|
|
|
281
331
|
}
|
|
282
332
|
signal.throwIfAborted();
|
|
283
333
|
status = 'researching';
|
|
334
|
+
workStartedAt = Date.now();
|
|
335
|
+
deadlineAt = workStartedAt + budget.workMs;
|
|
336
|
+
deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
|
|
284
337
|
context.markRunning();
|
|
285
338
|
research.event('team.ready');
|
|
286
339
|
await Promise.all(peers.map(async ({ peer, label, member }) => {
|
|
@@ -298,11 +351,15 @@ export default {
|
|
|
298
351
|
if (remaining <= 0)
|
|
299
352
|
break;
|
|
300
353
|
const review = member.reviewOfferedInTurn ? undefined : member.review;
|
|
301
|
-
|
|
354
|
+
const trainExhausted = research.state().budget.evaluations >= budget.maxEvaluations;
|
|
355
|
+
if (turn > 0 && !review && trainExhausted && !config.continueAfterTrainBudget)
|
|
302
356
|
break;
|
|
357
|
+
const remainingWork = trainExhausted
|
|
358
|
+
? 'Train capacity is exhausted. Review another peer’s candidate, run local checks and publish concrete findings.'
|
|
359
|
+
: 'Check updates, review or build on promising peers’ work, and propose the next evidence-backed improvement.';
|
|
303
360
|
const prompt = turn === 0
|
|
304
361
|
? `You are ${label}. Team objective: ${config.goal}\n${context.input.prompt}\nRead the project task statement and the board, claim an open direction and work toward a first testable patch promptly.`
|
|
305
|
-
:
|
|
362
|
+
: remainingWork;
|
|
306
363
|
const interrupting = new Error('Peer interrupt pending before dispatch.');
|
|
307
364
|
try {
|
|
308
365
|
await runInput(runtime, peer.id, review ? `${prompt}\n\n${reviewNotice(review)}` : prompt, {
|
|
@@ -328,8 +385,17 @@ export default {
|
|
|
328
385
|
research.event('peer.turn-ended', { agentId: peer.id, detail: error.message.slice(0, 250) });
|
|
329
386
|
}
|
|
330
387
|
}));
|
|
388
|
+
workEndedAt = Date.now();
|
|
331
389
|
searchEnd = research.stopReason() ?? (context.signal.aborted ? 'stopped' : controller.signal.aborted ? 'deadline' :
|
|
332
|
-
research.state().budget.evaluations >= budget.maxEvaluations ? 'evaluation-budget' : 'workers-settled');
|
|
390
|
+
!config.continueAfterTrainBudget && research.state().budget.evaluations >= budget.maxEvaluations ? 'evaluation-budget' : 'workers-settled');
|
|
391
|
+
if (searchEnd === 'workers-settled' && budget.maxModelRequests !== undefined) {
|
|
392
|
+
const attempts = await readdir(join(context.outputDir, runtime.id, 'model-trace')).catch(() => []);
|
|
393
|
+
if (attempts.length >= budget.maxModelRequests)
|
|
394
|
+
searchEnd = 'model-request-budget';
|
|
395
|
+
}
|
|
396
|
+
if (!controller.signal.aborted)
|
|
397
|
+
controller.abort(searchEnd);
|
|
398
|
+
research.event('research.stopped', { detail: searchEnd });
|
|
333
399
|
// The host owns the judge independently of the Runtime. Stop native work
|
|
334
400
|
// while the last admitted train call settles under its own deadline.
|
|
335
401
|
[close] = await Promise.all([
|
|
@@ -344,16 +410,32 @@ export default {
|
|
|
344
410
|
selected = research.selection();
|
|
345
411
|
if (selected && !context.signal.aborted) {
|
|
346
412
|
status = 'final evaluation';
|
|
413
|
+
finalStartedAt = Date.now();
|
|
347
414
|
research.event('final.selected', { agentId: selected.agentId, candidate: selected.id });
|
|
348
415
|
const finalSignal = AbortSignal.any([context.signal, AbortSignal.timeout(config.closeTimeoutMs ?? 240_000)]);
|
|
349
416
|
final = await withDeadline(finalSignal, () => config.evaluator.final(research.patch(selected), finalSignal));
|
|
350
|
-
|
|
417
|
+
finalEndedAt = Date.now();
|
|
418
|
+
const verdict = readFinalEvaluation(final);
|
|
419
|
+
const evidence = verdict?.evidence;
|
|
420
|
+
research.event('final.returned', { agentId: selected.agentId, candidate: selected.id,
|
|
421
|
+
score: verdict?.score, payloadDigest: evidence?.payload?.digest,
|
|
422
|
+
detail: evidence?.summary ?? verdict?.status ?? 'unverified evaluator result' });
|
|
351
423
|
}
|
|
352
424
|
}
|
|
353
425
|
catch (failure) {
|
|
354
|
-
error = failure.message
|
|
426
|
+
error = failure instanceof Error ? failure.message.slice(0, 500) : 'Research failed';
|
|
427
|
+
if (!runtime && runtimeAttempted && failure instanceof Error && failure.name === 'ResourceError') {
|
|
428
|
+
initFailure = failure;
|
|
429
|
+
}
|
|
430
|
+
if (runtime)
|
|
431
|
+
research.event(finalStartedAt === null ? 'run.failed' : 'final.failed', {
|
|
432
|
+
...(selected ? { agentId: selected.agentId, candidate: selected.id } : {}), detail: error,
|
|
433
|
+
});
|
|
355
434
|
}
|
|
356
435
|
finally {
|
|
436
|
+
cleanupStartedAt = Date.now();
|
|
437
|
+
workEndedAt ??= workStartedAt === null ? null : cleanupStartedAt;
|
|
438
|
+
finalEndedAt ??= finalStartedAt === null ? null : cleanupStartedAt;
|
|
357
439
|
clearTimeout(deadline);
|
|
358
440
|
controller.abort('closing');
|
|
359
441
|
research.close();
|
|
@@ -364,29 +446,51 @@ export default {
|
|
|
364
446
|
}
|
|
365
447
|
observation?.close();
|
|
366
448
|
judgeCleanup = await cleanupJudge();
|
|
449
|
+
if (runtime)
|
|
450
|
+
research.event('run.cleanup', {
|
|
451
|
+
detail: `Runtime ${close?.cleanup ?? 'pending'}; evaluator ${judgeCleanup}`,
|
|
452
|
+
});
|
|
367
453
|
}
|
|
368
454
|
const best = research.best();
|
|
369
455
|
const peers = research.state().peers;
|
|
370
456
|
const traceDirectory = runtime ? join(context.outputDir, runtime.id) : null;
|
|
371
|
-
const
|
|
457
|
+
const runtimeReceipt = close?.reportPath ?? initFailure?.reportPath ?? null;
|
|
458
|
+
const runtimeReport = runtimeReceipt ? await readFile(runtimeReceipt, 'utf8').then(text => JSON.parse(text)).catch(() => null) : null;
|
|
459
|
+
const usage = traceDirectory ? await modelUsage(traceDirectory, peers) : null;
|
|
460
|
+
const finalEvaluation = readFinalEvaluation(final);
|
|
461
|
+
const accepted = finalEvaluation?.status === 'valid' && finalEvaluation.meetsObjective !== false;
|
|
462
|
+
const reason = context.signal.aborted ? 'stopped'
|
|
463
|
+
: error ? searchEnd === 'train-outcome-unknown' ? searchEnd : finalStartedAt === null ? 'research-error' : 'final-error'
|
|
464
|
+
: !best ? 'no-valid-candidate'
|
|
465
|
+
: journalError ? 'trace-write-failed'
|
|
466
|
+
: !finalEvaluation || finalEvaluation.status === 'unknown' ? 'final-unconfirmed'
|
|
467
|
+
: finalEvaluation.status === 'rejected' ? 'final-rejected'
|
|
468
|
+
: !accepted ? 'objective-unmet'
|
|
469
|
+
: searchEnd;
|
|
470
|
+
const runtimeCleanup = close?.cleanup ?? initFailure?.cleanup ?? (runtimeAttempted ? 'pending' : 'complete');
|
|
471
|
+
const record = join(context.outputDir, 'research-result.json');
|
|
372
472
|
const result = {
|
|
373
|
-
runtimeId: runtime?.id ?? null, budget, searchEnd,
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
473
|
+
schemaVersion: 1, runId: context.runId, runtimeId: runtime?.id ?? initFailure?.runtimeId ?? null, goal: config.goal, budget, searchEnd,
|
|
474
|
+
timing: { startingAt, workStartedAt, workEndedAt, finalStartedAt, finalEndedAt, cleanupStartedAt, completedAt: Date.now() },
|
|
475
|
+
executor: typeof config.executor === 'string' ? config.executor : config.executor.kind,
|
|
476
|
+
initial: { digest: context.initial.digest, files: context.initial.fileCount },
|
|
477
|
+
model: { provider: config.model.provider, id: config.model.model, usage, trace: runtimeReport?.modelTrace ?? null, cost: 'unknown' },
|
|
478
|
+
peers, candidates: research.candidates(), best: best ?? null, selected: selected ?? null, final, finalEvaluation: finalEvaluation ?? null, journalError, error,
|
|
479
|
+
record, judge: config.evaluator.evidence?.() ?? null, traceDirectory,
|
|
480
|
+
cleanup: { runtime: runtimeCleanup, judge: judgeCleanup, runtimePending: close?.pending ?? runtimeReport?.pending ?? [],
|
|
481
|
+
runtimeReceipt, runtimeInitializationDetails: initFailure?.details ?? null },
|
|
380
482
|
};
|
|
381
483
|
await mkdir(context.outputDir, { recursive: true, mode: 0o700 });
|
|
382
|
-
await writeFile(
|
|
484
|
+
await writeFile(record + '.next', JSON.stringify(result, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
|
|
485
|
+
await rename(record + '.next', record);
|
|
486
|
+
const outcome = context.signal.aborted ? 'cancelled' : error || !best || !accepted || journalError ? 'failed' : 'completed';
|
|
383
487
|
return {
|
|
384
|
-
outcome
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
488
|
+
outcome, reason, result: encode(result),
|
|
489
|
+
acceptance: encode({ status: outcome === 'completed' ? 'verified' : finalEvaluation?.status === 'rejected' || finalEvaluation?.meetsObjective === false
|
|
490
|
+
? 'rejected' : 'unverified', final: finalEvaluation ?? null }),
|
|
491
|
+
artifacts: [...research.candidates().map(candidate => ({ path: candidate.path, sha256: candidate.sha256 })), { path: record }],
|
|
492
|
+
cleanup: { status: runtimeCleanup === 'complete' && judgeCleanup === 'complete' ? 'complete' : 'pending',
|
|
493
|
+
...(close?.pending.length ? { pending: encode(close.pending) } : {}) },
|
|
390
494
|
};
|
|
391
495
|
},
|
|
392
496
|
};
|