@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
@@ -1,186 +1,12 @@
1
- import { execFile, spawn } from 'node:child_process';
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { constants, createReadStream } from 'node:fs';
4
- import { access, mkdir, mkdtemp, readFile, readlink, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises';
5
- import { homedir } from 'node:os';
6
- import { basename, dirname, join, relative, resolve } from 'node:path';
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile, realpath } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
7
4
  import { fileURLToPath } from 'node:url';
8
5
  import { promisify } from 'node:util';
9
6
 
10
7
  const execute = promisify(execFile);
11
8
  const packageName = '@anyswarm/core';
12
- const previousPackageNames = ['@anyswarm/anyswarm', '@luna-shi/anyswarm'];
13
9
  const packageRoot = resolve(fileURLToPath(new URL('../..', import.meta.url)));
14
- const releaseRoot = 'https://github.com/AnySwarm/anyswarm/releases/download';
15
- const stableVersion = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
16
- const bins = ['anyswarm', 'swarm'] as const;
17
- const installDirectory = (prefix: string) => join(prefix, 'lib', 'anyswarm');
18
- const installedPackage = (stage: string) => join(stage, 'node_modules', packageName);
19
- const installBin = (prefix: string, name: typeof bins[number]) => join(prefix, 'bin', name);
20
-
21
- type Installation = {
22
- schema: 1;
23
- version: string;
24
- prefix: string;
25
- source: string;
26
- sha256: string;
27
- };
28
-
29
- async function manifest(root: string): Promise<{ name: string; version: string }> {
30
- return JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
31
- }
32
-
33
- export async function archiveDigest(path: string) {
34
- const hash = createHash('sha256');
35
- for await (const chunk of createReadStream(path)) hash.update(chunk);
36
- return hash.digest('hex');
37
- }
38
-
39
- async function replaceLink(path: string, target: string) {
40
- const temporary = join(dirname(path), `.anyswarm-link-${randomUUID()}`);
41
- try {
42
- await symlink(target, temporary);
43
- await rename(temporary, path);
44
- } finally {
45
- await rm(temporary, { force: true });
46
- }
47
- }
48
-
49
- async function inspectLink(path: string) {
50
- try { return await readlink(path); }
51
- catch (error) {
52
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
53
- if ((error as NodeJS.ErrnoException).code === 'EINVAL') throw new Error(`The regular file at ${path} belongs to another installation.`);
54
- throw error;
55
- }
56
- }
57
-
58
- function currentPath(prefix: string) {
59
- return join(installDirectory(prefix), 'current');
60
- }
61
-
62
- function binTarget(prefix: string, name: typeof bins[number]) {
63
- return relative(join(prefix, 'bin'), join(currentPath(prefix), 'node_modules', '.bin', name));
64
- }
65
-
66
- async function lockActivation<T>(prefix: string, action: () => Promise<T>, signal?: AbortSignal) {
67
- signal?.throwIfAborted();
68
- const lock = join(installDirectory(prefix), 'activation-flock');
69
- const child = spawn('flock', ['--exclusive', '--timeout', '15', lock, process.execPath, '-e',
70
- 'console.log("locked"); process.stdin.resume()'], { stdio: ['pipe', 'pipe', 'ignore'] });
71
- child.stdin.on('error', () => {});
72
- const cancelled = () => child.kill();
73
- signal?.addEventListener('abort', cancelled, { once: true });
74
- if (signal?.aborted) cancelled();
75
- try {
76
- await new Promise<void>((ready, reject) => {
77
- child.once('error', reject);
78
- child.once('exit', () => reject(new Error('The installation is busy. Retry after the other activation finishes.')));
79
- child.stdout.once('data', () => ready());
80
- });
81
- signal?.removeEventListener('abort', cancelled);
82
- signal?.throwIfAborted();
83
- return await action();
84
- } finally {
85
- signal?.removeEventListener('abort', cancelled);
86
- child.stdin.end();
87
- }
88
- }
89
-
90
- async function activate(prefix: string, stage: string, source: string, sha256: string, signal?: AbortSignal, expected?: string) {
91
- const root = installedPackage(stage);
92
- const { name, version } = await manifest(root);
93
- if (name !== packageName || !stableVersion.test(version)) throw new Error('The archive does not contain a stable AnySwarm distribution.');
94
- const { stdout } = await execute(join(stage, 'node_modules', '.bin', 'anyswarm'), ['--version'], {
95
- signal, timeout: 10_000, env: { ...process.env, NODE_OPTIONS: '' },
96
- });
97
- if (stdout.trim() !== version) throw new Error('The staged CLI did not report the package version.');
98
- await writeFile(join(stage, 'install.json'), JSON.stringify({ schema: 1, prefix, version, source, sha256 } satisfies Installation), { mode: 0o600 });
99
- await mkdir(join(prefix, 'bin'), { recursive: true });
100
- for (const bin of bins) {
101
- const path = join(stage, 'node_modules', '.bin', bin);
102
- if (await realpath(path) !== join(root, 'dist', 'scripts', `${bin}.js`)) {
103
- throw new Error(`The staged ${bin} entry does not belong to the package.`);
104
- }
105
- await access(path, constants.X_OK);
106
- }
107
- return lockActivation(prefix, async () => {
108
- const changed: { path: string; previous?: string }[] = [];
109
- try {
110
- const oldCurrent = await inspectLink(currentPath(prefix));
111
- if (expected !== undefined && (!oldCurrent || resolve(installDirectory(prefix), oldCurrent) !== expected)) {
112
- throw new Error('Another process already changed this installation. Run the current CLI to update.');
113
- }
114
- for (const bin of bins) {
115
- const path = installBin(prefix, bin);
116
- const target = binTarget(prefix, bin);
117
- const previous = await inspectLink(path);
118
- if (previous === target) continue;
119
- const npmTargets = [packageName, ...previousPackageNames].map(name =>
120
- join(prefix, 'lib', 'node_modules', name, 'dist', 'scripts', `${bin}.js`));
121
- if (previous && !npmTargets.includes(resolve(dirname(path), previous))) {
122
- throw new Error(`The link at ${path} belongs to another installation.`);
123
- }
124
- await replaceLink(path, target);
125
- changed.push({ path, previous });
126
- }
127
- signal?.throwIfAborted();
128
- await replaceLink(currentPath(prefix), relative(installDirectory(prefix), stage));
129
- return { version, packageRoot: root, path: installBin(prefix, 'anyswarm') };
130
- } catch (error) {
131
- for (const { path, previous } of changed.reverse()) {
132
- if (previous) await replaceLink(path, previous);
133
- else await rm(path);
134
- }
135
- throw error;
136
- }
137
- }, signal);
138
- }
139
-
140
- async function managedInstallation(invocation: string, version: string) {
141
- const stage = resolve(packageRoot, '../../..');
142
- const installation = await readFile(join(stage, 'install.json'), 'utf8')
143
- .then(data => JSON.parse(data) as Installation).catch(() => undefined);
144
- if (!installation || installation.schema !== 1 || installation.version !== version ||
145
- typeof installation.prefix !== 'string' ||
146
- dirname(stage) !== join(installDirectory(installation.prefix), 'versions') ||
147
- await realpath(invocation).catch(() => '') !== join(packageRoot, 'dist', 'scripts', 'anyswarm.js')) return undefined;
148
- const entry = installBin(installation.prefix, 'anyswarm');
149
- if (await realpath(entry).catch(() => '') !== await realpath(invocation)) {
150
- throw new Error(`This CLI version is no longer active. Run ${entry} update.`);
151
- }
152
- return { ...installation, stage, entry };
153
- }
154
-
155
- async function fetchFile(url: string, signal: AbortSignal) {
156
- const response = await fetch(url, { signal, headers: { 'User-Agent': 'AnySwarm-CLI' } });
157
- if (!response.ok) throw new Error(`GitHub returned HTTP ${response.status} for the release material.`);
158
- return response;
159
- }
160
-
161
- async function latestRelease(signal: AbortSignal) {
162
- const response = await fetchFile('https://api.github.com/repos/AnySwarm/anyswarm/releases/latest', signal);
163
- const data = await response.json() as { tag_name?: string; prerelease?: boolean; draft?: boolean };
164
- const version = data.tag_name?.slice(1);
165
- if (!data.tag_name?.startsWith('v') || !version || !stableVersion.test(version) || data.draft || data.prerelease) {
166
- throw new Error('GitHub did not return a stable AnySwarm release.');
167
- }
168
- return version;
169
- }
170
-
171
- async function releaseArchive(version: string, temporary: string, signal: AbortSignal) {
172
- const directory = `${releaseRoot}/v${version}`;
173
- const filename = `luna-shi-anyswarm-${version}.tgz`;
174
- const checksums = await (await fetchFile(`${directory}/SHA256SUMS`, signal)).text();
175
- const digest = checksums.split('\n').map(line => line.trim().split(/\s+/))
176
- .find(([hash, name]) => name === filename && /^[a-f0-9]{64}$/.test(hash))?.[0];
177
- if (!digest) throw new Error('The release does not contain a checksum for the package.');
178
- const source = `${directory}/${filename}`;
179
- const response = await fetchFile(source, signal);
180
- const path = join(temporary, filename);
181
- await writeFile(path, response.body as unknown as AsyncIterable<Uint8Array>, { signal });
182
- return { path, source, digest };
183
- }
184
10
 
