@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.
Files changed (210) hide show
  1. package/AGENTS.md +19 -4
  2. package/README.md +68 -61
  3. package/dist/examples/README.md +134 -84
  4. package/dist/examples/autoresearch/README.md +106 -21
  5. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
  6. package/dist/examples/autoresearch/config.d.ts +48 -5
  7. package/dist/examples/autoresearch/config.js +57 -23
  8. package/dist/examples/autoresearch/demo.d.ts +12 -4
  9. package/dist/examples/autoresearch/demo.js +65 -22
  10. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -2
  11. package/dist/examples/autoresearch/frontiercs2-config.js +13 -2
  12. package/dist/examples/autoresearch/frontiercs2.d.ts +18 -1
  13. package/dist/examples/autoresearch/frontiercs2.js +71 -14
  14. package/dist/examples/autoresearch/prepare-demo.js +34 -3
  15. package/dist/examples/autoresearch/prepare.d.ts +105 -53
  16. package/dist/examples/autoresearch/prepare.js +126 -57
  17. package/dist/examples/autoresearch/project.d.ts +6 -1
  18. package/dist/examples/autoresearch/project.js +130 -26
  19. package/dist/examples/autoresearch/research-service.d.ts +16 -1
  20. package/dist/examples/autoresearch/research-service.js +84 -44
  21. package/dist/examples/code/config.d.ts +1 -0
  22. package/dist/examples/first-harness/AGENTS.md +25 -0
  23. package/dist/examples/first-harness/README.md +136 -0
  24. package/dist/examples/first-harness/config.d.ts +9 -8
  25. package/dist/examples/first-harness/config.js +33 -26
  26. package/dist/examples/first-harness/eject.json +14 -0
  27. package/dist/examples/first-harness/handoff.js +3 -3
  28. package/dist/examples/first-harness/harness.d.ts +14 -18
  29. package/dist/examples/first-harness/harness.js +102 -77
  30. package/dist/examples/first-harness/input/README.md +7 -0
  31. package/dist/examples/first-harness/session.js +2 -1
  32. package/dist/examples/first-harness/tsconfig.json +2 -1
  33. package/dist/examples/harness-session/README.md +1 -1
  34. package/dist/examples/lead-worker/README.md +1 -1
  35. package/dist/examples/lead-worker/project-config.d.ts +1 -0
  36. package/dist/examples/messages/README.md +2 -2
  37. package/dist/examples/notes/README.md +2 -2
  38. package/dist/examples/notes/config.d.ts +1 -0
  39. package/dist/examples/parallel-swarm/AGENTS.md +32 -0
  40. package/dist/examples/parallel-swarm/README.md +136 -0
  41. package/dist/examples/parallel-swarm/board-service.js +25 -8
  42. package/dist/examples/parallel-swarm/board.d.ts +31 -1
  43. package/dist/examples/parallel-swarm/board.js +98 -13
  44. package/dist/examples/parallel-swarm/config.d.ts +11 -0
  45. package/dist/examples/parallel-swarm/config.js +39 -0
  46. package/dist/examples/parallel-swarm/eject.json +5 -0
  47. package/dist/examples/parallel-swarm/harness.d.ts +26 -20
  48. package/dist/examples/parallel-swarm/harness.js +77 -76
  49. package/dist/examples/parallel-swarm/report.d.ts +12 -0
  50. package/dist/examples/parallel-swarm/report.js +30 -0
  51. package/dist/examples/peermesh/README.md +1 -1
  52. package/dist/examples/peermesh/project-config.d.ts +1 -0
  53. package/dist/examples/services/agent-control/README.md +1 -1
  54. package/dist/examples/services/mathlib-search/README.md +1 -1
  55. package/dist/examples/services/mcp-managed/README.md +1 -1
  56. package/dist/examples/services/persistent-board/README.md +1 -1
  57. package/dist/examples/subagents/AGENTS.md +35 -0
  58. package/dist/examples/subagents/README.md +129 -93
  59. package/dist/examples/subagents/config.d.ts +2 -10
  60. package/dist/examples/subagents/config.js +8 -15
  61. package/dist/examples/subagents/eject.json +17 -0
  62. package/dist/examples/subagents/handoff-config.d.ts +41 -0
  63. package/dist/examples/subagents/handoff-config.js +13 -0
  64. package/dist/examples/subagents/model.d.ts +3 -0
  65. package/dist/examples/subagents/model.js +19 -0
  66. package/dist/examples/substrate/README.md +12 -6
  67. package/dist/examples/substrate/config.d.ts +1 -0
  68. package/dist/examples/substrate/project-config.d.ts +1 -0
  69. package/dist/examples/taskpool/README.md +1 -1
  70. package/dist/examples/taskpool/config.d.ts +1 -0
  71. package/dist/examples/taskpool/deploy/service-hosts/service-authority-snapshot.d.ts +4 -4
  72. package/dist/scripts/anyswarm-progress.js +36 -5
  73. package/dist/scripts/build-provenance.json +1 -1
  74. package/dist/scripts/generate-architecture-coverage.js +1 -1
  75. package/dist/scripts/generate-architecture-prompts.js +18 -10
  76. package/dist/scripts/local-environment.d.ts +3 -3
  77. package/dist/scripts/local-environment.js +6 -1
  78. package/dist/scripts/local-setup.js +25 -18
  79. package/dist/scripts/pack-release.js +27 -3
  80. package/dist/src/core/index.js +1 -1
  81. package/dist/src/core/sandbox/opensandbox-backend.js +10 -4
  82. package/dist/src/core/sandbox/sandbox-connection.d.ts +9 -2
  83. package/dist/src/core/sandbox/sandbox-connection.js +22 -7
  84. package/dist/src/harness/project-harness.js +3 -2
  85. package/dist/src/harness/project-rpc-client.js +19 -0
  86. package/dist/src/harness/typescript-loader.d.ts +2 -0
  87. package/dist/src/harness/typescript-loader.js +26 -8
  88. package/dist/src/trace-viewer/command.mjs +6 -3
  89. package/dist/src/trace-viewer/public/app.js +239 -59
  90. package/dist/src/trace-viewer/public/index.html +5 -0
  91. package/dist/src/trace-viewer/public/style.css +22 -0
  92. package/dist/src/trace-viewer/reader.mjs +242 -26
  93. package/dist/src/trace-viewer/run-root.d.mts +1 -0
  94. package/dist/src/trace-viewer/run-root.mjs +7 -0
  95. package/dist/src/trace-viewer/server.mjs +3 -1
  96. package/docs/INDEX.md +9 -8
  97. package/docs/architecture/06-observability-experiments.md +21 -7
  98. package/docs/architecture/07-run-configuration.md +97 -12
  99. package/docs/architecture/08-prompts.md +21 -2
  100. package/docs/architecture/10-service-api-reference.md +12 -5
  101. package/docs/architecture/12-code-coverage.md +129 -86
  102. package/docs/architecture/15-core-runtime.md +1 -1
  103. package/docs/architecture/16-pi-opensandbox-backend.md +2 -0
  104. package/docs/architecture/17-harness-reporting.md +78 -0
  105. package/docs/architecture/22-website.md +53 -18
  106. package/docs/architecture/23-project-harness.md +63 -16
  107. package/docs/architecture/28-autoresearch.md +16 -22
  108. package/docs/architecture/prompts/11-first-sdk-harness.md +9 -9
  109. package/docs/architecture/prompts/16-parallel-swarm.md +46 -13
  110. package/docs/architecture/prompts/22-autoresearch.md +9 -2
  111. package/docs/architecture/prompts/source-manifest.json +78 -54
  112. package/docs/architecture/source-map.json +396 -36
  113. package/docs/designs/core-harness/06-project-harness.md +1 -1
  114. package/docs/en/autoresearch.md +41 -0
  115. package/docs/en/blog/100b-tokens.md +157 -0
  116. package/docs/en/build-your-harness.md +47 -22
  117. package/docs/en/changelog.md +22 -1
  118. package/docs/en/first-harness.md +40 -32
  119. package/docs/en/harnesses/index.md +23 -23
  120. package/docs/en/harnesses/subagents.md +8 -29
  121. package/docs/en/latest.md +26 -5
  122. package/docs/en/overview.md +22 -22
  123. package/docs/en/quickstart.md +55 -21
  124. package/docs/en/reference/api.md +1 -1
  125. package/docs/en/trace-viewer.md +32 -12
  126. package/docs/operations/trace-viewer.md +25 -10
  127. package/docs/workflows/development.md +160 -120
  128. package/docs/workflows/release-and-docs-versioning.md +207 -55
  129. package/docs/workflows/release-cli-acceptance.md +124 -47
  130. package/docs/zh/autoresearch.md +41 -0
  131. package/docs/zh/blog/100b-tokens.md +102 -0
  132. package/docs/zh/build-your-harness.md +48 -23
  133. package/docs/zh/changelog.md +22 -1
  134. package/docs/zh/first-harness.md +43 -35
  135. package/docs/zh/harnesses/index.md +23 -23
  136. package/docs/zh/harnesses/subagents.md +8 -29
  137. package/docs/zh/latest.md +26 -5
  138. package/docs/zh/overview.md +23 -23
  139. package/docs/zh/quickstart.md +51 -21
  140. package/docs/zh/reference/api.md +1 -1
  141. package/docs/zh/trace-viewer.md +32 -12
  142. package/examples/README.md +134 -84
  143. package/examples/autoresearch/README.md +106 -21
  144. package/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
  145. package/examples/autoresearch/config.ts +64 -25
  146. package/examples/autoresearch/demo.ts +75 -22
  147. package/examples/autoresearch/frontiercs2-config.ts +13 -2
  148. package/examples/autoresearch/frontiercs2.ts +64 -11
  149. package/examples/autoresearch/prepare-demo.ts +32 -3
  150. package/examples/autoresearch/prepare.ts +134 -60
  151. package/examples/autoresearch/project.ts +119 -26
  152. package/examples/autoresearch/research-service.ts +91 -41
  153. package/examples/first-harness/AGENTS.md +25 -0
  154. package/examples/first-harness/README.md +136 -0
  155. package/examples/first-harness/config.ts +41 -27
  156. package/examples/first-harness/eject.json +14 -0
  157. package/examples/first-harness/handoff.ts +3 -3
  158. package/examples/first-harness/harness.ts +104 -72
  159. package/examples/first-harness/input/README.md +7 -0
  160. package/examples/first-harness/session.ts +2 -1
  161. package/examples/first-harness/tsconfig.json +2 -1
  162. package/examples/harness-session/README.md +1 -1
  163. package/examples/lead-worker/README.md +1 -1
  164. package/examples/messages/README.md +2 -2
  165. package/examples/notes/README.md +2 -2
  166. package/examples/parallel-swarm/AGENTS.md +32 -0
  167. package/examples/parallel-swarm/README.md +136 -0
  168. package/examples/parallel-swarm/board-service.ts +28 -9
  169. package/examples/parallel-swarm/board.ts +107 -13
  170. package/examples/parallel-swarm/config.ts +47 -0
  171. package/examples/parallel-swarm/eject.json +5 -0
  172. package/examples/parallel-swarm/harness.ts +83 -71
  173. package/examples/parallel-swarm/report.ts +33 -0
  174. package/examples/peermesh/README.md +1 -1
  175. package/examples/services/agent-control/README.md +1 -1
  176. package/examples/services/mathlib-search/README.md +1 -1
  177. package/examples/services/mcp-managed/README.md +1 -1
  178. package/examples/services/persistent-board/README.md +1 -1
  179. package/examples/subagents/AGENTS.md +35 -0
  180. package/examples/subagents/README.md +129 -93
  181. package/examples/subagents/config.ts +8 -15
  182. package/examples/subagents/eject.json +17 -0
  183. package/examples/subagents/handoff-config.ts +14 -0
  184. package/examples/subagents/model.ts +20 -0
  185. package/examples/substrate/README.md +12 -6
  186. package/examples/taskpool/README.md +1 -1
  187. package/npm-shrinkwrap.development.json +9 -2
  188. package/npm-shrinkwrap.json +9 -2
  189. package/package.development.json +2 -1
  190. package/package.json +2 -1
  191. package/scripts/anyswarm-progress.ts +36 -6
  192. package/scripts/generate-architecture-coverage.ts +1 -1
  193. package/scripts/generate-architecture-prompts.ts +21 -10
  194. package/scripts/local-environment.ts +8 -1
  195. package/scripts/local-setup.ts +22 -17
  196. package/scripts/pack-release.ts +24 -3
  197. package/src/core/index.ts +1 -1
  198. package/src/core/sandbox/opensandbox-backend.ts +10 -4
  199. package/src/core/sandbox/sandbox-connection.ts +22 -7
  200. package/src/harness/project-harness.ts +3 -2
  201. package/src/harness/project-rpc-client.ts +23 -0
  202. package/src/harness/typescript-loader.ts +28 -8
  203. package/src/trace-viewer/command.mjs +6 -3
  204. package/src/trace-viewer/public/app.js +239 -59
  205. package/src/trace-viewer/public/index.html +5 -0
  206. package/src/trace-viewer/public/style.css +22 -0
  207. package/src/trace-viewer/reader.mjs +242 -26
  208. package/src/trace-viewer/run-root.d.mts +1 -0
  209. package/src/trace-viewer/run-root.mjs +7 -0
  210. package/src/trace-viewer/server.mjs +3 -1
