@anyswarm/core 0.5.0 → 0.5.2

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 (403) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +21 -13
  3. package/deploy/worker/Dockerfile +12 -4
  4. package/dist/deploy/worker/Dockerfile +12 -4
  5. package/dist/examples/README.md +35 -12
  6. package/dist/examples/authoring/README.md +24 -0
  7. package/dist/examples/authoring/business.d.ts +2 -0
  8. package/dist/examples/authoring/business.js +4 -0
  9. package/dist/examples/authoring/config.d.ts +5 -0
  10. package/dist/examples/authoring/config.js +2 -0
  11. package/dist/examples/authoring/eject.json +5 -0
  12. package/dist/examples/authoring/harness.d.ts +4 -0
  13. package/dist/examples/authoring/harness.js +19 -0
  14. package/dist/examples/autoresearch/README.md +40 -0
  15. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +11 -0
  16. package/dist/examples/autoresearch/config.d.ts +51 -0
  17. package/dist/examples/autoresearch/config.js +57 -0
  18. package/dist/examples/autoresearch/demo.d.ts +11 -0
  19. package/dist/examples/autoresearch/demo.js +52 -0
  20. package/dist/examples/autoresearch/eject.json +17 -0
  21. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -0
  22. package/dist/examples/autoresearch/frontiercs2-config.js +3 -0
  23. package/dist/examples/autoresearch/frontiercs2.d.ts +87 -0
  24. package/dist/examples/autoresearch/frontiercs2.js +211 -0
  25. package/dist/examples/autoresearch/prepare-demo.d.ts +1 -0
  26. package/dist/examples/autoresearch/prepare-demo.js +15 -0
  27. package/dist/examples/autoresearch/prepare.d.ts +95 -0
  28. package/dist/examples/autoresearch/prepare.js +257 -0
  29. package/dist/examples/autoresearch/process.d.ts +13 -0
  30. package/dist/examples/autoresearch/process.js +48 -0
  31. package/dist/examples/autoresearch/project.d.ts +21 -0
  32. package/dist/examples/autoresearch/project.js +392 -0
  33. package/dist/examples/autoresearch/research-service.d.ts +106 -0
  34. package/dist/examples/autoresearch/research-service.js +255 -0
  35. package/dist/examples/code/README.md +33 -0
  36. package/dist/examples/code/REQUIREMENTS.zh.md +11 -0
  37. package/dist/examples/code/candidate.d.ts +19 -0
  38. package/dist/examples/code/candidate.js +80 -0
  39. package/dist/examples/code/config.d.ts +32 -0
  40. package/dist/examples/code/config.js +18 -0
  41. package/dist/examples/code/eject.json +5 -0
  42. package/dist/examples/code/project.d.ts +3 -0
  43. package/dist/examples/code/project.js +605 -0
  44. package/dist/examples/code/prompts.d.ts +5 -0
  45. package/dist/examples/code/prompts.js +12 -0
  46. package/dist/examples/code/verification.d.ts +19 -0
  47. package/dist/examples/code/verification.js +268 -0
  48. package/dist/examples/code/worktree.d.ts +17 -0
  49. package/dist/examples/code/worktree.js +233 -0
  50. package/dist/examples/harness-session/README.md +3 -6
  51. package/dist/examples/lead-worker/harness/dynamic-scheduler.d.ts +2 -1
  52. package/dist/examples/lead-worker/harness/dynamic-scheduler.js +5 -2
  53. package/dist/examples/lead-worker/harness/index.d.ts +60 -0
  54. package/dist/examples/lead-worker/harness/index.js +77 -6
  55. package/dist/examples/lead-worker/project.js +2 -2
  56. package/dist/examples/lead-worker/services/board.d.ts +5 -0
  57. package/dist/examples/lead-worker/services/board.js +19 -1
  58. package/dist/examples/messages/README.md +5 -5
  59. package/dist/examples/messages/handoff.d.ts +2 -0
  60. package/dist/examples/messages/handoff.js +5 -1
  61. package/dist/examples/messages/project.js +52 -2
  62. package/dist/examples/notes/README.md +13 -18
  63. package/dist/examples/notes/project.js +67 -6
  64. package/dist/examples/peermesh/harness/router.js +3 -1
  65. package/dist/examples/peermesh/harness/team.d.ts +8 -0
  66. package/dist/examples/peermesh/harness/team.js +13 -0
  67. package/dist/examples/peermesh/project.js +22 -4
  68. package/dist/examples/services/agent-control/README.md +3 -3
  69. package/dist/examples/services/mathlib-search/Dockerfile +4 -2
  70. package/dist/examples/services/mathlib-search/README.md +1 -1
  71. package/dist/examples/services/mcp-managed/README.md +2 -2
  72. package/dist/examples/services/persistent-board/README.md +16 -3
  73. package/dist/examples/services/persistent-board/business.d.ts +7 -0
  74. package/dist/examples/services/persistent-board/business.js +7 -0
  75. package/dist/examples/services/persistent-board/index.js +10 -0
  76. package/dist/examples/services/persistent-board/live.d.ts +3 -0
  77. package/dist/examples/services/persistent-board/live.js +58 -0
  78. package/dist/examples/subagents/README.md +5 -5
  79. package/dist/examples/subagents/business.js +3 -1
  80. package/dist/examples/subagents/config.js +3 -3
  81. package/dist/examples/subagents/harness/controller.d.ts +15 -0
  82. package/dist/examples/subagents/harness/controller.js +181 -32
  83. package/dist/examples/subagents/project.d.ts +2 -0
  84. package/dist/examples/subagents/project.js +43 -34
  85. package/dist/examples/subagents/prompts/prompts.d.ts +1 -0
  86. package/dist/examples/subagents/prompts/prompts.js +3 -0
  87. package/dist/examples/subagents/services/collaboration-service.d.ts +3 -2
  88. package/dist/examples/subagents/services/collaboration-service.js +14 -2
  89. package/dist/examples/substrate/README.md +2 -2
  90. package/dist/examples/substrate/harness/index.d.ts +1 -1
  91. package/dist/examples/substrate/harness/index.js +77 -12
  92. package/dist/examples/substrate/project.js +4 -1
  93. package/dist/examples/super/README.md +52 -0
  94. package/dist/examples/super/actions.d.ts +95 -0
  95. package/dist/examples/super/actions.js +230 -0
  96. package/dist/examples/super/artifact.d.ts +4 -0
  97. package/dist/examples/super/artifact.js +51 -0
  98. package/dist/examples/super/config.d.ts +80 -0
  99. package/dist/examples/super/config.js +83 -0
  100. package/dist/examples/super/coordinator.d.ts +33 -0
  101. package/dist/examples/super/coordinator.js +151 -0
  102. package/dist/examples/super/daemon.d.ts +11 -0
  103. package/dist/examples/super/daemon.js +109 -0
  104. package/dist/examples/super/decisions.d.ts +8 -0
  105. package/dist/examples/super/decisions.js +52 -0
  106. package/dist/examples/super/eject.json +5 -0
  107. package/dist/examples/super/execution.d.ts +11 -0
  108. package/dist/examples/super/execution.js +136 -0
  109. package/dist/examples/super/github.d.ts +62 -0
  110. package/dist/examples/super/github.js +269 -0
  111. package/dist/examples/super/inbox.d.ts +162 -0
  112. package/dist/examples/super/inbox.js +284 -0
  113. package/dist/examples/super/location.d.ts +5 -0
  114. package/dist/examples/super/location.js +64 -0
  115. package/dist/examples/super/operator.d.ts +1 -0
  116. package/dist/examples/super/operator.js +31 -0
  117. package/dist/examples/super/outbox.d.ts +5 -0
  118. package/dist/examples/super/outbox.js +103 -0
  119. package/dist/examples/super/project.d.ts +4 -0
  120. package/dist/examples/super/project.js +251 -0
  121. package/dist/examples/super/prompts.d.ts +3 -0
  122. package/dist/examples/super/prompts.js +25 -0
  123. package/dist/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  124. package/dist/examples/taskpool/harness/controller.d.ts +35 -6
  125. package/dist/examples/taskpool/harness/controller.js +73 -7
  126. package/dist/examples/taskpool/project.js +18 -2
  127. package/dist/scripts/anyswarm-arguments.d.ts +18 -6
  128. package/dist/scripts/anyswarm-arguments.js +88 -52
  129. package/dist/scripts/anyswarm-author.d.ts +5 -0
  130. package/dist/scripts/anyswarm-author.js +24 -0
  131. package/dist/scripts/anyswarm-eject.d.ts +11 -0
  132. package/dist/scripts/anyswarm-eject.js +164 -0
  133. package/dist/scripts/anyswarm-harnesses.d.ts +1 -0
  134. package/dist/scripts/anyswarm-harnesses.js +10 -0
  135. package/dist/scripts/anyswarm-installation.d.ts +7 -40
  136. package/dist/scripts/anyswarm-installation.js +17 -285
  137. package/dist/scripts/anyswarm-launch.d.ts +7 -0
  138. package/dist/scripts/anyswarm-launch.js +37 -0
  139. package/dist/scripts/anyswarm-progress.d.ts +6 -0
  140. package/dist/scripts/anyswarm-progress.js +102 -0
  141. package/dist/scripts/anyswarm-project.d.ts +3 -1
  142. package/dist/scripts/anyswarm-project.js +49 -35
  143. package/dist/scripts/anyswarm-source-runner.d.ts +1 -0
  144. package/dist/scripts/anyswarm-source-runner.js +200 -0
  145. package/dist/scripts/anyswarm.js +28 -3
  146. package/dist/scripts/build-provenance.json +1 -0
  147. package/dist/scripts/build.js +7 -1
  148. package/dist/scripts/generate-architecture-api.js +2 -0
  149. package/dist/scripts/generate-architecture-prompts.js +24 -2
  150. package/dist/scripts/local-environment.d.ts +13 -2
  151. package/dist/scripts/local-environment.js +111 -28
  152. package/dist/scripts/local-setup-smoke.js +3 -2
  153. package/dist/scripts/local-setup-worker.d.ts +1 -1
  154. package/dist/scripts/local-setup-worker.js +15 -6
  155. package/dist/scripts/local-setup.d.ts +5 -2
  156. package/dist/scripts/local-setup.js +167 -79
  157. package/dist/scripts/opensandbox-agent-worker.js +2 -2
  158. package/dist/scripts/pack-release.d.ts +1 -0
  159. package/dist/scripts/pack-release.js +66 -0
  160. package/dist/scripts/pi-session-bridge.js +11 -3
  161. package/dist/scripts/run-harness.js +3 -1
  162. package/dist/scripts/setup-bootstrap.js +43 -6
  163. package/dist/src/core/allocation-ledger.js +4 -3
  164. package/dist/src/core/host-identity.d.ts +2 -0
  165. package/dist/src/core/host-identity.js +11 -0
  166. package/dist/src/core/index.d.ts +4 -2
  167. package/dist/src/core/index.js +12 -4
  168. package/dist/src/core/mcp-service.js +2 -2
  169. package/dist/src/core/runtime-management.d.ts +6 -0
  170. package/dist/src/core/runtime-management.js +24 -0
  171. package/dist/src/core/sandbox/executor-driver.d.ts +4 -2
  172. package/dist/src/core/sandbox/executor-driver.js +12 -14
  173. package/dist/src/core/sandbox/local-executor.d.ts +13 -1
  174. package/dist/src/core/sandbox/local-executor.js +69 -19
  175. package/dist/src/core/sandbox/local-worker.js +32 -21
  176. package/dist/src/core/sandbox/opensandbox-backend.d.ts +2 -0
  177. package/dist/src/core/sandbox/opensandbox-backend.js +36 -11
  178. package/dist/src/core/sandbox/sandbox-connection.d.ts +2 -0
  179. package/dist/src/core/sandbox/sandbox-connection.js +14 -6
  180. package/dist/src/core/service-live-state.d.ts +14 -0
  181. package/dist/src/core/service-live-state.js +161 -0
  182. package/dist/src/core/service-observation-types.d.ts +21 -1
  183. package/dist/src/core/service-process.d.ts +1 -1
  184. package/dist/src/core/service-process.js +45 -4
  185. package/dist/src/core/service-types.d.ts +5 -1
  186. package/dist/src/core/services.d.ts +1 -1
  187. package/dist/src/core/services.js +8 -3
  188. package/dist/src/core/types.d.ts +3 -0
  189. package/dist/src/core/worker-image.js +3 -3
  190. package/dist/src/harness/harness-session-types.d.ts +10 -0
  191. package/dist/src/harness/harness-session.js +42 -5
  192. package/dist/src/harness/project-harness.d.ts +14 -1
  193. package/dist/src/harness/project-harness.js +38 -12
  194. package/dist/src/harness/project-input.js +81 -15
  195. package/dist/src/harness/project-rpc-client.d.ts +1 -0
  196. package/dist/src/harness/project-rpc-client.js +5 -0
  197. package/dist/src/harness/project-rpc.d.ts +8 -2
  198. package/dist/src/harness/project-rpc.js +31 -7
  199. package/dist/src/harness/project-runtime.js +6 -2
  200. package/dist/src/harness/typescript-loader.d.ts +2 -0
  201. package/dist/src/harness/typescript-loader.js +41 -0
  202. package/dist/src/trace-viewer/public/app.js +6 -5
  203. package/dist/src/trace-viewer/reader.mjs +42 -2
  204. package/docs/INDEX.md +5 -2
  205. package/docs/architecture/00-overview.md +1 -1
  206. package/docs/architecture/01-agent-core.md +1 -1
  207. package/docs/architecture/04-services.md +1 -1
  208. package/docs/architecture/06-observability-experiments.md +1 -1
  209. package/docs/architecture/07-run-configuration.md +38 -18
  210. package/docs/architecture/08-prompts.md +22 -0
  211. package/docs/architecture/10-service-api-reference.md +53 -18
  212. package/docs/architecture/11-storage-reference.md +18 -1
  213. package/docs/architecture/12-code-coverage.md +152 -89
  214. package/docs/architecture/15-core-runtime.md +8 -0
  215. package/docs/architecture/16-pi-opensandbox-backend.md +5 -5
  216. package/docs/architecture/17-harness-reporting.md +1 -1
  217. package/docs/architecture/19-substrate-harness.md +28 -1
  218. package/docs/architecture/20-lead-worker-harness.md +34 -1
  219. package/docs/architecture/22-website.md +5 -6
  220. package/docs/architecture/23-project-harness.md +152 -8
  221. package/docs/architecture/24-runtime-recovery.md +10 -3
  222. package/docs/architecture/26-code.md +54 -0
  223. package/docs/architecture/27-personal.md +58 -0
  224. package/docs/architecture/28-autoresearch.md +43 -0
  225. package/docs/architecture/INDEX.md +3 -0
  226. package/docs/architecture/prompts/08-lead-worker-harness.md +4 -2
  227. package/docs/architecture/prompts/08-subagents-harness.md +21 -0
  228. package/docs/architecture/prompts/21-personal.md +44 -0
  229. package/docs/architecture/prompts/22-autoresearch.md +63 -0
  230. package/docs/architecture/prompts/26-code.md +55 -0
  231. package/docs/architecture/prompts/source-manifest.json +152 -33
  232. package/docs/architecture/source-map.json +473 -25
  233. package/docs/designs/core-harness/01-core.md +2 -2
  234. package/docs/designs/core-harness/06-project-harness.md +13 -2
  235. package/docs/designs/core-harness/README.md +7 -2
  236. package/docs/en/agents.md +1 -1
  237. package/docs/en/build-your-harness.md +3 -5
  238. package/docs/en/changelog.md +20 -4
  239. package/docs/en/first-harness.md +9 -12
  240. package/docs/en/harnesses/lead-worker.md +1 -1
  241. package/docs/en/harnesses/peermesh.md +2 -2
  242. package/docs/en/harnesses/subagents.md +2 -2
  243. package/docs/en/harnesses/substrate.md +4 -4
  244. package/docs/en/harnesses/taskpool.md +2 -2
  245. package/docs/en/latest.md +14 -121
  246. package/docs/en/overview.md +1 -1
  247. package/docs/en/quickstart.md +42 -39
  248. package/docs/en/reference/api.md +14 -4
  249. package/docs/en/reference/cli.md +53 -47
  250. package/docs/en/runtime.md +2 -2
  251. package/docs/en/sandbox.md +3 -3
  252. package/docs/en/services.md +4 -0
  253. package/docs/operations/trace-viewer.md +1 -1
  254. package/docs/workflows/development.md +28 -21
  255. package/docs/workflows/release-and-docs-versioning.md +77 -0
  256. package/docs/workflows/release-cli-acceptance.md +85 -0
  257. package/docs/zh/agents.md +1 -1
  258. package/docs/zh/build-your-harness.md +3 -5
  259. package/docs/zh/changelog.md +20 -4
  260. package/docs/zh/first-harness.md +9 -12
  261. package/docs/zh/harnesses/lead-worker.md +1 -1
  262. package/docs/zh/harnesses/peermesh.md +2 -2
  263. package/docs/zh/harnesses/subagents.md +2 -2
  264. package/docs/zh/harnesses/substrate.md +4 -4
  265. package/docs/zh/harnesses/taskpool.md +2 -2
  266. package/docs/zh/latest.md +15 -122
  267. package/docs/zh/overview.md +1 -1
  268. package/docs/zh/quickstart.md +42 -39
  269. package/docs/zh/reference/api.md +14 -4
  270. package/docs/zh/reference/cli.md +24 -40
  271. package/docs/zh/runtime.md +2 -2
  272. package/docs/zh/sandbox.md +3 -3
  273. package/docs/zh/services.md +4 -0
  274. package/examples/README.md +35 -12
  275. package/examples/authoring/README.md +24 -0
  276. package/examples/authoring/business.ts +4 -0
  277. package/examples/authoring/config.ts +2 -0
  278. package/examples/authoring/eject.json +5 -0
  279. package/examples/authoring/harness.ts +21 -0
  280. package/examples/autoresearch/README.md +40 -0
  281. package/examples/autoresearch/REQUIREMENTS.zh.md +11 -0
  282. package/examples/autoresearch/config.ts +90 -0
  283. package/examples/autoresearch/demo.ts +55 -0
  284. package/examples/autoresearch/eject.json +17 -0
  285. package/examples/autoresearch/frontiercs2-config.ts +4 -0
  286. package/examples/autoresearch/frontiercs2.ts +237 -0
  287. package/examples/autoresearch/prepare-demo.ts +15 -0
  288. package/examples/autoresearch/prepare.ts +267 -0
  289. package/examples/autoresearch/process.ts +50 -0
  290. package/examples/autoresearch/project.ts +380 -0
  291. package/examples/autoresearch/research-service.ts +302 -0
  292. package/examples/code/README.md +33 -0
  293. package/examples/code/REQUIREMENTS.zh.md +11 -0
  294. package/examples/code/candidate.ts +89 -0
  295. package/examples/code/config.ts +19 -0
  296. package/examples/code/eject.json +5 -0
  297. package/examples/code/project.ts +581 -0
  298. package/examples/code/prompts.ts +16 -0
  299. package/examples/code/verification.ts +239 -0
  300. package/examples/code/worktree.ts +188 -0
  301. package/examples/harness-session/README.md +3 -6
  302. package/examples/lead-worker/harness/dynamic-scheduler.ts +6 -3
  303. package/examples/lead-worker/harness/index.ts +61 -6
  304. package/examples/lead-worker/project.ts +2 -2
  305. package/examples/lead-worker/services/board.ts +14 -1
  306. package/examples/messages/README.md +5 -5
  307. package/examples/messages/handoff.ts +6 -2
  308. package/examples/messages/project.ts +47 -2
  309. package/examples/notes/README.md +13 -18
  310. package/examples/notes/project.ts +57 -9
  311. package/examples/peermesh/harness/router.ts +2 -2
  312. package/examples/peermesh/harness/team.ts +11 -0
  313. package/examples/peermesh/project.ts +19 -4
  314. package/examples/services/agent-control/README.md +3 -3
  315. package/examples/services/mathlib-search/Dockerfile +4 -2
  316. package/examples/services/mathlib-search/README.md +1 -1
  317. package/examples/services/mcp-managed/README.md +2 -2
  318. package/examples/services/persistent-board/README.md +16 -3
  319. package/examples/services/persistent-board/business.ts +10 -0
  320. package/examples/services/persistent-board/index.ts +10 -0
  321. package/examples/services/persistent-board/live.ts +54 -0
  322. package/examples/subagents/README.md +5 -5
  323. package/examples/subagents/business.ts +3 -1
  324. package/examples/subagents/config.ts +4 -3
  325. package/examples/subagents/harness/controller.ts +161 -29
  326. package/examples/subagents/project.ts +47 -33
  327. package/examples/subagents/prompts/prompts.ts +4 -0
  328. package/examples/subagents/services/collaboration-service.ts +14 -2
  329. package/examples/substrate/README.md +2 -2
  330. package/examples/substrate/harness/index.ts +67 -11
  331. package/examples/substrate/project.ts +5 -1
  332. package/examples/super/README.md +52 -0
  333. package/examples/super/actions.ts +196 -0
  334. package/examples/super/artifact.ts +56 -0
  335. package/examples/super/config.ts +95 -0
  336. package/examples/super/coordinator.ts +158 -0
  337. package/examples/super/daemon.ts +84 -0
  338. package/examples/super/decisions.ts +46 -0
  339. package/examples/super/eject.json +5 -0
  340. package/examples/super/execution.ts +131 -0
  341. package/examples/super/github.ts +242 -0
  342. package/examples/super/inbox.ts +306 -0
  343. package/examples/super/location.ts +54 -0
  344. package/examples/super/operator.ts +28 -0
  345. package/examples/super/outbox.ts +97 -0
  346. package/examples/super/project.ts +225 -0
  347. package/examples/super/prompts.ts +27 -0
  348. package/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  349. package/examples/taskpool/harness/controller.ts +59 -7
  350. package/examples/taskpool/project.ts +18 -2
  351. package/npm-shrinkwrap.development.json +700 -0
  352. package/npm-shrinkwrap.json +95 -1969
  353. package/package.development.json +88 -0
  354. package/package.json +11 -8
  355. package/scripts/anyswarm-arguments.ts +91 -54
  356. package/scripts/anyswarm-author.ts +25 -0
  357. package/scripts/anyswarm-eject.ts +145 -0
  358. package/scripts/anyswarm-harnesses.ts +10 -0
  359. package/scripts/anyswarm-installation.ts +18 -288
  360. package/scripts/anyswarm-launch.ts +36 -0
  361. package/scripts/anyswarm-progress.ts +95 -0
  362. package/scripts/anyswarm-project.ts +35 -34
  363. package/scripts/anyswarm-source-runner.ts +176 -0
  364. package/scripts/anyswarm.ts +24 -3
  365. package/scripts/build.ts +8 -1
  366. package/scripts/generate-architecture-api.ts +2 -0
  367. package/scripts/generate-architecture-prompts.ts +35 -2
  368. package/scripts/local-environment.ts +117 -28
  369. package/scripts/local-setup-smoke.ts +3 -2
  370. package/scripts/local-setup-worker.ts +17 -7
  371. package/scripts/local-setup.ts +166 -73
  372. package/scripts/opensandbox-agent-worker.ts +2 -2
  373. package/scripts/pack-release.ts +70 -0
  374. package/scripts/pi-session-bridge.ts +10 -2
  375. package/scripts/run-harness.ts +3 -1
  376. package/scripts/setup-bootstrap.ts +41 -6
  377. package/src/core/allocation-ledger.ts +5 -3
  378. package/src/core/host-identity.ts +11 -0
  379. package/src/core/index.ts +12 -6
  380. package/src/core/mcp-service.ts +2 -2
  381. package/src/core/runtime-management.ts +22 -0
  382. package/src/core/sandbox/executor-driver.ts +15 -18
  383. package/src/core/sandbox/local-executor.ts +65 -19
  384. package/src/core/sandbox/local-worker.ts +29 -21
  385. package/src/core/sandbox/opensandbox-backend.ts +36 -11
  386. package/src/core/sandbox/sandbox-connection.ts +14 -5
  387. package/src/core/service-live-state.ts +156 -0
  388. package/src/core/service-observation-types.ts +23 -1
  389. package/src/core/service-process.ts +36 -3
  390. package/src/core/service-types.ts +3 -1
  391. package/src/core/services.ts +8 -3
  392. package/src/core/types.ts +3 -0
  393. package/src/core/worker-image.ts +3 -3
  394. package/src/harness/harness-session-types.ts +13 -1
  395. package/src/harness/harness-session.ts +40 -7
  396. package/src/harness/project-harness.ts +38 -12
  397. package/src/harness/project-input.ts +73 -15
  398. package/src/harness/project-rpc-client.ts +5 -0
  399. package/src/harness/project-rpc.ts +29 -8
  400. package/src/harness/project-runtime.ts +4 -2
  401. package/src/harness/typescript-loader.ts +37 -0
  402. package/src/trace-viewer/public/app.js +6 -5
  403. package/src/trace-viewer/reader.mjs +42 -2