185
11
  const quoted = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
186
12
 
@@ -195,124 +21,28 @@ async function npmGlobalPrefix(invocation: string, signal: AbortSignal) {
195
21
  }
196
22
 
197
23
  function packageManagerRemedy(path: string) {
198
- const archive = 'https://github.com/AnySwarm/anyswarm/releases/latest/download/luna-shi-anyswarm.tgz';
24
+ const latest = packageName + '@latest';
199
25
  if (path.includes('/.pnpm/') || path.includes('/pnpm/global/')) {
200
- return `Use pnpm in the original scope: pnpm add${path.includes('/pnpm/global/') ? ' --global' : ''} ${archive}. Package: ${path}.`;
26
+ return `Use pnpm in the original scope: pnpm add${path.includes('/pnpm/global/') ? ' --global' : ''} ${latest}. Package: ${path}.`;
201
27
  }
202
28
  if (path.includes('/.yarn/') || path.includes('/yarn/global/')) {
203
- return `Use Yarn in the original scope: yarn ${path.includes('/yarn/global/') ? 'global ' : ''}add ${archive}. Package: ${path}.`;
29
+ return `Use Yarn in the original scope: yarn ${path.includes('/yarn/global/') ? 'global ' : ''}add ${latest}. Package: ${path}.`;
204
30
  }
205
31
  if (path.includes('/node_modules/')) {
206
32
  const prefix = path.slice(0, path.lastIndexOf('/node_modules/'));
207
- return `To change this project's SDK explicitly, run npm install --prefix ${quoted(prefix)} ${archive}. Package: ${path}.`;
33
+ return `To change this project's SDK explicitly, run npm install --prefix ${quoted(prefix)} ${latest}. Package: ${path}.`;
208
34
  }
209
- return `Review the installer at ${path} or select a prefix with npm_config_prefix before running the official installer: https://anyswarm.github.io/anyswarm/install.sh`;
35
+ return `Update the package in its original installation scope. Package: ${path}.`;
210
36
  }
