@anyswarm/core 0.5.1 → 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 +20 -5
- package/README.md +69 -55
- package/dist/examples/README.md +138 -77
- package/dist/examples/authoring/README.md +4 -4
- package/dist/examples/autoresearch/README.md +108 -16
- package/dist/examples/autoresearch/REQUIREMENTS.zh.md +13 -12
- 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/eject.json +2 -0
- package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -0
- package/dist/examples/autoresearch/frontiercs2-config.js +14 -0
- package/dist/examples/autoresearch/frontiercs2.d.ts +18 -1
- package/dist/examples/autoresearch/frontiercs2.js +71 -14
- package/dist/examples/autoresearch/prepare-demo.d.ts +1 -0
- package/dist/examples/autoresearch/prepare-demo.js +46 -0
- 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 -95
- package/dist/examples/autoresearch/project.js +131 -45
- package/dist/examples/autoresearch/research-service.d.ts +16 -1
- package/dist/examples/autoresearch/research-service.js +84 -44
- package/dist/examples/code/README.md +25 -17
- package/dist/examples/code/REQUIREMENTS.zh.md +3 -3
- 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 +4 -4
- 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 +5 -5
- 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 +6 -3
- 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 +9 -16
- 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/super/README.md +34 -22
- package/dist/examples/super/actions.d.ts +1 -1
- package/dist/examples/super/actions.js +11 -11
- package/dist/examples/super/config.js +3 -3
- package/dist/examples/super/eject.json +1 -1
- package/dist/examples/super/location.js +1 -1
- package/dist/examples/super/operator.d.ts +1 -0
- package/dist/examples/super/operator.js +31 -0
- package/dist/examples/super/project.d.ts +0 -107
- package/dist/examples/super/project.js +1 -3
- 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-arguments.d.ts +7 -25
- package/dist/scripts/anyswarm-arguments.js +69 -97
- package/dist/scripts/anyswarm-eject.js +1 -1
- package/dist/scripts/anyswarm-harnesses.d.ts +0 -1
- package/dist/scripts/anyswarm-harnesses.js +1 -22
- package/dist/scripts/anyswarm-installation.d.ts +7 -40
- package/dist/scripts/anyswarm-installation.js +17 -291
- package/dist/scripts/anyswarm-launch.d.ts +6 -36
- package/dist/scripts/anyswarm-launch.js +32 -81
- package/dist/scripts/anyswarm-progress.d.ts +6 -0
- package/dist/scripts/anyswarm-progress.js +133 -0
- package/dist/scripts/anyswarm-project.d.ts +1 -9
- package/dist/scripts/anyswarm-project.js +40 -127
- package/dist/scripts/anyswarm-source-runner.js +9 -41
- package/dist/scripts/anyswarm.js +6 -26
- 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 +13 -7
- package/dist/scripts/local-environment.js +73 -21
- package/dist/scripts/local-setup.d.ts +3 -0
- package/dist/scripts/local-setup.js +153 -118
- package/dist/scripts/pack-release.js +31 -4
- 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/core/worker-image.js +1 -1
- package/dist/src/harness/project-harness.d.ts +1 -0
- package/dist/src/harness/project-harness.js +5 -4
- package/dist/src/harness/project-rpc-client.js +19 -0
- package/dist/src/harness/project-runtime.js +3 -1
- 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 +11 -9
- package/docs/architecture/04-services.md +1 -1
- package/docs/architecture/06-observability-experiments.md +21 -7
- package/docs/architecture/07-run-configuration.md +118 -19
- 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 +157 -115
- 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 +79 -1
- package/docs/architecture/22-website.md +52 -20
- package/docs/architecture/23-project-harness.md +109 -37
- package/docs/architecture/26-code.md +20 -5
- package/docs/architecture/27-personal.md +23 -8
- package/docs/architecture/28-autoresearch.md +18 -12
- package/docs/architecture/INDEX.md +1 -2
- 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 +76 -52
- package/docs/architecture/source-map.json +445 -105
- package/docs/designs/core-harness/01-core.md +2 -2
- package/docs/designs/core-harness/06-project-harness.md +3 -3
- package/docs/designs/core-harness/README.md +2 -2
- package/docs/en/agents.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 +29 -1
- package/docs/en/first-harness.md +40 -32
- package/docs/en/harnesses/index.md +23 -23
- package/docs/en/harnesses/lead-worker.md +1 -1
- package/docs/en/harnesses/peermesh.md +2 -2
- package/docs/en/harnesses/subagents.md +10 -31
- package/docs/en/harnesses/substrate.md +4 -4
- package/docs/en/harnesses/taskpool.md +2 -2
- package/docs/en/latest.md +30 -5
- package/docs/en/overview.md +22 -22
- package/docs/en/quickstart.md +69 -56
- package/docs/en/reference/api.md +1 -1
- package/docs/en/reference/cli.md +47 -85
- package/docs/en/sandbox.md +3 -3
- package/docs/en/trace-viewer.md +32 -12
- package/docs/operations/trace-viewer.md +26 -11
- package/docs/third-party-notices.md +0 -1
- package/docs/workflows/development.md +160 -118
- package/docs/workflows/release-and-docs-versioning.md +207 -54
- package/docs/workflows/release-cli-acceptance.md +162 -0
- package/docs/zh/agents.md +1 -1
- 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 +29 -1
- package/docs/zh/first-harness.md +43 -35
- package/docs/zh/harnesses/index.md +23 -23
- package/docs/zh/harnesses/lead-worker.md +1 -1
- package/docs/zh/harnesses/peermesh.md +2 -2
- package/docs/zh/harnesses/subagents.md +10 -31
- package/docs/zh/harnesses/substrate.md +4 -4
- package/docs/zh/harnesses/taskpool.md +2 -2
- package/docs/zh/latest.md +30 -5
- package/docs/zh/overview.md +23 -23
- package/docs/zh/quickstart.md +66 -57
- package/docs/zh/reference/api.md +1 -1
- package/docs/zh/reference/cli.md +19 -79
- package/docs/zh/sandbox.md +3 -3
- package/docs/zh/trace-viewer.md +32 -12
- package/examples/README.md +138 -77
- package/examples/authoring/README.md +4 -4
- package/examples/autoresearch/README.md +108 -16
- package/examples/autoresearch/REQUIREMENTS.zh.md +13 -12
- package/examples/autoresearch/config.ts +64 -25
- package/examples/autoresearch/demo.ts +75 -22
- package/examples/autoresearch/eject.json +2 -0
- package/examples/autoresearch/frontiercs2-config.ts +15 -0
- package/examples/autoresearch/frontiercs2.ts +64 -11
- package/examples/autoresearch/prepare-demo.ts +44 -0
- package/examples/autoresearch/prepare.ts +134 -60
- package/examples/autoresearch/project.ts +120 -44
- package/examples/autoresearch/research-service.ts +91 -41
- package/examples/code/README.md +25 -17
- package/examples/code/REQUIREMENTS.zh.md +3 -3
- 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 +4 -4
- package/examples/lead-worker/README.md +1 -1
- package/examples/messages/README.md +2 -2
- package/examples/notes/README.md +5 -5
- 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 +6 -3
- package/examples/subagents/AGENTS.md +35 -0
- package/examples/subagents/README.md +129 -93
- package/examples/subagents/config.ts +9 -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/super/README.md +34 -22
- package/examples/super/actions.ts +11 -11
- package/examples/super/config.ts +3 -3
- package/examples/super/eject.json +1 -1
- package/examples/super/location.ts +1 -1
- package/examples/super/operator.ts +28 -0
- package/examples/super/project.ts +1 -3
- package/examples/taskpool/README.md +1 -1
- package/npm-shrinkwrap.development.json +46 -1538
- package/npm-shrinkwrap.json +10 -43
- package/package.development.json +3 -6
- package/package.json +3 -5
- package/scripts/anyswarm-arguments.ts +67 -96
- package/scripts/anyswarm-eject.ts +1 -1
- package/scripts/anyswarm-harnesses.ts +1 -18
- package/scripts/anyswarm-installation.ts +18 -294
- package/scripts/anyswarm-launch.ts +30 -102
- package/scripts/anyswarm-progress.ts +125 -0
- package/scripts/anyswarm-project.ts +31 -123
- package/scripts/anyswarm-source-runner.ts +9 -36
- package/scripts/anyswarm.ts +4 -24
- package/scripts/generate-architecture-coverage.ts +1 -1
- package/scripts/generate-architecture-prompts.ts +21 -10
- package/scripts/local-environment.ts +79 -21
- package/scripts/local-setup.ts +150 -105
- package/scripts/pack-release.ts +28 -4
- 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/core/worker-image.ts +1 -1
- package/src/harness/project-harness.ts +5 -4
- package/src/harness/project-rpc-client.ts +23 -0
- package/src/harness/project-runtime.ts +2 -1
- 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
- package/dist/scripts/anyswarm-applications.d.ts +0 -19
- package/dist/scripts/anyswarm-applications.js +0 -19
- package/dist/scripts/anyswarm-tui-config.d.ts +0 -36
- package/dist/scripts/anyswarm-tui-config.js +0 -189
- package/dist/scripts/anyswarm-tui-session.d.ts +0 -66
- package/dist/scripts/anyswarm-tui-session.js +0 -304
- package/dist/scripts/anyswarm-tui-terminal.d.ts +0 -41
- package/dist/scripts/anyswarm-tui-terminal.js +0 -154
- package/dist/scripts/anyswarm-tui.d.ts +0 -2
- package/dist/scripts/anyswarm-tui.js +0 -1012
- package/docs/architecture/25-foreground-tui.md +0 -51
- package/scripts/anyswarm-applications.ts +0 -39
- package/scripts/anyswarm-tui-config.ts +0 -174
- package/scripts/anyswarm-tui-session.ts +0 -295
- package/scripts/anyswarm-tui-terminal.ts +0 -147
- package/scripts/anyswarm-tui.ts +0 -912
|
@@ -1,11 +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,
|
|
6
|
-
import {
|
|
7
|
-
import { prepareFrontier } from './prepare.js';
|
|
8
|
-
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';
|
|
9
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.
|
|
10
10
|
Use the following CLI directly in your private project. The host already provides this Service.
|
|
11
11
|
swarm service invoke research board
|
|
@@ -35,34 +35,22 @@ function configuration(value) {
|
|
|
35
35
|
!config.evaluator || typeof config.evaluator.train !== 'function' || typeof config.evaluator.final !== 'function' ||
|
|
36
36
|
!config.executor || !config.image || !config.model || !config.sandbox || !config.connection ||
|
|
37
37
|
(config.targetScore !== undefined && !Number.isFinite(config.targetScore))) {
|
|
38
|
-
throw new ProjectPreflightError('AUTORESEARCH_CONFIG_REQUIRED', '
|
|
38
|
+
throw new ProjectPreflightError('AUTORESEARCH_CONFIG_REQUIRED', 'Run anyswarm --harness autoresearch --config ./research.ts --prompt <goal> with a trusted evaluator and runtime settings.');
|
|
39
39
|
}
|
|
40
40
|
for (const ms of [config.evaluationTimeoutMs, config.closeTimeoutMs]) {
|
|
41
41
|
if (ms !== undefined && (!Number.isSafeInteger(ms) || ms < 1 || ms > 2_147_483_647)) {
|
|
42
42
|
throw new ProjectPreflightError('AUTORESEARCH_CONFIG_INVALID', 'Evaluator timeouts must be positive millisecond values.');
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
+
const problem = modelConfigurationError(config.model, config.executor);
|
|
46
|
+
if (problem)
|
|
47
|
+
throw new ProjectPreflightError('AUTORESEARCH_MODEL_REQUIRED', problem);
|
|
45
48
|
return { ...config, budget: checkBudget(config.budget) };
|
|
46
49
|
}
|
|
47
50
|
export function resolveWorkspace({ cwd, configuration }) {
|
|
48
51
|
const target = configuration?.targetPath;
|
|
49
52
|
return typeof target === 'string' && target.trim() ? resolve(cwd, target) : cwd;
|
|
50
53
|
}
|
|
51
|
-
export const slashActions = {
|
|
52
|
-
async prepare({ args, signal, progress = console.error }) {
|
|
53
|
-
if (args && args !== 'frontiercs2')
|
|
54
|
-
throw new Error('Usage: /prepare [frontiercs2]');
|
|
55
|
-
const result = await prepareFrontier({ signal, progress });
|
|
56
|
-
return result.ok ? result : { kind: 'action-report', exitCode: 2, result };
|
|
57
|
-
},
|
|
58
|
-
async demo({ args, signal }) {
|
|
59
|
-
if (args !== 'frontiercs2')
|
|
60
|
-
throw new Error('Usage: /demo frontiercs2');
|
|
61
|
-
const { configuration, starter } = await frontierDemo();
|
|
62
|
-
signal.throwIfAborted();
|
|
63
|
-
return { kind: 'start-run', cwd: starter, prompt: demoGoal, configuration };
|
|
64
|
-
},
|
|
65
|
-
};
|
|
66
54
|
const streamedEvents = new Set([
|
|
67
55
|
'peer.ready', 'peer.claim', 'peer.steer', 'peer.interrupt', 'peer.stop', 'peer.turn-ended', 'team.ready',
|
|
68
56
|
'peer.review-notice', 'peer.read-patch', 'peer.review', 'candidate.queued', 'candidate.built-on', 'candidate.best', 'train.returned', 'train.unknown', 'final.selected', 'final.returned',
|
|
@@ -74,6 +62,8 @@ async function modelUsage(directory, peers) {
|
|
|
74
62
|
let outputTokens = 0;
|
|
75
63
|
let attemptsWithUsage = 0;
|
|
76
64
|
const intervals = [];
|
|
65
|
+
const upstreamModels = new Map();
|
|
66
|
+
const requestIntervals = [];
|
|
77
67
|
const summarized = new Map(peers.map(peer => [peer.agentId, { ...peer, dispatched: 0, succeeded: 0 }]));
|
|
78
68
|
for (const id of attempts) {
|
|
79
69
|
const attempt = (file) => readFile(join(trace, id, file), 'utf8').then(text => JSON.parse(text)).catch(() => null);
|
|
@@ -90,6 +80,29 @@ async function modelUsage(directory, peers) {
|
|
|
90
80
|
if (result?.state !== 'completed' || result?.upstreamStatus !== 200)
|
|
91
81
|
continue;
|
|
92
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
|
+
}
|
|
93
106
|
const start = Date.parse(request.startedAt);
|
|
94
107
|
const end = Date.parse(result.endedAt);
|
|
95
108
|
if (start < end)
|
|
@@ -97,7 +110,12 @@ async function modelUsage(directory, peers) {
|
|
|
97
110
|
}
|
|
98
111
|
const current = new Map();
|
|
99
112
|
let peakConcurrentPeers = 0;
|
|
113
|
+
let lastAt;
|
|
100
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;
|
|
101
119
|
const next = (current.get(point.agentId) ?? 0) + point.delta;
|
|
102
120
|
if (next)
|
|
103
121
|
current.set(point.agentId, next);
|
|
@@ -109,6 +127,13 @@ async function modelUsage(directory, peers) {
|
|
|
109
127
|
dispatched: attempts.length, attemptsWithUsage, attemptsWithoutUsage: attempts.length - attemptsWithUsage,
|
|
110
128
|
inputTokens: attemptsWithUsage ? inputTokens : null, outputTokens: attemptsWithUsage ? outputTokens : null,
|
|
111
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
|
+
}, {}),
|
|
112
137
|
};
|
|
113
138
|
}
|
|
114
139
|
const encode = (value) => JSON.parse(JSON.stringify(value));
|
|
@@ -118,6 +143,7 @@ export default {
|
|
|
118
143
|
async run(context) {
|
|
119
144
|
const config = configuration(context.configuration);
|
|
120
145
|
const { budget } = config;
|
|
146
|
+
await config.validateStarter?.(context.initial);
|
|
121
147
|
if (config.requiredFiles?.some(path => !Object.hasOwn(context.initial.files, path))) {
|
|
122
148
|
throw new ProjectPreflightError('AUTORESEARCH_STARTER_INCOMPLETE', 'Project capture missed required starter files. Verify the prepared Git checkout and retry.');
|
|
123
149
|
}
|
|
@@ -128,6 +154,11 @@ export default {
|
|
|
128
154
|
: Promise.resolve('complete');
|
|
129
155
|
const registry = new ServiceRegistry();
|
|
130
156
|
let deadlineAt = 0;
|
|
157
|
+
let workStartedAt = null;
|
|
158
|
+
let workEndedAt = null;
|
|
159
|
+
const startingAt = Date.now();
|
|
160
|
+
let runtimeAttempted = false;
|
|
161
|
+
let initFailure;
|
|
131
162
|
let runtime;
|
|
132
163
|
const peerLabels = Array.from({ length: budget.workers }, (_, index) => `peer-${index + 1}`);
|
|
133
164
|
const profile = { model: 'research', image: config.image, writable: true, services: { research: researchOperations }, addedSystemPrompt: instructions, ...(config.restrictNetwork ? { network: { allow: [] } } : {}) };
|
|
@@ -156,7 +187,7 @@ export default {
|
|
|
156
187
|
}
|
|
157
188
|
}
|
|
158
189
|
const research = createResearch({
|
|
159
|
-
outputDir
|
|
190
|
+
get outputDir() { return join(context.outputDir, runtime.id); }, direction: config.direction, maxEvaluations: budget.maxEvaluations, targetScore: config.targetScore,
|
|
160
191
|
get deadlineAt() { return deadlineAt; }, signal, trainSignal: context.signal, evaluator: config.evaluator, evaluationTimeoutMs: config.evaluationTimeoutMs ?? 190_000,
|
|
161
192
|
stopWork: reason => controller.abort(reason),
|
|
162
193
|
statusChanged: () => {
|
|
@@ -205,6 +236,9 @@ export default {
|
|
|
205
236
|
let final = null;
|
|
206
237
|
let judgeCleanup = 'complete';
|
|
207
238
|
let error = null;
|
|
239
|
+
let finalStartedAt = null;
|
|
240
|
+
let finalEndedAt = null;
|
|
241
|
+
let cleanupStartedAt = null;
|
|
208
242
|
let searchEnd = 'workers-settled';
|
|
209
243
|
let selected;
|
|
210
244
|
try {
|
|
@@ -212,8 +246,7 @@ export default {
|
|
|
212
246
|
const startSignal = AbortSignal.any([context.signal, AbortSignal.timeout(360_000)]);
|
|
213
247
|
await withDeadline(startSignal, () => config.evaluator.start(context.outputDir, startSignal));
|
|
214
248
|
}
|
|
215
|
-
|
|
216
|
-
deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
|
|
249
|
+
runtimeAttempted = true;
|
|
217
250
|
runtime = await createRuntime({
|
|
218
251
|
sandbox: createSandbox(config.sandbox), connection: { ...config.connection, modelGateway: {
|
|
219
252
|
...config.connection.modelGateway,
|
|
@@ -281,7 +314,6 @@ export default {
|
|
|
281
314
|
: { status: 'unknown', requestId: request.requestId };
|
|
282
315
|
},
|
|
283
316
|
});
|
|
284
|
-
context.emit({ kind: 'trace.request', runDirectory: context.outputDir });
|
|
285
317
|
status = 'spawning peers';
|
|
286
318
|
research.event('run.start');
|
|
287
319
|
const setup = await Promise.allSettled(peerLabels.map(async (label) => {
|
|
@@ -299,6 +331,9 @@ export default {
|
|
|
299
331
|
}
|
|
300
332
|
signal.throwIfAborted();
|
|
301
333
|
status = 'researching';
|
|
334
|
+
workStartedAt = Date.now();
|
|
335
|
+
deadlineAt = workStartedAt + budget.workMs;
|
|
336
|
+
deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
|
|
302
337
|
context.markRunning();
|
|
303
338
|
research.event('team.ready');
|
|
304
339
|
await Promise.all(peers.map(async ({ peer, label, member }) => {
|
|
@@ -316,11 +351,15 @@ export default {
|
|
|
316
351
|
if (remaining <= 0)
|
|
317
352
|
break;
|
|
318
353
|
const review = member.reviewOfferedInTurn ? undefined : member.review;
|
|
319
|
-
|
|
354
|
+
const trainExhausted = research.state().budget.evaluations >= budget.maxEvaluations;
|
|
355
|
+
if (turn > 0 && !review && trainExhausted && !config.continueAfterTrainBudget)
|
|
320
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.';
|
|
321
360
|
const prompt = turn === 0
|
|
322
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.`
|
|
323
|
-
:
|
|
362
|
+
: remainingWork;
|
|
324
363
|
const interrupting = new Error('Peer interrupt pending before dispatch.');
|
|
325
364
|
try {
|
|
326
365
|
await runInput(runtime, peer.id, review ? `${prompt}\n\n${reviewNotice(review)}` : prompt, {
|
|
@@ -346,8 +385,17 @@ export default {
|
|
|
346
385
|
research.event('peer.turn-ended', { agentId: peer.id, detail: error.message.slice(0, 250) });
|
|
347
386
|
}
|
|
348
387
|
}));
|
|
388
|
+
workEndedAt = Date.now();
|
|
349
389
|
searchEnd = research.stopReason() ?? (context.signal.aborted ? 'stopped' : controller.signal.aborted ? 'deadline' :
|
|
350
|
-
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 });
|
|
351
399
|
// The host owns the judge independently of the Runtime. Stop native work
|
|
352
400
|
// while the last admitted train call settles under its own deadline.
|
|
353
401
|
[close] = await Promise.all([
|
|
@@ -362,16 +410,32 @@ export default {
|
|
|
362
410
|
selected = research.selection();
|
|
363
411
|
if (selected && !context.signal.aborted) {
|
|
364
412
|
status = 'final evaluation';
|
|
413
|
+
finalStartedAt = Date.now();
|
|
365
414
|
research.event('final.selected', { agentId: selected.agentId, candidate: selected.id });
|
|
366
415
|
const finalSignal = AbortSignal.any([context.signal, AbortSignal.timeout(config.closeTimeoutMs ?? 240_000)]);
|
|
367
416
|
final = await withDeadline(finalSignal, () => config.evaluator.final(research.patch(selected), finalSignal));
|
|
368
|
-
|
|
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' });
|
|
369
423
|
}
|
|
370
424
|
}
|
|
371
425
|
catch (failure) {
|
|
372
|
-
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
|
+
});
|
|
373
434
|
}
|
|
374
435
|
finally {
|
|
436
|
+
cleanupStartedAt = Date.now();
|
|
437
|
+
workEndedAt ??= workStartedAt === null ? null : cleanupStartedAt;
|
|
438
|
+
finalEndedAt ??= finalStartedAt === null ? null : cleanupStartedAt;
|
|
375
439
|
clearTimeout(deadline);
|
|
376
440
|
controller.abort('closing');
|
|
377
441
|
research.close();
|
|
@@ -382,29 +446,51 @@ export default {
|
|
|
382
446
|
}
|
|
383
447
|
observation?.close();
|
|
384
448
|
judgeCleanup = await cleanupJudge();
|
|
449
|
+
if (runtime)
|
|
450
|
+
research.event('run.cleanup', {
|
|
451
|
+
detail: `Runtime ${close?.cleanup ?? 'pending'}; evaluator ${judgeCleanup}`,
|
|
452
|
+
});
|
|
385
453
|
}
|
|
386
454
|
const best = research.best();
|
|
387
455
|
const peers = research.state().peers;
|
|
388
456
|
const traceDirectory = runtime ? join(context.outputDir, runtime.id) : null;
|
|
389
|
-
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');
|
|
390
472
|
const result = {
|
|
391
|
-
runtimeId: runtime?.id ?? null, budget, searchEnd,
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
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 },
|
|
398
482
|
};
|
|
399
483
|
await mkdir(context.outputDir, { recursive: true, mode: 0o700 });
|
|
400
|
-
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';
|
|
401
487
|
return {
|
|
402
|
-
outcome
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
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) } : {}) },
|
|
408
494
|
};
|
|
409
495
|
},
|
|
410
496
|
};
|
|
@@ -4,13 +4,24 @@ export interface Evaluation {
|
|
|
4
4
|
valid: boolean;
|
|
5
5
|
score: number | null;
|
|
6
6
|
feedback: JsonValue;
|
|
7
|
+
payload?: {
|
|
8
|
+
digest: string;
|
|
9
|
+
size: number;
|
|
10
|
+
};
|
|
7
11
|
}
|
|
12
|
+
export type FinalEvaluation = {
|
|
13
|
+
status: 'valid' | 'rejected' | 'unknown';
|
|
14
|
+
score: number | null;
|
|
15
|
+
meetsObjective: boolean | null;
|
|
16
|
+
evidence: JsonValue;
|
|
17
|
+
};
|
|
18
|
+
export declare function readFinalEvaluation(value: JsonValue): FinalEvaluation | undefined;
|
|
8
19
|
export interface Evaluator {
|
|
9
20
|
start?(directory: string, signal: AbortSignal): Promise<void>;
|
|
10
21
|
close?(): Promise<'complete' | 'pending'>;
|
|
11
22
|
evidence?(): JsonValue;
|
|
12
23
|
train(candidate: Buffer, signal: AbortSignal, admitted: (reference: string | number) => void): Promise<Evaluation>;
|
|
13
|
-
final(candidate: Buffer, signal: AbortSignal): Promise<JsonValue>;
|
|
24
|
+
final(candidate: Buffer, signal: AbortSignal): Promise<FinalEvaluation | JsonValue>;
|
|
14
25
|
}
|
|
15
26
|
export interface Candidate {
|
|
16
27
|
id: string;
|
|
@@ -38,6 +49,8 @@ interface ResearchEvent {
|
|
|
38
49
|
basedOnSha256?: string;
|
|
39
50
|
score?: number | null;
|
|
40
51
|
officialJob?: string | number;
|
|
52
|
+
payloadDigest?: string;
|
|
53
|
+
bytes?: number;
|
|
41
54
|
label?: string;
|
|
42
55
|
}
|
|
43
56
|
export declare const researchOperations: string[];
|
|
@@ -86,6 +99,8 @@ export declare function createResearch(options: {
|
|
|
86
99
|
basedOnSha256?: string;
|
|
87
100
|
score?: number | null;
|
|
88
101
|
officialJob?: string | number;
|
|
102
|
+
payloadDigest?: string;
|
|
103
|
+
bytes?: number;
|
|
89
104
|
label?: string;
|
|
90
105
|
peer: string | undefined;
|
|
91
106
|
}[];
|
|
@@ -1,12 +1,21 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { appendFileSync } from 'node:fs';
|
|
3
|
-
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { mkdir, unlink, writeFile } from 'node:fs/promises';
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { inProcessService } from '@anyswarm/core';
|
|
6
6
|
export const candidatePath = '.anyswarm-candidate.patch';
|
|
7
7
|
const maxPatch = 1024 * 1024 - 1536;
|
|
8
8
|
const patchChunk = 24 * 1024;
|
|
9
|
-
const
|
|
9
|
+
const maxMutations = 16_384;
|
|
10
|
+
export function readFinalEvaluation(value) {
|
|
11
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) ||
|
|
12
|
+
!['valid', 'rejected', 'unknown'].includes(value.status) ||
|
|
13
|
+
(value.score !== null && (typeof value.score !== 'number' || !Number.isFinite(value.score))) ||
|
|
14
|
+
(value.meetsObjective !== null && typeof value.meetsObjective !== 'boolean') ||
|
|
15
|
+
value.evidence === undefined)
|
|
16
|
+
return undefined;
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
10
19
|
const text = (maxLength) => ({ type: 'string', minLength: 1, maxLength });
|
|
11
20
|
const object = (properties, required) => ({ type: 'object', properties, required, additionalProperties: false });
|
|
12
21
|
const identifier = text(200);
|
|
@@ -41,21 +50,44 @@ export function createResearch(options) {
|
|
|
41
50
|
const claims = new Map();
|
|
42
51
|
let best;
|
|
43
52
|
let reserved = 0;
|
|
53
|
+
let nextCandidate = 0;
|
|
54
|
+
let storing = Promise.resolve();
|
|
55
|
+
const mutations = new Map();
|
|
44
56
|
let closed = false;
|
|
45
57
|
let stopReason;
|
|
46
58
|
let queue = Promise.resolve();
|
|
47
59
|
const project = (record) => record;
|
|
48
60
|
const reached = (score, target) => options.direction === 'max' ? score >= target : score <= target;
|
|
49
61
|
function event(operation, data = {}) {
|
|
50
|
-
const
|
|
62
|
+
const candidate = data.candidate && candidates.get(data.candidate);
|
|
63
|
+
const entry = { ...(candidate ? { sha256: candidate.sha256 } : {}), ...data, seq: events.length + 1, at: new Date().toISOString(), type: 'research', operation };
|
|
51
64
|
events.push(entry);
|
|
52
65
|
options.traceEvent(entry);
|
|
53
66
|
options.statusChanged();
|
|
54
67
|
}
|
|
55
68
|
function admit() {
|
|
56
|
-
if (closed || stopReason || options.signal.aborted
|
|
69
|
+
if (closed || stopReason || options.signal.aborted)
|
|
57
70
|
throw new Error('Research admissions are closed');
|
|
58
71
|
}
|
|
72
|
+
function mutation(operation, handler) {
|
|
73
|
+
return (input, context) => {
|
|
74
|
+
context.assertAuthorized();
|
|
75
|
+
const key = JSON.stringify([context.caller.agentId, context.envelope.operation_id]);
|
|
76
|
+
const payload = input;
|
|
77
|
+
const fingerprint = JSON.stringify([operation, Object.entries(payload).sort(([left], [right]) => left.localeCompare(right))]);
|
|
78
|
+
const entry = mutations.get(key);
|
|
79
|
+
if (entry) {
|
|
80
|
+
if (entry.fingerprint !== fingerprint)
|
|
81
|
+
throw new Error('Operation ID already identifies a different research action');
|
|
82
|
+
return entry.receipt;
|
|
83
|
+
}
|
|
84
|
+
if (mutations.size >= maxMutations)
|
|
85
|
+
throw new Error('Research mutation receipt limit reached');
|
|
86
|
+
const receipt = Promise.resolve().then(() => handler(input, context));
|
|
87
|
+
mutations.set(key, { fingerprint, receipt });
|
|
88
|
+
return receipt;
|
|
89
|
+
};
|
|
90
|
+
}
|
|
59
91
|
function state() {
|
|
60
92
|
return {
|
|
61
93
|
peers: [...peers].map(([agentId, label]) => ({ agentId, label })),
|
|
@@ -86,7 +118,8 @@ export function createResearch(options) {
|
|
|
86
118
|
}));
|
|
87
119
|
candidate.evaluation = evaluation;
|
|
88
120
|
candidate.state = validScore(evaluation) ? 'scored' : 'invalid';
|
|
89
|
-
event('train.returned', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score
|
|
121
|
+
event('train.returned', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score,
|
|
122
|
+
officialJob: candidate.officialJob, payloadDigest: evaluation.payload?.digest });
|
|
90
123
|
if (validScore(evaluation) && (!best || (evaluation.score !== best.evaluation.score && reached(evaluation.score, best.evaluation.score)))) {
|
|
91
124
|
best = candidate;
|
|
92
125
|
event('candidate.best', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score });
|
|
@@ -112,7 +145,7 @@ export function createResearch(options) {
|
|
|
112
145
|
candidates: [...candidates.values()].slice(-8).map(({ path: _, ...candidate }) => candidate),
|
|
113
146
|
});
|
|
114
147
|
},
|
|
115
|
-
claim: (input, { caller, assertAuthorized }) => {
|
|
148
|
+
claim: mutation('claim', (input, { caller, assertAuthorized }) => {
|
|
116
149
|
assertAuthorized();
|
|
117
150
|
admit();
|
|
118
151
|
const direction = input.direction.trim();
|
|
@@ -125,8 +158,8 @@ export function createResearch(options) {
|
|
|
125
158
|
claims.set(key, caller.agentId);
|
|
126
159
|
event('peer.claim', { agentId: caller.agentId, detail: direction });
|
|
127
160
|
return { claimed: true, agentId: caller.agentId };
|
|
128
|
-
},
|
|
129
|
-
publish: (input, { caller, assertAuthorized }) => {
|
|
161
|
+
}),
|
|
162
|
+
publish: mutation('publish', (input, { caller, assertAuthorized }) => {
|
|
130
163
|
assertAuthorized();
|
|
131
164
|
admit();
|
|
132
165
|
const { kind, summary, candidate } = input;
|
|
@@ -139,8 +172,8 @@ export function createResearch(options) {
|
|
|
139
172
|
event(`peer.${kind}`, { agentId: caller.agentId, detail: summary,
|
|
140
173
|
...(reviewed ? { candidate: reviewed.id, sha256: reviewed.sha256 } : {}) });
|
|
141
174
|
return { published: true };
|
|
142
|
-
},
|
|
143
|
-
message: (input, { caller, assertAuthorized }) => {
|
|
175
|
+
}),
|
|
176
|
+
message: mutation('message', (input, { caller, assertAuthorized }) => {
|
|
144
177
|
assertAuthorized();
|
|
145
178
|
admit();
|
|
146
179
|
const { peer, summary } = input;
|
|
@@ -148,7 +181,7 @@ export function createResearch(options) {
|
|
|
148
181
|
throw new Error('Peer does not belong to this Run');
|
|
149
182
|
event('peer.message', { agentId: caller.agentId, to: peer, detail: summary });
|
|
150
183
|
return { sent: true };
|
|
151
|
-
},
|
|
184
|
+
}),
|
|
152
185
|
read_patch: (input, { caller, assertAuthorized }) => {
|
|
153
186
|
assertAuthorized();
|
|
154
187
|
admit();
|
|
@@ -172,47 +205,54 @@ export function createResearch(options) {
|
|
|
172
205
|
}
|
|
173
206
|
return { candidate, sha256, data: bytes.subarray(start, end).toString('base64'), nextOffset: end < bytes.length ? end : null };
|
|
174
207
|
},
|
|
175
|
-
submit: async (input, { caller, envelope, assertAuthorized }) => {
|
|
208
|
+
submit: mutation('submit', async (input, { caller, envelope, assertAuthorized }) => {
|
|
176
209
|
assertAuthorized();
|
|
177
210
|
admit();
|
|
178
211
|
const { summary, basedOn } = input;
|
|
179
|
-
|
|
180
|
-
|
|
212
|
+
const parent = basedOn ? candidates.get(basedOn) : undefined;
|
|
213
|
+
if (basedOn && (!parent || parent.agentId === caller.agentId || !readEntirePatch(caller.agentId, basedOn))) {
|
|
214
|
+
throw new Error('Read the referenced peer candidate before building on it');
|
|
215
|
+
}
|
|
181
216
|
const bytes = await options.readPatch(caller.agentId, envelope.operation_id);
|
|
182
|
-
assertAuthorized();
|
|
183
|
-
admit();
|
|
184
217
|
if (!bytes.length || bytes.length > maxPatch)
|
|
185
218
|
throw new Error('Candidate patch is empty or exceeds the size limit');
|
|
186
219
|
const sha256 = createHash('sha256').update(bytes).digest('hex');
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
if (reserved >= options.maxEvaluations)
|
|
191
|
-
throw new Error('Shared evaluation budget is exhausted');
|
|
192
|
-
reserved++;
|
|
193
|
-
const id = `candidate-${reserved}`;
|
|
194
|
-
const path = join(options.outputDir, 'candidates', `${id}.patch`);
|
|
195
|
-
const candidate = { id, agentId: caller.agentId, summary, basedOn: basedOn ?? null, path,
|
|
196
|
-
sha256, bytes: bytes.length, state: 'queued' };
|
|
197
|
-
known.set(sha256, candidate);
|
|
198
|
-
try {
|
|
199
|
-
await mkdir(join(options.outputDir, 'candidates'), { recursive: true, mode: 0o700 });
|
|
200
|
-
await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
|
|
220
|
+
// Serialize the host file commit and quota admission, once the private
|
|
221
|
+
// workspace snapshot is available. No duplicate can observe a half write.
|
|
222
|
+
const result = storing.then(async () => {
|
|
201
223
|
assertAuthorized();
|
|
202
224
|
admit();
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
225
|
+
const previous = known.get(sha256);
|
|
226
|
+
if (previous)
|
|
227
|
+
return { candidate: previous.id, status: previous.state, duplicate: true, sha256 };
|
|
228
|
+
if (reserved >= options.maxEvaluations)
|
|
229
|
+
throw new Error('Shared evaluation budget is exhausted');
|
|
230
|
+
const id = `candidate-${++nextCandidate}`;
|
|
231
|
+
const path = join(options.outputDir, 'candidates', `${id}.patch`);
|
|
232
|
+
const candidate = { id, agentId: caller.agentId, summary, basedOn: basedOn ?? null, path,
|
|
233
|
+
sha256, bytes: bytes.length, state: 'queued' };
|
|
234
|
+
await mkdir(join(options.outputDir, 'candidates'), { recursive: true, mode: 0o700 });
|
|
235
|
+
await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
|
|
236
|
+
try {
|
|
237
|
+
assertAuthorized();
|
|
238
|
+
admit();
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
await unlink(path);
|
|
242
|
+
throw error;
|
|
243
|
+
}
|
|
244
|
+
reserved++;
|
|
245
|
+
known.set(sha256, candidate);
|
|
246
|
+
patches.set(id, bytes);
|
|
206
247
|
candidates.set(id, candidate);
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
},
|
|
248
|
+
event(parent ? 'candidate.built-on' : 'candidate.queued', { agentId: caller.agentId, candidate: id, sha256, bytes: bytes.length, detail: summary,
|
|
249
|
+
...(parent ? { basedOn, basedOnSha256: parent.sha256 } : {}) });
|
|
250
|
+
queue = queue.then(() => evaluate(candidate, bytes));
|
|
251
|
+
return { candidate: id, status: 'queued', duplicate: false, sha256 };
|
|
252
|
+
});
|
|
253
|
+
storing = result.then(() => { }, () => { });
|
|
254
|
+
return result;
|
|
255
|
+
}),
|
|
216
256
|
}, {
|
|
217
257
|
readState: () => ({
|
|
218
258
|
state: project(state()), capturedAt: new Date().toISOString(), revision: String(events.length),
|
|
@@ -229,10 +269,10 @@ export function createResearch(options) {
|
|
|
229
269
|
addPeer: (id, label) => { peers.set(id, label); event('peer.ready', { agentId: id, label }); },
|
|
230
270
|
close: () => { closed = true; },
|
|
231
271
|
stopReason: () => stopReason,
|
|
232
|
-
drained: () => queue,
|
|
272
|
+
drained: async () => { await storing; await queue; },
|
|
233
273
|
best: () => best,
|
|
234
274
|
peerLabel: (agentId) => peers.get(agentId),
|
|
235
|
-
selection: () => best
|
|
275
|
+
selection: () => best,
|
|
236
276
|
patch: (candidate) => Buffer.from(patches.get(candidate.id)),
|
|
237
277
|
candidates: () => [...candidates.values()], };
|
|
238
278
|
}
|
|
@@ -1,25 +1,33 @@
|
|
|
1
|
-
# Code
|
|
1
|
+
# Code SDK example
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Code runs a coding Agent in a writable Sandbox, verifies a candidate on the Linux
|
|
4
|
+
host and applies authorized edits to the project. Ask the lead Agent to delegate
|
|
5
|
+
a separable task when you want an editor to work in parallel. Between turns,
|
|
6
|
+
Code reconciles edits made by the user and returns conflicting paths for review.
|
|
4
7
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
anys -u code "Add a test for the empty-input case"
|
|
8
|
-
```
|
|
9
|
-
|
|
10
|
-
You can also start `anys` and enter `/code`. Enter sends, Alt+Enter adds a line, Ctrl+C interrupts the current task, and `/quit` closes the team. `/diff` prints the latest completed turn's paths, patch preview and full patch location into the conversation. Use `/agents` for the member roster, `@<editor> <message>` to steer an active editor, and `/stop <editor>` to stop that editor. Answer inline verification confirmations with `/y` or `/n`, and editor questions with `/reply <id> <answer>`. Use `/config` and `/doctor` for setup information and `/trace` for Trace Viewer.
|
|
11
|
-
|
|
12
|
-
The main Agent edits and tests a copy of your current project in one writable Sandbox. Follow-up requests reuse its conversation. AnySwarm reconciles your files before each turn, including edits you made between turns. To delegate, write a request such as “Ask a subagent to write the regression test while you fix the implementation.” The main Agent can continue while the child works in a separate Sandbox, then collect and review the result. The host checks the integrated changes before writeback. If an edit conflicts with yours, resolve the reported path before retrying.
|
|
13
|
-
|
|
14
|
-
The default configuration reads `ANYSWARM_MODEL_URL`, optional `ANYSWARM_MODEL_TOKEN`, `ANYSWARM_MODEL_ID` and `ANYSWARM_MODEL_PROVIDER`. Code-specific `ANYSWARM_CODE_*` equivalents take precedence. Use `anys -u code --config ./trusted.ts` for an explicit model/Sandbox configuration. The application can ask before running a detected `npm test` or `make test`. Set `check` to an argv array in a trusted config to authorize it for each candidate, or set `check: false` to skip verification. Checks run locally with your permissions in a temporary copy. Code copies a supported existing Node dependency installation into that copy. Install the project's dependencies first if the checker reports an unavailable environment. A failed verification leaves the original project files in place. After a successful task, `/quit` returns 0 when cleanup completes and keeps the report location visible.
|
|
15
|
-
|
|
16
|
-
To edit the application itself:
|
|
8
|
+
Prepare OpenSandbox, a supported Pi or Codex Worker and a model route. Export the
|
|
9
|
+
source outside the target project and install its pinned SDK.
|
|
17
10
|
|
|
18
11
|
```sh
|
|
19
|
-
|
|
12
|
+
anyswarm eject code --dir ./my-code
|
|
20
13
|
cd ./my-code
|
|
21
14
|
npm install
|
|
22
|
-
|
|
15
|
+
npm run start -- --cwd /path/to/project --config ./trusted.ts --prompt "Add a test for empty input" --output-dir ./runs
|
|
16
|
+
anyswarm trace --root ./runs
|
|
23
17
|
```
|
|
24
18
|
|
|
25
|
-
The
|
|
19
|
+
The default configuration reads `ANYSWARM_MODEL_URL`, optional
|
|
20
|
+
`ANYSWARM_MODEL_TOKEN`, `ANYSWARM_MODEL_ID` and `ANYSWARM_MODEL_PROVIDER`.
|
|
21
|
+
Code-specific `ANYSWARM_CODE_*` values take precedence. The example command uses
|
|
22
|
+
an explicit trusted config. Set `check` to an argv array to authorize
|
|
23
|
+
verification, or set `check: false` to skip it. Checks run with the host user's
|
|
24
|
+
permissions in a temporary copy and can reuse a supported Node dependency
|
|
25
|
+
installation. A failed check or writeback conflict retains the original files.
|
|
26
|
+
The Run report includes verification, changed paths and the retained diff.
|
|
27
|
+
|
|
28
|
+
For follow-up turns and questions, import the Harness in an application and
|
|
29
|
+
drive it through `createHarnessSession`, or connect to
|
|
30
|
+
`npm run start -- --mode rpc --lifetime interactive --interaction questions`
|
|
31
|
+
with `HarnessRpcClient`. Send the target directory in the RPC `run` input.
|
|
32
|
+
See [HarnessSession clients](../harness-session/README.md) for the protocol and
|
|
33
|
+
[Code architecture](../../docs/architecture/26-code.md) for writeback rules.
|