@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
@@ -14,7 +14,7 @@ import { projectRuntimeEvidence } from './project-runtime.js';
14
14
  import { HarnessEventStream } from './harness-event-stream.js';
15
15
  import type { HarnessAgentRegistration, HarnessAgents, HarnessAnswer, HarnessAnswerReceipt, HarnessDescriptor, HarnessDispatchRequest, HarnessEvent,
16
16
  HarnessInputDescriptor, HarnessInputReceipt, HarnessOperation, HarnessQuestion, HarnessQuestionRequest, HarnessQuestionSource,
17
- HarnessRequest, HarnessResult, HarnessSession, HarnessSessionOptions, HarnessStartReceipt, HarnessState, HarnessStopReceipt } from './harness-session-types.js';
17
+ HarnessRequest, HarnessResult, HarnessServices, HarnessSession, HarnessSessionOptions, HarnessStartReceipt, HarnessState, HarnessStopReceipt } from './harness-session-types.js';
18
18
 
19
19
  interface OperationRecord {
20
20
  operation: string;
@@ -192,12 +192,30 @@ export function createHarnessSession(definition: Harness, options: HarnessSessio
192
192
  const event = runtimeObject.event;
193
193
  if (!event || typeof event !== 'object' || Array.isArray(event) || !('messageId' in event) || typeof event.messageId !== 'string') return;
194
194
  const eventObject = event as { readonly [key: string]: HarnessJson };
195
- const key = String(runtimeObject.agentId ?? '') + ':' + eventObject.messageId;
196
- const previous = output.get(key) as { text?: string } | undefined;
197
- if (eventObject.type === 'textDelta' && typeof eventObject.delta === 'string') {
198
- output.set(key, { agentId: runtimeObject.agentId ?? null, messageId: eventObject.messageId, text: ((previous?.text ?? '') + eventObject.delta).slice(-16_384), truncated: (previous?.text?.length ?? 0) + eventObject.delta.length > 16_384, complete: false });
195
+ const agentId = runtimeObject.agentId ?? null;
196
+ const messageId = eventObject.messageId;
197
+ const key = JSON.stringify([agentId, messageId]);
198
+ const previous = output.get(key) as { blocks?: readonly (readonly [number, string])[]; complete?: boolean; truncated?: boolean } | undefined;
199
+ if (eventObject.type === 'textDelta' && typeof eventObject.delta === 'string' && !previous?.complete) {
200
+ const index = Number.isSafeInteger(eventObject.blockIndex) ? Number(eventObject.blockIndex) : 0;
201
+ const blocks = new Map(previous?.blocks);
202
+ blocks.set(index, (blocks.get(index) ?? '') + eventObject.delta);
203
+ let truncated = previous?.truncated ?? false;
204
+ if (blocks.size > 64) { blocks.delete(blocks.keys().next().value!); truncated = true; }
205
+ const ordered = [...blocks].sort(([left], [right]) => left - right);
206
+ let available = 16_384;
207
+ for (let position = ordered.length - 1; position >= 0; position--) {
208
+ const block = ordered[position];
209
+ if (block[1].length > available) {
210
+ block[1] = available ? block[1].slice(-available) : '';
211
+ truncated = true;
212
+ }
213
+ available -= block[1].length;
214
+ }
215
+ output.set(key, { agentId, messageId, text: ordered.map(([, text]) => text).join(''),
216
+ blocks: ordered, truncated, complete: false });
199
217
  } else if (eventObject.type === 'messageEnd') {
200
- output.set(key, { agentId: runtimeObject.agentId ?? null, messageId: eventObject.messageId, message: boundedView(eventObject.message ?? null, 16_384), complete: true });
218
+ output.set(key, { agentId, messageId, message: boundedView(eventObject.message ?? null, 16_384), complete: true });
201
219
  }
202
220
  while (output.size > 8 || Buffer.byteLength(JSON.stringify([...output.values()])) > Math.floor(limits.snapshotBytes / 4)) output.delete(output.keys().next().value!);
203
221
  }
@@ -564,8 +582,23 @@ export function createHarnessSession(definition: Harness, options: HarnessSessio
564
582
  interrupt: (agentId, request) => control('interrupt', agentId, null, request) as ReturnType<HarnessAgents['interrupt']>,
565
583
  stop: (agentId, options) => control('stop', agentId, { reason: options.reason }, options) as ReturnType<HarnessAgents['stop']>,
566
584
  };
585
+ const services: HarnessServices = {
586
+ async list() {
587
+ if (stopping || finalizing) return [];
588
+ return [...registrations.keys()].flatMap(({ runtime }) =>
589
+ (runtime.services?.listState?.() ?? []).map(source => ({ runtimeId: runtime.id, ...source })));
590
+ },
591
+ async read(runtimeId, name) {
592
+ const owner = [...registrations.keys()].find(({ runtime }) => runtime.id === runtimeId);
593
+ if (owner && !stopping && !finalizing && owner.runtime.services?.readState) {
594
+ const state = await owner.runtime.services.readState(name);
595
+ if (!stopping && !finalizing && registrations.has(owner)) return state;
596
+ }
597
+ return { status: 'unavailable', reason: 'Runtime does not provide live Service state for this Run' };
598
+ },
599
+ };
567
600
  const session: HarnessSession = {
568
- agents,
601
+ agents, services,
569
602
  async describe() { for (const registration of registrations.keys()) await refreshTargets(registration); return structuredClone(descriptor()); },
570
603
  async getState() { return snapshot(); },
571
604
  onEvent(handler, subscribeOptions) {
@@ -1,3 +1,4 @@
1
+ import { installSourceLoader } from './typescript-loader.js';
1
2
  import { errorDiagnostic, frameworkErrorFields } from '../core/error-diagnostics.js';
2
3
  import { loadAnySwarmConfig } from '../core/sandbox/sandbox-connection.js';
3
4
  import { createHash, randomUUID } from 'node:crypto';
@@ -44,6 +45,8 @@ export interface HarnessContext {
44
45
  readonly lifetime: HarnessLifetime;
45
46
  readonly agentEventsManaged?: boolean;
46
47
  readonly clientCapabilities: Readonly<{ questions: boolean }>;
48
+ /** Capture the live project with the same scope and policy as the initial input. Release temporary bytes when done. */
49
+ captureProject(signal?: AbortSignal): Promise<InitialProject & { dispose(): Promise<void> }>;
47
50
  registerAgentControls(registration: HarnessAgentRegistration): () => void;
48
51
  /** Run owned work and use the close receipt in this Run's final report. */
49
52
  runWithRuntime<R extends CloseableRuntime>(options: HarnessRuntimeRunOptions<R>): Promise<HarnessRunOutcome>;
@@ -76,8 +79,8 @@ export type ProjectHarnessResult = Awaited<ReturnType<Harness['run']>>;
76
79
 
77
80
  function moduleSpecifier(directory: string, specifier: string) {
78
81
  if (isAbsolute(specifier) || specifier.startsWith('./') || specifier.startsWith('../')) {
79
- if (!['.mjs', '.js'].includes(extname(specifier))) {
80
- throw projectError('INVALID_HARNESS_MODULE', 'Local Harness modules must be built .mjs or .js files');
82
+ if (!['.mjs', '.js', '.ts', '.mts'].includes(extname(specifier))) {
83
+ throw projectError('INVALID_HARNESS_MODULE', 'Local Harness modules must be .ts, .mts, .mjs or .js files');
81
84
  }
82
85
  return pathToFileURL(resolve(directory, specifier)).href;
83
86
  }
@@ -88,11 +91,13 @@ function moduleSpecifier(directory: string, specifier: string) {
88
91
  return specifier;
89
92
  }
90
93
 
91
- export async function loadProjectHarness(directory: string, specifier: string, builtins: Readonly<Record<string, string>> = {}) {
94
+ export async function loadProjectHarnessModule(directory: string, specifier: string, builtins: Readonly<Record<string, string>> = {},
95
+ options: { onSourceError?: (error: unknown) => void } = {}) {
96
+ installSourceLoader();
92
97
  const builtin = Object.hasOwn(builtins, specifier) ? builtins[specifier] : undefined;
93
98
  const target = builtin ?? moduleSpecifier(directory, specifier);
94
99
  const parentURL = pathToFileURL(join(directory, '.anyswarm-harness-resolver.mjs')).href;
95
- let module: { default?: Partial<ProjectHarness> };
100
+ let module: { default?: Partial<ProjectHarness> } & Record<string, unknown>;
96
101
  try {
97
102
  // Anchor package lookup at the launching project, keeping Node's ESM import conditions.
98
103
  const hook = target.startsWith('file:') ? null : registerHooks({
@@ -106,7 +111,8 @@ export async function loadProjectHarness(directory: string, specifier: string, b
106
111
  } finally {
107
112
  hook?.deregister();
108
113
  }
109
- } catch {
114
+ } catch (error) {
115
+ options.onSourceError?.(error);
110
116
  throw projectError('HARNESS_MODULE_LOAD_FAILED', `Could not load Harness ${JSON.stringify(specifier)}`);
111
117
  }
112
118
  const definition = module.default;
@@ -115,7 +121,18 @@ export async function loadProjectHarness(directory: string, specifier: string, b
115
121
  typeof definition.run !== 'function' || (definition.input !== undefined && definition.input !== true)) {
116
122
  throw projectError('INVALID_HARNESS_MODULE', 'Harness default export requires apiVersion 1, a stable id and run(context)');
117
123
  }
118
- return definition as ProjectHarness;
124
+ if (options.onSourceError) {
125
+ const harness = definition as ProjectHarness;
126
+ return { module, definition: { ...harness, async run(context: HarnessContext) {
127
+ try { return await harness.run(context); }
128
+ catch (error) { options.onSourceError!(error); throw error; }
129
+ } } };
130
+ }
131
+ return { module, definition: definition as Harness };
132
+ }
133
+
134
+ export async function loadProjectHarness(...args: Parameters<typeof loadProjectHarnessModule>) {
135
+ return (await loadProjectHarnessModule(...args)).definition;
119
136
  }
120
137
 
121
138
  type Phase = 'idle' | 'starting' | 'running' | 'stopping' | 'finished';
@@ -148,7 +165,7 @@ export function failureCode(error: unknown, fallback: string) {
148
165
  (errorDiagnostic(error) && /^[a-z][a-z0-9_]{0,79}$/.test(code))) ? code : fallback;
149
166
  }
150
167
 
151
- async function loadConfiguration(directory: string, path: string | undefined): Promise<unknown> {
168
+ export async function loadProjectConfiguration(directory: string, path: string | undefined): Promise<unknown> {
152
169
  if (!path) return undefined;
153
170
  let value: unknown;
154
171
  try {
@@ -261,7 +278,7 @@ export function createProjectHost(definition: ProjectHarness, options: StartupOp
261
278
  let enteredHarness = false;
262
279
  let failure: Failure | null = null;
263
280
  const signal = controller.signal;
264
- let staged: ReturnType<typeof fileSpool>;
281
+ const spools = new Set<string>();
265
282
  const work = async () => {
266
283
  // Resolve the directory first so an explicitly nested output can be excluded.
267
284
  cwd = await resolveProjectDirectory(raw.cwd);
@@ -273,14 +290,22 @@ export function createProjectHost(definition: ProjectHarness, options: StartupOp
273
290
  await writeFile(path, raw.prompt, { flag: 'wx', mode: 0o600 });
274
291
  promptPath = path;
275
292
  signal.throwIfAborted();
276
- const configuration = options.configuration !== undefined ? validateConfiguration(options.configuration) : await loadConfiguration(options.launchDirectory, options.configPath);
293
+ const configuration = options.configuration !== undefined ? validateConfiguration(options.configuration) : await loadProjectConfiguration(options.launchDirectory, options.configPath);
277
294
  signal.throwIfAborted();
278
295
  let filePolicy;
279
296
  try { filePolicy = resolveFilePolicy((configuration as { filePolicy?: FilePolicy } | undefined)?.filePolicy); }
280
297
  catch { throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Invalid project file policy'); }
281
- const captured = await captureProject(cwd, outputDir, signal, filePolicy);
298
+ const capture = async (requestSignal?: AbortSignal) => {
299
+ const captured = await captureProject(cwd, outputDir, requestSignal ? AbortSignal.any([signal, requestSignal]) : signal, filePolicy);
300
+ const directory = fileSpool(captured.files)!.directory;
301
+ spools.add(directory);
302
+ return { ...captured, async dispose() {
303
+ await rm(directory, { recursive: true, force: true });
304
+ spools.delete(directory);
305
+ } };
306
+ };
307
+ const { dispose: _dispose, ...captured } = await capture();
282
308
  const { files, manifest, ...source } = captured;
283
- staged = fileSpool(files);
284
309
  initial = { ...source, manifestPath: null };
285
310
  signal.throwIfAborted();
286
311
  const manifestPath = join(outputDir, 'initial-files.json');
@@ -291,6 +316,7 @@ export function createProjectHost(definition: ProjectHarness, options: StartupOp
291
316
  return validateResult(await definition.run({
292
317
  input: Object.freeze({ cwd, prompt: raw.prompt }), initial: captured, configuration, runId: id, outputDir, signal,
293
318
  lifetime: 'task', clientCapabilities: { questions: false },
319
+ captureProject: capture,
294
320
  registerAgentControls() { return () => {}; },
295
321
  runWithRuntime() { throw projectError('INVALID_HARNESS_SESSION', 'Runtime reporting requires a HarnessSession'); },
296
322
  askUser() { return Promise.reject(projectError('OPERATION_UNSUPPORTED', 'No question channel is available')); },
@@ -312,7 +338,7 @@ export function createProjectHost(definition: ProjectHarness, options: StartupOp
312
338
  let workFinished = false;
313
339
  const running = work().finally(() => { workFinished = true; });
314
340
  const removeSpool = async () => {
315
- if (staged) await rm(staged.directory, { recursive: true, force: true });
341
+ await Promise.all([...spools].map(directory => rm(directory, { recursive: true, force: true })));
316
342
  };
317
343
  let business: ProjectHarnessResult;
318
344
  try {
@@ -1,4 +1,4 @@
1
- import { execFile } from 'node:child_process';
1
+ import { execFile, spawn } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { constants, type BigIntStats } from 'node:fs';
4
4
  import { lstat, mkdtemp, open, opendir, realpath, rm, type FileHandle } from 'node:fs/promises';
@@ -13,8 +13,12 @@ const git = promisify(execFile);
13
13
  const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
14
14
  const maxPathBytes = 4095;
15
15
  const maxPathDepth = 128;
16
- const directoryFlags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY;
17
- const fileFlags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
16
+ // Darwin's sys/fcntl.h O_NOFOLLOW_ANY checks every path component during open.
17
+ // Linux opens children relative to the already validated /proc directory descriptor.
18
+ const darwin = process.platform === 'darwin';
19
+ const noLinks = darwin ? 0x20000000 : constants.O_NOFOLLOW;
20
+ const directoryFlags = constants.O_RDONLY | noLinks | constants.O_DIRECTORY;
21
+ const fileFlags = constants.O_RDONLY | noLinks | constants.O_NONBLOCK;
18
22
 
19
23
  export function projectError(code: string, message: string) {
20
24
  return Object.assign(new Error(message), { code });
@@ -76,8 +80,48 @@ function sourceChanged(path: string) {
76
80
  return projectError('PROJECT_SOURCE_CHANGED', `Project source changed while capturing ${JSON.stringify(path)}`);
77
81
  }
78
82
 
79
- function accessPath(directory: FileHandle, name: string) {
80
- return `/proc/self/fd/${directory.fd}/${name}`;
83
+ async function* directoryNames(directory: FileHandle, label: string, signal: AbortSignal) {
84
+ if (!darwin) {
85
+ // Node returns byte names for this option, which the opendir types omit.
86
+ const listing = await opendir(`/proc/self/fd/${directory.fd}/.`, { encoding: 'buffer' as BufferEncoding });
87
+ for await (const entry of listing) yield entry.name;
88
+ return;
89
+ }
90
+ // Perl chdir on a filehandle uses fchdir. The helper opens "." relative to
91
+ // that descriptor, so concurrent path changes cannot redirect enumeration.
92
+ const listing = spawn('/usr/bin/perl', ['-e', String.raw`
93
+ open(my $anchor, "<&=3") or exit 1;
94
+ chdir($anchor) or exit 1;
95
+ opendir(my $directory, ".") or exit 1;
96
+ while (defined(my $name = readdir($directory))) {
97
+ print $name, "\0" unless $name eq "." || $name eq "..";
98
+ }
99
+ closedir($directory) or exit 1;
100
+ `], { stdio: ['ignore', 'pipe', 'ignore', directory.fd], env: { PATH: '/usr/bin:/bin' }, signal });
101
+ const exit = new Promise<number | null>(resolveExit => {
102
+ listing.once('error', () => resolveExit(null));
103
+ listing.once('close', resolveExit);
104
+ });
105
+ try {
106
+ let partial = Buffer.alloc(0);
107
+ for await (const chunk of listing.stdout!) {
108
+ signal.throwIfAborted();
109
+ const data = partial.length ? Buffer.concat([partial, chunk]) : chunk;
110
+ let offset = 0;
111
+ for (let end = data.indexOf(0); end !== -1; end = data.indexOf(0, offset)) {
112
+ yield data.subarray(offset, end);
113
+ offset = end + 1;
114
+ }
115
+ partial = data.subarray(offset);
116
+ if (partial.length > maxPathBytes) throw sourceChanged(label);
117
+ }
118
+ const status = await exit;
119
+ signal.throwIfAborted();
120
+ if (status !== 0 || partial.length) throw sourceChanged(label);
121
+ } finally {
122
+ if (listing.exitCode === null && listing.signalCode === null) listing.kill();
123
+ await exit;
124
+ }
81
125
  }
82
126
 
83
127
  async function gitFiles(cwd: string, signal: AbortSignal, maxEntries: number) {
@@ -150,11 +194,24 @@ export async function captureProject(cwd: string, outputDir: string, signal: Abo
150
194
  }
151
195
 
152
196
  async function readProject(cwd: string, outputDir: string, spool: string, signal: AbortSignal, policy: ResolvedFilePolicy) {
197
+ if (darwin) {
198
+ cwd = await resolveProjectDirectory(cwd);
199
+ outputDir = await realpath(outputDir);
200
+ }
153
201
  const excluded = isInside(cwd, outputDir) ? relative(cwd, outputDir) : null;
202
+ const directoryPaths = new WeakMap<FileHandle, { path: string; stat: BigIntStats }>();
203
+ async function accessPath(directory: FileHandle, name: string, label: string) {
204
+ if (!darwin) return `/proc/self/fd/${directory.fd}/${name}`;
205
+ const expected = directoryPaths.get(directory)!;
206
+ const current = await lstat(expected.path, { bigint: true }).catch(() => { throw sourceChanged(label); });
207
+ if (!sameFile(expected.stat, current)) throw sourceChanged(label);
208
+ return join(expected.path, name);
209
+ }
154
210
  const entries: SpoolFile[] = [];
155
211
  const budget = policy.initial;
156
212
  const buffer = Buffer.alloc(MAX_COLLECTION_CHUNK_BYTES);
157
- const skip = (path: string) => isGitPath(path) ||
213
+ const skip = (path: string, tracked = false) => isGitPath(path) ||
214
+ (!tracked && /^(?:node_modules|\.anyswarm-sdk|\.anyswarm-code-recovery-[A-Za-z0-9]{6})(?:\/|$)/.test(path)) ||
158
215
  (excluded !== null && (path === excluded || path.startsWith(excluded + '/')));
159
216
  let bytes = 0;
160
217
  let count = 0;
@@ -164,6 +221,7 @@ async function readProject(cwd: string, outputDir: string, spool: string, signal
164
221
  const handle = await open(path, flags).catch(() => { throw sourceChanged(label); });
165
222
  try {
166
223
  if (!sameFile(before, await handle.stat({ bigint: true }))) throw sourceChanged(label);
224
+ if (darwin && before.isDirectory()) directoryPaths.set(handle, { path, stat: before });
167
225
  return handle;
168
226
  } catch (error) {
169
227
  await handle.close();
@@ -180,7 +238,7 @@ async function readProject(cwd: string, outputDir: string, spool: string, signal
180
238
  info.size > BigInt(Math.min(budget.maxBytes, policy.controllerSpoolBytes) - bytes)) {
181
239
  throw projectError('PROJECT_FILE_LIMIT', `Project exceeds the file count or byte limit at ${JSON.stringify(path)}`);
182
240
  }
183
- const location = accessPath(parent, name);
241
+ const location = await accessPath(parent, name, path);
184
242
  // Check the shared physical filesystem before each file; write failures
185
243
  // still take precedence if another process consumes that space meanwhile.
186
244
  await checkFileSpace(spool, Number(info.size), 1, 'Controller staging');
@@ -222,7 +280,7 @@ async function readProject(cwd: string, outputDir: string, spool: string, signal
222
280
  if (!info.isDirectory()) {
223
281
  throw projectError('PROJECT_FILE_UNSUPPORTED', `Project ancestor is not a directory: ${JSON.stringify(path)}`);
224
282
  }
225
- const location = accessPath(parent, name);
283
+ const location = await accessPath(parent, name, path);
226
284
  const child = await openChecked(location, info, directoryFlags, path);
227
285
  try {
228
286
  await visit(child);
@@ -239,7 +297,8 @@ async function readProject(cwd: string, outputDir: string, spool: string, signal
239
297
  signal.throwIfAborted();
240
298
  const name = parts[depth];
241
299
  const path = parts.slice(0, depth + 1).join('/');
242
- const info = await lstat(accessPath(parent, name), { bigint: true }).catch(error => {
300
+ const location = await accessPath(parent, name, path);
301
+ const info = await lstat(location, { bigint: true }).catch(error => {
243
302
  if (error.code === 'ENOENT' && tracked) return null;
244
303
  if (error.code === 'ENOENT') throw sourceChanged(path);
245
304
  throw error;
@@ -254,18 +313,17 @@ async function readProject(cwd: string, outputDir: string, spool: string, signal
254
313
  }
255
314
 
256
315
  async function walk(directory: FileHandle, prefix = '') {
257
- // Node returns byte names for this option, which the opendir types omit.
258
- const listing = await opendir(accessPath(directory, '.'), { encoding: 'buffer' as BufferEncoding });
259
- for await (const entry of listing) {
316
+ for await (const entry of directoryNames(directory, prefix || '.', signal)) {
260
317
  signal.throwIfAborted();
261
- const name = decodePath(entry.name);
318
+ const name = decodePath(entry);
262
319
  const path = prefix + name;
263
320
  if (++enumerated > budget.maxEntries) {
264
321
  throw projectError('PROJECT_FILE_LIMIT', `Project exceeds the directory enumeration limit at ${JSON.stringify(path)}`);
265
322
  }
266
323
  if (skip(path)) continue;
267
324
  normalizedPath(path);
268
- const info = await lstat(accessPath(directory, name), { bigint: true }).catch(() => { throw sourceChanged(path); });
325
+ const location = await accessPath(directory, name, path);
326
+ const info = await lstat(location, { bigint: true }).catch(() => { throw sourceChanged(path); });
269
327
  if (info.isDirectory()) await inDirectory(directory, name, path, info, child => walk(child, path + '/'));
270
328
  else await captureFile(directory, name, path, info);
271
329
  }
@@ -281,7 +339,7 @@ async function readProject(cwd: string, outputDir: string, spool: string, signal
281
339
  if (paths) {
282
340
  if (paths.size > budget.maxEntries) throw projectError('PROJECT_FILE_LIMIT', 'Project exceeds its Git enumeration limit');
283
341
  for (const [path, { tracked, gitlink }] of paths) {
284
- if (skip(path)) continue;
342
+ if (skip(path, tracked)) continue;
285
343
  if (path.endsWith('/')) {
286
344
  throw projectError('PROJECT_GITLINK_UNSUPPORTED', `Nested repository is in the project scope: ${JSON.stringify(path)}`);
287
345
  }
@@ -48,6 +48,7 @@ type Pending = {
48
48
  export class HarnessRpcClient implements HarnessSession {
49
49
  readonly ready: Promise<HarnessRpcReady>;
50
50
  readonly agents: HarnessSession['agents'];
51
+ readonly services: HarnessSession['services'];
51
52
  readonly #ready = Promise.withResolvers<HarnessRpcReady>();
52
53
  readonly #result = Promise.withResolvers<HarnessResult>();
53
54
  readonly #pending = new Map<string, Pending>();
@@ -117,6 +118,10 @@ export class HarnessRpcClient implements HarnessSession {
117
118
  interrupt: (agentId, { requestId, ...options }) => this.#call('agent.interrupt', { agentId, options }, requestId),
118
119
  stop: (agentId, { requestId, ...options }) => this.#call('agent.stop', { agentId, options }, requestId),
119
120
  });
121
+ this.services = Object.freeze<HarnessSession['services']>({
122
+ list: () => this.#call('service.list'),
123
+ read: (runtimeId, name) => this.#call('service.read', { runtimeId, name }),
124
+ });
120
125
  }
121
126
 
122
127
  describe(): ReturnType<HarnessSession['describe']> {
@@ -1,7 +1,6 @@
1
1
  import { frameworkErrorFields } from '../core/error-diagnostics.js';
2
2
  import type { AgentSessionPatch, ContextInput, ContextSendOptions } from '../core/session-types.js';
3
3
  import type { SendOptions } from '../core/types.js';
4
- import type { Readable } from 'node:stream';
5
4
  import { createHash } from 'node:crypto';
6
5
  import { stableStringify } from '../protocol/stable-json.js';
7
6
  import { MAX_COMMAND_BYTES } from './foreground-commands.js';
@@ -10,15 +9,16 @@ import {
10
9
  type HarnessInput, type HarnessJson,
11
10
  } from './project-harness.js';
12
11
  import { projectError, resolveHarnessInput } from './project-input.js';
13
- import { readRpcLines } from './project-rpc-lines.js';
12
+ import { readRpcLines, type RpcReadable } from './project-rpc-lines.js';
14
13
  import type { HarnessEvent, HarnessSession } from './harness-session-types.js';
15
14
 
16
15
  type Writer = (record: unknown, replaceableState?: boolean) => Promise<void>;
16
+ type RpcServerInput = RpcReadable & { readonly destroyed: boolean; pause(): unknown };
17
17
  type ParametersObject = Record<string, unknown>;
18
18
  type RpcRequest = { id: string; operation: string; input?: HarnessJson; requestId?: string };
19
19
  type QueryReceipt = { fingerprint: string; timer: NodeJS.Timeout };
20
20
 
21
- const queryOperations = new Set(['status', 'describe', 'agent.getState', 'agent.getStats', 'agent.getMessages']);
21
+ const queryOperations = new Set(['status', 'describe', 'agent.getState', 'agent.getStats', 'agent.getMessages', 'service.list', 'service.read']);
22
22
  const mutationOperations = new Set([
23
23
  'run', 'input', 'answer', 'stop', 'agent.configure', 'agent.compact',
24
24
  'agent.abortRetry', 'agent.clearQueue', 'agent.send', 'agent.interrupt', 'agent.stop',
@@ -78,6 +78,13 @@ function dispatch(session: HarnessSession, request: RpcRequest, launchDirectory:
78
78
  optional(input, []);
79
79
  if (input !== undefined) throw projectError('INVALID_REQUEST', 'Describe takes no input');
80
80
  return session.describe();
81
+ case 'service.list':
82
+ if (input !== undefined) throw projectError('INVALID_REQUEST', 'Service list takes no input');
83
+ return session.services.list();
84
+ case 'service.read': {
85
+ const { runtimeId, name } = named(input, ['runtimeId', 'name']);
86
+ return session.services.read(requiredString(runtimeId), requiredString(name));
87
+ }
81
88
  case 'answer': {
82
89
  const { questionId, answer } = named(input, ['questionId', 'answer']);
83
90
  if (typeof answer !== 'string' && typeof answer !== 'boolean') throw projectError('INVALID_REQUEST', 'Invalid answer');
@@ -158,7 +165,7 @@ function eventRecord(event: HarnessEvent) {
158
165
  }
159
166
 
160
167
  export async function runProjectRpc(
161
- session: HarnessSession, input: Readable, write: Writer, launchDirectory: string, initialInput?: HarnessInput,
168
+ session: HarnessSession, input: RpcServerInput, write: Writer, launchDirectory: string, initialInput?: HarnessInput, options: { detachOnDisconnect?: boolean } = {},
162
169
  ) {
163
170
  const done = Promise.withResolvers<number>();
164
171
  const queryReceipts = new Map<string, QueryReceipt>();
@@ -180,7 +187,7 @@ export async function runProjectRpc(
180
187
 
181
188
  function watchCompletion() {
182
189
  const completion = session.completion;
183
- if (!completion || watchingCompletion) return;
190
+ if (!completion || watchingCompletion || options.detachOnDisconnect) return;
184
191
  watchingCompletion = true;
185
192
  void completion.then(async result => {
186
193
  closed = true;
@@ -253,6 +260,11 @@ export async function runProjectRpc(
253
260
  }
254
261
  signal.addEventListener('abort', stopTransport, { once: true });
255
262
  const unsubscribe = session.onEvent(event => {
263
+ if (event.type === 'result' && options.detachOnDisconnect) {
264
+ void write({ type: 'result', runId: event.result.runId, result: event.result })
265
+ .then(() => done.resolve(getHarnessExitCode(session) ?? 1), done.reject);
266
+ return;
267
+ }
256
268
  const record = eventRecord(event);
257
269
  if (record) send(record, event.type === 'state');
258
270
  });
@@ -261,15 +273,24 @@ export async function runProjectRpc(
261
273
  const descriptor = await session.describe();
262
274
  const status = captureHarnessSnapshot(session);
263
275
  send({ type: 'ready', version: 'v1', harness: status.harness, status, descriptor });
276
+ if (options.detachOnDisconnect && status.phase === 'finished' && session.completion) {
277
+ const result = await session.completion;
278
+ await write({ type: 'result', runId: result.runId, result });
279
+ return getHarnessExitCode(session) ?? 1;
280
+ }
264
281
  if (signal.aborted) stopTransport();
265
282
  else if (initialInput) onLine(JSON.stringify({ id: 'foreground-start', operation: 'run', input: initialInput }));
283
+ const disconnect = (reason: string) => {
284
+ if (options.detachOnDisconnect) done.resolve(0);
285
+ else stopHarnessTransport(session, reason);
286
+ };
266
287
  detach = readRpcLines(input, MAX_COMMAND_BYTES, {
267
288
  line: onLine,
268
289
  invalid: () => send(errorRecord('INVALID_REQUEST')),
269
- end: () => stopHarnessTransport(session, 'input-ended'),
270
- error: () => stopHarnessTransport(session, 'input-failed'),
290
+ end: () => disconnect('input-ended'),
291
+ error: () => disconnect('input-failed'),
271
292
  });
272
- if (input.readableEnded) stopHarnessTransport(session, 'input-ended');
293
+ if (input.readableEnded || input.destroyed) disconnect('input-ended');
273
294
  return await done.promise;
274
295
  } finally {
275
296
  closed = true;
@@ -28,6 +28,7 @@ export function observeProjectRuntime(runtime: Runtime, context: ProjectHarnessC
28
28
  }
29
29
 
30
30
  async function refresh() {
31
+ if (!business) return;
31
32
  pending = true;
32
33
  if (refreshing || closed) return;
33
34
  refreshing = true;
@@ -35,7 +36,7 @@ export function observeProjectRuntime(runtime: Runtime, context: ProjectHarnessC
35
36
  while (pending && !closed) {
36
37
  pending = false;
37
38
  try {
38
- const detail = await read(business?.() ?? null);
39
+ const detail = await read(business());
39
40
  if (!closed && !signal.aborted) context.updateStatus({
40
41
  business: json({ runtimeId: runtime.id, runtimeState: runtime.state, detail }),
41
42
  });
@@ -62,7 +63,8 @@ export async function projectConfiguration<C>(context: ProjectHarnessContext, de
62
63
  if (!value || typeof value !== 'object' || !('sandbox' in value) || !('models' in value) || !('image' in value)) {
63
64
  throw new Error('Missing sandbox, models or image');
64
65
  }
65
- } catch {
66
+ } catch (error) {
67
+ if (error instanceof ProjectPreflightError) throw error;
66
68
  throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Configure sandbox, models and image for this Harness');
67
69
  }
68
70
  context.signal.throwIfAborted();
@@ -0,0 +1,37 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { registerHooks, stripTypeScriptTypes } from 'node:module';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ let installed = false;
6
+
7
+ /** Enable trusted author TypeScript without changing the author's package scope. */
8
+ export function installSourceLoader() {
9
+ if (installed) return;
10
+ installed = true;
11
+ // Node 22.19+ supports transformation and inline maps, including enums.
12
+ const transform = stripTypeScriptTypes as unknown as (source: string, options: { mode: 'transform'; sourceMap: true; sourceUrl: string }) => string;
13
+ const sdk = new URL('../core/index.js', import.meta.url).href;
14
+ registerHooks({
15
+ resolve(specifier, context, nextResolve) {
16
+ try {
17
+ return nextResolve(specifier, context);
18
+ } catch (error) {
19
+ if ((error as NodeJS.ErrnoException).code !== 'ERR_MODULE_NOT_FOUND' &&
20
+ (error as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') throw error;
21
+ if (specifier === '@anyswarm/core') return { url: sdk, shortCircuit: true };
22
+ if (context.parentURL?.startsWith('file:') && /^(?:\.{1,2}\/|\/)/.test(specifier) && /\.m?js$/.test(specifier)) {
23
+ const source = new URL(specifier.replace(/\.m?js$/, match => match === '.mjs' ? '.mts' : '.ts'), context.parentURL);
24
+ if (existsSync(source)) return { url: source.href, shortCircuit: true };
25
+ }
26
+ throw error;
27
+ }
28
+ },
29
+ load(url, context, nextLoad) {
30
+ if (!url.startsWith('file:') || !/\.(?:ts|mts)$/.test(new URL(url).pathname)) return nextLoad(url, context);
31
+ const source = transform(readFileSync(fileURLToPath(url), 'utf8'), {
32
+ mode: 'transform', sourceMap: true, sourceUrl: url,
33
+ });
34
+ return { format: 'module', source, shortCircuit: true };
35
+ },
36
+ });
37
+ }
@@ -13,6 +13,7 @@ const TRACK_DEFS = [
13
13
  { key: "model", label: "Model", color: "var(--purple)" },
14
14
  { key: "tool", label: "Tools", color: "var(--amber)" },
15
15
  { key: "service", label: "Service", color: "var(--teal)" },
16
+ { key: "research", label: "Research", color: "var(--teal)" },
16
17
  ];
17
18
 
18
19
  const state = {
@@ -1125,10 +1126,8 @@ function renderSwimlane() {
1125
1126
  let curY = rulerH;
1126
1127
  const geom = [];
1127
1128
  for (const ag of agents) {
1128
- const hasSvc = state.timelineItems.some(
1129
- (i) => laneContains(ag, i.agentId) && i.kind === "service",
1130
- );
1131
- const tracks = TRACK_DEFS.filter((td) => td.key !== "service" || hasSvc);
1129
+ const active = new Set(state.timelineItems.filter(item => laneContains(ag, item.agentId)).map(item => item.kind));
1130
+ const tracks = TRACK_DEFS.filter(track => !["service", "research"].includes(track.key) || active.has(track.key));
1132
1131
  const startY = curY;
1133
1132
  const rowY = {};
1134
1133
  curY += headH;
@@ -1453,7 +1452,7 @@ function renderSwimlane() {
1453
1452
  it.startedAt - state.domainStart <= state.winEnd,
1454
1453
  );
1455
1454
  const isPointTrack =
1456
- td.key === "input" || (td.key === "tool" && !run.hasNative);
1455
+ td.key === "input" || td.key === "research" || (td.key === "tool" && !run.hasNative);
1457
1456
  const { rects, merged, overlaps } = layoutTrackBars(
1458
1457
  trackItems,
1459
1458
  xOf,
@@ -1759,6 +1758,7 @@ function renderTrajectory() {
1759
1758
  tool: state.timelineItems.filter((i) => i.kind === "tool").length,
1760
1759
  service: state.timelineItems.filter((i) => i.kind === "service").length,
1761
1760
  input: state.timelineItems.filter((i) => i.kind === "input").length,
1761
+ research: state.timelineItems.filter((i) => i.kind === "research").length,
1762
1762
  error: state.timelineItems.filter((i) => i.isError).length,
1763
1763
  };
1764
1764
  const pills = $("#track-filter-pills");
@@ -1770,6 +1770,7 @@ function renderTrajectory() {
1770
1770
  ["service", `Service (${counts.service})`],
1771
1771
  ["input", `Input (${counts.input})`],
1772
1772
  ];
1773
+ if (counts.research) defs.push(["research", `Research (${counts.research})`]);
1773
1774
  if (counts.error) defs.push(["error", `Errors (${counts.error})`]);
1774
1775
  for (const [key, label] of defs) {
1775
1776
  const b = button(