211
37
 
212
- export async function updateAnySwarm(
213
- options: { archive?: string; sha256?: string },
214
- signal: AbortSignal,
215
- progress: (message: string) => void,
216
- ) {
217
- const { version: before } = await manifest(packageRoot);
218
- const invocation = resolve(process.argv[1]);
219
- const installation = await managedInstallation(invocation, before);
220
- if (!installation) {
221
- const npmPrefix = await npmGlobalPrefix(invocation, signal);
222
- if (npmPrefix) return {
223
- ok: false, before, after: before, path: invocation, packageRoot, source: 'npm global',
224
- result: 'preserved', environment: 'separate',
225
- detail: `Once a managed release is available, run the official installer for this npm prefix, then use anyswarm update. \`curl -fsSL https://anyswarm.github.io/anyswarm/install.sh | npm_config_prefix=${quoted(npmPrefix)} sh\``,
226
- };
227
- return {
228
- ok: false, before, path: invocation, packageRoot, source: 'other',
229
- detail: packageManagerRemedy(packageRoot), environment: 'separate',
230
- };
231
- }
232
-
233
- const status = { before, path: installation.entry, packageRoot, source: installation.source, environment: 'separate' };
234
- let temporary: string | undefined;
235
- let stage: string | undefined;
236
- let activated = false;
237
- try {
238
- const deadline = AbortSignal.any([signal, AbortSignal.timeout(180_000)]);
239
- const release = options.archive ? undefined : await latestRelease(deadline);
240
- if (release) {
241
- const current = before.split('.').map(Number);
242
- const candidate = release.split('.').map(Number);
243
- const firstChange = candidate.findIndex((part, index) => part !== current[index]);
244
- if (firstChange < 0 || candidate[firstChange] < current[firstChange]) {
245
- return { ok: true, ...status, after: before, result: 'up-to-date' };
246
- }
247
- }
248
- const parent = installDirectory(installation.prefix);
249
- temporary = await mkdtemp(join(parent, 'anyswarm-download-'));
250
- const archive = options.archive
251
- ? { path: resolve(options.archive), source: resolve(options.archive), digest: options.sha256! }
252
- : await releaseArchive(release!, temporary, deadline);
253
- if (await archiveDigest(archive.path) !== archive.digest) throw new Error('The archive SHA-256 does not match the expected checksum.');
254
- const verifiedArchive = join(temporary, 'verified.tgz');
255
- if (options.archive) {
256
- await writeFile(verifiedArchive, createReadStream(archive.path), { signal: deadline });
257
- if (await archiveDigest(verifiedArchive) !== archive.digest) throw new Error('The archive changed while it was being staged.');
258
- }
259
- progress(`Preparing ${release ? `AnySwarm ${release}` : 'the specified AnySwarm archive'}`);
260
- const approvedArchive = options.archive ? verifiedArchive : archive.path;
261
- const npmFlags = ['--omit=dev', '--prefer-offline', '--ignore-scripts', '--no-audit', '--no-fund'];
262
- stage = await mkdtemp(join(parent, 'versions', 'release-'));
263
- await execute('npm', ['install', '--prefix', stage, ...npmFlags, approvedArchive], { timeout: 120_000, signal: deadline });
264
- const { version } = await manifest(installedPackage(stage));
265
- if (release && version !== release) throw new Error('The release archive version does not match its release tag.');
266
- const updated = await activate(installation.prefix, stage, archive.source, archive.digest, deadline, installation.stage);
267
- activated = true;
268
- return { ok: true, ...status, ...updated, after: updated.version, source: archive.source, sha256: archive.digest, result: 'updated' };
269
- } catch (error) {
270
- const detail = error instanceof Error && 'cmd' in error
271
- ? 'A command failed while installing or verifying the staged CLI. Check npm connectivity and installation permissions.'
272
- : error instanceof Error ? error.message : String(error);
273
- const activePath = await realpath(status.path).catch(() => undefined);
274
- const preserved = activePath === join(packageRoot, 'dist', 'scripts', 'anyswarm.js');
275
- return { ok: false, ...status, ...(preserved ? { after: before } : {}), result: preserved ? 'preserved' : 'failed', detail };
276
- } finally {
277
- if (temporary) await rm(temporary, { recursive: true, force: true }).catch(() => {});
278
- if (stage && !activated) await rm(stage, { recursive: true, force: true }).catch(() => {});
279
- }
280
- }
281
-
282
- export async function activateOfficialInstall(input: {
283
- prefix: string; stage: string; source: string; sha256: string; expectedVersion?: string;
284
- }) {
285
- const prefix = await realpath(resolve(input.prefix));
286
- const stage = await realpath(resolve(input.stage));
287
- if (dirname(stage) !== join(installDirectory(prefix), 'versions')) throw new Error('The staged installation is outside the selected prefix.');
288
- if (!/^[a-f0-9]{64}$/.test(input.sha256)) throw new Error('A verified archive SHA-256 is required.');
289
- if (input.expectedVersion && (await manifest(installedPackage(stage))).version !== input.expectedVersion) {
290
- throw new Error('The archive version does not match the requested GitHub release.');
291
- }
292
- const result = await activate(prefix, stage, input.source, input.sha256);
293
- console.log(`Installed AnySwarm ${result.version} at ${result.path}`);
294
- console.log(`Package root: ${result.packageRoot}\nInstall source: ${input.source}\nArchive SHA-256: ${input.sha256}`);
295
- let resolvedOnPath: string | undefined;
296
- for (const entry of (process.env.PATH ?? '').split(':')) {
297
- const path = resolve(entry, 'anyswarm');
298
- if (await access(path, constants.X_OK).then(() => true, () => false)) {
299
- resolvedOnPath = path;
300
- break;
301
- }
302
- }
303
- if (resolvedOnPath !== result.path) {
304
- const directory = dirname(result.path);
305
- const display = directory === join(homedir(), '.local', 'bin') ? '"$HOME/.local/bin:$PATH"'
306
- : `'${directory.replaceAll("'", "'\\''")}':"$PATH"`;
307
- console.error(`Add the installation to PATH:\n export PATH=${display}`);
308
- }
309
- }
310
-
311
- if (basename(process.argv[1] ?? '') === 'anyswarm-installation.js') {
312
- const [prefix, stage, source, sha256, expectedVersion] = process.argv.slice(2);
313
- try { await activateOfficialInstall({ prefix, stage, source, sha256, expectedVersion }); }
314
- catch (error) {
315
- console.error(error instanceof Error ? error.message : String(error));
316
- process.exitCode = 1;
317
- }
38
+ export async function updateAnySwarm(signal: AbortSignal) {
39
+ const { version } = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'utf8'));
40
+ const path = resolve(process.argv[1]);
41
+ const prefix = await npmGlobalPrefix(path, signal);
42
+ const result = { ok: false, before: version, path, packageRoot, environment: 'separate' };
43
+ if (prefix) return {
44
+ ...result, ok: true, after: version, source: 'npm global', result: 'preserved',
45
+ detail: `This CLI was installed with npm. Update it with \`npm install -g --prefix ${quoted(prefix)} ${packageName}@latest\`.`,
46
+ };
47
+ return { ...result, source: 'other', detail: packageManagerRemedy(packageRoot) };
318
48
  }
