@anyswarm/core 0.5.0 → 0.5.1

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 (398) hide show
  1. package/README.md +11 -10
  2. package/deploy/worker/Dockerfile +12 -4
  3. package/dist/deploy/worker/Dockerfile +12 -4
  4. package/dist/examples/README.md +24 -12
  5. package/dist/examples/authoring/README.md +24 -0
  6. package/dist/examples/authoring/business.d.ts +2 -0
  7. package/dist/examples/authoring/business.js +4 -0
  8. package/dist/examples/authoring/config.d.ts +5 -0
  9. package/dist/examples/authoring/config.js +2 -0
  10. package/dist/examples/authoring/eject.json +5 -0
  11. package/dist/examples/authoring/harness.d.ts +4 -0
  12. package/dist/examples/authoring/harness.js +19 -0
  13. package/dist/examples/autoresearch/README.md +33 -0
  14. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +18 -0
  15. package/dist/examples/autoresearch/config.d.ts +51 -0
  16. package/dist/examples/autoresearch/config.js +57 -0
  17. package/dist/examples/autoresearch/demo.d.ts +11 -0
  18. package/dist/examples/autoresearch/demo.js +52 -0
  19. package/dist/examples/autoresearch/eject.json +15 -0
  20. package/dist/examples/autoresearch/frontiercs2.d.ts +87 -0
  21. package/dist/examples/autoresearch/frontiercs2.js +211 -0
  22. package/dist/examples/autoresearch/prepare.d.ts +95 -0
  23. package/dist/examples/autoresearch/prepare.js +257 -0
  24. package/dist/examples/autoresearch/process.d.ts +13 -0
  25. package/dist/examples/autoresearch/process.js +48 -0
  26. package/dist/examples/autoresearch/project.d.ts +115 -0
  27. package/dist/examples/autoresearch/project.js +410 -0
  28. package/dist/examples/autoresearch/research-service.d.ts +106 -0
  29. package/dist/examples/autoresearch/research-service.js +255 -0
  30. package/dist/examples/code/README.md +25 -0
  31. package/dist/examples/code/REQUIREMENTS.zh.md +11 -0
  32. package/dist/examples/code/candidate.d.ts +19 -0
  33. package/dist/examples/code/candidate.js +80 -0
  34. package/dist/examples/code/config.d.ts +32 -0
  35. package/dist/examples/code/config.js +18 -0
  36. package/dist/examples/code/eject.json +5 -0
  37. package/dist/examples/code/project.d.ts +3 -0
  38. package/dist/examples/code/project.js +605 -0
  39. package/dist/examples/code/prompts.d.ts +5 -0
  40. package/dist/examples/code/prompts.js +12 -0
  41. package/dist/examples/code/verification.d.ts +19 -0
  42. package/dist/examples/code/verification.js +268 -0
  43. package/dist/examples/code/worktree.d.ts +17 -0
  44. package/dist/examples/code/worktree.js +233 -0
  45. package/dist/examples/harness-session/README.md +3 -6
  46. package/dist/examples/lead-worker/harness/dynamic-scheduler.d.ts +2 -1
  47. package/dist/examples/lead-worker/harness/dynamic-scheduler.js +5 -2
  48. package/dist/examples/lead-worker/harness/index.d.ts +60 -0
  49. package/dist/examples/lead-worker/harness/index.js +77 -6
  50. package/dist/examples/lead-worker/project.js +2 -2
  51. package/dist/examples/lead-worker/services/board.d.ts +5 -0
  52. package/dist/examples/lead-worker/services/board.js +19 -1
  53. package/dist/examples/messages/README.md +5 -5
  54. package/dist/examples/messages/handoff.d.ts +2 -0
  55. package/dist/examples/messages/handoff.js +5 -1
  56. package/dist/examples/messages/project.js +52 -2
  57. package/dist/examples/notes/README.md +13 -18
  58. package/dist/examples/notes/project.js +67 -6
  59. package/dist/examples/peermesh/harness/router.js +3 -1
  60. package/dist/examples/peermesh/harness/team.d.ts +8 -0
  61. package/dist/examples/peermesh/harness/team.js +13 -0
  62. package/dist/examples/peermesh/project.js +22 -4
  63. package/dist/examples/services/agent-control/README.md +3 -3
  64. package/dist/examples/services/mathlib-search/Dockerfile +4 -2
  65. package/dist/examples/services/mathlib-search/README.md +1 -1
  66. package/dist/examples/services/mcp-managed/README.md +2 -2
  67. package/dist/examples/services/persistent-board/README.md +13 -3
  68. package/dist/examples/services/persistent-board/business.d.ts +7 -0
  69. package/dist/examples/services/persistent-board/business.js +7 -0
  70. package/dist/examples/services/persistent-board/index.js +10 -0
  71. package/dist/examples/services/persistent-board/live.d.ts +3 -0
  72. package/dist/examples/services/persistent-board/live.js +58 -0
  73. package/dist/examples/subagents/README.md +5 -5
  74. package/dist/examples/subagents/business.js +3 -1
  75. package/dist/examples/subagents/harness/controller.d.ts +15 -0
  76. package/dist/examples/subagents/harness/controller.js +181 -32
  77. package/dist/examples/subagents/project.d.ts +2 -0
  78. package/dist/examples/subagents/project.js +43 -34
  79. package/dist/examples/subagents/prompts/prompts.d.ts +1 -0
  80. package/dist/examples/subagents/prompts/prompts.js +3 -0
  81. package/dist/examples/subagents/services/collaboration-service.d.ts +3 -2
  82. package/dist/examples/subagents/services/collaboration-service.js +14 -2
  83. package/dist/examples/substrate/README.md +2 -2
  84. package/dist/examples/substrate/harness/index.d.ts +1 -1
  85. package/dist/examples/substrate/harness/index.js +77 -12
  86. package/dist/examples/substrate/project.js +4 -1
  87. package/dist/examples/super/README.md +40 -0
  88. package/dist/examples/super/actions.d.ts +95 -0
  89. package/dist/examples/super/actions.js +230 -0
  90. package/dist/examples/super/artifact.d.ts +4 -0
  91. package/dist/examples/super/artifact.js +51 -0
  92. package/dist/examples/super/config.d.ts +80 -0
  93. package/dist/examples/super/config.js +83 -0
  94. package/dist/examples/super/coordinator.d.ts +33 -0
  95. package/dist/examples/super/coordinator.js +151 -0
  96. package/dist/examples/super/daemon.d.ts +11 -0
  97. package/dist/examples/super/daemon.js +109 -0
  98. package/dist/examples/super/decisions.d.ts +8 -0
  99. package/dist/examples/super/decisions.js +52 -0
  100. package/dist/examples/super/eject.json +5 -0
  101. package/dist/examples/super/execution.d.ts +11 -0
  102. package/dist/examples/super/execution.js +136 -0
  103. package/dist/examples/super/github.d.ts +62 -0
  104. package/dist/examples/super/github.js +269 -0
  105. package/dist/examples/super/inbox.d.ts +162 -0
  106. package/dist/examples/super/inbox.js +284 -0
  107. package/dist/examples/super/location.d.ts +5 -0
  108. package/dist/examples/super/location.js +64 -0
  109. package/dist/examples/super/outbox.d.ts +5 -0
  110. package/dist/examples/super/outbox.js +103 -0
  111. package/dist/examples/super/project.d.ts +111 -0
  112. package/dist/examples/super/project.js +253 -0
  113. package/dist/examples/super/prompts.d.ts +3 -0
  114. package/dist/examples/super/prompts.js +25 -0
  115. package/dist/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  116. package/dist/examples/taskpool/harness/controller.d.ts +35 -6
  117. package/dist/examples/taskpool/harness/controller.js +73 -7
  118. package/dist/examples/taskpool/project.js +18 -2
  119. package/dist/scripts/anyswarm-applications.d.ts +19 -0
  120. package/dist/scripts/anyswarm-applications.js +19 -0
  121. package/dist/scripts/anyswarm-arguments.d.ts +35 -5
  122. package/dist/scripts/anyswarm-arguments.js +87 -23
  123. package/dist/scripts/anyswarm-author.d.ts +5 -0
  124. package/dist/scripts/anyswarm-author.js +24 -0
  125. package/dist/scripts/anyswarm-eject.d.ts +11 -0
  126. package/dist/scripts/anyswarm-eject.js +164 -0
  127. package/dist/scripts/anyswarm-harnesses.d.ts +2 -0
  128. package/dist/scripts/anyswarm-harnesses.js +31 -0
  129. package/dist/scripts/anyswarm-installation.js +19 -13
  130. package/dist/scripts/anyswarm-launch.d.ts +37 -0
  131. package/dist/scripts/anyswarm-launch.js +86 -0
  132. package/dist/scripts/anyswarm-project.d.ts +12 -2
  133. package/dist/scripts/anyswarm-project.js +121 -20
  134. package/dist/scripts/anyswarm-source-runner.d.ts +1 -0
  135. package/dist/scripts/anyswarm-source-runner.js +232 -0
  136. package/dist/scripts/anyswarm-tui-config.d.ts +36 -0
  137. package/dist/scripts/anyswarm-tui-config.js +189 -0
  138. package/dist/scripts/anyswarm-tui-session.d.ts +66 -0
  139. package/dist/scripts/anyswarm-tui-session.js +304 -0
  140. package/dist/scripts/anyswarm-tui-terminal.d.ts +41 -0
  141. package/dist/scripts/anyswarm-tui-terminal.js +154 -0
  142. package/dist/scripts/anyswarm-tui.d.ts +2 -0
  143. package/dist/scripts/anyswarm-tui.js +1012 -0
  144. package/dist/scripts/anyswarm.js +47 -2
  145. package/dist/scripts/build-provenance.json +1 -0
  146. package/dist/scripts/build.js +7 -1
  147. package/dist/scripts/generate-architecture-api.js +2 -0
  148. package/dist/scripts/generate-architecture-prompts.js +24 -2
  149. package/dist/scripts/local-environment.d.ts +6 -1
  150. package/dist/scripts/local-environment.js +52 -16
  151. package/dist/scripts/local-setup-smoke.js +3 -2
  152. package/dist/scripts/local-setup-worker.d.ts +1 -1
  153. package/dist/scripts/local-setup-worker.js +15 -6
  154. package/dist/scripts/local-setup.d.ts +2 -2
  155. package/dist/scripts/local-setup.js +72 -12
  156. package/dist/scripts/opensandbox-agent-worker.js +2 -2
  157. package/dist/scripts/pack-release.d.ts +1 -0
  158. package/dist/scripts/pack-release.js +63 -0
  159. package/dist/scripts/pi-session-bridge.js +11 -3
  160. package/dist/scripts/run-harness.js +3 -1
  161. package/dist/scripts/setup-bootstrap.js +43 -6
  162. package/dist/src/core/allocation-ledger.js +4 -3
  163. package/dist/src/core/host-identity.d.ts +2 -0
  164. package/dist/src/core/host-identity.js +11 -0
  165. package/dist/src/core/index.d.ts +4 -2
  166. package/dist/src/core/index.js +12 -4
  167. package/dist/src/core/mcp-service.js +2 -2
  168. package/dist/src/core/runtime-management.d.ts +6 -0
  169. package/dist/src/core/runtime-management.js +24 -0
  170. package/dist/src/core/sandbox/executor-driver.d.ts +4 -2
  171. package/dist/src/core/sandbox/executor-driver.js +12 -14
  172. package/dist/src/core/sandbox/local-executor.d.ts +13 -1
  173. package/dist/src/core/sandbox/local-executor.js +69 -19
  174. package/dist/src/core/sandbox/local-worker.js +32 -21
  175. package/dist/src/core/sandbox/opensandbox-backend.d.ts +2 -0
  176. package/dist/src/core/sandbox/opensandbox-backend.js +36 -11
  177. package/dist/src/core/sandbox/sandbox-connection.d.ts +2 -0
  178. package/dist/src/core/sandbox/sandbox-connection.js +14 -6
  179. package/dist/src/core/service-live-state.d.ts +14 -0
  180. package/dist/src/core/service-live-state.js +161 -0
  181. package/dist/src/core/service-observation-types.d.ts +21 -1
  182. package/dist/src/core/service-process.d.ts +1 -1
  183. package/dist/src/core/service-process.js +45 -4
  184. package/dist/src/core/service-types.d.ts +5 -1
  185. package/dist/src/core/services.d.ts +1 -1
  186. package/dist/src/core/services.js +8 -3
  187. package/dist/src/core/types.d.ts +3 -0
  188. package/dist/src/core/worker-image.js +3 -3
  189. package/dist/src/harness/harness-session-types.d.ts +10 -0
  190. package/dist/src/harness/harness-session.js +42 -5
  191. package/dist/src/harness/project-harness.d.ts +13 -1
  192. package/dist/src/harness/project-harness.js +36 -10
  193. package/dist/src/harness/project-input.js +81 -15
  194. package/dist/src/harness/project-rpc-client.d.ts +1 -0
  195. package/dist/src/harness/project-rpc-client.js +5 -0
  196. package/dist/src/harness/project-rpc.d.ts +8 -2
  197. package/dist/src/harness/project-rpc.js +31 -7
  198. package/dist/src/harness/project-runtime.js +3 -1
  199. package/dist/src/harness/typescript-loader.d.ts +2 -0
  200. package/dist/src/harness/typescript-loader.js +41 -0
  201. package/dist/src/trace-viewer/public/app.js +6 -5
  202. package/dist/src/trace-viewer/reader.mjs +42 -2
  203. package/docs/INDEX.md +3 -1
  204. package/docs/architecture/00-overview.md +1 -1
  205. package/docs/architecture/01-agent-core.md +1 -1
  206. package/docs/architecture/06-observability-experiments.md +1 -1
  207. package/docs/architecture/07-run-configuration.md +18 -12
  208. package/docs/architecture/08-prompts.md +22 -0
  209. package/docs/architecture/10-service-api-reference.md +53 -18
  210. package/docs/architecture/11-storage-reference.md +18 -1
  211. package/docs/architecture/12-code-coverage.md +148 -84
  212. package/docs/architecture/15-core-runtime.md +8 -0
  213. package/docs/architecture/16-pi-opensandbox-backend.md +5 -5
  214. package/docs/architecture/17-harness-reporting.md +1 -1
  215. package/docs/architecture/19-substrate-harness.md +28 -1
  216. package/docs/architecture/20-lead-worker-harness.md +34 -1
  217. package/docs/architecture/22-website.md +5 -3
  218. package/docs/architecture/23-project-harness.md +124 -5
  219. package/docs/architecture/24-runtime-recovery.md +10 -3
  220. package/docs/architecture/25-foreground-tui.md +51 -0
  221. package/docs/architecture/26-code.md +39 -0
  222. package/docs/architecture/27-personal.md +43 -0
  223. package/docs/architecture/28-autoresearch.md +31 -0
  224. package/docs/architecture/INDEX.md +4 -0
  225. package/docs/architecture/prompts/08-lead-worker-harness.md +4 -2
  226. package/docs/architecture/prompts/08-subagents-harness.md +21 -0
  227. package/docs/architecture/prompts/21-personal.md +44 -0
  228. package/docs/architecture/prompts/22-autoresearch.md +63 -0
  229. package/docs/architecture/prompts/26-code.md +55 -0
  230. package/docs/architecture/prompts/source-manifest.json +152 -33
  231. package/docs/architecture/source-map.json +489 -21
  232. package/docs/designs/core-harness/06-project-harness.md +13 -2
  233. package/docs/designs/core-harness/README.md +5 -0
  234. package/docs/en/agents.md +1 -1
  235. package/docs/en/build-your-harness.md +3 -5
  236. package/docs/en/changelog.md +13 -4
  237. package/docs/en/first-harness.md +8 -11
  238. package/docs/en/harnesses/lead-worker.md +1 -1
  239. package/docs/en/harnesses/peermesh.md +2 -2
  240. package/docs/en/harnesses/subagents.md +2 -2
  241. package/docs/en/harnesses/substrate.md +4 -4
  242. package/docs/en/harnesses/taskpool.md +2 -2
  243. package/docs/en/latest.md +12 -123
  244. package/docs/en/overview.md +1 -1
  245. package/docs/en/quickstart.md +40 -16
  246. package/docs/en/reference/api.md +14 -4
  247. package/docs/en/reference/cli.md +58 -14
  248. package/docs/en/runtime.md +2 -2
  249. package/docs/en/services.md +4 -0
  250. package/docs/third-party-notices.md +1 -0
  251. package/docs/workflows/development.md +17 -12
  252. package/docs/workflows/release-and-docs-versioning.md +76 -0
  253. package/docs/zh/agents.md +1 -1
  254. package/docs/zh/build-your-harness.md +3 -5
  255. package/docs/zh/changelog.md +13 -4
  256. package/docs/zh/first-harness.md +8 -11
  257. package/docs/zh/harnesses/lead-worker.md +1 -1
  258. package/docs/zh/harnesses/peermesh.md +2 -2
  259. package/docs/zh/harnesses/subagents.md +2 -2
  260. package/docs/zh/harnesses/substrate.md +4 -4
  261. package/docs/zh/harnesses/taskpool.md +2 -2
  262. package/docs/zh/latest.md +13 -124
  263. package/docs/zh/overview.md +1 -1
  264. package/docs/zh/quickstart.md +40 -16
  265. package/docs/zh/reference/api.md +14 -4
  266. package/docs/zh/reference/cli.md +58 -14
  267. package/docs/zh/runtime.md +2 -2
  268. package/docs/zh/services.md +4 -0
  269. package/examples/README.md +24 -12
  270. package/examples/authoring/README.md +24 -0
  271. package/examples/authoring/business.ts +4 -0
  272. package/examples/authoring/config.ts +2 -0
  273. package/examples/authoring/eject.json +5 -0
  274. package/examples/authoring/harness.ts +21 -0
  275. package/examples/autoresearch/README.md +33 -0
  276. package/examples/autoresearch/REQUIREMENTS.zh.md +18 -0
  277. package/examples/autoresearch/config.ts +90 -0
  278. package/examples/autoresearch/demo.ts +55 -0
  279. package/examples/autoresearch/eject.json +15 -0
  280. package/examples/autoresearch/frontiercs2.ts +237 -0
  281. package/examples/autoresearch/prepare.ts +267 -0
  282. package/examples/autoresearch/process.ts +50 -0
  283. package/examples/autoresearch/project.ts +397 -0
  284. package/examples/autoresearch/research-service.ts +302 -0
  285. package/examples/code/README.md +25 -0
  286. package/examples/code/REQUIREMENTS.zh.md +11 -0
  287. package/examples/code/candidate.ts +89 -0
  288. package/examples/code/config.ts +19 -0
  289. package/examples/code/eject.json +5 -0
  290. package/examples/code/project.ts +581 -0
  291. package/examples/code/prompts.ts +16 -0
  292. package/examples/code/verification.ts +239 -0
  293. package/examples/code/worktree.ts +188 -0
  294. package/examples/harness-session/README.md +3 -6
  295. package/examples/lead-worker/harness/dynamic-scheduler.ts +6 -3
  296. package/examples/lead-worker/harness/index.ts +61 -6
  297. package/examples/lead-worker/project.ts +2 -2
  298. package/examples/lead-worker/services/board.ts +14 -1
  299. package/examples/messages/README.md +5 -5
  300. package/examples/messages/handoff.ts +6 -2
  301. package/examples/messages/project.ts +47 -2
  302. package/examples/notes/README.md +13 -18
  303. package/examples/notes/project.ts +57 -9
  304. package/examples/peermesh/harness/router.ts +2 -2
  305. package/examples/peermesh/harness/team.ts +11 -0
  306. package/examples/peermesh/project.ts +19 -4
  307. package/examples/services/agent-control/README.md +3 -3
  308. package/examples/services/mathlib-search/Dockerfile +4 -2
  309. package/examples/services/mathlib-search/README.md +1 -1
  310. package/examples/services/mcp-managed/README.md +2 -2
  311. package/examples/services/persistent-board/README.md +13 -3
  312. package/examples/services/persistent-board/business.ts +10 -0
  313. package/examples/services/persistent-board/index.ts +10 -0
  314. package/examples/services/persistent-board/live.ts +54 -0
  315. package/examples/subagents/README.md +5 -5
  316. package/examples/subagents/business.ts +3 -1
  317. package/examples/subagents/harness/controller.ts +161 -29
  318. package/examples/subagents/project.ts +47 -33
  319. package/examples/subagents/prompts/prompts.ts +4 -0
  320. package/examples/subagents/services/collaboration-service.ts +14 -2
  321. package/examples/substrate/README.md +2 -2
  322. package/examples/substrate/harness/index.ts +67 -11
  323. package/examples/substrate/project.ts +5 -1
  324. package/examples/super/README.md +40 -0
  325. package/examples/super/actions.ts +196 -0
  326. package/examples/super/artifact.ts +56 -0
  327. package/examples/super/config.ts +95 -0
  328. package/examples/super/coordinator.ts +158 -0
  329. package/examples/super/daemon.ts +84 -0
  330. package/examples/super/decisions.ts +46 -0
  331. package/examples/super/eject.json +5 -0
  332. package/examples/super/execution.ts +131 -0
  333. package/examples/super/github.ts +242 -0
  334. package/examples/super/inbox.ts +306 -0
  335. package/examples/super/location.ts +54 -0
  336. package/examples/super/outbox.ts +97 -0
  337. package/examples/super/project.ts +227 -0
  338. package/examples/super/prompts.ts +27 -0
  339. package/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  340. package/examples/taskpool/harness/controller.ts +59 -7
  341. package/examples/taskpool/project.ts +18 -2
  342. package/npm-shrinkwrap.development.json +2199 -0
  343. package/npm-shrinkwrap.json +86 -1920
  344. package/package.development.json +92 -0
  345. package/package.json +13 -7
  346. package/scripts/anyswarm-applications.ts +39 -0
  347. package/scripts/anyswarm-arguments.ts +94 -28
  348. package/scripts/anyswarm-author.ts +25 -0
  349. package/scripts/anyswarm-eject.ts +145 -0
  350. package/scripts/anyswarm-harnesses.ts +27 -0
  351. package/scripts/anyswarm-installation.ts +19 -13
  352. package/scripts/anyswarm-launch.ts +108 -0
  353. package/scripts/anyswarm-project.ts +114 -21
  354. package/scripts/anyswarm-source-runner.ts +203 -0
  355. package/scripts/anyswarm-tui-config.ts +174 -0
  356. package/scripts/anyswarm-tui-session.ts +295 -0
  357. package/scripts/anyswarm-tui-terminal.ts +147 -0
  358. package/scripts/anyswarm-tui.ts +912 -0
  359. package/scripts/anyswarm.ts +43 -2
  360. package/scripts/build.ts +8 -1
  361. package/scripts/generate-architecture-api.ts +2 -0
  362. package/scripts/generate-architecture-prompts.ts +35 -2
  363. package/scripts/local-environment.ts +55 -17
  364. package/scripts/local-setup-smoke.ts +3 -2
  365. package/scripts/local-setup-worker.ts +17 -7
  366. package/scripts/local-setup.ts +66 -13
  367. package/scripts/opensandbox-agent-worker.ts +2 -2
  368. package/scripts/pack-release.ts +67 -0
  369. package/scripts/pi-session-bridge.ts +10 -2
  370. package/scripts/run-harness.ts +3 -1
  371. package/scripts/setup-bootstrap.ts +41 -6
  372. package/src/core/allocation-ledger.ts +5 -3
  373. package/src/core/host-identity.ts +11 -0
  374. package/src/core/index.ts +12 -6
  375. package/src/core/mcp-service.ts +2 -2
  376. package/src/core/runtime-management.ts +22 -0
  377. package/src/core/sandbox/executor-driver.ts +15 -18
  378. package/src/core/sandbox/local-executor.ts +65 -19
  379. package/src/core/sandbox/local-worker.ts +29 -21
  380. package/src/core/sandbox/opensandbox-backend.ts +36 -11
  381. package/src/core/sandbox/sandbox-connection.ts +14 -5
  382. package/src/core/service-live-state.ts +156 -0
  383. package/src/core/service-observation-types.ts +23 -1
  384. package/src/core/service-process.ts +36 -3
  385. package/src/core/service-types.ts +3 -1
  386. package/src/core/services.ts +8 -3
  387. package/src/core/types.ts +3 -0
  388. package/src/core/worker-image.ts +3 -3
  389. package/src/harness/harness-session-types.ts +13 -1
  390. package/src/harness/harness-session.ts +40 -7
  391. package/src/harness/project-harness.ts +36 -10
  392. package/src/harness/project-input.ts +73 -15
  393. package/src/harness/project-rpc-client.ts +5 -0
  394. package/src/harness/project-rpc.ts +29 -8
  395. package/src/harness/project-runtime.ts +2 -1
  396. package/src/harness/typescript-loader.ts +37 -0
  397. package/src/trace-viewer/public/app.js +6 -5
  398. package/src/trace-viewer/reader.mjs +42 -2