@@ -1,40 +1,125 @@
1
- # AutoResearch
1
+ # AutoResearch with FrontierCS-2
2
2
 
3
- An AutoResearch Run starts equal peers in separate AnySwarm Sandboxes. Each peer chooses a direction, writes a patch, and can read, review and build on another peer's patch. The Harness provides the shared research Service and enforces the team's budget. A trusted evaluator decides whether a candidate is valid and returns the score used for selection.
3
+ Run a team of independent research peers on the official `binary_fuse_filter` task. The peers write patches, inspect each other's work and share train feedback. At the end, the trusted evaluator runs the official final on the selected patch. Open Trace Viewer during the run or replay it afterward.
4
4
 
5
- ## FrontierCS-2 quickstart
5
+ ## 1. Install and choose your backend
6
6
 
7
- Use a Linux x86-64 machine with Git LFS, Python 3, a local Docker daemon and an existing authenticated OpenSandbox deployment with `dns+nft` egress. Prepare a supported Pi Worker using the normal AnySwarm setup flow. Configure the existing Kimi K3 Responses route using `ANYSWARM_MODEL_URL`, `ANYSWARM_MODEL_TOKEN`, `ANYSWARM_MODEL_PROVIDER=kimi_proxy` and `ANYSWARM_MODEL_ID=k3`. Keep the token in trusted host configuration if your proxy requires one.
7
+ Use a Linux x86-64 controller. The CLI supports Node.js 22.19 or newer. The exported TypeScript example is tested with Node.js 24 LTS. Install Git, Git LFS, Python 3, Docker Engine and Docker Buildx. For a new Debian 13 VM, install Docker Engine 29 and its Buildx plugin from Docker's apt repository. Debian 13's stock Docker 26 can pass the image-store check and still fail when Pumpkin tags a just-built image. [Install Docker Engine on Debian](https://docs.docker.com/engine/install/debian/)
8
+
9
+ ```sh
10
+ sudo apt-get update
11
+ sudo apt-get install git git-lfs python3 ca-certificates curl xz-utils util-linux
12
+ sudo systemctl enable --now docker
13
+ docker version --format '{{ .Server.Version }}'
14
+ docker buildx version
15
+ docker info --format '{{ .DriverStatus }}'
16
+ ```
17
+
18
+ If those Docker commands report permission denied on your own Linux VM, add your account to the Docker group with `sudo usermod -aG docker "$USER"` and open a fresh login session before retrying. Keep Docker management access on the controller. [AnySwarm setup guide](https://anyswarm.github.io/anyswarm/docs/quickstart/)
19
+
20
+ Before running AnySwarm setup, verify that the Docker output contains `io.containerd.snapshotter.v1`. Pumpkin needs the containerd image store to resolve pinned images by digest. On a fresh Linux VM where the marker is absent, add `"containerd-snapshotter": true` under `"features"` in `/etc/docker/daemon.json`, run `sudo systemctl restart docker`, and check again. Existing images and containers from the previous store become hidden when switching stores. On a shared host, choose or provision a suitable Docker context first. [Docker image store setup](https://docs.docker.com/engine/storage/containerd/)
21
+
22
+ Install the CLI from a release that includes this example using `npm install -g @anyswarm/core`, or use `npm install -g /path/to/anyswarm-core.tgz` for a supplied candidate archive. A user-owned Node installation lets you install these packages without `sudo`. If you choose Pi, install the executable before setup:
23
+
24
+ ```sh
25
+ npm install -g @earendil-works/pi-coding-agent
26
+ anyswarm setup --backend pi
27
+ anyswarm doctor --smoke
28
+ ```
29
+
30
+ If you choose Codex, install its executable, choose a Responses model, then use `anyswarm setup --backend codex` and `anyswarm doctor --smoke`. Use `--backend-path` if your executable is outside your shell path. For an existing deployment, set its Lifecycle URL and API key and use `anyswarm setup --mode existing`. Make the matching Worker image available on that deployment, configure `dns+nft` egress and a callback URL reachable from the Workers, then repeat `anyswarm doctor --mode existing --smoke`. Pumpkin and its judges still run on the controller's selected Docker daemon.
31
+
32
+ ## 2. Export the example and configure your model and budget
8
33
 
9
34
  ```sh
10
35
  anyswarm eject autoresearch --dir ./research-demo
11
36
  cd ./research-demo
12
37
  npm install
13
- npm exec -- anyswarm run ./prepare-demo.ts
14
- npm run start -- --config ./frontiercs2-config.ts --prompt "Run the prepared FrontierCS-2 task." --output-dir ./runs
15
38
  ```
16
39
 
17
- Preparation prints prerequisite checks and the resource plan. It reports K3 configuration and HTTP route reachability separately, and reports inference as not attempted. It fetches only the pinned task and shared dependencies, checks the Pumpkin release hash, builds images, completes an independent no-model reference run and checks the authorized submission role. Initial image builds can take several minutes. Rerunning preparation reuses verified materials and images. Reference records are environment evidence. The model receives a clean starter and only public train feedback.
40
+ Edit `frontiercs2-config.ts`. Its default export is the shared configuration for prepare and run. The supplied template reads these values from the current shell. Use the provider’s full HTTP request URL. Load the token from your own credential store.
41
+
42
+ | Setting | What to supply |
43
+ | --- | --- |
44
+ | `ANYSWARM_MODEL_PROVIDER` | Your provider label |
45
+ | `ANYSWARM_MODEL_ID` | Exact model ID at the upstream |
46
+ | `ANYSWARM_MODEL_URL` | Full HTTP(S) request endpoint ending in `/v1/responses` or `/v1/chat/completions` for the built-in transports |
47
+ | `ANYSWARM_MODEL_PROTOCOL` | `responses` by default. For Pi with Chat Completions, set `chat-completions` |
48
+ | `ANYSWARM_MODEL_TOKEN` | Bearer token if the endpoint requires one. Load it into your shell from private storage |
49
+ | `ANYSWARM_AUTORESEARCH_STATE_DIR` | Optional path for prepared material and reference records |
50
+
51
+ For a Responses endpoint, replace the placeholders in this shell snippet. Keep the same shell or load the same settings before prepare and run.
52
+
53
+ ```bash
54
+ export ANYSWARM_MODEL_PROVIDER='my-provider'
55
+ export ANYSWARM_MODEL_ID='model-id-from-my-provider'
56
+ export ANYSWARM_MODEL_URL='https://my-provider.example/v1/responses'
57
+ # Skip these two lines if your endpoint needs no bearer token.
58
+ read -rsp 'Model token: ' ANYSWARM_MODEL_TOKEN && printf '\n'
59
+ export ANYSWARM_MODEL_TOKEN
60
+ ```
61
+
62
+ You can supply an ordinary `ModelConfig` in the TypeScript file instead. For a reasoning model outside the executor catalog, set its catalog-backed `capabilities` with `contextWindow`, `maxOutputTokens`, `tools: true` and `reasoning`. Use `model.upstream.headers` for custom authentication. Supply `executor`, `image`, `sandbox` and `connection` to override your saved setup.
63
+
64
+ The template reserves two peers, a shared 12-minute search window, four train admissions and 128 new model requests across the team. You can edit `goal` and `budget`. An omitted `maxModelRequests` leaves the Gateway's request count uncapped. Set `continueAfterTrainBudget: true` if peers should keep reviewing and testing locally until another stop condition. The app budget and Pumpkin's official grant are reported independently.
65
+
66
+ ## 3. Check and prepare
67
+
68
+ ```sh
69
+ npm exec -- anyswarm run ./prepare-demo.ts --config ./frontiercs2-config.ts --check
70
+ npm exec -- anyswarm run ./prepare-demo.ts --config ./frontiercs2-config.ts
71
+ ```
72
+
73
+ Read the `ACTION` lines to see which command or configuration field to fix. `--check` reports configuration, authentication, endpoint reachability, placement and available capacity. It makes a bounded HTTP HEAD probe to the model route and reports inference as unattempted. A successful real tool turn and continuation during the run establish actual inference.
18
74
 
19
- The demo configuration selects the clean pinned starter and trusted FrontierCS-2 evaluator. The
20
- terminal prints Run and Agent milestones. Use `anyswarm trace --root ./runs`
21
- during or after the Run for peer claims, patches, reviews, train scores and final
22
- records. For a remote controller, forward the Trace port over SSH.
75
+ | If a check reports an action | Where to start |
76
+ | --- | --- |
77
+ | `model-config` | Check the exact model ID and request endpoint. Codex uses Responses. Pi can also use Chat Completions. |
78
+ | `model-http` | Check controller DNS and outbound access. For HTTP 401/403, check the model token and provider access. |
79
+ | `opensandbox`, `callback` or `worker-image` | Repeat `anyswarm setup` and `anyswarm doctor --smoke` for the selected backend. Existing deployments also need a Worker-reachable callback and the matching image. |
80
+ | `run-capacity` or `storage` | Compare the plan below with the reported controller resources. Check both the state directory and `TMPDIR`. |
81
+ | `task-materials` | Run prepare. Use a different state directory when switching Docker contexts. |
82
+ | Pumpkin reports `can't be tagged` and `No such image` after a build | Check the server version and Buildx on the selected context. Try Docker Engine 29 with Docker's Buildx plugin and the containerd image store, then rerun prepare. |
23
83
 
24
- The default smoke budget is four Kimi K3 peers, a shared twelve-minute work window and eight train admissions. The demo records actual model usage without capping the request count. The application reserves additional time for final and cleanup. The result includes every frozen candidate, its hash and author, best candidate, Pumpkin record, final result and cleanup receipt. A valid candidate with a low score is a completed evaluation. A run without a valid candidate returns failure, even when it records an official zero for a selected invalid candidate.
84
+ | Phase | Controller plan when Workers are local |
85
+ | --- | --- |
86
+ | Prepare | 8 vCPU, 14 GiB RAM for the reference or bridge check, controller and build headroom |
87
+ | Run, two Workers | 10 vCPU, 18 GiB RAM |
88
+ | Run, four Workers | 14 vCPU, 26 GiB RAM |
25
89
 
26
- ## Run your own project
90
+ Each Worker, the submission bridge and the active judge have a 2 vCPU / 4 GiB allowance. For remote Workers, check their capacity and image separately. The controller still needs its own Docker capacity. Allow 12 GiB on the state mount, 1 GiB for temporary files and at least 25,000 free inodes on both mounts. No GPU is required.
91
+
92
+ Preparation fetches the pinned task and dependencies, checks Pumpkin, completes a no-model reference train and final and validates the submission bridge. The first prepare can take several minutes. Repeat the same command to reuse verified material and keep existing records.
93
+
94
+ ## 4. Run and verify the result
27
95
 
28
96
  ```sh
29
- anyswarm --harness autoresearch --config ./research.ts --prompt "Your objective" --output-dir ./runs
30
- anyswarm eject autoresearch --dir ./my-research
97
+ npm exec -- anyswarm run ./project.ts --config ./frontiercs2-config.ts --prompt 'Run the FrontierCS-2 task.' --output-dir ./runs
98
+ npm exec -- anyswarm trace --root ./runs
31
99
  ```
32
100
 
33
- The trusted TypeScript configuration exports a `ResearchConfiguration` object. Set `targetPath` relative to the invocation directory, `goal`, `direction` (`max` or `min`), optional `targetScore`, shared `budget` with an optional `maxModelRequests`, `model`, `executor`, `image`, `sandbox` and `connection`. The evaluator receives an immutable copy of the patch. Its `train(patch, signal, admitted)` returns `{valid, score, feedback}`. Call `admitted` with the trusted job identifier when one exists. `final(patch, signal)` returns the result of the independent final evaluation. The optional `start` and `close` own evaluator resources. All callbacks run as trusted host code. Run candidate code only inside an evaluator-owned isolated environment. Apply the patch to a fresh copy of the baseline, keep evaluator rules inaccessible to it and honor each supplied abort signal.
101
+ Run the Trace command in another terminal to watch live. For a remote controller, use `ssh -N -L 8787:127.0.0.1:8787 user@controller` with your connection options. Open `http://127.0.0.1:8787` in your browser. Select the matching Run and use the **Research** track. Search by candidate ID or patch SHA-256, open the candidate and follow the related full-read, review, train and final records. **Related evidence** opens the saved patch with SHA-256 verification. The **Model** track shows the actual request intervals and saved upstream responses for each peer. Reopen the same Run after it finishes to replay it.
102
+
103
+ The Run directory contains:
104
+
105
+ - `research-result.json` with goal, model, budget, actual use, candidate list, best, selected, typed final result and separate cleanup receipts.
106
+ - `<runtime-id>/candidates/*.patch` with the immutable candidate files and `research-events.jsonl` with their research events.
107
+ - The `pumpkin/<run-id>/` record with the official admission and final verdict. Match the candidate's patch hash and the official payload digest in the research journal. Final metrics stay on the controller.
108
+
109
+ To inspect the selected patch against the clean baseline, copy the prepared state's `reference/tasks/binary_fuse_filter/repo` directory to scratch, then run `git apply --check /absolute/path/to/candidate.patch` and `git apply /absolute/path/to/candidate.patch` from the copy. The original official final is in the Run's Pumpkin record. Leave the prepared starter intact for the next run.
110
+
111
+ The final result distinguishes a valid score, objective attainment, rejection and an unconfirmed result. Set `targetScore` to add a numeric objective. The official comparison with the reference is recorded separately. The research timer starts when all peers are ready. Prepare, train settlement, final and cleanup take their own time. If cleanup is pending, use the recorded Runtime receipt and Pumpkin run/container IDs to check those specific resources. Keep those records until reconciliation.
112
+
113
+ ## Use your own project and evaluator
114
+
115
+ ```sh
116
+ anyswarm --harness autoresearch --config ./research.ts --prompt 'Your research objective' --output-dir ./runs
117
+ ```
118
+
119
+ Default-export a `ResearchConfiguration` from trusted TypeScript. Choose `targetPath` relative to the launch directory, or pass `--cwd`. Set `goal`, `direction` (`max` or `min`), optional `targetScore`, `budget`, `model`, `executor`, `image`, `sandbox` and `connection`. Use the exported `frontiercs2-config.ts` as the model and backend example.
120
+
121
+ Implement `evaluator.train(patch, signal, admitted)` and return `{ valid, score, feedback }`. Set `valid: true` for a legal zero score. Call `admitted(jobId)` when a trusted external job is accepted. Implement `evaluator.final(patch, signal)` returning `{ status, score, meetsObjective, evidence }`. Use `status: 'valid' | 'rejected' | 'unknown'`, `score: null` if unknown, and `meetsObjective: null` when no application objective was evaluated. Legacy JSON output remains visible as unconfirmed evidence. `start` and `close` own evaluator resources. Report pending resources through `evidence()`.
34
122
 
35
- The exported `project.ts` is the editable Harness. Run `npm install` in the export directory
36
- to install the pinned SDK, then run
37
- `npm run start -- --cwd /path/to/project --config ./research.ts --prompt "Your objective"`.
38
- The export includes the FrontierCS-2 preparation and adapter sources.
123
+ Keep model credentials, judges and Docker management on the host. Run candidate code only in evaluator-owned isolation, apply each patch to a clean baseline, bound every callback and honor its abort signal. Evaluate the selected patch independently and keep final feedback out of the search loop.
39
124
 
40
- See [the requirements](REQUIREMENTS.zh.md).
125
+ See the [中文需求和配置提示](REQUIREMENTS.zh.md).
@@ -1,11 +1,19 @@
1
- # AutoResearch 需求
1
+ # AutoResearch 需求与配置提示
2
2
 
3
- 用户配置目标、可信评测和总预算后,团队自动研究、评测、选择候选并收尾。单次命令显示运行阶段和清理结果。Trace 提供认领方向、候选、train 反馈、消息、复核和回执,可在运行中查看,结束后回放。SDK 和 RPC 客户端可以向成员发送建议、中断当前轮次或停止成员。
3
+ 用户选择 backend、模型、人数和预算后,同一份配置用于预检、准备和运行。成员平级,各自在独立 Sandbox 研究,可以分享候选、完整读取并互评。官方 train 反馈可用于搜索,final 只进入宿主结果。
4
4
 
5
- FrontierCS-2 demo 固定 `7e48965c7cef2a567c2669c8e2f10b06386289c9` 的 `binary_fuse_filter` 和该版本的 Pumpkin。团队至少四名平级 AnySwarm Worker,同一次 Run 使用真实 `kimi_proxy/k3`,没有统一 Lead。成员自行认领研究方向、交流和选择沿用的成果。Harness 管理资源、共享预算与可信评测。demo 的研究窗口为 12 分钟,官方 train 额度为 8 次,记录模型请求数但不限制次数。官方 train 公开反馈进入看板,final 结果只写入用户记录。
5
+ ## 首次设置
6
6
 
7
- 参照[快速上手](README.md)准备并运行。
7
+ 1. 准备 Linux x86-64 控制端、Node.js 24 LTS、Git、Git LFS、Python 3、Docker 和 Buildx。新 Debian 13 VM 请从 Docker 官方 apt 仓库安装 Docker Engine 29 和 Buildx 插件。Debian 自带的 Docker 26 即使通过镜像存储检查,Pumpkin 给新构建的镜像打标签时仍可能报 `No such image`。`docker info --format '{{ .DriverStatus }}'` 必须显示 `io.containerd.snapshotter.v1`,Pumpkin 才能按 digest 找到镜像。请在 AnySwarm setup 之前打开这个镜像存储。切换会隐藏旧存储中的容器和镜像,共享主机请先选择合适的 Docker context。其他依赖和命令见 [README](README.md#1-install-and-choose-your-backend)、[Docker 安装文档](https://docs.docker.com/engine/install/debian/) 和 [镜像存储文档](https://docs.docker.com/engine/storage/containerd/)。
8
+ 2. 先安装所选执行器。Pi 可用 `npm install -g @earendil-works/pi-coding-agent` 安装。安装 AnySwarm 后运行 `anyswarm setup --backend pi` 或 `anyswarm setup --backend codex`。已有 OpenSandbox 时使用 `--mode existing`,配置 Lifecycle 地址、鉴权、匹配的 Worker 镜像、`dns+nft` 和可达的回调。用 `anyswarm doctor --smoke` 检查连接及 Worker。
9
+ 3. `anyswarm eject autoresearch --dir ./research-demo`,进入导出目录执行 `npm install`。编辑 `frontiercs2-config.ts`。模板所需的模型设置是 `ANYSWARM_MODEL_PROVIDER`、`ANYSWARM_MODEL_ID` 和请求 URL `ANYSWARM_MODEL_URL`。路由需要凭证时设置 `ANYSWARM_MODEL_TOKEN`。Pi 的 Chat Completions 路由需要另设 `ANYSWARM_MODEL_PROTOCOL=chat-completions`。也可直接传入普通 `ModelConfig`,并按模型目录填写推理与工具能力。
10
+ 4. `npm exec -- anyswarm run ./prepare-demo.ts --config ./frontiercs2-config.ts --check`。先处理 `ACTION` 行,再去掉 `--check` 准备固定材料。首次准备执行独立的官方无模型 reference。重复准备复用已验证材料和镜像。四 Peer、GPT-6.1 Sol、60 分钟是本机验收配置,导出的模板由用户选择模型和预算。
11
+ 5. `npm exec -- anyswarm run ./project.ts --config ./frontiercs2-config.ts --prompt '运行 FrontierCS-2 任务' --output-dir ./runs`。模板默认 2 Peer、12 分钟、4 次 train 和 128 次团队新模型请求。修改 `budget` 会同时影响准备计划和实际运行。完整命令、资源表和自定义评测入口见 [README](README.md)。
8
12
 
9
- 验收从候选包开始。独立 reference 完成无模型 train/final。实际 demo 从干净 starter 开始,保存四路真实 K3 活动重叠的证据、至少一次可关联到具体候选的同行复核或采用,以及 Worker 候选、官方 train、最终保存、final 和资源回收的关联记录。记录全队的资源、模型用量与费用。未知回执和待清理资源保留可核对的标识。官方零分作为求解结果记录。
13
+ ## 结果与验收
10
14
 
11
- 研究范围以 [#337](https://github.com/AnySwarm/anyswarm/issues/337) 和随后确认的四成员、Agensh 式扁平协作、实时 Trace 为准。宿主入口遵循 [#351](https://github.com/AnySwarm/anyswarm/issues/351)。
15
+ 固定使用 FrontierCS-2 `7e48965c7cef2a567c2669c8e2f10b06386289c9` 的 `binary_fuse_filter` 和原有 Pumpkin 评测。Worker 只获得干净 starter 和公开 train 反馈。应用侧 train 上限、官方 grant 和团队模型预算分别记录。
16
+
17
+ 在运行中或结束后执行 `npm exec -- anyswarm trace --root ./runs`。用候选 ID 或 patch SHA-256 找到同一次 Run 的候选、完整读取、具体 review、train 回执、最终选择和 final。若声称采用另一 Peer 的贡献,用实际 patch 差异核实改动。按 Model 泳道中的请求区间核对真实并行。合法低分、无效候选、终验未达业务目标和未确认结果独立记录。清理保留 Runtime 和评测器各自的状态与待核对资源。
18
+
19
+ 验收从仓库外固定候选包开始。记录任务版本、候选包及 hash、真实 backend 和模型、用量、耗时、候选关系和两类清理。正式评测以 Pumpkin 原始回执为准。应用范围见 [#337](https://github.com/AnySwarm/anyswarm/issues/337),宿主入口见 [#351](https://github.com/AnySwarm/anyswarm/issues/351)。
@@ -1,4 +1,4 @@
1
- import { ProjectPreflightError, resolveSandboxConnection, workerImageFor, type ExecutorSelection,
1
+ import { ProjectPreflightError, resolveSandboxConnection, workerImageFor, type ExecutorSelection, type HarnessContext,
2
2
  type ModelConfig, type RuntimeConnectionOptions, type SandboxConfig } from '@anyswarm/core';
3
3
  import { homedir } from 'node:os';
4
4
  import { join, resolve } from 'node:path';
@@ -14,6 +14,7 @@ export interface ResearchBudget {
14
14
  export interface ResearchConfiguration {
15
15
  targetPath?: string;
16
16
  requiredFiles?: readonly string[];
17
+ validateStarter?(initial: HarnessContext['initial']): Promise<void>;
17
18
  goal: string;
18
19
  direction: 'max' | 'min';
19
20
  targetScore?: number;
@@ -27,14 +28,18 @@ export interface ResearchConfiguration {
27
28
  evaluationTimeoutMs?: number;
28
29
  closeTimeoutMs?: number;
29
30
  restrictNetwork?: boolean;
31
+ continueAfterTrainBudget?: boolean;
30
32
  }
31
33
 
32
34
  export const demoBudget: Readonly<ResearchBudget> = Object.freeze({
33
35
  workers: 4, workMs: 720_000, maxEvaluations: 8,
34
36
  });
35
- export function frontierBudget(saved: ResearchBudget = demoBudget): ResearchBudget {
36
- const { workers, workMs, maxEvaluations } = saved;
37
- return checkBudget({ workers, workMs, maxEvaluations }, 4);
37
+ export const smallBudget: Readonly<ResearchBudget> = Object.freeze({
38
+ workers: 2, workMs: 720_000, maxEvaluations: 4, maxModelRequests: 128,
39
+ });
40
+
41
+ export function frontierBudget(budget: ResearchBudget = demoBudget): ResearchBudget {
42
+ return checkBudget(budget, 2);
38
43
  }
39
44
  export const demoGoal = 'Solve the official FrontierCS-2 binary_fuse_filter task described in README.md. The 8-bit and 16-bit population routines in include/binaryfusefilter.h are stubs. Implement both routines and send a complete first patch to public train promptly. If a local C compiler is unavailable, use train for compile and correctness feedback. Then explore memory, construction or lookup performance. Change only include/, coordinate directly and review peers’ patches against the official public train feedback.';
40
45
  export const demoCloseTimeoutMs = 365_000;
@@ -44,36 +49,70 @@ export function frontierHome() {
44
49
  join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'anyswarm', 'autoresearch', 'frontiercs2'));
45
50
  }
46
51
 
47
- export function defaultResearchConnection() {
48
- const saved = resolveSandboxConnection({}, 'AUTORESEARCH');
52
+ type ResearchConnection = Pick<ResearchConfiguration, 'executor' | 'image' | 'sandbox' | 'connection'>;
53
+
54
+ export function defaultResearchConnection(options: Partial<ResearchConnection> = {}) {
55
+ const { sandbox, connection } = options;
56
+ const saved = resolveSandboxConnection({
57
+ ...sandbox, publicUrl: connection?.publicUrl, advertiseHost: connection?.advertiseHost, image: options.image,
58
+ }, 'AUTORESEARCH', { includePreparedImage: true });
59
+ const executor = options.executor ?? saved.executor ?? 'pi';
60
+ const kind = typeof executor === 'string' ? executor : executor.kind;
49
61
  return {
50
- executor: saved.executor ?? 'pi',
51
- image: saved.image ?? workerImageFor(saved.executor ?? 'pi'),
62
+ executor,
63
+ image: saved.image ?? workerImageFor(executor),
64
+ // Setup records the immutable image separately from the Runtime's local Worker selector.
65
+ preparedWorker: saved.image === undefined && saved.executor === kind ? saved.preparedImage : undefined,
52
66
  sandbox: {
67
+ ...sandbox, endpoint: undefined,
53
68
  lifecycleBaseUrl: saved.lifecycleBaseUrl, apiKey: saved.apiKey,
54
69
  useServerProxy: saved.useServerProxy, egressMode: saved.egressMode,
55
- resourceLimits: { cpu: '2', memory: '4Gi' },
70
+ resourceLimits: sandbox?.resourceLimits ?? { cpu: '2', memory: '4Gi' },
56
71
  },
57
- connection: { publicUrl: saved.publicUrl, advertiseHost: saved.advertiseHost },
58
- } satisfies Pick<ResearchConfiguration, 'executor' | 'image' | 'sandbox' | 'connection'>;
72
+ connection: { ...connection, publicUrl: saved.publicUrl, advertiseHost: saved.advertiseHost },
73
+ } satisfies ResearchConnection & { preparedWorker?: string };
74
+ }
75
+
76
+ export function modelFromEnvironment(env = process.env): ModelConfig {
77
+ const protocol = env.ANYSWARM_MODEL_PROTOCOL as ModelConfig['protocol'];
78
+ const token = env.ANYSWARM_MODEL_TOKEN;
79
+ return {
80
+ provider: env.ANYSWARM_MODEL_PROVIDER ?? '',
81
+ model: env.ANYSWARM_MODEL_ID ?? '',
82
+ protocol,
83
+ upstream: { url: env.ANYSWARM_MODEL_URL ?? '', headers: token ? { authorization: `Bearer ${token}` } : {} },
84
+ };
59
85
  }
60
86
 
61
- export function kimiModel(): ModelConfig {
62
- const url = process.env.ANYSWARM_MODEL_URL;
63
- if (!url) throw new ProjectPreflightError('AUTORESEARCH_MODEL_REQUIRED', 'Set ANYSWARM_MODEL_URL for the Kimi K3 route and ANYSWARM_MODEL_TOKEN if required by your proxy.');
64
- const provider = process.env.ANYSWARM_MODEL_PROVIDER ?? 'kimi_proxy';
65
- const model = process.env.ANYSWARM_MODEL_ID ?? 'k3';
66
- if (provider !== 'kimi_proxy' || model !== 'k3') {
67
- throw new ProjectPreflightError('AUTORESEARCH_K3_REQUIRED', 'Select the kimi_proxy/k3 model for the FrontierCS-2 demo.');
87
+ export function modelConfigurationError(model: ModelConfig | undefined, executor?: ExecutorSelection) {
88
+ if (!model?.provider?.trim() || !model.model?.trim() || !model.upstream?.url || !model.upstream.headers) {
89
+ return 'Set model.provider, model.model and model.upstream in the shared configuration, or set ANYSWARM_MODEL_PROVIDER, ANYSWARM_MODEL_ID and ANYSWARM_MODEL_URL. Set ANYSWARM_MODEL_TOKEN if your endpoint requires a token.';
90
+ }
91
+ const url = URL.canParse(model.upstream.url) ? new URL(model.upstream.url) : undefined;
92
+ if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
93
+ return 'Use a full HTTP(S) request URL in model.upstream.url. Put credentials in protected headers instead of the URL.';
94
+ }
95
+ const protocol = typeof model.protocol === 'object' ? model.protocol.clientProtocol : model.protocol ?? 'responses';
96
+ const backend = typeof executor === 'object' ? executor.kind : executor;
97
+ if ((!protocol && typeof model.protocol !== 'object') || (backend === 'codex' && protocol !== 'responses') ||
98
+ (backend === 'pi' && protocol !== 'responses' && protocol !== 'chat-completions')) {
99
+ return 'Select a model protocol supported by your backend. Codex uses Responses. Pi supports Responses and Chat Completions.';
100
+ }
101
+ const suffix = protocol === 'chat-completions' ? '/v1/chat/completions' : '/v1/responses';
102
+ if (typeof model.protocol === 'object' ? model.protocol.validateUpstream(url) !== true : !url.pathname.endsWith(suffix)) {
103
+ return `Set the full model request URL for the selected protocol, ending in ${suffix} for the built-in transport.`;
104
+ }
105
+ if (model.provider === 'kimi_proxy' && model.model === 'k3' && protocol !== 'responses') {
106
+ return 'The kimi_proxy/k3 configuration requires a fixed /v1/responses URL without a query string.';
68
107
  }
69
- const endpoint = URL.canParse(url) ? new URL(url) : undefined;
70
- if (!endpoint || !['http:', 'https:'].includes(endpoint.protocol) || endpoint.username || endpoint.password ||
71
- endpoint.search || endpoint.hash || !endpoint.pathname.endsWith('/v1/responses')) {
72
- throw new ProjectPreflightError('AUTORESEARCH_MODEL_URL_INVALID',
73
- 'Set ANYSWARM_MODEL_URL to a fixed HTTP(S) /v1/responses endpoint without credentials, query or fragment.');
108
+ if (model.capabilities?.tools === false) return 'Select a tool-capable model so peers can work on files and use the research Service.';
109
+ if (model.capabilities && (!Number.isSafeInteger(model.capabilities.contextWindow) ||
110
+ model.capabilities.contextWindow < 16 || !Number.isSafeInteger(model.capabilities.maxOutputTokens) ||
111
+ model.capabilities.maxOutputTokens < 16 || model.capabilities.maxOutputTokens > model.capabilities.contextWindow ||
112
+ typeof model.capabilities.reasoning !== 'boolean' || model.capabilities.tools !== true)) {
113
+ return 'Set capabilities from your provider catalog: contextWindow, maxOutputTokens, tools: true and reasoning.';
74
114
  }
75
- const token = process.env.ANYSWARM_MODEL_TOKEN;
76
- return { provider, model, upstream: { url: endpoint.href, headers: token ? { authorization: `Bearer ${token}` } : {} } };
115
+ return undefined;
77
116
  }
78
117
 
79
118
  export function checkBudget(budget: ResearchBudget, minimum = 1): ResearchBudget {
@@ -1,8 +1,12 @@
1
1
  import type { JsonValue } from '@anyswarm/core';
2
- import { join } from 'node:path';
3
- import { defaultResearchConnection, demoCloseTimeoutMs, demoGoal, kimiModel, type ResearchConfiguration } from './config.js';
4
- import { FrontierRun, frontierFinalTimeMs, frontierSubmission, judgeTimeMs } from './frontiercs2.js';
5
- import { loadPrepared, resourcePlan } from './prepare.js';
2
+ import type { FinalEvaluation } from './research-service.js';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { join, resolve } from 'node:path';
5
+ import { ProjectPreflightError } from '@anyswarm/core';
6
+ import { defaultResearchConnection, demoCloseTimeoutMs, demoGoal, frontierBudget, frontierHome, modelConfigurationError, modelFromEnvironment, type ResearchConfiguration } from './config.js';
7
+ import { command, requireSuccess } from './process.js';
8
+ import { digest, FrontierRun, frontierFinalTimeMs, frontierSubmission, judgeTimeMs } from './frontiercs2.js';
9
+ import { loadPrepared, resourcePlan, starterPath } from './prepare.js';
6
10
 
7
11
  export function frontierTrainEvaluation(returned: Record<string, unknown>) {
8
12
  const observed = returned.raw_score;
@@ -16,40 +20,89 @@ export function frontierTrainEvaluation(returned: Record<string, unknown>) {
16
20
  };
17
21
  }
18
22
 
19
- export async function frontierDemo() {
20
- const ready = await loadPrepared().catch(() => { throw new Error('Prepare the pinned demo first with anyswarm run ./prepare-demo.ts.'); });
21
- const { budget, paths, saved, starter } = ready;
22
- const defaults = defaultResearchConnection();
23
- const model = kimiModel();
23
+ export function frontierFinalEvaluation(result: Awaited<ReturnType<FrontierRun['finish']>>, targetScore?: number): FinalEvaluation {
24
+ const values = new Map(result.verdict.result?.values?.map(({ name, value }) => [name, value]));
25
+ const reportedScore = values.get('score');
26
+ const score = typeof reportedScore === 'number' && Number.isFinite(reportedScore) ? reportedScore : null;
27
+ const reportedSummary = values.get('summary');
28
+ const summary = typeof reportedSummary === 'string' ? reportedSummary : null;
29
+ const beatsReference = values.get('beats_reference');
30
+ const evidence = { record: result.record, payload: result.submission.payload, summary,
31
+ beatsReference: beatsReference === 1 ? true : beatsReference === 0 ? false : null };
32
+ if (summary?.startsWith('invalid candidate:')) return { status: 'rejected', score, meetsObjective: false, evidence };
33
+ if (score === null || !(summary === 'strict PASS' || summary?.startsWith('valid;'))) {
34
+ return { status: 'unknown', score: null, meetsObjective: null, evidence };
35
+ }
36
+ return { status: 'valid', score, meetsObjective: targetScore === undefined ? null : score >= targetScore, evidence };
37
+ }
38
+
39
+ export interface FrontierConfiguration extends ResearchConfiguration {
40
+ frontierStateDir: string;
41
+ preparedWorker?: string;
42
+ }
43
+
44
+ type FrontierOptions = Partial<Pick<ResearchConfiguration,
45
+ 'budget' | 'model' | 'goal' | 'executor' | 'image' | 'sandbox' | 'connection' | 'continueAfterTrainBudget' | 'targetScore'>> &
46
+ { home?: string };
47
+
48
+ export function frontierDemo(options: FrontierOptions = {}): FrontierConfiguration {
49
+ const { home: stateDir = frontierHome(), executor, image, sandbox: worker, connection, ...settings } = options;
50
+ const home = resolve(stateDir);
51
+ const defaults = defaultResearchConnection({ executor, image, sandbox: worker, connection });
52
+ const budget = frontierBudget(settings.budget);
53
+ const model = settings.model ?? modelFromEnvironment();
54
+ const { sandbox } = defaults;
55
+ // The official bridge starts before the Workers. Budget startup, one active
56
+ // judge at the stop boundary, final and cleanup independently of research.
57
+ const setupSeconds = 360;
58
+ const settleSeconds = Math.ceil((judgeTimeMs + frontierFinalTimeMs + demoCloseTimeoutMs) / 1000);
59
+ const lifetimeSeconds = setupSeconds + Math.ceil(budget.workMs / 1000) + settleSeconds;
24
60
  let frontier: FrontierRun | undefined;
25
- const configuration: ResearchConfiguration = {
26
- ...defaults, model, restrictNetwork: true, goal: demoGoal, direction: 'max', budget,
27
- sandbox: { ...defaults.sandbox, timeoutSeconds: Math.ceil((budget.workMs + demoCloseTimeoutMs) / 1000) + 60 },
28
- targetPath: starter,
61
+ let ready: Awaited<ReturnType<typeof loadPrepared>> | undefined;
62
+ return {
63
+ ...defaults, ...settings, model, restrictNetwork: true, goal: settings.goal ?? demoGoal, direction: 'max', budget,
64
+ sandbox: { ...sandbox, timeoutSeconds: sandbox.timeoutSeconds ?? lifetimeSeconds },
65
+ frontierStateDir: home,
66
+ targetPath: starterPath(home),
29
67
  requiredFiles: ['README.md', 'include/binaryfusefilter.h'],
68
+ async validateStarter(initial) {
69
+ ready = await loadPrepared(home);
70
+ const tracked = requireSuccess(await command('git', ['ls-files', '-z', '--', '.'],
71
+ { cwd: ready.starter, timeoutMs: 5000 }), 'Read tracked FrontierCS-2 starter files').split('\0').filter(Boolean);
72
+ const captured = new Map(initial.manifest.map(file => [file.path, file.sha256]));
73
+ const expected = await Promise.all(tracked.map(async file => [file, digest(await readFile(join(ready!.starter, file)))] as const));
74
+ if (captured.size !== expected.length || expected.some(([path, hash]) => captured.get(path) !== hash)) {
75
+ throw new ProjectPreflightError('AUTORESEARCH_STARTER_CHANGED', 'Use the prepared, unchanged FrontierCS-2 starter. Remove --cwd when running the FrontierCS-2 configuration.');
76
+ }
77
+ },
30
78
  evaluationTimeoutMs: judgeTimeMs + 25_000,
31
79
  closeTimeoutMs: demoCloseTimeoutMs,
32
80
  evaluator: {
33
81
  async start(directory, signal) {
34
- frontier = new FrontierRun(paths, join(directory, 'pumpkin'));
35
- await frontier.start(Math.ceil((budget.workMs + frontierFinalTimeMs) / 1000), signal);
36
- if (frontier.imageId !== saved.bridgeImage || JSON.stringify(frontier.judges) !== JSON.stringify(saved.judges)) {
37
- throw new Error('Pumpkin image identity changed after preparation');
82
+ const problem = modelConfigurationError(model, defaults.executor);
83
+ if (problem) throw new ProjectPreflightError('AUTORESEARCH_MODEL_REQUIRED', problem);
84
+ ready ??= await loadPrepared(home);
85
+ frontier = new FrontierRun(ready.paths, join(directory, 'pumpkin'));
86
+ await frontier.start(lifetimeSeconds, signal, undefined, budget.maxEvaluations);
87
+ if (frontier.imageId !== ready.saved.bridgeImage || JSON.stringify(frontier.judges) !== JSON.stringify(ready.saved.judges)) {
88
+ throw new Error('Pumpkin image identity changed after preparation. Run prepare again.');
38
89
  }
39
90
  },
40
91
  async train(patch, signal, admitted) {
41
92
  const receipt = await frontier!.train(frontierSubmission(patch), signal, admitted);
42
- return frontierTrainEvaluation(receipt.returned);
93
+ return { ...frontierTrainEvaluation(receipt.returned), payload: receipt.payload };
43
94
  },
44
95
  async final(patch, signal) {
45
- return await frontier!.finish(frontierSubmission(patch), signal) as unknown as JsonValue;
96
+ return frontierFinalEvaluation(await frontier!.finish(frontierSubmission(patch), signal), settings.targetScore);
46
97
  },
47
98
  async close() { return frontier ? await frontier.close() : 'complete'; },
48
99
  evidence() {
49
- return { reference: saved.referenceRecord, record: frontier?.record ?? null, bridgeImage: frontier?.imageId ?? null, judges: frontier?.judges ?? null,
50
- benchmark: saved.revision, pumpkin: saved.pumpkin, resources: resourcePlan(budget) };
100
+ return {
101
+ reference: ready?.saved.referenceRecord ?? null, record: frontier?.record ?? null, bridgeImage: frontier?.imageId ?? null,
102
+ judges: frontier?.judges ?? null, grants: frontier?.grants ?? null, cleanup: frontier?.cleanupEvidence ?? null,
103
+ benchmark: ready?.saved.revision ?? null, pumpkin: ready?.saved.pumpkin ?? null, resources: resourcePlan(budget, sandbox),
104
+ };
51
105
  },
52
106
  },
53
107
  };
54
- return { configuration, starter };
55
108
  }
@@ -1,4 +1,15 @@
1
1
  import { frontierDemo } from './demo.js';
2
+ import { modelFromEnvironment, smallBudget } from './config.js';
2
3
 
3
- const { configuration } = await frontierDemo();
4
- export default configuration;
4
+ export default frontierDemo({
5
+ // Run anyswarm setup to choose an executor and Worker, or set executor, image,
6
+ // sandbox and connection here for an existing OpenSandbox deployment.
7
+ // Set ANYSWARM_MODEL_PROVIDER, ANYSWARM_MODEL_ID and ANYSWARM_MODEL_URL.
8
+ // Optional: ANYSWARM_MODEL_PROTOCOL (responses by default) and ANYSWARM_MODEL_TOKEN.
9
+ // You can replace this model with your own ModelConfig, including capabilities
10
+ // from your provider catalog for a reasoning model. Keep tokens in the environment.
11
+ model: modelFromEnvironment(),
12
+ budget: { ...smallBudget },
13
+ // For timed runs, set continueAfterTrainBudget: true to keep reviewing and
14
+ // testing locally after the last train admission, within the model budget.
15
+ });
@@ -1,5 +1,6 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { mkdir, open, readFile, readdir, writeFile } from 'node:fs/promises';
3
4
  import { join } from 'node:path';
4
5
  import { setTimeout as delay } from 'node:timers/promises';
5
6
  import { command, requireSuccess } from './process.js';
@@ -8,9 +9,28 @@ export const frontierRevision = '7e48965c7cef2a567c2669c8e2f10b06386289c9';
8
9
  export const pumpkinPin = '2026-11-30 ca3ce7ae0da5616464b00ee7962aecac0fc0b38d a1bb9c633f1f700ea42bceb9cd9512f684e9063d3a8ae6c9485526a1dd68016f';
9
10
  export const frontierTask = 'tasks/binary_fuse_filter/task.star';
10
11
  export const submissionLimit = 1024 * 1024;
12
+ const officialJudgeSeconds = 180;
13
+ const grantCallTimeoutSeconds = 181;
11
14
  export const judgeTimeMs = 190_000;
12
15
  export const frontierFinalTimeMs = 250_000;
13
16
 
17
+ export async function preparePumpkin(source: string, cache: string, signal: AbortSignal) {
18
+ await mkdir(cache, { recursive: true, mode: 0o700 });
19
+ // The pinned launcher extracts with the caller's umask. Only the bootstrap
20
+ // needs 022; prepare and the official evaluation keep the operator's umask.
21
+ requireSuccess(await command('/bin/sh', ['-c', 'umask 022; exec ./pumpkin --version'], {
22
+ cwd: source, env: { ...process.env, XDG_CACHE_HOME: cache }, timeoutMs: 240_000, signal,
23
+ }), 'Initialize pinned Pumpkin tools');
24
+ // Repair a cache populated by an earlier prepare under a restrictive umask.
25
+ const checksum = pumpkinPin.split(' ')[2];
26
+ const binary = await open(join(cache, 'pumpkin', checksum, 'bin', 'sandboxd'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
27
+ try {
28
+ const info = await binary.stat();
29
+ if (!info.isFile()) throw new Error('The pinned Pumpkin sandboxd is not a regular file');
30
+ if ((info.mode & 0o111) !== 0o111) await binary.chmod((info.mode & 0o777) | 0o111);
31
+ } finally { await binary.close(); }
32
+ }
33
+
14
34
  export function digest(bytes: Uint8Array | string): string {
15
35
  return createHash('sha256').update(bytes).digest('hex');
16
36
  }
@@ -110,6 +130,9 @@ export class FrontierRun {
110
130
  container?: string;
111
131
  imageId?: string;
112
132
  judges?: JudgeImages;
133
+ grants?: { trainCalls: number; trainCumulativeSeconds: number; judgeSeconds: number; callTimeoutSeconds: number; maxBytes: number };
134
+ cleanupEvidence: { status: 'complete' | 'pending'; runIds: string[]; pendingContainers: string[] } =
135
+ { status: 'pending', runIds: [], pendingContainers: [] };
113
136
  private closed = false;
114
137
 
115
138
  constructor(readonly paths: FrontierPaths, readonly runs: string) {}
@@ -124,7 +147,7 @@ export class FrontierRun {
124
147
 
125
148
  get record() { return this.id ? join(this.runs, this.id) : undefined; }
126
149
 
127
- async start(seconds: number, signal: AbortSignal, timeoutMs = 360_000): Promise<void> {
150
+ async start(seconds: number, signal: AbortSignal, timeoutMs = 360_000, maxEvaluations = 1): Promise<void> {
128
151
  await mkdir(this.runs, { recursive: true, mode: 0o700 });
129
152
  const start = await this.pumpkin(['run', frontierTask, '--arg', 'agent=anyswarm', '--arg', `deadline_seconds=${seconds}`,
130
153
  '--config', this.paths.config, '--runs', this.runs], timeoutMs, signal);
@@ -147,11 +170,14 @@ export class FrontierRun {
147
170
  const role = ir.roles?.find((role: { name: string }) => role.name === 'agent');
148
171
  const grantTrain = role?.runtime?.agent?.grants?.find((grant: { name: string }) => grant.name === 'train');
149
172
  const grantFinal = role?.runtime?.agent?.grants?.find((grant: { name: string }) => grant.name === 'final');
150
- if (grantTrain?.job?.target !== 'train_judge' || !(grantTrain.job.calls >= 8) ||
173
+ if (grantTrain?.job?.target !== 'train_judge' || !(grantTrain.job.calls >= maxEvaluations) ||
174
+ grantTrain.job.cumulative_seconds !== 12_000 || grantTrain.job.call_timeout_seconds !== grantCallTimeoutSeconds ||
151
175
  grantTrain.job.payload_max_bytes !== submissionLimit || grantFinal?.now?.payload_max_bytes !== submissionLimit ||
152
176
  grantFinal.now.body?.arguments?.finalize?.type !== 'bool' || ir.final?.target !== undefined && ir.final.target !== 'final_judge') {
153
- throw new Error('The Pumpkin role does not have the pinned train and final grants');
177
+ throw new Error('The Pumpkin role does not authorize the requested train budget or the pinned judge limits');
154
178
  }
179
+ this.grants = { trainCalls: grantTrain.job.calls, trainCumulativeSeconds: grantTrain.job.cumulative_seconds,
180
+ judgeSeconds: officialJudgeSeconds, callTimeoutSeconds: grantTrain.job.call_timeout_seconds, maxBytes: grantTrain.job.payload_max_bytes };
155
181
  const grants = await this.docker(['exec', this.container, '/bin/sh', '-eu', '-c',
156
182
  'test -w /pumpkin; exec /.pumpkin/bin/sandboxctl ops'], 5_000, started);
157
183
  const ops = JSON.parse(requireSuccess(grants, 'Check official Pumpkin grants and submission scratch space'));
@@ -180,7 +206,26 @@ export class FrontierRun {
180
206
  const reply = await this.docker(['exec', this.container!, '/.pumpkin/bin/sandboxctl', 'status', String(job)], 5_000, deadline);
181
207
  const state = JSON.parse(reply.stdout) as PumpkinReply;
182
208
  if (state.kind !== 'status' || state.job !== job) throw new Error('Official train status is unknown');
183
- if (state.state === 'completed' && state.returned) return { job, returned: state.returned };
209
+ if (state.state === 'completed' && state.returned) {
210
+ const payload = { digest: `sha256:${digest(bytes)}`, size: bytes.byteLength };
211
+ // A score can be available while Pumpkin is still releasing the job's
212
+ // sandbox. The next admission is safe only after the recorded teardown.
213
+ while (true) {
214
+ const log = await readFile(join(this.record!, 'log.jsonl'), { encoding: 'utf8', signal: deadline });
215
+ const lines = log.split('\n');
216
+ lines.pop(); // The last line may still be in flight.
217
+ const entries = lines.map(line => JSON.parse(line));
218
+ const action = entries.flatMap(entry => entry.actions ?? [])
219
+ .find(entry => entry.kind === 'start_call' && entry.grant === 'train' && entry.job === job);
220
+ if (action?.payload?.digest !== payload.digest || action.payload.size !== payload.size) {
221
+ throw new Error('Official train result does not match the submitted payload');
222
+ }
223
+ if (entries.some(({ event }) => event?.kind === 'call_torn_down' && event.job === job)) {
224
+ return { job, returned: state.returned, payload };
225
+ }
226
+ await delay(250, undefined, { signal: deadline });
227
+ }
228
+ }
184
229
  if (state.state === 'errored') throw new Error(`Official train job ${job} failed`);
185
230
  if (state.state !== 'queued' && state.state !== 'running') throw new Error(`Official train job ${job} has an unknown status`);
186
231
  await delay(750, undefined, { signal: deadline });
@@ -212,17 +257,25 @@ export class FrontierRun {
212
257
  }
213
258
 
214
259
  async close(): Promise<'complete' | 'pending'> {
260
+ this.cleanupEvidence = { status: 'pending', runIds: [], pendingContainers: [] };
215
261
  try {
216
- const ids = this.id ? [this.id] : (await readdir(this.runs, { withFileTypes: true }).catch(() => []))
217
- .filter(entry => entry.isDirectory() && runId.test(entry.name)).map(entry => entry.name);
262
+ const ids = this.id ? [this.id] : (await readdir(this.runs, { withFileTypes: true }).catch(error => {
263
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
264
+ throw error;
265
+ })).filter(entry => entry.isDirectory() && runId.test(entry.name)).map(entry => entry.name);
266
+ this.cleanupEvidence.runIds = ids;
267
+ let confirmed = true;
218
268
  for (const id of ids) {
219
269
  const finished = this.closed || await readFile(join(this.runs, id, 'outcome.json'), 'utf8')
220
270
  .then(raw => JSON.parse(raw).state === 'finished').catch(() => false);
221
- if (!finished) await this.pumpkin(['cancel', '--runs', this.runs, id], 20_000).catch(() => {});
222
- const remaining = await this.docker(['container', 'ls', '-a', '--filter', `label=pumpkin.run=${id}`, '--format', '{{.ID}}'], 5_000);
223
- if (remaining.code !== 0 || remaining.stdout.trim()) return 'pending';
271
+ const cancelled = finished || (await this.pumpkin(['cancel', '--runs', this.runs, id], 20_000).catch(() => undefined))?.code === 0;
272
+ const remaining = await this.docker(['container', 'ls', '-a', '--no-trunc', '--filter', `label=pumpkin.run=${id}`, '--format', '{{.ID}}'], 5_000)
273
+ .catch(() => undefined);
274
+ if (!cancelled || remaining?.code !== 0) confirmed = false;
275
+ if (remaining?.code === 0) this.cleanupEvidence.pendingContainers.push(...remaining.stdout.trim().split('\n').filter(Boolean));
224
276
  }
225
- return 'complete';
277
+ if (confirmed && !this.cleanupEvidence.pendingContainers.length) this.cleanupEvidence.status = 'complete';
278
+ return this.cleanupEvidence.status;
226
279
  } catch { return 'pending'; }
227
280
  }
228
281
  }