@@ -0,0 +1,36 @@
1
+ import { createHarnessSession, loadProjectConfiguration, loadProjectHarnessModule } from '../src/harness/project-harness.js';
2
+ import { ProjectPreflightError } from '../src/harness/project-input.js';
3
+ import type { ProjectCommand } from './anyswarm-arguments.js';
4
+ import { builtins } from './anyswarm-harnesses.js';
5
+
6
+ export async function prepareProjectLaunch(command: ProjectCommand, launchDirectory: string,
7
+ options: Parameters<typeof loadProjectHarnessModule>[3], signal: AbortSignal) {
8
+ const { module, definition } = await loadProjectHarnessModule(launchDirectory, command.harness, builtins, options);
9
+ signal.throwIfAborted();
10
+ let cwd = command.mode === 'foreground' ? command.cwd : undefined;
11
+ let configuration: unknown;
12
+ let stopTimeoutMs: number | undefined;
13
+ if (command.mode === 'foreground' && typeof module.resolveWorkspace === 'function') {
14
+ configuration = await loadProjectConfiguration(launchDirectory, command.configPath);
15
+ signal.throwIfAborted();
16
+ if (cwd === undefined) {
17
+ try { cwd = module.resolveWorkspace({ cwd: launchDirectory, configuration }); }
18
+ catch { throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Could not resolve the Harness workspace'); }
19
+ if (typeof cwd !== 'string' || !cwd.trim()) {
20
+ throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'The Harness workspace resolver must return a directory');
21
+ }
22
+ }
23
+ const config = configuration as Record<string, unknown> | undefined;
24
+ const timeout = config?.closeTimeoutMs ?? config?.cleanupTimeoutMs;
25
+ if (typeof timeout === 'number' && Number.isSafeInteger(timeout) && timeout > 0) {
26
+ stopTimeoutMs = Math.min(2_147_483_647, timeout + 5000);
27
+ }
28
+ }
29
+ const session = createHarnessSession(definition, {
30
+ launchDirectory, configuration, stopTimeoutMs,
31
+ configPath: configuration === undefined ? command.configPath : undefined, outputRoot: command.outputRoot,
32
+ lifetime: command.mode === 'foreground' ? 'task' : command.lifetime,
33
+ clientCapabilities: { questions: command.mode === 'rpc' && command.interaction === 'questions' },
34
+ });
35
+ return { session, cwd, harnessId: definition.id };
36
+ }
@@ -0,0 +1,95 @@
1
+ import { dirname, join, resolve } from 'node:path';
2
+ import { homedir } from 'node:os';
3
+ import type { HarnessEvent, HarnessResult, HarnessSession } from '../src/harness/harness-session-types.js';
4
+
5
+ function object(value: unknown): Record<string, unknown> {
6
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
7
+ }
8
+
9
+ function shellPath(path: string) {
10
+ return /^[\w./-]+$/.test(path) ? path : "'" + path.replaceAll("'", "'\\''") + "'";
11
+ }
12
+
13
+ const serviceActions = new Set(['service.register', 'service.start', 'service.restart', 'service.stop', 'service.retire']);
14
+
15
+ export function foregroundProgress(session: HarnessSession, harnessId: string, launchDirectory: string,
16
+ outputRoot: string | undefined, write: (message: string) => Promise<void>) {
17
+ const root = outputRoot ? resolve(launchDirectory, outputRoot)
18
+ : resolve(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'anyswarm', 'runs');
19
+ const report = (message: string) => write(message.replace(/[\p{Cc}\p{Cf}]/gu, character =>
20
+ '\\u' + character.charCodeAt(0).toString(16).padStart(4, '0')));
21
+ const trace = (directory: string) => report('Trace anyswarm trace --root ' + shellPath(directory));
22
+ void report('Starting ' + harnessId);
23
+ void trace(root);
24
+ const agents = new Map<string, string>();
25
+ let phase: string | undefined;
26
+ let services: Promise<void> | undefined;
27
+ let closed = false;
28
+ function observe(event: HarnessEvent) {
29
+ if (event.type === 'state' || event.type === 'snapshot') {
30
+ if (phase !== event.state.phase) {
31
+ phase = event.state.phase;
32
+ if (phase === 'running') {
33
+ void report('Harness running');
34
+ services = session.services.list().then(async sources => {
35
+ const names = [...new Set(sources.map(source => source.name))].sort();
36
+ if (!closed && names.length) await report('Services available ' + names.join(', '));
37
+ }).catch(() => {});
38
+ }
39
+ if (phase === 'stopping') void report('Stopping Run and waiting for cleanup');
40
+ }
41
+ if (!Array.isArray(event.state.agents)) return;
42
+ for (const item of event.state.agents) {
43
+ const { id, profile, status } = object(item);
44
+ if (typeof id !== 'string' || typeof profile !== 'string' || typeof status !== 'string') continue;
45
+ const previous = agents.get(id);
46
+ if (status === previous) continue;
47
+ agents.set(id, status);
48
+ const label = profile + ' [' + id.slice(0, 8) + ']';
49
+ if (status === 'starting') void report('Agent starting ' + label);
50
+ if ((!previous || previous === 'starting') && (status === 'idle' || status === 'running')) {
51
+ void report('Sandbox ready ' + label);
52
+ }
53
+ if (status === 'closed') void report('Agent closed ' + label);
54
+ }
55
+ }
56
+ if (event.type !== 'event') return;
57
+ const { kind, event: raw } = object(event.event);
58
+ if (kind !== 'agent') return;
59
+ const runtime = object(raw);
60
+ if (runtime.type === 'settled' && typeof runtime.agentId === 'string') {
61
+ void report('Agent settled [' + runtime.agentId.slice(0, 8) + '] ' + String(runtime.outcome));
62
+ }
63
+ if (runtime.type !== 'management') return;
64
+ const { operation, definition } = object(runtime.change);
65
+ const { id, state } = object(definition);
66
+ if (typeof operation === 'string' && serviceActions.has(operation) && typeof id === 'string' && typeof state === 'string') {
67
+ void report('Service ' + operation.slice('service.'.length) + ' ' + id + ' (' + state + ')');
68
+ }
69
+ }
70
+ return {
71
+ observe,
72
+ async finish(result: HarnessResult) {
73
+ await services;
74
+ closed = true;
75
+ const message = result.failure?.message ?? result.reportSaveFailure?.message;
76
+ void report('Run ' + result.outcome + ' ' + result.reason + (message ? ' (' + message + ')' : ''));
77
+ for (const artifact of result.artifacts.slice(0, 5)) {
78
+ const path = typeof artifact === 'string' ? artifact : object(artifact).path;
79
+ if (typeof path === 'string') void report('Artifact ' + path);
80
+ }
81
+ if (result.artifacts.length > 5) void report('Additional artifacts ' + (result.artifacts.length - 5));
82
+ if (result.export) void report('Export ' + result.export.status);
83
+ void report('Cleanup ' + result.cleanup.status);
84
+ if (result.reportPath) void report('Run report ' + result.reportPath);
85
+ const prompt = object(object(result).prompt).path;
86
+ const recordPath = result.reportPath ?? (typeof prompt === 'string' ? prompt : undefined);
87
+ await trace(recordPath ? dirname(dirname(recordPath)) : root);
88
+ },
89
+ async fail(code: string, message?: string) {
90
+ closed = true;
91
+ void report(code + (message ? ' ' + message : ''));
92
+ await trace(root);
93
+ },
94
+ };
95
+ }
@@ -1,18 +1,11 @@
1
1
  import { frameworkErrorFields } from '../src/core/error-diagnostics.js';