@@ -0,0 +1,24 @@
1
+ # Editable TypeScript Harness
2
+
3
+ Run this complete example with the installed AnySwarm CLI.
4
+
5
+ ```sh
6
+ anys run ./harness.ts
7
+ anys run ./harness.ts --config ./config.ts --prompt 'Create a greeting'
8
+ ```
9
+
10
+ Edit `business.ts` and run the command again to change the result. `harness.ts`
11
+ defines the Harness lifecycle, `business.ts` contains its rule, and `config.ts`
12
+ provides its default public configuration. This example uses no model or Sandbox.
13
+
14
+ `anys eject example --dir ./my-harness` exports these sources and a local SDK
15
+ archive. The generated package depends on that archive, so `npm install` retains
16
+ the exact candidate SDK. Direct `anys run` can also resolve the invoking CLI's SDK.
17
+ Use the same candidate CLI recorded in `anyswarm-source.json`.
18
+
19
+ Application authors use the same export mechanism by providing `eject.json` in
20
+ `examples/code`, `examples/autoresearch`, or `examples/super`. Its `apiVersion`
21
+ is `1`, `entry` names the runnable TS entry, and `files` explicitly lists every
22
+ relative source, prompt, Service, public config and README needed by that app.
23
+ Credentials, `.env`, runtime records, dependencies and build directories are
24
+ excluded by the engine. Exporting into a nonempty directory fails.
@@ -0,0 +1,4 @@
1
+ /** Edit this business rule and run harness.ts again. */
2
+ export function greeting(name: string) {
3
+ return name ? `Hello, ${name}` : 'Hello from your TypeScript Harness';
4
+ }
@@ -0,0 +1,2 @@
1
+ /** Optional public author configuration. Keep credentials outside exported files. */
2
+ export default { name: '' };
@@ -0,0 +1,5 @@
1
+ {
2
+ "apiVersion": 1,
3
+ "entry": "harness.ts",
4
+ "files": ["harness.ts", "business.ts", "config.ts", "README.md"]
5
+ }
@@ -0,0 +1,21 @@
1
+ import type { Harness } from '@anyswarm/core';
2
+ import { greeting } from './business.js';
3
+ import defaults from './config.js';
4
+
5
+ /** A complete finite Harness with editable business logic and no external resources. */
6
+ const harness: Harness = {
7
+ apiVersion: 1,
8
+ id: 'editable-typescript-example',
9
+ lifetimes: ['task'],
10
+ async run(context) {
11
+ context.markRunning();
12
+ const config = (context.configuration ?? defaults) as typeof defaults;
13
+ const message = greeting(config.name);
14
+ context.updateStatus({ business: { message } });
15
+ return {
16
+ outcome: 'completed', reason: 'greeting-created', result: { message }, artifacts: [],
17
+ export: { status: 'complete' }, cleanup: { status: 'complete' },
18
+ };
19
+ },
20
+ };
21
+ export default harness;
@@ -0,0 +1,33 @@
1
+ # AutoResearch
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.
4
+
5
+ ## FrontierCS-2 quickstart
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.
8
+
9
+ ```sh
10
+ anys -u autoresearch --cmd /prepare
11
+ anys -u autoresearch
12
+ ```
13
+
14
+ 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.
15
+
16
+ Type `/demo frontiercs2` in the composer. The stream shows peer claims, submitted candidates, patch reads, reviews and train scores. When a candidate becomes available, eligible peers receive a prompt to read and review its exact version. The live Trace shows detailed research, peer messages and reviews. Use `@peer-2 <suggestion>`, `/interrupt peer-2` or `/stop peer-2` to control one peer. The Trace link serves the current Run on loopback. For a remote controller, forward its port over SSH. After the CLI exits, use the printed replay command.
17
+
18
+ For a script or pipe, use `anys -u autoresearch --cmd '/demo frontiercs2'`. The live Trace URL goes to stderr. Session events and the final result go to stdout as JSONL.
19
+
20
+ 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.
21
+
22
+ ## Run your own project
23
+
24
+ ```sh
25
+ anys -u autoresearch --config ./research.ts "Your objective"
26
+ anys eject autoresearch --dir ./my-research
27
+ ```
28
+
29
+ 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.
30
+
31
+ The exported `project.ts` is the editable Harness. Install its pinned SDK archive with `npm install` in the export directory, then run `anys -u ./project.ts --cwd /path/to/project --config ./research.ts "Your objective"`. The export includes the FrontierCS-2 adapter and preparation source. The installed CLI hosts the terminal and live Trace.
32
+
33
+ See [the requirements](REQUIREMENTS.zh.md).
@@ -0,0 +1,18 @@
1
+ # AutoResearch 需求
2
+
3
+ 用户配置目标、可信评测和总预算后,团队自动研究、评测、选择候选并收尾。流式终端显示认领方向、提交候选和 train 反馈,支持向单个成员发送建议、中断当前轮次和停止成员。实时 Trace 提供消息、复核、候选沿用和回执,结束后可回放。
4
+
5
+ FrontierCS-2 demo 固定 `7e48965c7cef2a567c2669c8e2f10b06386289c9` 的 `binary_fuse_filter` 和该版本的 Pumpkin。团队至少四名平级 AnySwarm Worker,同一次 Run 使用真实 `kimi_proxy/k3`,没有统一 Lead。成员自行认领研究方向、交流和选择沿用的成果。Harness 管理资源、共享预算与可信评测。demo 的研究窗口为 12 分钟,官方 train 额度为 8 次,记录模型请求数但不限制次数。官方 train 公开反馈进入看板,final 结果只写入用户记录。
6
+
7
+ ```sh
8
+ anys -u autoresearch --cmd /prepare
9
+ anys -u autoresearch --cmd "/demo frontiercs2"
10
+ anys -u autoresearch --config ./research.ts "研究目标"
11
+ anys eject autoresearch --dir ./my-research
12
+ ```
13
+
14
+ 验收从候选包开始。独立 reference 完成无模型 train/final。实际 demo 从干净 starter 开始,保存四路真实 K3 活动重叠的证据、至少一次可关联到具体候选的同行复核或采用,以及 Worker 候选、官方 train、最终保存、final 和资源回收的关联记录。记录全队的资源、模型用量与费用。未知回执和待清理资源保留可核对的标识。官方零分作为求解结果记录。
15
+
16
+ 在交互入口 `anys -u autoresearch` 也可输入 `/prepare` 和 `/demo frontiercs2`。
17
+
18
+ 范围以 [#337](https://github.com/AnySwarm/anyswarm/issues/337) 和随后确认的四成员、Agensh 式扁平协作、实时 Trace 为准。终端交互遵循 [#344](https://github.com/AnySwarm/anyswarm/issues/344)。
@@ -0,0 +1,90 @@
1
+ import { ProjectPreflightError, resolveSandboxConnection, workerImageFor, type ExecutorSelection,
2
+ type ModelConfig, type RuntimeConnectionOptions, type SandboxConfig } from '@anyswarm/core';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import type { Evaluator } from './research-service.js';
6
+
7
+ export interface ResearchBudget {
8
+ workers: number;
9
+ workMs: number;
10
+ maxModelRequests?: number;
11
+ maxEvaluations: number;
12
+ }
13
+
14
+ export interface ResearchConfiguration {
15
+ targetPath?: string;
16
+ requiredFiles?: readonly string[];
17
+ goal: string;
18
+ direction: 'max' | 'min';
19
+ targetScore?: number;
20
+ budget: ResearchBudget;
21
+ evaluator: Evaluator;
22
+ executor: ExecutorSelection;
23
+ image: string;
24
+ model: ModelConfig;
25
+ sandbox: SandboxConfig;
26
+ connection: RuntimeConnectionOptions;
27
+ evaluationTimeoutMs?: number;
28
+ closeTimeoutMs?: number;
29
+ restrictNetwork?: boolean;
30
+ }
31
+
32
+ export const demoBudget: Readonly<ResearchBudget> = Object.freeze({
33
+ workers: 4, workMs: 720_000, maxEvaluations: 8,
34
+ });
35
+ export function frontierBudget(saved: ResearchBudget = demoBudget): ResearchBudget {
36
+ const { workers, workMs, maxEvaluations } = saved;
37
+ return checkBudget({ workers, workMs, maxEvaluations }, 4);
38
+ }
39
+ 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
+ export const demoCloseTimeoutMs = 365_000;
41
+
42
+ export function frontierHome() {
43
+ return resolve(process.env.ANYSWARM_AUTORESEARCH_STATE_DIR ??
44
+ join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'anyswarm', 'autoresearch', 'frontiercs2'));
45
+ }
46
+
47
+ export function defaultResearchConnection() {
48
+ const saved = resolveSandboxConnection({}, 'AUTORESEARCH');
49
+ return {
50
+ executor: saved.executor ?? 'pi',
51
+ image: saved.image ?? workerImageFor(saved.executor ?? 'pi'),
52
+ sandbox: {
53
+ lifecycleBaseUrl: saved.lifecycleBaseUrl, apiKey: saved.apiKey,
54
+ useServerProxy: saved.useServerProxy, egressMode: saved.egressMode,
55
+ resourceLimits: { cpu: '2', memory: '4Gi' },
56
+ },
57
+ connection: { publicUrl: saved.publicUrl, advertiseHost: saved.advertiseHost },
58
+ } satisfies Pick<ResearchConfiguration, 'executor' | 'image' | 'sandbox' | 'connection'>;
59
+ }
60
+
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.');
68
+ }
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.');
74
+ }
75
+ const token = process.env.ANYSWARM_MODEL_TOKEN;
76
+ return { provider, model, upstream: { url: endpoint.href, headers: token ? { authorization: `Bearer ${token}` } : {} } };
77
+ }
78
+
79
+ export function checkBudget(budget: ResearchBudget, minimum = 1): ResearchBudget {
80
+ const bounded = (value: number, min: number, max: number) => Number.isSafeInteger(value) && value >= min && value <= max;
81
+ if (!budget || !bounded(budget.workers, minimum, 8) || !bounded(budget.workMs, 10_000, 18_000_000) ||
82
+ !bounded(budget.maxEvaluations, 1, 100) ||
83
+ (budget.maxModelRequests !== undefined && !bounded(budget.maxModelRequests, budget.workers, 10_000))) {
84
+ throw new ProjectPreflightError('AUTORESEARCH_BUDGET_INVALID', 'Set a valid shared worker, time and evaluation budget, and a valid model-request cap if supplied.');
85
+ }
86
+ const { workers, workMs, maxEvaluations, maxModelRequests } = budget;
87
+ return { workers, workMs, maxEvaluations, ...(maxModelRequests === undefined ? {} : { maxModelRequests }) };
88
+ }
89
+
90
+ export default undefined;
@@ -0,0 +1,55 @@
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';
6
+
7
+ export function frontierTrainEvaluation(returned: Record<string, unknown>) {
8
+ const observed = returned.raw_score;
9
+ const score = typeof observed === 'number' && Number.isFinite(observed) ? observed : null;
10
+ return {
11
+ // This task's valid benchmark score is strictly positive. Some construction
12
+ // failures return only a zero score and omit both failure and rejected.
13
+ valid: score !== null && score > 0 && !returned.rejected && !returned.failure,
14
+ score,
15
+ feedback: returned as JsonValue,
16
+ };
17
+ }
18
+
19
+ export async function frontierDemo() {
20
+ const ready = await loadPrepared().catch(() => { throw new Error('Prepare the pinned demo first with anys -u autoresearch --cmd /prepare.'); });
21
+ const { budget, paths, saved, starter } = ready;
22
+ const defaults = defaultResearchConnection();
23
+ const model = kimiModel();
24
+ 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,
29
+ requiredFiles: ['README.md', 'include/binaryfusefilter.h'],
30
+ evaluationTimeoutMs: judgeTimeMs + 25_000,
31
+ closeTimeoutMs: demoCloseTimeoutMs,
32
+ evaluator: {
33
+ 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');
38
+ }
39
+ },
40
+ async train(patch, signal, admitted) {
41
+ const receipt = await frontier!.train(frontierSubmission(patch), signal, admitted);
42
+ return frontierTrainEvaluation(receipt.returned);
43
+ },
44
+ async final(patch, signal) {
45
+ return await frontier!.finish(frontierSubmission(patch), signal) as unknown as JsonValue;
46
+ },
47
+ async close() { return frontier ? await frontier.close() : 'complete'; },
48
+ 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) };
51
+ },
52
+ },
53
+ };
54
+ return { configuration, starter };
55
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "apiVersion": 1,
3
+ "entry": "project.ts",
4
+ "files": [
5
+ "README.md",
6
+ "REQUIREMENTS.zh.md",
7
+ "project.ts",
8
+ "config.ts",
9
+ "research-service.ts",
10
+ "demo.ts",
11
+ "prepare.ts",
12
+ "frontiercs2.ts",
13
+ "process.ts"
14
+ ]
15
+ }
@@ -0,0 +1,237 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { command, requireSuccess } from './process.js';
6
+
7
+ export const frontierRevision = '7e48965c7cef2a567c2669c8e2f10b06386289c9';
8
+ export const pumpkinPin = '2026-11-30 ca3ce7ae0da5616464b00ee7962aecac0fc0b38d a1bb9c633f1f700ea42bceb9cd9512f684e9063d3a8ae6c9485526a1dd68016f';
9
+ export const frontierTask = 'tasks/binary_fuse_filter/task.star';
10
+ export const submissionLimit = 1024 * 1024;
11
+ export const judgeTimeMs = 190_000;
12
+ export const frontierFinalTimeMs = 250_000;
13
+
14
+ export function digest(bytes: Uint8Array | string): string {
15
+ return createHash('sha256').update(bytes).digest('hex');
16
+ }
17
+
18
+ export function frontierSubmission(patch: Uint8Array): Buffer {
19
+ const bytes = Math.ceil(patch.byteLength / 512) * 512 + 512 * 3;
20
+ if (!patch.byteLength || bytes > submissionLimit) throw new Error('Patch exceeds the FrontierCS-2 submission limit or is empty');
21
+ const archive = Buffer.alloc(bytes);
22
+ archive.write('payload/solution.patch');
23
+ archive.write('0000644\0', 100);
24
+ archive.write('0000000\0', 108);
25
+ archive.write('0000000\0', 116);
26
+ archive.write(patch.byteLength.toString(8).padStart(11, '0') + '\0', 124);
27
+ archive.write('00000000000\0', 136);
28
+ archive.fill(32, 148, 156);
29
+ archive.write('0', 156);
30
+ archive.write('ustar\0' + '00', 257);
31
+ let checksum = 0;
32
+ for (const byte of archive.subarray(0, 512)) checksum += byte;
33
+ archive.write(checksum.toString(8).padStart(6, '0') + '\0 ', 148);
34
+ archive.set(patch, 512);
35
+ return archive;
36
+ }
37
+
38
+ function replaceOnce(source: string, needle: string, replacement: string) {
39
+ const first = source.indexOf(needle);
40
+ if (first < 0 || source.indexOf(needle, first + needle.length) >= 0) throw new Error('Unexpected pinned FrontierCS-2 workflow');
41
+ return source.replace(needle, replacement);
42
+ }
43
+
44
+ export const bridgeDockerfile = 'FROM ubuntu:24.04@sha256:fe81560990fae86dc4743202b2cb4d3df98d0bcf949173cecef15ce1127ef852\n';
45
+
46
+ export function bridgeWorkflow(source: string): string {
47
+ return replaceOnce(source, ' elif AGENT == "reference":', ` elif AGENT == "anyswarm":
48
+ agent_role = {
49
+ "name": "agent",
50
+ "image": image("Dockerfile", context = "//lib/anyswarm-bridge"),
51
+ "user": AGENT_USER,
52
+ "needs": agent,
53
+ "runtime": {"agent": {
54
+ "command": {"argv": ["/bin/sh", "-c", "while :; do sleep 1; done"], "cwd": "/pumpkin"},
55
+ "finalize_grace_seconds": 1,
56
+ }},
57
+ }
58
+ elif AGENT == "reference":`);
59
+ }
60
+
61
+ interface PumpkinReply {
62
+ kind?: string;
63
+ job?: number;
64
+ state?: string;
65
+ returned?: Record<string, unknown>;
66
+ result?: { state?: string };
67
+ message?: string;
68
+ failure?: unknown;
69
+ }
70
+
71
+ interface Submission {
72
+ payload: { digest: string; size: number };
73
+ finalized: boolean;
74
+ }
75
+
76
+ interface Outcome {
77
+ state?: string;
78
+ agents?: { role: string; submission: Submission | null }[];
79
+ verdict?: { kind: string; result?: { values: { name: string; value: unknown }[] } };
80
+ usage?: unknown;
81
+ driver?: unknown;
82
+ }
83
+
84
+ export type JudgeImages = { train_judge: string; final_judge: string };
85
+
86
+ export async function judgeImages(record: string): Promise<JudgeImages> {
87
+ const ir = JSON.parse(await readFile(join(record, 'ir.json'), 'utf8'));
88
+ function image(name: string): string {
89
+ const roles = ir.roles?.filter((role: { name: string }) => role.name === name);
90
+ const id = roles?.[0]?.image;
91
+ if (roles?.length !== 1 || typeof id !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(id)) {
92
+ throw new Error(`Cannot establish pinned Pumpkin image for ${name}`);
93
+ }
94
+ return id;
95
+ }
96
+ return { train_judge: image('train_judge'), final_judge: image('final_judge') };
97
+ }
98
+
99
+ const runId = /^\d{8}-\d{6}-[a-f0-9]{8}$/;
100
+
101
+ export interface FrontierPaths {
102
+ source: string;
103
+ config: string;
104
+ dockerContext: string;
105
+ cache: string;
106
+ }
107
+
108
+ export class FrontierRun {
109
+ id?: string;
110
+ container?: string;
111
+ imageId?: string;
112
+ judges?: JudgeImages;
113
+ private closed = false;
114
+
115
+ constructor(readonly paths: FrontierPaths, readonly runs: string) {}
116
+
117
+ private pumpkin(args: string[], timeoutMs: number, signal?: AbortSignal) {
118
+ return command('./pumpkin', args, { cwd: this.paths.source, env: { ...process.env, XDG_CACHE_HOME: this.paths.cache }, timeoutMs, signal });
119
+ }
120
+
121
+ private docker(args: string[], timeoutMs: number, signal?: AbortSignal, input?: Uint8Array) {
122
+ return command('docker', ['--context', this.paths.dockerContext, ...args], { timeoutMs, signal, input });
123
+ }
124
+
125
+ get record() { return this.id ? join(this.runs, this.id) : undefined; }
126
+
127
+ async start(seconds: number, signal: AbortSignal, timeoutMs = 360_000): Promise<void> {
128
+ await mkdir(this.runs, { recursive: true, mode: 0o700 });
129
+ const start = await this.pumpkin(['run', frontierTask, '--arg', 'agent=anyswarm', '--arg', `deadline_seconds=${seconds}`,
130
+ '--config', this.paths.config, '--runs', this.runs], timeoutMs, signal);
131
+ const id = requireSuccess(start, 'Start official Pumpkin workflow').split(/\s+/)[0];
132
+ if (!runId.test(id)) throw new Error('Pumpkin returned an invalid run ID');
133
+ this.id = id;
134
+ const started = AbortSignal.any([signal, AbortSignal.timeout(20_000)]);
135
+ while (!this.container) {
136
+ const result = await this.docker(['container', 'ls', '--no-trunc', '--filter', `label=pumpkin.run=${id}`,
137
+ '--filter', 'label=pumpkin.role=agent', '--format', '{{.ID}}'], 5_000, started);
138
+ const ids = requireSuccess(result, 'Find the official agent role').split(/\s+/).filter(Boolean);
139
+ if (ids.length > 1 || (ids.length && !/^[a-f0-9]{64}$/.test(ids[0]))) throw new Error('Ambiguous Pumpkin agent container');
140
+ this.container = ids[0];
141
+ if (!this.container) await delay(250, undefined, { signal: started });
142
+ }
143
+ this.imageId = requireSuccess(await this.docker(['inspect', '--format', '{{.Image}}', this.container], 5_000, started), 'Inspect bridge image');
144
+ const record = this.record!;
145
+ this.judges = await judgeImages(record);
146
+ const ir = JSON.parse(await readFile(join(record, 'ir.json'), 'utf8'));
147
+ const role = ir.roles?.find((role: { name: string }) => role.name === 'agent');
148
+ const grantTrain = role?.runtime?.agent?.grants?.find((grant: { name: string }) => grant.name === 'train');
149
+ const grantFinal = role?.runtime?.agent?.grants?.find((grant: { name: string }) => grant.name === 'final');
150
+ if (grantTrain?.job?.target !== 'train_judge' || !(grantTrain.job.calls >= 8) ||
151
+ grantTrain.job.payload_max_bytes !== submissionLimit || grantFinal?.now?.payload_max_bytes !== submissionLimit ||
152
+ 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');
154
+ }
155
+ const grants = await this.docker(['exec', this.container, '/bin/sh', '-eu', '-c',
156
+ 'test -w /pumpkin; exec /.pumpkin/bin/sandboxctl ops'], 5_000, started);
157
+ const ops = JSON.parse(requireSuccess(grants, 'Check official Pumpkin grants and submission scratch space'));
158
+ if (ops.kind !== 'ops') throw new Error('The Pumpkin role has no official grants');
159
+ }
160
+
161
+ private async call(name: 'train' | 'final', bytes: Uint8Array, signal: AbortSignal): Promise<PumpkinReply> {
162
+ if (!this.container || this.closed) throw new Error('Pumpkin submission role is unavailable');
163
+ const result = await this.docker(['exec', '-i', this.container, '/bin/sh', '-eu', '-c',
164
+ 'umask 077; file="/pumpkin/$1.tar"; shift; trap \'rm -f -- "$file"\' EXIT; cat > "$file"; name="$1"; shift; /.pumpkin/bin/sandboxctl call "$name" "$file" "$@"',
165
+ 'anyswarm-submit', randomUUID(), name, ...(name === 'final' ? ['--arg', 'finalize=true'] : [])], 15_000, signal, bytes);
166
+ if (!result.stdout.trim()) {
167
+ throw new Error(`Official ${name} admission is unknown: ${result.stderr.trim().slice(-320) || `exit ${result.code}`}`);
168
+ }
169
+ return JSON.parse(result.stdout) as PumpkinReply;
170
+ }
171
+
172
+ async train(bytes: Uint8Array, signal: AbortSignal, onAdmission: (job: number) => void) {
173
+ const reply = await this.call('train', bytes, signal);
174
+ if (reply.kind === 'refused') throw new Error(reply.message ?? 'Official train refused the candidate');
175
+ if (reply.kind !== 'call' || !Number.isSafeInteger(reply.job)) throw new Error('Official train admission is unknown');
176
+ const job = reply.job!;
177
+ onAdmission(job);
178
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(judgeTimeMs)]);
179
+ while (true) {
180
+ const reply = await this.docker(['exec', this.container!, '/.pumpkin/bin/sandboxctl', 'status', String(job)], 5_000, deadline);
181
+ const state = JSON.parse(reply.stdout) as PumpkinReply;
182
+ 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 };
184
+ if (state.state === 'errored') throw new Error(`Official train job ${job} failed`);
185
+ if (state.state !== 'queued' && state.state !== 'running') throw new Error(`Official train job ${job} has an unknown status`);
186
+ await delay(750, undefined, { signal: deadline });
187
+ }
188
+ }
189
+
190
+ async finish(bytes: Uint8Array, signal: AbortSignal) {
191
+ const sha256 = digest(bytes);
192
+ const reply = await this.call('final', bytes, signal).catch(() => undefined);
193
+ if (reply?.kind === 'refused') throw new Error(reply.message ?? 'Official final refused the candidate');
194
+ // A missing acknowledgement may still have stored and locked the payload. Verify
195
+ // the authoritative outcome against the immutable payload before crediting it.
196
+ const { outcome, record } = await this.outcome(signal);
197
+ const submission = outcome.agents?.find(agent => agent.role === 'agent')?.submission;
198
+ if (outcome.state !== 'finished' || outcome.verdict?.kind !== 'returned' ||
199
+ submission?.payload?.digest !== `sha256:${sha256}` || submission.payload.size !== bytes.byteLength || !submission.finalized) {
200
+ throw new Error('Official final result could not be associated with the selected candidate');
201
+ }
202
+ return { record, submission, verdict: outcome.verdict, usage: outcome.usage ?? null, driver: outcome.driver ?? null };
203
+ }
204
+
205
+ async outcome(signal: AbortSignal) {
206
+ const record = this.record;
207
+ if (!record) throw new Error('There is no official Pumpkin run');
208
+ await this.pumpkin(['wait', '--runs', this.runs, '--outcome', this.id!], frontierFinalTimeMs, signal);
209
+ const outcome = JSON.parse(await readFile(join(record, 'outcome.json'), 'utf8')) as Outcome;
210
+ this.closed = outcome.state === 'finished';
211
+ return { outcome, record };
212
+ }
213
+
214
+ async close(): Promise<'complete' | 'pending'> {
215
+ 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);
218
+ for (const id of ids) {
219
+ const finished = this.closed || await readFile(join(this.runs, id, 'outcome.json'), 'utf8')
220
+ .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';
224
+ }
225
+ return 'complete';
226
+ } catch { return 'pending'; }
227
+ }
228
+ }
229
+
230
+ export async function installBridge(source: string) {
231
+ const file = join(source, 'lib', 'fcs.star');
232
+ const original = await readFile(file, 'utf8');
233
+ const role = join(source, 'lib', 'anyswarm-bridge');
234
+ await mkdir(role, { recursive: true, mode: 0o700 });
235
+ await writeFile(join(role, 'Dockerfile'), bridgeDockerfile);
236
+ await writeFile(file, bridgeWorkflow(original));
237
+ }