@@ -0,0 +1,239 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { constants, type BigIntStats } from 'node:fs';
3
+ import { copyFile, lstat, mkdir, mkdtemp, open, opendir, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
4
+ import { basename, dirname, isAbsolute, join, relative } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { decodeFileTree, type CompleteFileDigest, type FileBudget, type FileTree } from '@anyswarm/core';
7
+ import type { CodeChange } from './candidate.js';
8
+
9
+ const exec = promisify(execFile);
10
+
11
+ export function suggestedCheck(files: FileTree) {
12
+ const entry = Object.hasOwn(files, 'package.json') ? files['package.json'] : undefined;
13
+ if (entry) {
14
+ try {
15
+ const manifest = JSON.parse(Buffer.from(entry.data, entry.encoding).toString('utf8'));
16
+ if (typeof manifest?.scripts?.test === 'string' && manifest.scripts.test.trim()) return ['npm', 'test'];
17
+ } catch { /* An invalid manifest cannot select a command. */ }
18
+ }
19
+ for (const name of ['Makefile', 'makefile']) {
20
+ const make = Object.hasOwn(files, name) ? files[name] : undefined;
21
+ if (make && /^test\s*:/m.test(Buffer.from(make.data, make.encoding).toString('utf8'))) return ['make', 'test'];
22
+ }
23
+ }
24
+
25
+ async function materialize(directory: string, files: FileTree, budget?: FileBudget) {
26
+ await mkdir(directory, { recursive: true });
27
+ for (const { path, bytes, mode } of decodeFileTree(files, budget).entries) {
28
+ const file = join(directory, path);
29
+ await mkdir(dirname(file), { recursive: true });
30
+ await writeFile(file, bytes, { mode, flag: 'wx' });
31
+ }
32
+ }
33
+
34
+ export async function writeCodeDiff(outputDir: string, turn: number, changes: readonly CodeChange[], budget?: FileBudget, observed = false) {
35
+ if (!changes.length) return null;
36
+ const temp = await mkdtemp(join(outputDir, '.diff-'));
37
+ try {
38
+ await materialize(join(temp, 'before'), Object.fromEntries(changes.flatMap(({ path, before }) => before ? [[path, before]] : [])), budget);
39
+ await materialize(join(temp, 'after'), Object.fromEntries(changes.flatMap(({ path, after }) => after ? [[path, after]] : [])), budget);
40
+ const diff = await exec('git', ['--no-pager', 'diff', '--no-index', '--no-color', '--no-ext-diff', '--no-textconv', '--binary', '--', 'before', 'after'], {
41
+ cwd: temp, timeout: 15_000, maxBuffer: 64 * 1024 ** 2,
42
+ env: { PATH: process.env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' },
43
+ }).then(({ stdout }) => stdout, error => {
44
+ if (error.code === 1 && typeof error.stdout === 'string') return error.stdout;
45
+ throw error;
46
+ });
47
+ const path = join(outputDir, `code-turn-${turn}${observed ? '-observed' : ''}.patch`);
48
+ await writeFile(path, diff, { mode: 0o600, flag: 'wx' });
49
+ return { path, preview: Buffer.from(diff).subarray(0, 12 * 1024).toString('utf8') };
50
+ } finally { await rm(temp, { recursive: true, force: true }); }
51
+ }
52
+
53
+ export type CodeVerification = {
54
+ status: 'passed' | 'failed' | 'timed-out' | 'cancelled' | 'unverified' | 'stale' | 'candidate-modified' | 'dependency-environment-unavailable';
55
+ candidateDigest: CompleteFileDigest;
56
+ command: readonly string[] | null;
57
+ exitCode: number | null;
58
+ terminatedBy: NodeJS.Signals | null;
59
+ output: string;
60
+ };
61
+
62
+ async function unchangedCandidate(directory: string, files: FileTree, signal: AbortSignal, budget?: FileBudget) {
63
+ const examined = new Set<string>();
64
+ for (const { path, bytes, mode } of decodeFileTree(files, budget).entries) {
65
+ signal.throwIfAborted();
66
+ try {
67
+ let location = directory;
68
+ const parts = path.split('/');
69
+ for (const part of parts.slice(0, -1)) {
70
+ location = join(location, part);
71
+ if (!examined.has(location) && !(await lstat(location)).isDirectory()) return false;
72
+ examined.add(location);
73
+ }
74
+ const file = await open(join(location, parts.at(-1)!), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
75
+ try {
76
+ const stat = await file.stat();
77
+ if (!stat.isFile() || stat.size !== bytes.length || ((stat.mode & 0o111) !== 0 ? 0o755 : 0o644) !== mode ||
78
+ !(await file.readFile()).equals(bytes)) return false;
79
+ } finally { await file.close(); }
80
+ } catch { return false; }
81
+ }
82
+ return true;
83
+ }
84
+
85
+ class DependencyEnvironmentError extends Error {}
86
+
87
+ // Dependency copies have their own bounds because ignored installs are outside FileTree.
88
+ const dependencyLimits = { bytes: 256 * 1024 ** 2, entries: 50_000, ancestorDepth: 8 };
89
+
90
+ async function dependencyDirectories(projectDirectory: string, signal: AbortSignal) {
91
+ const project = await realpath(projectDirectory);
92
+ const directories = [project];
93
+ let parent = dirname(project);
94
+ for (let depth = 0; depth < dependencyLimits.ancestorDepth && parent !== dirname(parent); depth++) {
95
+ signal.throwIfAborted();
96
+ try {
97
+ const manifest = JSON.parse(await readFile(join(parent, 'package.json'), 'utf8'));
98
+ if (Array.isArray(manifest.workspaces) || Array.isArray(manifest.workspaces?.packages)) {
99
+ directories.push(parent);
100
+ break;
101
+ }
102
+ } catch (error) {
103
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error;
104
+ }
105
+ parent = dirname(parent);
106
+ }
107
+ return directories;
108
+ }
109
+
110
+ function dependencyIdentity(stat: BigIntStats) {
111
+ return [stat.dev, stat.ino, stat.mode, stat.size, stat.mtimeNs, stat.ctimeNs].join(':');
112
+ }
113
+
114
+ async function prepareDependencies(projectDirectory: string, temp: string, signal: AbortSignal) {
115
+ const directories = await dependencyDirectories(projectDirectory, signal);
116
+ const workspace = directories.at(-1)!;
117
+ const mirror = join(temp, 'dependencies');
118
+ const cwd = join(mirror, relative(workspace, directories[0]));
119
+ let totalBytes = 0;
120
+ let entries = 0;
121
+ const inventory = new Map<string, string>();
122
+ for (const directory of directories) {
123
+ signal.throwIfAborted();
124
+ const sourceRoot = join(directory, 'node_modules');
125
+ const sourceStat = await lstat(sourceRoot, { bigint: true }).catch(error => {
126
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
127
+ throw error;
128
+ });
129
+ if (!sourceStat) continue;
130
+ if (!sourceStat.isDirectory()) throw new DependencyEnvironmentError('DEPENDENCIES_UNSUPPORTED: node_modules must be a directory');
131
+ const targetRoot = join(mirror, relative(workspace, directory), 'node_modules');
132
+ async function copy(path: string) {
133
+ signal.throwIfAborted();
134
+ if (++entries > dependencyLimits.entries) throw new DependencyEnvironmentError('DEPENDENCIES_TOO_LARGE: copy exceeds 50,000 entries');
135
+ const source = join(sourceRoot, path);
136
+ const target = join(targetRoot, path);
137
+ const stat = await lstat(source, { bigint: true });
138
+ inventory.set(source, dependencyIdentity(stat));
139
+ if (stat.isDirectory()) {
140
+ await mkdir(target, { recursive: true });
141
+ for await (const entry of await opendir(source)) await copy(join(path, entry.name));
142
+ } else if (stat.isFile()) {
143
+ totalBytes += Number(stat.size);
144
+ if (totalBytes > dependencyLimits.bytes) throw new DependencyEnvironmentError('DEPENDENCIES_TOO_LARGE: copy exceeds 256 MiB');
145
+ await copyFile(source, target, constants.COPYFILE_FICLONE);
146
+ } else if (stat.isSymbolicLink()) {
147
+ const actual = await realpath(source);
148
+ const local = relative(sourceRoot, actual);
149
+ if (local === '..' || local.startsWith('../') || isAbsolute(local)) {
150
+ throw new DependencyEnvironmentError('DEPENDENCIES_UNSUPPORTED: installed package link escapes node_modules');
151
+ }
152
+ await symlink(relative(dirname(target), join(targetRoot, local)), target);
153
+ } else throw new DependencyEnvironmentError('DEPENDENCIES_UNSUPPORTED: install contains a special file');
154
+ }
155
+ await copy('');
156
+ }
157
+ const localModules = join(cwd, 'node_modules');
158
+ if (directories.length > 1 && !(await lstat(localModules).catch(() => undefined))) {
159
+ const hoisted = join(mirror, 'node_modules');
160
+ if (await lstat(hoisted).catch(() => undefined)) {
161
+ await mkdir(cwd, { recursive: true });
162
+ await symlink(relative(cwd, hoisted), localModules);
163
+ }
164
+ }
165
+ for (const [path, identity] of inventory) {
166
+ signal.throwIfAborted();
167
+ if (dependencyIdentity(await lstat(path, { bigint: true })) !== identity) {
168
+ throw new DependencyEnvironmentError('DEPENDENCIES_CHANGED: installed dependencies changed during copying');
169
+ }
170
+ }
171
+ return cwd;
172
+ }
173
+
174
+ export async function verifyCodeCandidate(outputDir: string, candidate: { files: FileTree; digest: CompleteFileDigest },
175
+ command: readonly string[] | undefined, timeoutMs: number, signal: AbortSignal, budget?: FileBudget, projectDirectory?: string): Promise<CodeVerification> {
176
+ const evidence = { candidateDigest: candidate.digest, command: command ?? null, exitCode: null, terminatedBy: null, output: '' };
177
+ if (!command) return { ...evidence, status: 'unverified' };
178
+
179
+ const temp = await mkdtemp(join(outputDir, '.verify-'));
180
+ const started = performance.now();
181
+ const preparation = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
182
+ try {
183
+ let cwd = join(temp, 'project');
184
+ if (projectDirectory && Object.hasOwn(candidate.files, 'package.json')) {
185
+ try { cwd = await prepareDependencies(projectDirectory, temp, preparation); }
186
+ catch (error) {
187
+ if (signal.aborted) return { ...evidence, status: 'cancelled' };
188
+ if (preparation.aborted) return { ...evidence, status: 'timed-out', output: 'Dependency environment preparation exceeded the check deadline' };
189
+ return { ...evidence, status: 'dependency-environment-unavailable', output: error instanceof DependencyEnvironmentError
190
+ ? error.message : 'DEPENDENCIES_UNAVAILABLE: installed dependencies could not be copied safely' };
191
+ }
192
+ }
193
+ await mkdir(dirname(cwd), { recursive: true });
194
+ await materialize(cwd, candidate.files, budget);
195
+ await mkdir(join(temp, 'home'));
196
+ signal.throwIfAborted();
197
+ const env = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: join(temp, 'home'), TMPDIR: temp, CI: 'true', LC_ALL: 'C' };
198
+ if (/^npm(?:\.cmd)?$/.test(basename(command[0])) && command.includes('test')) {
199
+ try {
200
+ await exec(command[0], ['ls', '--offline', '--depth=0', '--json'], { cwd, env, signal: preparation,
201
+ timeout: Math.max(1, Math.ceil(timeoutMs - (performance.now() - started))), maxBuffer: 64 * 1024 });
202
+ } catch (error) {
203
+ if (signal.aborted) return { ...evidence, status: 'cancelled' };
204
+ if (preparation.aborted) return { ...evidence, status: 'timed-out', output: 'Dependency environment validation exceeded the check deadline' };
205
+ return { ...evidence, status: 'dependency-environment-unavailable', output: 'DEPENDENCIES_MISSING_OR_INVALID: npm test needs installed dependencies matching package.json. Prepare the project install and retry.\n' +
206
+ String((error as { stderr?: string }).stderr ?? '').slice(-4096) };
207
+ }
208
+ }
209
+ const remaining = timeoutMs - (performance.now() - started);
210
+ if (remaining <= 0) return { ...evidence, status: 'timed-out' };
211
+ const child = spawn(command[0], command.slice(1), { cwd, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env });
212
+ let output = Buffer.alloc(0);
213
+ const consume = (data: Buffer) => { output = Buffer.concat([output, data]).subarray(-8192); };
214
+ child.stdout.on('data', consume);
215
+ child.stderr.on('data', consume);
216
+ let stop: 'timed-out' | 'cancelled' | undefined;
217
+ const kill = () => {
218
+ if (!child.pid) return;
219
+ try { process.kill(-child.pid, 'SIGKILL'); }
220
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error; }
221
+ };
222
+ const cancel = () => { stop ??= 'cancelled'; kill(); };
223
+ const timer = setTimeout(() => { stop ??= 'timed-out'; kill(); }, remaining);
224
+ signal.addEventListener('abort', cancel, { once: true });
225
+ try {
226
+ const verification = await new Promise<CodeVerification>(resolve => {
227
+ child.once('error', (error: NodeJS.ErrnoException) => resolve({ ...evidence, status: stop ?? 'failed', output: error.code ?? 'CHECK_SPAWN_FAILED' }));
228
+ child.once('exit', kill);
229
+ child.once('close', (exitCode, terminatedBy) => resolve({ ...evidence, status: stop ?? (exitCode === 0 ? 'passed' : 'failed'),
230
+ exitCode, terminatedBy, output: output.toString('utf8') }));
231
+ if (signal.aborted) cancel();
232
+ });
233
+ if (verification.status === 'passed' && (!await unchangedCandidate(cwd, candidate.files, signal, budget))) {
234
+ return { ...verification, status: 'candidate-modified' };
235
+ }
236
+ return verification;
237
+ } finally { clearTimeout(timer); signal.removeEventListener('abort', cancel); }
238
+ } finally { await rm(temp, { recursive: true, force: true }); }
239
+ }
@@ -0,0 +1,188 @@
1
+ import { constants, type BigIntStats } from 'node:fs';
2
+ import { chmod, link, lstat, mkdir, mkdtemp, open, rename, rm, rmdir, unlink, writeFile, type FileHandle } from 'node:fs/promises';
3
+ import { basename, join } from 'node:path';
4
+ import { isGitTreePath, type FileEntry } from '@anyswarm/core';
5
+ import type { CodeChange } from './candidate.js';
6
+
7
+ const directoryFlags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
8
+ const fileFlags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
9
+ const anchored = (directory: FileHandle, name: string) => `/proc/self/fd/${directory.fd}/${name}`;
10
+ const code = (error: unknown) => (error as NodeJS.ErrnoException)?.code;
11
+ const bytes = (entry: FileEntry) => Buffer.from(entry.data, entry.encoding);
12
+
13
+ class WorktreeConflict extends Error {
14
+ constructor(readonly path: string) { super(`Worktree changed at ${JSON.stringify(path)}`); }
15
+ }
16
+
17
+ type ApplyResult = { status: 'applied'; paths: readonly string[]; recoveryDirectory?: string } |
18
+ { status: 'conflict'; paths: readonly string[] } |
19
+ { status: 'recovery-required'; paths: readonly string[]; recoveryDirectory: string; reason: string };
20
+
21
+ function sameInode(a: BigIntStats, b: BigIntStats) {
22
+ return a.dev === b.dev && a.ino === b.ino;
23
+ }
24
+
25
+ async function expectFile(target: string, path: string, expected: FileEntry | undefined) {
26
+ const listed = await lstat(target, { bigint: true }).catch(error => {
27
+ if (code(error) === 'ENOENT') return undefined;
28
+ throw error;
29
+ });
30
+ if (!listed && !expected) return;
31
+ if (!listed?.isFile() || listed.nlink !== 1n || !expected || listed.size !== BigInt(bytes(expected).length) ||
32
+ ((listed.mode & 0o111n) !== 0n) !== (expected.mode === 0o755)) throw new WorktreeConflict(path);
33
+ const handle = await open(target, fileFlags).catch(error => {
34
+ if (code(error) === 'ENOENT' || code(error) === 'ELOOP') throw new WorktreeConflict(path);
35
+ throw error;
36
+ });
37
+ try {
38
+ const before = await handle.stat({ bigint: true });
39
+ if (!sameInode(listed, before) || before.size !== listed.size || before.ctimeNs !== listed.ctimeNs) throw new WorktreeConflict(path);
40
+ const wanted = bytes(expected);
41
+ const actual = Buffer.alloc(wanted.length + 1);
42
+ let offset = 0;
43
+ while (offset < actual.length) {
44
+ const { bytesRead } = await handle.read(actual, offset, actual.length - offset, offset);
45
+ if (bytesRead === 0) break;
46
+ offset += bytesRead;
47
+ }
48
+ const after = await handle.stat({ bigint: true });
49
+ if (offset !== wanted.length || !actual.subarray(0, offset).equals(wanted) ||
50
+ before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) throw new WorktreeConflict(path);
51
+ return after;
52
+ } finally { await handle.close(); }
53
+ }
54
+
55
+ async function inParent<T>(root: FileHandle, path: string, work: (target: string | undefined, parent: FileHandle) => Promise<T>,
56
+ create?: Set<string>) {
57
+ const parts = path.split('/');
58
+ let directory = root;
59
+ try {
60
+ for (const [index, part] of parts.slice(0, -1).entries()) {
61
+ const at = anchored(directory, part);
62
+ if (create) {
63
+ await mkdir(at).then(() => create.add(parts.slice(0, index + 1).join('/')), error => {
64
+ if (code(error) !== 'EEXIST') throw error;
65
+ });
66
+ }
67
+ const child = await open(at, directoryFlags).catch(error => {
68
+ if (code(error) === 'ENOENT') return undefined;
69
+ if (code(error) === 'ENOTDIR' || code(error) === 'ELOOP') throw new WorktreeConflict(path);
70
+ throw error;
71
+ });
72
+ if (!child) return await work(undefined, directory);
73
+ if (directory !== root) await directory.close();
74
+ directory = child;
75
+ }
76
+ return await work(anchored(directory, parts.at(-1)!), directory);
77
+ } finally { if (directory !== root) await directory.close(); }
78
+ }
79
+
80
+ function outputMode(after: FileEntry, original?: BigIntStats) {
81
+ if (!original) return after.mode ?? 0o644;
82
+ const mode = Number(original.mode) & 0o777;
83
+ if ((mode & 0o111) !== 0) return after.mode === 0o755 ? mode : mode & ~0o111;
84
+ return after.mode === 0o755 ? mode | 0o100 : mode;
85
+ }
86
+
87
+ /** Install only the prepared paths. Moving originals into staging lets us detect a concurrent replacement before publishing. */
88
+ export async function applyCodeChanges(cwd: string, outputDir: string, changes: readonly CodeChange[], signal?: AbortSignal): Promise<ApplyResult> {
89
+ if (changes.some(change => !isGitTreePath(change.path) || change.path.startsWith('.anyswarm-code-recovery-') || (!change.before && !change.after)) ||
90
+ new Set(changes.map(change => change.path)).size !== changes.length) throw new TypeError('Invalid Code write set');
91
+ const root = await open(cwd, directoryFlags);
92
+ let stage: string | undefined;
93
+ let preserveStage = false;
94
+ try {
95
+ const conflicts: string[] = [];
96
+ for (const change of changes) {
97
+ signal?.throwIfAborted();
98
+ await inParent(root, change.path, async target => {
99
+ if (target) await expectFile(target, change.path, change.before);
100
+ else if (change.before) throw new WorktreeConflict(change.path);
101
+ }).catch(error => {
102
+ if (!(error instanceof WorktreeConflict)) throw error;
103
+ conflicts.push(error.path);
104
+ });
105
+ }
106
+ if (conflicts.length) return { status: 'conflict', paths: conflicts };
107
+ if (changes.length === 0) return { status: 'applied', paths: [] };
108
+
109
+ stage = await mkdtemp(anchored(root, '.anyswarm-code-recovery-'));
110
+ const created = new Set<string>();
111
+ const journal: { change: CodeChange; parent: BigIntStats; backup?: string; published: boolean }[] = [];
112
+ try {
113
+ await writeFile(join(stage, 'paths.json'), JSON.stringify(changes.map(({ path, before }, index) => ({ path,
114
+ original: before ? `original-${index}` : null }))) + '\n', { flag: 'wx', mode: 0o600 });
115
+ for (const [index, change] of changes.entries()) {
116
+ signal?.throwIfAborted();
117
+ if (!sameInode(await root.stat({ bigint: true }), await lstat(cwd, { bigint: true }))) throw new WorktreeConflict(change.path);
118
+ await inParent(root, change.path, async (target, parent) => {
119
+ if (!target) throw new WorktreeConflict(change.path);
120
+ const original = await expectFile(target, change.path, change.before);
121
+ const item: typeof journal[number] = { change, parent: await parent.stat({ bigint: true }), published: false };
122
+ journal.push(item);
123
+ const incoming = join(stage!, `new-${index}`);
124
+ if (change.after) {
125
+ const mode = outputMode(change.after, original);
126
+ await writeFile(incoming, bytes(change.after), { mode, flag: 'wx' });
127
+ if (original) await chmod(incoming, mode);
128
+ }
129
+ if (original) {
130
+ const backup = join(stage!, `original-${index}`);
131
+ await rename(target, backup);
132
+ item.backup = backup;
133
+ const saved = await expectFile(backup, change.path, change.before);
134
+ if (!saved || !sameInode(original, saved) || saved.mode !== original.mode) throw new WorktreeConflict(change.path);
135
+ }
136
+ if (change.after) {
137
+ try { await link(incoming, target); }
138
+ catch (error) { if (code(error) === 'EEXIST') throw new WorktreeConflict(change.path); throw error; }
139
+ item.published = true;
140
+ await unlink(incoming);
141
+ }
142
+ }, change.before ? undefined : created);
143
+ }
144
+ const paths = changes.map(change => change.path);
145
+ if (!journal.some(item => item.backup)) return { status: 'applied', paths };
146
+ // An existing writer can still hold the moved inode open. Keep that inode
147
+ // recoverable rather than deleting later writes through the open handle.
148
+ preserveStage = true;
149
+ const name = basename(stage);
150
+ const moved = await rename(stage, join(outputDir, name)).then(() => true, () => false);
151
+ return { status: 'applied', paths, recoveryDirectory: join(moved ? outputDir : cwd, name) };
152
+ } catch (error) {
153
+ const unresolved: string[] = [];
154
+ for (const [index, { change, parent, backup, published }] of journal.reverse().entries()) {
155
+ if (!backup && !published) continue;
156
+ try {
157
+ await inParent(root, change.path, async (target, directory) => {
158
+ if (!target || !sameInode(parent, await directory.stat({ bigint: true }))) throw new WorktreeConflict(change.path);
159
+ if (published) {
160
+ const undo = join(stage!, `undo-${index}`);
161
+ await rename(target, undo);
162
+ try { await expectFile(undo, change.path, change.after); }
163
+ catch (conflict) {
164
+ await link(undo, target);
165
+ await unlink(undo);
166
+ throw conflict;
167
+ }
168
+ }
169
+ if (backup) await link(backup, target);
170
+ });
171
+ } catch { unresolved.push(change.path); }
172
+ }
173
+ for (const path of [...created].reverse()) {
174
+ await inParent(root, path, async target => { if (target) await rmdir(target); }).catch(() => {});
175
+ }
176
+ if (unresolved.length) {
177
+ preserveStage = true;
178
+ return { status: 'recovery-required', paths: unresolved, recoveryDirectory: join(cwd, basename(stage)),
179
+ reason: error instanceof WorktreeConflict ? error.message : code(error) ?? 'APPLICATION_FAILED' };
180
+ }
181
+ if (error instanceof WorktreeConflict) return { status: 'conflict', paths: [error.path] };
182
+ throw error;
183
+ }
184
+ } finally {
185
+ try { if (stage && !preserveStage) await rm(stage, { recursive: true, force: true }); }
186
+ finally { await root.close(); }
187
+ }
188
+ }
@@ -12,15 +12,12 @@ outside the checkout. Copy the example from that SDK.
12
12
  ```sh
13
13
  npm init -y
14
14
  npm install --ignore-scripts "${ANYSWARM_SDK_ARCHIVE:-@anyswarm/core@0.5.0}"
15
- npm install --save-dev typescript @types/node
16
15
  sdk=node_modules/@anyswarm/core
17
16
  cp -R "$sdk"/examples/harness-session demo
18
17
  cd demo
19
- npm run check
20
- npm run build
21
- npm run sdk -- /absolute/path/to/project 'Run the direct SDK example'
22
- npm run rpc -- /absolute/path/to/project 'Run the RPC example'
23
- npm start -- /absolute/path/to/project 'Ask me the two business questions'
18
+ ../node_modules/.bin/anyswarm run ./sdk.ts /absolute/path/to/project 'Run the direct SDK example'
19
+ ../node_modules/.bin/anyswarm run ./rpc.ts /absolute/path/to/project 'Run the RPC example'
20
+ ../node_modules/.bin/anyswarm run ./terminal.ts /absolute/path/to/project 'Ask me the two business questions'
24
21
  ```
25
22
 
26
23
  The SDK and RPC programs answer both questions and send a subsequent input
@@ -1,19 +1,20 @@
1
1
  import type { createBoard } from '../services/board.js';
2
2
 
3
3
  type Notice = {
4
- kind: 'task' | 'member-ready' | 'feedback' | 'delivery' | 'incomplete';
4
+ kind: 'task' | 'member-ready' | 'feedback' | 'delivery' | 'incomplete' | 'user-intervention';
5
5
  id: string | number;
6
6
  taskId?: string;
7
7
  revision?: number;
8
8
  agentId?: string;
9
9
  };
10
10
 
11
- export async function runDynamicSchedule({ board, team, goal, signal, dispatch }: {
11
+ export async function runDynamicSchedule({ board, team, goal, signal, dispatch, canDispatch = () => true }: {
12
12
  board: ReturnType<typeof createBoard>;
13
13
  team: Record<string, string>;
14
14
  goal: string;
15
15
  signal: AbortSignal;
16
16
  dispatch(role: string, requestId: string, message: unknown, signal: AbortSignal): Promise<unknown>;
17
+ canDispatch?(agentId: string): boolean;
17
18
  }) {
18
19
  const pending = new Map<string, Map<string, Notice>>();
19
20
  const active = new Set<string>();
@@ -65,13 +66,15 @@ export async function runDynamicSchedule({ board, team, goal, signal, dispatch }
65
66
  }
66
67
  } else if (event.type === 'member_ready') {
67
68
  queue(lead, { kind: 'member-ready', id: event.seq, agentId: event.actor });
69
+ } else if (event.type === 'user_control' && event.actor !== lead) {
70
+ queue(lead, { kind: 'user-intervention', id: event.seq, agentId: event.actor });
68
71
  } else if (event.actor !== lead && ['note', 'landed', 'complete'].includes(event.type)) {
69
72
  queue(lead, { kind: event.type === 'note' ? 'feedback' : 'delivery', id: event.seq,
70
73
  taskId: event.subtaskId ?? event.subtask_id, agentId: event.actor });
71
74
  }
72
75
  }
73
76
  for (const [agentId, notices] of pending) {
74
- if (!state.members[agentId]?.ready || active.has(agentId)) continue;
77
+ if (!state.members[agentId]?.ready || active.has(agentId) || !canDispatch(agentId)) continue;
75
78
  pending.delete(agentId);
76
79
  const updates = [...notices.values()].filter(notice => notice.kind !== 'task' ||
77
80
  state.subtasks.some((row: any) => row.id === notice.id && row.state === 'ready'));
@@ -1,6 +1,6 @@
1
1
  import { mkdir } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
- import { createRuntime, ServiceRegistry, createOwnedResources, seededCheckoutInstruction, runInput, runWithReport } from '@anyswarm/core';
3
+ import { createRuntime, getExecutorCapabilities, ServiceRegistry, createOwnedResources, seededCheckoutInstruction, runInput, runWithReport } from '@anyswarm/core';
4
4
  import { createBoard, boardPermissions, projectBoardPermissions } from '../services/board.js';
5
5
  import { leadWorkerRoles } from './team.js';
6
6
  import { createDynamicLeadWorker, dynamicServices, type DynamicLeadWorkerOptions } from './dynamic.js';
@@ -33,13 +33,57 @@ export async function createLeadWorkerHarness(options: any) {
33
33
  let dynamicControl: ReturnType<typeof createDynamicLeadWorker> | undefined;
34
34
  let runtime: any; let board: any; let git: any; let unsubscribe: any; let closing = false; let closeWork: any; let complete: any; let workflowUsed = false; let boardFenceFailure: any;
35
35
  const pendingFences: any = new Map(); const activeInputs: any = new Set();
36
+ const pendingMemberControls = new Map<string, { kind: 'interrupt' | 'stop'; requestId: string }>();
37
+ function recordMemberControl(agentId: string, control: { kind: 'interrupt' | 'stop'; requestId: string }) {
38
+ try { board.interveneMember({ agentId, ...control }); pendingMemberControls.delete(agentId); }
39
+ catch { pendingMemberControls.set(agentId, control); }
40
+ }
41
+ const userControls = new Map<string, { kind: 'interrupt' | 'stop'; requestId: string }>();
42
+ const heldMembers = new Map<string, ReturnType<typeof Promise.withResolvers<void>>>();
43
+ async function waitForMember(agentId: string, signal: AbortSignal) {
44
+ if (userControls.get(agentId)?.kind !== 'interrupt') return;
45
+ let waiting = heldMembers.get(agentId);
46
+ if (!waiting) heldMembers.set(agentId, waiting = Promise.withResolvers<void>());
47
+ const abort = () => waiting!.reject(fail('WORKFLOW_STOPPED'));
48
+ signal.addEventListener('abort', abort, { once: true });
49
+ try { signal.throwIfAborted(); await waiting.promise; }
50
+ finally { signal.removeEventListener('abort', abort); }
51
+ }
52
+ const memberControls = {
53
+ capabilities: {
54
+ send: { supported: getExecutorCapabilities(executor ?? 'pi').activeSteer, text: true, modes: ['steer'] },
55
+ interrupt: { supported: getExecutorCapabilities(executor ?? 'pi').queuedInputCancellation },
56
+ stop: { supported: true },
57
+ },
58
+ handlers: {
59
+ send(agentId: string, payload: any, request: any) {
60
+ const { input, options } = payload;
61
+ return runtime.send(agentId, input, { ...options, requestId: request.operationId });
62
+ },
63
+ async interrupt(agentId: string, _payload: any, request: any) {
64
+ const control = { kind: 'interrupt' as const, requestId: request.requestId };
65
+ userControls.set(agentId, control);
66
+ recordMemberControl(agentId, control);
67
+ const core = await runtime.interrupt(agentId, { requestId: request.operationId });
68
+ return { core, harnessEffects: { held: true, rescheduled: false, boardRecorded: !pendingMemberControls.has(agentId) } };
69
+ },
70
+ async stop(agentId: string, payload: any, request: any) {
71
+ const control = { kind: 'stop' as const, requestId: request.requestId };
72
+ userControls.set(agentId, control);
73
+ recordMemberControl(agentId, control);
74
+ heldMembers.get(agentId)?.resolve();
75
+ const core = await runtime.stop(agentId, { requestId: request.operationId, reason: payload?.reason });
76
+ return { core, harnessEffects: { stopped: true, rescheduled: false, boardRecorded: !pendingMemberControls.has(agentId) } };
77
+ },
78
+ },
79
+ };
36
80
  const team: any = {}; const inputs: any[] = []; const events: any[] = [];
37
81
  const stages: any[] = []; const rejections: any[] = []; let stageActive = false; let preparedStages: any;
38
82
  const redact = (value: any) => { let body = JSON.stringify(value); for (const secret of [...secrets].sort((a: any, b: any) => b.length - a.length)) body = body.split(JSON.stringify(secret).slice(1, -1)).join('[redacted]'); return JSON.parse(body); };
39
83
  const snapshot = () => {
40
84
  let publicBoard: any; let boardReadFailure: any;
41
85
  try { publicBoard = board?.snapshot(); } catch { boardReadFailure = { code: 'BOARD_READ_FAILED' }; }
42
- return { runId, runtimeId: runtime?.id, initialCommit, initialDigest: options.initialDigest, boardPath, team: { ...team }, stages: structuredClone(stages), rejections: structuredClone(rejections), preparation: structuredClone(preparedStages ?? null), git: git?.identities(), board: publicBoard, ...(boardReadFailure ? { boardReadFailure } : {}), inputs: structuredClone(inputs), events: structuredClone(events),
86
+ return { userControls: Object.fromEntries(userControls), pendingMemberControls: Object.fromEntries(pendingMemberControls), runId, runtimeId: runtime?.id, initialCommit, initialDigest: options.initialDigest, boardPath, team: { ...team }, stages: structuredClone(stages), rejections: structuredClone(rejections), preparation: structuredClone(preparedStages ?? null), git: git?.identities(), board: publicBoard, ...(boardReadFailure ? { boardReadFailure } : {}), inputs: structuredClone(inputs), events: structuredClone(events),
43
87
  delivered: publicBoard?.subtasks.filter((row: any) => row.delivery?.verified) ?? [], unfinished: publicBoard?.subtasks.filter((row: any) => row.state !== 'complete') ?? [], inputUnknown: inputs.filter((row: any) => row.uncertain).map((row: any) => ({ agentId: row.agentId, requestId: row.requestId, inputId: row.inputId, code: row.code })), resources: resources.snapshot(),
44
88
  ...(boardFenceFailure ? { boardFenceFailure, pendingBoardFailures: [...pendingFences.values()] } : {}), ...(dynamicControl ? { dynamic: dynamicControl.snapshot() } : {}),
45
89
  limitations: ['Local SQLite Board and exclusive turn controller', dynamic ? 'One dynamic member and no claim reclamation' : 'Fixed preconfigured team; no replacement or claim reclamation', 'Upstream scale and performance not verified'] };
@@ -67,7 +111,8 @@ export async function createLeadWorkerHarness(options: any) {
67
111
  for (const [agentId, failure] of pendingFences) failures.set(agentId, failure);
68
112
  for (const [agentId, failure] of failures) recordFence({ agentId, code: failure.code, execution: core.agents?.find((row: any) => row.agentId === agentId)?.execution === 'stopped' ? 'stopped' : 'unknown' });
69
113
  if (boardFenceFailure) recordFence();
70
- if (boardReadFailed || boardFenceFailure || pendingFences.size) return { ...core, cleanup: 'pending', harness: { cleanup: 'pending', pending: [{ kind: 'board-evidence', id: boardPath, action: 'persist-failure', error: { code: 'BOARD_FENCE_FAILED' } }], resources: resources.snapshot() } };
114
+ for (const [agentId, control] of pendingMemberControls) recordMemberControl(agentId, control);
115
+ if (boardReadFailed || boardFenceFailure || pendingFences.size || pendingMemberControls.size) return { ...core, cleanup: 'pending', harness: { cleanup: 'pending', pending: [{ kind: 'board-evidence', id: boardPath, action: 'persist-failure', error: { code: 'BOARD_FENCE_FAILED' } }], resources: resources.snapshot() } };
71
116
  if (core.cleanup !== 'complete' || core.agents.some((row: any) => row.execution !== 'stopped' || row.cleanup !== 'complete')) return { ...core, harness: { cleanup: 'pending', pending: resources.snapshot().filter((row: any) => !['closed', 'retained'].includes(row.state)) } };
72
117
  if (dynamicControl && !await dynamicControl.settled(timeoutMs)) {
73
118
  return { ...core, cleanup: 'pending', harness: { cleanup: 'pending', resources: resources.snapshot(),
@@ -80,14 +125,23 @@ export async function createLeadWorkerHarness(options: any) {
80
125
  }
81
126
  const dispatch = async (role: any, requestId: any, payload: any, workSignal: any, deadlineAtMs?: number) => {
82
127
  if (workSignal.aborted || closing) throw fail('WORKFLOW_STOPPED');
128
+ await waitForMember(team[role], workSignal);
129
+ if (userControls.get(team[role])?.kind === 'stop') return { status: 'user-stopped' };
83
130
  const timeoutMs = deadlineAtMs === undefined ? turnTimeoutMs : Math.ceil(deadlineAtMs - performance.now());
84
131
  if (timeoutMs < 1) throw fail('WORKFLOW_STOPPED');
85
132
  const row: any = { role, agentId: team[role], requestId, source: payload.type,
86
133
  ...(dynamic && payload.type === 'board-updates' ? { boardRevision: payload.revision, updates: structuredClone(payload.updates) } : {}) };
87
134
  inputs.push(row); activeInputs.add(team[role]);
88
135
  try {
89
- const result = await runInput(runtime, team[role], JSON.stringify(payload), { requestId, timeoutMs, signal: workSignal }); Object.assign(row, { inputId: result.inputId, receipt: result.receipt, state: 'completed', settled: { agentId: result.settled.agentId, outcome: result.settled.outcome } }); return result;
136
+ const result = await runInput(runtime, team[role], JSON.stringify(payload), { requestId, timeoutMs, signal: workSignal,
137
+ beforeSend() { if (userControls.has(team[role])) throw fail('MEMBER_HELD'); },
138
+ }); Object.assign(row, { inputId: result.inputId, receipt: result.receipt, state: 'completed', settled: { agentId: result.settled.agentId, outcome: result.settled.outcome } }); return result;
90
139
  } catch (error: any) { Object.assign(row, { inputId: error.inputId, receipt: error.receipt, state: 'failed', code: error.code ?? 'INPUT_FAILED', uncertain: !['input_failed', 'input_aborted'].includes(error.code) });
140
+ if (userControls.has(team[role])) {
141
+ row.state = userControls.get(team[role])!.kind === 'stop' ? 'user-stopped' : 'user-interrupted';
142
+ await waitForMember(team[role], workSignal);
143
+ return { status: row.state };
144
+ }
91
145
  if (dynamic && error.code === 'input_unknown') {
92
146
  const recorded = runtime.send(team[role], JSON.stringify(payload), { requestId, mode: 'followUp' });
93
147
  try { row.reconciledReceipt = await recorded; } catch { /* preserve original uncertainty */ }
@@ -131,10 +185,11 @@ export async function createLeadWorkerHarness(options: any) {
131
185
  }));
132
186
  runtime = await createRuntime({ sandbox, executor, models, connection, filePolicy, services, profiles, maxAgents: roles.length + (dynamic ? 1 : 0), outputDir, ...(dynamicControl ? { agentAccessPolicy: dynamicControl.agentAccessPolicy } : {}) });
133
187
  if (startup.aborted) throw fail('HARNESS_START_ABORTED');
134
- options.onRuntime?.(runtime, snapshot, board.subscribe);
188
+ options.onRuntime?.(runtime, snapshot, board.subscribe, memberControls);
135
189
  unsubscribe = runtime.onEvent((event: any) => {
136
190
  if (event.type === 'session') return;
137
191
  if (events.length < (dynamic ? 2048 : 256)) events.push({ agentId: event.agentId, seq: events.length + 1, type: event.type, ...(event.outcome ? { outcome: event.outcome } : {}) });
192
+ if (userControls.has(event.agentId) && (event.type === 'settled' && event.outcome === 'aborted' || event.type === 'exit')) return;
138
193
  if (!dynamic && events.length >= 256 || event.type === 'error' && event.fatal || event.type === 'settled' && event.outcome !== 'completed' || event.type === 'exit' && !event.expected) {
139
194
  if (!closing) { recordFence({ agentId: event.agentId, code: 'AGENT_FAILED' });
140
195
  // The exclusive helper owns terminal-event/late-receipt ordering.
@@ -157,7 +212,7 @@ export async function createLeadWorkerHarness(options: any) {
157
212
  const workSignal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(workTimeoutMs), ...(signal ? [signal] : [])]);
158
213
  try {
159
214
  workSignal.throwIfAborted();
160
- const submitted = await runDynamicSchedule({ board, team, goal: dynamic.goal, signal: workSignal, dispatch: dispatchWork });
215
+ const submitted = await runDynamicSchedule({ board, team, goal: dynamic.goal, signal: workSignal, dispatch: dispatchWork, canDispatch: agentId => !userControls.has(agentId) });
161
216
  if (!dynamic.verifyFinal) return { submitted, harness: snapshot() };
162
217
  const verdict = await dynamic.verifyFinal({ repositoryUrl: facilities.repositoryUrl, token: facilities.actors.lead.token,
163
218
  commit: submitted.delivery.commit, sha256: submitted.delivery.sha256, signal: workSignal, resources });
@@ -45,8 +45,8 @@ const leadWorker = {
45
45
  ...config, sandbox, runId: context.runId.replaceAll('-', '').slice(0, 24), outputDir: context.outputDir,
46
46
  signal: context.signal, projectFiles: context.initial.files, initialDigest: context.initial.digest,
47
47
  dynamic: deploy ? { goal: context.input.prompt, projectFiles: context.initial.files, deploy } : undefined,
48
- onRuntime: (runtime: Parameters<typeof observeProjectRuntime>[0], snapshot: () => unknown, subscribeBoard: (listener: () => void) => () => void) => {
49
- observation = observeProjectRuntime(runtime, context, snapshot);
48
+ onRuntime: (runtime: Parameters<typeof observeProjectRuntime>[0], snapshot: () => unknown, subscribeBoard: (listener: () => void) => () => void, controls: Parameters<typeof observeProjectRuntime>[3]) => {
49
+ observation = observeProjectRuntime(runtime, context, snapshot, controls);
50
50
  unsubscribeBoard = subscribeBoard(() => { void observation?.refresh(); });
51
51
  },
52
52
  beforeInitialDispatch: () => context.markRunning(),