2
- import { captureHarnessSnapshot, createHarnessSession, failureCode, getHarnessExitCode, loadProjectHarness, stopHarnessTransport } from '../src/harness/project-harness.js';
2
+ import { captureHarnessSnapshot, createHarnessSession, failureCode, getHarnessExitCode, stopHarnessTransport } from '../src/harness/project-harness.js';
3
3
  import { resolveHarnessInput } from '../src/harness/project-input.js';
4
4
  import { runProjectRpc } from '../src/harness/project-rpc.js';
5
5
  import type { ProjectCommand } from './anyswarm-arguments.js';
6
6
 
7
- const builtins = {
8
- 'lead-worker': new URL('../examples/lead-worker/project.js', import.meta.url).href,
9
- peermesh: new URL('../examples/peermesh/project.js', import.meta.url).href,
10
- notes: new URL('../examples/notes/project.js', import.meta.url).href,
11
- messages: new URL('../examples/messages/project.js', import.meta.url).href,
12
- taskpool: new URL('../examples/taskpool/project.js', import.meta.url).href,
13
- substrate: new URL('../examples/substrate/project.js', import.meta.url).href,
14
- subagents: new URL('../examples/subagents/project.js', import.meta.url).href,
15
- };
7
+ import { prepareProjectLaunch } from './anyswarm-launch.js';
8
+ import { foregroundProgress } from './anyswarm-progress.js';
16
9
 
17
10
  const MAX_QUEUED_OUTPUT_BYTES = 1_048_576;
18
11
  const MAX_OUTPUT_RECORD_BYTES = 8 * 1024 * 1024;
@@ -25,13 +18,16 @@ interface OutputFrame {
25
18
  flushed: PromiseWithResolvers<void>;
26
19
  }
27
20
 
28
- export async function runProjectCommand(command: ProjectCommand, launchDirectory: string) {
21
+ export async function runProjectCommand(command: ProjectCommand, launchDirectory: string,
22
+ options: { onSourceError?: (error: unknown) => void } = {}) {
23
+ const human = command.mode === 'foreground' && process.stdout.isTTY;
29
24
  const stdout = process.stdout.write;
30
25
  const transport = stdout.bind(process.stdout);
31
26
  const startup = new AbortController();
32
27
  let session: ReturnType<typeof createHarnessSession> | undefined;
33
28
  let signalCode: number | undefined;
34
29
  let outputFailed = false;
30
+ let progress: ReturnType<typeof foregroundProgress> | undefined;
35
31
  let lastWrite: Promise<void> | undefined;
36
32
  const outputQueue: OutputFrame[] = [];
37
33
  let queuedBytes = 0;
@@ -76,16 +72,8 @@ export async function runProjectCommand(command: ProjectCommand, launchDirectory
76
72
  }
77
73
  }
78
74
 
79
- const write = (record: unknown, replaceableState = false): Promise<void> => {
75
+ const enqueue = (data: string, replaceableState = false): Promise<void> => {
80
76
  if (outputFailed) return Promise.resolve();
81
- let encoded: string;
82
- try {
83
- encoded = JSON.stringify(record);
84
- } catch {
85
- pipeFailed();
86
- return Promise.resolve();
87
- }
88
- const data = encoded + '\n';
89
77
  const bytes = Buffer.byteLength(data);
90
78
  const last = outputQueue.at(-1);
91
79
  const replace = replaceableState && last?.replaceableState ? last : undefined;
@@ -105,6 +93,10 @@ export async function runProjectCommand(command: ProjectCommand, launchDirectory
105
93
  void flushOutput();
106
94
  return lastWrite;
107
95
  };
96
+ const write = (record: unknown, replaceableState = false): Promise<void> => {
97
+ try { return enqueue(JSON.stringify(record) + '\n', replaceableState); }
98
+ catch { pipeFailed(); return Promise.resolve(); }
99
+ };
108
100
  const ignoreDiagnosticError = () => {};
109
101
  process.on('SIGINT', signal);
110
102
  process.on('SIGTERM', signal);
@@ -113,35 +105,44 @@ export async function runProjectCommand(command: ProjectCommand, launchDirectory
113
105
  // Only the host's captured transport can write protocol output.
114
106
  process.stdout.write = process.stderr.write.bind(process.stderr);
115
107
  try {
116
- const config = { launchDirectory, configPath: command.configPath, outputRoot: command.outputRoot,
117
- lifetime: command.lifetime, clientCapabilities: { questions: command.interaction === 'questions' } };
118
108
  const stopped = Promise.withResolvers<never>();
119
109
  const abortStartup = () => stopped.reject(startup.signal.reason);
120
110
  startup.signal.addEventListener('abort', abortStartup, { once: true });
121
- let definition;
111
+ let launch;
122
112
  try {
123
- definition = await Promise.race([loadProjectHarness(launchDirectory, command.harness, builtins), stopped.promise]);
113
+ launch = await Promise.race([prepareProjectLaunch(command, launchDirectory, options, startup.signal), stopped.promise]);
114
+ session = launch.session;
124
115
  startup.signal.throwIfAborted();
125
116
  } finally {
126
117
  startup.signal.removeEventListener('abort', abortStartup);
127
118
  }
128
- session = createHarnessSession(definition, config);
129
- const input = command.mode === 'foreground'
130
- ? resolveHarnessInput({ cwd: command.cwd, prompt: command.prompt }, launchDirectory)
131
- : undefined;
132
- if (command.mode === 'rpc' || command.lifetime === 'interactive' || config.clientCapabilities.questions) {
133
- const code = await runProjectRpc(session, process.stdin, write, launchDirectory, input);
119
+ if (command.mode === 'rpc') {
120
+ const code = await runProjectRpc(session, process.stdin, write, launchDirectory);
134
121
  await lastWrite;
135
122
  return signalCode ?? (outputFailed ? 1 : code);
136
123
  }
137
- await session.start(input!, { requestId: 'foreground-start' });
138
- const result = await session.completion!;
139
- await write({ type: 'result', runId: result.runId, result });
124
+ if (human) progress = foregroundProgress(session, launch.harnessId, launchDirectory, command.outputRoot, message => enqueue(message + '\n'));
125
+ const input = resolveHarnessInput({ cwd: launch.cwd, prompt: command.prompt }, launchDirectory);
126
+ const unsubscribe = progress && session.onEvent(progress.observe, {
127
+ initialSnapshot: false,
128
+ onError: () => { void enqueue('Live progress unavailable. Follow the Run in Trace.\n'); },
129
+ });
130
+ let result;
131
+ try {
132
+ await session.start(input, { requestId: 'foreground-start' });
133
+ result = await session.completion!;
134
+ } finally { unsubscribe?.(); }
135
+ if (progress) await progress.finish(result);
136
+ else await write({ type: 'result', runId: result.runId, result });
140
137
  return signalCode ?? (outputFailed ? 1 : getHarnessExitCode(session));
141
138
  } catch (error) {
142
139
  if (!startup.signal.aborted) {
143
140
  const code = failureCode(error, 'HARNESS_COMMAND_FAILED');
144
- await write({ type: 'error', code, ...(error instanceof Error ? { message: error.message } : {}), ...frameworkErrorFields(error) });
141
+ const message = error instanceof Error ? error.message : undefined;
142
+ if (human) {
143
+ if (progress) await progress.fail(code, message);
144
+ else console.error(code + (message ? ' ' + message : ''));
145
+ } else await write({ type: 'error', code, ...(message ? { message } : {}), ...frameworkErrorFields(error) });
145
146
  }
146
147
  return signalCode ?? (outputFailed ? 1 : 2);
147
148
  } finally {