@anyswarm/core 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (403) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +21 -13
  3. package/deploy/worker/Dockerfile +12 -4
  4. package/dist/deploy/worker/Dockerfile +12 -4
  5. package/dist/examples/README.md +35 -12
  6. package/dist/examples/authoring/README.md +24 -0
  7. package/dist/examples/authoring/business.d.ts +2 -0
  8. package/dist/examples/authoring/business.js +4 -0
  9. package/dist/examples/authoring/config.d.ts +5 -0
  10. package/dist/examples/authoring/config.js +2 -0
  11. package/dist/examples/authoring/eject.json +5 -0
  12. package/dist/examples/authoring/harness.d.ts +4 -0
  13. package/dist/examples/authoring/harness.js +19 -0
  14. package/dist/examples/autoresearch/README.md +40 -0
  15. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +11 -0
  16. package/dist/examples/autoresearch/config.d.ts +51 -0
  17. package/dist/examples/autoresearch/config.js +57 -0
  18. package/dist/examples/autoresearch/demo.d.ts +11 -0
  19. package/dist/examples/autoresearch/demo.js +52 -0
  20. package/dist/examples/autoresearch/eject.json +17 -0
  21. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -0
  22. package/dist/examples/autoresearch/frontiercs2-config.js +3 -0
  23. package/dist/examples/autoresearch/frontiercs2.d.ts +87 -0
  24. package/dist/examples/autoresearch/frontiercs2.js +211 -0
  25. package/dist/examples/autoresearch/prepare-demo.d.ts +1 -0
  26. package/dist/examples/autoresearch/prepare-demo.js +15 -0
  27. package/dist/examples/autoresearch/prepare.d.ts +95 -0
  28. package/dist/examples/autoresearch/prepare.js +257 -0
  29. package/dist/examples/autoresearch/process.d.ts +13 -0
  30. package/dist/examples/autoresearch/process.js +48 -0
  31. package/dist/examples/autoresearch/project.d.ts +21 -0
  32. package/dist/examples/autoresearch/project.js +392 -0
  33. package/dist/examples/autoresearch/research-service.d.ts +106 -0
  34. package/dist/examples/autoresearch/research-service.js +255 -0
  35. package/dist/examples/code/README.md +33 -0
  36. package/dist/examples/code/REQUIREMENTS.zh.md +11 -0
  37. package/dist/examples/code/candidate.d.ts +19 -0
  38. package/dist/examples/code/candidate.js +80 -0
  39. package/dist/examples/code/config.d.ts +32 -0
  40. package/dist/examples/code/config.js +18 -0
  41. package/dist/examples/code/eject.json +5 -0
  42. package/dist/examples/code/project.d.ts +3 -0
  43. package/dist/examples/code/project.js +605 -0
  44. package/dist/examples/code/prompts.d.ts +5 -0
  45. package/dist/examples/code/prompts.js +12 -0
  46. package/dist/examples/code/verification.d.ts +19 -0
  47. package/dist/examples/code/verification.js +268 -0
  48. package/dist/examples/code/worktree.d.ts +17 -0
  49. package/dist/examples/code/worktree.js +233 -0
  50. package/dist/examples/harness-session/README.md +3 -6
  51. package/dist/examples/lead-worker/harness/dynamic-scheduler.d.ts +2 -1
  52. package/dist/examples/lead-worker/harness/dynamic-scheduler.js +5 -2
  53. package/dist/examples/lead-worker/harness/index.d.ts +60 -0
  54. package/dist/examples/lead-worker/harness/index.js +77 -6
  55. package/dist/examples/lead-worker/project.js +2 -2
  56. package/dist/examples/lead-worker/services/board.d.ts +5 -0
  57. package/dist/examples/lead-worker/services/board.js +19 -1
  58. package/dist/examples/messages/README.md +5 -5
  59. package/dist/examples/messages/handoff.d.ts +2 -0
  60. package/dist/examples/messages/handoff.js +5 -1
  61. package/dist/examples/messages/project.js +52 -2
  62. package/dist/examples/notes/README.md +13 -18
  63. package/dist/examples/notes/project.js +67 -6
  64. package/dist/examples/peermesh/harness/router.js +3 -1
  65. package/dist/examples/peermesh/harness/team.d.ts +8 -0
  66. package/dist/examples/peermesh/harness/team.js +13 -0
  67. package/dist/examples/peermesh/project.js +22 -4
  68. package/dist/examples/services/agent-control/README.md +3 -3
  69. package/dist/examples/services/mathlib-search/Dockerfile +4 -2
  70. package/dist/examples/services/mathlib-search/README.md +1 -1
  71. package/dist/examples/services/mcp-managed/README.md +2 -2
  72. package/dist/examples/services/persistent-board/README.md +16 -3
  73. package/dist/examples/services/persistent-board/business.d.ts +7 -0
  74. package/dist/examples/services/persistent-board/business.js +7 -0
  75. package/dist/examples/services/persistent-board/index.js +10 -0
  76. package/dist/examples/services/persistent-board/live.d.ts +3 -0
  77. package/dist/examples/services/persistent-board/live.js +58 -0
  78. package/dist/examples/subagents/README.md +5 -5
  79. package/dist/examples/subagents/business.js +3 -1
  80. package/dist/examples/subagents/config.js +3 -3
  81. package/dist/examples/subagents/harness/controller.d.ts +15 -0
  82. package/dist/examples/subagents/harness/controller.js +181 -32
  83. package/dist/examples/subagents/project.d.ts +2 -0
  84. package/dist/examples/subagents/project.js +43 -34
  85. package/dist/examples/subagents/prompts/prompts.d.ts +1 -0
  86. package/dist/examples/subagents/prompts/prompts.js +3 -0
  87. package/dist/examples/subagents/services/collaboration-service.d.ts +3 -2
  88. package/dist/examples/subagents/services/collaboration-service.js +14 -2
  89. package/dist/examples/substrate/README.md +2 -2
  90. package/dist/examples/substrate/harness/index.d.ts +1 -1
  91. package/dist/examples/substrate/harness/index.js +77 -12
  92. package/dist/examples/substrate/project.js +4 -1
  93. package/dist/examples/super/README.md +52 -0
  94. package/dist/examples/super/actions.d.ts +95 -0
  95. package/dist/examples/super/actions.js +230 -0
  96. package/dist/examples/super/artifact.d.ts +4 -0
  97. package/dist/examples/super/artifact.js +51 -0
  98. package/dist/examples/super/config.d.ts +80 -0
  99. package/dist/examples/super/config.js +83 -0
  100. package/dist/examples/super/coordinator.d.ts +33 -0
  101. package/dist/examples/super/coordinator.js +151 -0
  102. package/dist/examples/super/daemon.d.ts +11 -0
  103. package/dist/examples/super/daemon.js +109 -0
  104. package/dist/examples/super/decisions.d.ts +8 -0
  105. package/dist/examples/super/decisions.js +52 -0
  106. package/dist/examples/super/eject.json +5 -0
  107. package/dist/examples/super/execution.d.ts +11 -0
  108. package/dist/examples/super/execution.js +136 -0
  109. package/dist/examples/super/github.d.ts +62 -0
  110. package/dist/examples/super/github.js +269 -0
  111. package/dist/examples/super/inbox.d.ts +162 -0
  112. package/dist/examples/super/inbox.js +284 -0
  113. package/dist/examples/super/location.d.ts +5 -0
  114. package/dist/examples/super/location.js +64 -0
  115. package/dist/examples/super/operator.d.ts +1 -0
  116. package/dist/examples/super/operator.js +31 -0
  117. package/dist/examples/super/outbox.d.ts +5 -0
  118. package/dist/examples/super/outbox.js +103 -0
  119. package/dist/examples/super/project.d.ts +4 -0
  120. package/dist/examples/super/project.js +251 -0
  121. package/dist/examples/super/prompts.d.ts +3 -0
  122. package/dist/examples/super/prompts.js +25 -0
  123. package/dist/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  124. package/dist/examples/taskpool/harness/controller.d.ts +35 -6
  125. package/dist/examples/taskpool/harness/controller.js +73 -7
  126. package/dist/examples/taskpool/project.js +18 -2
  127. package/dist/scripts/anyswarm-arguments.d.ts +18 -6
  128. package/dist/scripts/anyswarm-arguments.js +88 -52
  129. package/dist/scripts/anyswarm-author.d.ts +5 -0
  130. package/dist/scripts/anyswarm-author.js +24 -0
  131. package/dist/scripts/anyswarm-eject.d.ts +11 -0
  132. package/dist/scripts/anyswarm-eject.js +164 -0
  133. package/dist/scripts/anyswarm-harnesses.d.ts +1 -0
  134. package/dist/scripts/anyswarm-harnesses.js +10 -0
  135. package/dist/scripts/anyswarm-installation.d.ts +7 -40
  136. package/dist/scripts/anyswarm-installation.js +17 -285
  137. package/dist/scripts/anyswarm-launch.d.ts +7 -0
  138. package/dist/scripts/anyswarm-launch.js +37 -0
  139. package/dist/scripts/anyswarm-progress.d.ts +6 -0
  140. package/dist/scripts/anyswarm-progress.js +102 -0
  141. package/dist/scripts/anyswarm-project.d.ts +3 -1
  142. package/dist/scripts/anyswarm-project.js +49 -35
  143. package/dist/scripts/anyswarm-source-runner.d.ts +1 -0
  144. package/dist/scripts/anyswarm-source-runner.js +200 -0
  145. package/dist/scripts/anyswarm.js +28 -3
  146. package/dist/scripts/build-provenance.json +1 -0
  147. package/dist/scripts/build.js +7 -1
  148. package/dist/scripts/generate-architecture-api.js +2 -0
  149. package/dist/scripts/generate-architecture-prompts.js +24 -2
  150. package/dist/scripts/local-environment.d.ts +13 -2
  151. package/dist/scripts/local-environment.js +111 -28
  152. package/dist/scripts/local-setup-smoke.js +3 -2
  153. package/dist/scripts/local-setup-worker.d.ts +1 -1
  154. package/dist/scripts/local-setup-worker.js +15 -6
  155. package/dist/scripts/local-setup.d.ts +5 -2
  156. package/dist/scripts/local-setup.js +167 -79
  157. package/dist/scripts/opensandbox-agent-worker.js +2 -2
  158. package/dist/scripts/pack-release.d.ts +1 -0
  159. package/dist/scripts/pack-release.js +66 -0
  160. package/dist/scripts/pi-session-bridge.js +11 -3
  161. package/dist/scripts/run-harness.js +3 -1
  162. package/dist/scripts/setup-bootstrap.js +43 -6
  163. package/dist/src/core/allocation-ledger.js +4 -3
  164. package/dist/src/core/host-identity.d.ts +2 -0
  165. package/dist/src/core/host-identity.js +11 -0
  166. package/dist/src/core/index.d.ts +4 -2
  167. package/dist/src/core/index.js +12 -4
  168. package/dist/src/core/mcp-service.js +2 -2
  169. package/dist/src/core/runtime-management.d.ts +6 -0
  170. package/dist/src/core/runtime-management.js +24 -0
  171. package/dist/src/core/sandbox/executor-driver.d.ts +4 -2
  172. package/dist/src/core/sandbox/executor-driver.js +12 -14
  173. package/dist/src/core/sandbox/local-executor.d.ts +13 -1
  174. package/dist/src/core/sandbox/local-executor.js +69 -19
  175. package/dist/src/core/sandbox/local-worker.js +32 -21
  176. package/dist/src/core/sandbox/opensandbox-backend.d.ts +2 -0
  177. package/dist/src/core/sandbox/opensandbox-backend.js +36 -11
  178. package/dist/src/core/sandbox/sandbox-connection.d.ts +2 -0
  179. package/dist/src/core/sandbox/sandbox-connection.js +14 -6
  180. package/dist/src/core/service-live-state.d.ts +14 -0
  181. package/dist/src/core/service-live-state.js +161 -0
  182. package/dist/src/core/service-observation-types.d.ts +21 -1
  183. package/dist/src/core/service-process.d.ts +1 -1
  184. package/dist/src/core/service-process.js +45 -4
  185. package/dist/src/core/service-types.d.ts +5 -1
  186. package/dist/src/core/services.d.ts +1 -1
  187. package/dist/src/core/services.js +8 -3
  188. package/dist/src/core/types.d.ts +3 -0
  189. package/dist/src/core/worker-image.js +3 -3
  190. package/dist/src/harness/harness-session-types.d.ts +10 -0
  191. package/dist/src/harness/harness-session.js +42 -5
  192. package/dist/src/harness/project-harness.d.ts +14 -1
  193. package/dist/src/harness/project-harness.js +38 -12
  194. package/dist/src/harness/project-input.js +81 -15
  195. package/dist/src/harness/project-rpc-client.d.ts +1 -0
  196. package/dist/src/harness/project-rpc-client.js +5 -0
  197. package/dist/src/harness/project-rpc.d.ts +8 -2
  198. package/dist/src/harness/project-rpc.js +31 -7
  199. package/dist/src/harness/project-runtime.js +6 -2
  200. package/dist/src/harness/typescript-loader.d.ts +2 -0
  201. package/dist/src/harness/typescript-loader.js +41 -0
  202. package/dist/src/trace-viewer/public/app.js +6 -5
  203. package/dist/src/trace-viewer/reader.mjs +42 -2
  204. package/docs/INDEX.md +5 -2
  205. package/docs/architecture/00-overview.md +1 -1
  206. package/docs/architecture/01-agent-core.md +1 -1
  207. package/docs/architecture/04-services.md +1 -1
  208. package/docs/architecture/06-observability-experiments.md +1 -1
  209. package/docs/architecture/07-run-configuration.md +38 -18
  210. package/docs/architecture/08-prompts.md +22 -0
  211. package/docs/architecture/10-service-api-reference.md +53 -18
  212. package/docs/architecture/11-storage-reference.md +18 -1
  213. package/docs/architecture/12-code-coverage.md +152 -89
  214. package/docs/architecture/15-core-runtime.md +8 -0
  215. package/docs/architecture/16-pi-opensandbox-backend.md +5 -5
  216. package/docs/architecture/17-harness-reporting.md +1 -1
  217. package/docs/architecture/19-substrate-harness.md +28 -1
  218. package/docs/architecture/20-lead-worker-harness.md +34 -1
  219. package/docs/architecture/22-website.md +5 -6
  220. package/docs/architecture/23-project-harness.md +152 -8
  221. package/docs/architecture/24-runtime-recovery.md +10 -3
  222. package/docs/architecture/26-code.md +54 -0
  223. package/docs/architecture/27-personal.md +58 -0
  224. package/docs/architecture/28-autoresearch.md +43 -0
  225. package/docs/architecture/INDEX.md +3 -0
  226. package/docs/architecture/prompts/08-lead-worker-harness.md +4 -2
  227. package/docs/architecture/prompts/08-subagents-harness.md +21 -0
  228. package/docs/architecture/prompts/21-personal.md +44 -0
  229. package/docs/architecture/prompts/22-autoresearch.md +63 -0
  230. package/docs/architecture/prompts/26-code.md +55 -0
  231. package/docs/architecture/prompts/source-manifest.json +152 -33
  232. package/docs/architecture/source-map.json +473 -25
  233. package/docs/designs/core-harness/01-core.md +2 -2
  234. package/docs/designs/core-harness/06-project-harness.md +13 -2
  235. package/docs/designs/core-harness/README.md +7 -2
  236. package/docs/en/agents.md +1 -1
  237. package/docs/en/build-your-harness.md +3 -5
  238. package/docs/en/changelog.md +20 -4
  239. package/docs/en/first-harness.md +9 -12
  240. package/docs/en/harnesses/lead-worker.md +1 -1
  241. package/docs/en/harnesses/peermesh.md +2 -2
  242. package/docs/en/harnesses/subagents.md +2 -2
  243. package/docs/en/harnesses/substrate.md +4 -4
  244. package/docs/en/harnesses/taskpool.md +2 -2
  245. package/docs/en/latest.md +14 -121
  246. package/docs/en/overview.md +1 -1
  247. package/docs/en/quickstart.md +42 -39
  248. package/docs/en/reference/api.md +14 -4
  249. package/docs/en/reference/cli.md +53 -47
  250. package/docs/en/runtime.md +2 -2
  251. package/docs/en/sandbox.md +3 -3
  252. package/docs/en/services.md +4 -0
  253. package/docs/operations/trace-viewer.md +1 -1
  254. package/docs/workflows/development.md +28 -21
  255. package/docs/workflows/release-and-docs-versioning.md +77 -0
  256. package/docs/workflows/release-cli-acceptance.md +85 -0
  257. package/docs/zh/agents.md +1 -1
  258. package/docs/zh/build-your-harness.md +3 -5
  259. package/docs/zh/changelog.md +20 -4
  260. package/docs/zh/first-harness.md +9 -12
  261. package/docs/zh/harnesses/lead-worker.md +1 -1
  262. package/docs/zh/harnesses/peermesh.md +2 -2
  263. package/docs/zh/harnesses/subagents.md +2 -2
  264. package/docs/zh/harnesses/substrate.md +4 -4
  265. package/docs/zh/harnesses/taskpool.md +2 -2
  266. package/docs/zh/latest.md +15 -122
  267. package/docs/zh/overview.md +1 -1
  268. package/docs/zh/quickstart.md +42 -39
  269. package/docs/zh/reference/api.md +14 -4
  270. package/docs/zh/reference/cli.md +24 -40
  271. package/docs/zh/runtime.md +2 -2
  272. package/docs/zh/sandbox.md +3 -3
  273. package/docs/zh/services.md +4 -0
  274. package/examples/README.md +35 -12
  275. package/examples/authoring/README.md +24 -0
  276. package/examples/authoring/business.ts +4 -0
  277. package/examples/authoring/config.ts +2 -0
  278. package/examples/authoring/eject.json +5 -0
  279. package/examples/authoring/harness.ts +21 -0
  280. package/examples/autoresearch/README.md +40 -0
  281. package/examples/autoresearch/REQUIREMENTS.zh.md +11 -0
  282. package/examples/autoresearch/config.ts +90 -0
  283. package/examples/autoresearch/demo.ts +55 -0
  284. package/examples/autoresearch/eject.json +17 -0
  285. package/examples/autoresearch/frontiercs2-config.ts +4 -0
  286. package/examples/autoresearch/frontiercs2.ts +237 -0
  287. package/examples/autoresearch/prepare-demo.ts +15 -0
  288. package/examples/autoresearch/prepare.ts +267 -0
  289. package/examples/autoresearch/process.ts +50 -0
  290. package/examples/autoresearch/project.ts +380 -0
  291. package/examples/autoresearch/research-service.ts +302 -0
  292. package/examples/code/README.md +33 -0
  293. package/examples/code/REQUIREMENTS.zh.md +11 -0
  294. package/examples/code/candidate.ts +89 -0
  295. package/examples/code/config.ts +19 -0
  296. package/examples/code/eject.json +5 -0
  297. package/examples/code/project.ts +581 -0
  298. package/examples/code/prompts.ts +16 -0
  299. package/examples/code/verification.ts +239 -0
  300. package/examples/code/worktree.ts +188 -0
  301. package/examples/harness-session/README.md +3 -6
  302. package/examples/lead-worker/harness/dynamic-scheduler.ts +6 -3
  303. package/examples/lead-worker/harness/index.ts +61 -6
  304. package/examples/lead-worker/project.ts +2 -2
  305. package/examples/lead-worker/services/board.ts +14 -1
  306. package/examples/messages/README.md +5 -5
  307. package/examples/messages/handoff.ts +6 -2
  308. package/examples/messages/project.ts +47 -2
  309. package/examples/notes/README.md +13 -18
  310. package/examples/notes/project.ts +57 -9
  311. package/examples/peermesh/harness/router.ts +2 -2
  312. package/examples/peermesh/harness/team.ts +11 -0
  313. package/examples/peermesh/project.ts +19 -4
  314. package/examples/services/agent-control/README.md +3 -3
  315. package/examples/services/mathlib-search/Dockerfile +4 -2
  316. package/examples/services/mathlib-search/README.md +1 -1
  317. package/examples/services/mcp-managed/README.md +2 -2
  318. package/examples/services/persistent-board/README.md +16 -3
  319. package/examples/services/persistent-board/business.ts +10 -0
  320. package/examples/services/persistent-board/index.ts +10 -0
  321. package/examples/services/persistent-board/live.ts +54 -0
  322. package/examples/subagents/README.md +5 -5
  323. package/examples/subagents/business.ts +3 -1
  324. package/examples/subagents/config.ts +4 -3
  325. package/examples/subagents/harness/controller.ts +161 -29
  326. package/examples/subagents/project.ts +47 -33
  327. package/examples/subagents/prompts/prompts.ts +4 -0
  328. package/examples/subagents/services/collaboration-service.ts +14 -2
  329. package/examples/substrate/README.md +2 -2
  330. package/examples/substrate/harness/index.ts +67 -11
  331. package/examples/substrate/project.ts +5 -1
  332. package/examples/super/README.md +52 -0
  333. package/examples/super/actions.ts +196 -0
  334. package/examples/super/artifact.ts +56 -0
  335. package/examples/super/config.ts +95 -0
  336. package/examples/super/coordinator.ts +158 -0
  337. package/examples/super/daemon.ts +84 -0
  338. package/examples/super/decisions.ts +46 -0
  339. package/examples/super/eject.json +5 -0
  340. package/examples/super/execution.ts +131 -0
  341. package/examples/super/github.ts +242 -0
  342. package/examples/super/inbox.ts +306 -0
  343. package/examples/super/location.ts +54 -0
  344. package/examples/super/operator.ts +28 -0
  345. package/examples/super/outbox.ts +97 -0
  346. package/examples/super/project.ts +225 -0
  347. package/examples/super/prompts.ts +27 -0
  348. package/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  349. package/examples/taskpool/harness/controller.ts +59 -7
  350. package/examples/taskpool/project.ts +18 -2
  351. package/npm-shrinkwrap.development.json +700 -0
  352. package/npm-shrinkwrap.json +95 -1969
  353. package/package.development.json +88 -0
  354. package/package.json +11 -8
  355. package/scripts/anyswarm-arguments.ts +91 -54
  356. package/scripts/anyswarm-author.ts +25 -0
  357. package/scripts/anyswarm-eject.ts +145 -0
  358. package/scripts/anyswarm-harnesses.ts +10 -0
  359. package/scripts/anyswarm-installation.ts +18 -288
  360. package/scripts/anyswarm-launch.ts +36 -0
  361. package/scripts/anyswarm-progress.ts +95 -0
  362. package/scripts/anyswarm-project.ts +35 -34
  363. package/scripts/anyswarm-source-runner.ts +176 -0
  364. package/scripts/anyswarm.ts +24 -3
  365. package/scripts/build.ts +8 -1
  366. package/scripts/generate-architecture-api.ts +2 -0
  367. package/scripts/generate-architecture-prompts.ts +35 -2
  368. package/scripts/local-environment.ts +117 -28
  369. package/scripts/local-setup-smoke.ts +3 -2
  370. package/scripts/local-setup-worker.ts +17 -7
  371. package/scripts/local-setup.ts +166 -73
  372. package/scripts/opensandbox-agent-worker.ts +2 -2
  373. package/scripts/pack-release.ts +70 -0
  374. package/scripts/pi-session-bridge.ts +10 -2
  375. package/scripts/run-harness.ts +3 -1
  376. package/scripts/setup-bootstrap.ts +41 -6
  377. package/src/core/allocation-ledger.ts +5 -3
  378. package/src/core/host-identity.ts +11 -0
  379. package/src/core/index.ts +12 -6
  380. package/src/core/mcp-service.ts +2 -2
  381. package/src/core/runtime-management.ts +22 -0
  382. package/src/core/sandbox/executor-driver.ts +15 -18
  383. package/src/core/sandbox/local-executor.ts +65 -19
  384. package/src/core/sandbox/local-worker.ts +29 -21
  385. package/src/core/sandbox/opensandbox-backend.ts +36 -11
  386. package/src/core/sandbox/sandbox-connection.ts +14 -5
  387. package/src/core/service-live-state.ts +156 -0
  388. package/src/core/service-observation-types.ts +23 -1
  389. package/src/core/service-process.ts +36 -3
  390. package/src/core/service-types.ts +3 -1
  391. package/src/core/services.ts +8 -3
  392. package/src/core/types.ts +3 -0
  393. package/src/core/worker-image.ts +3 -3
  394. package/src/harness/harness-session-types.ts +13 -1
  395. package/src/harness/harness-session.ts +40 -7
  396. package/src/harness/project-harness.ts +38 -12
  397. package/src/harness/project-input.ts +73 -15
  398. package/src/harness/project-rpc-client.ts +5 -0
  399. package/src/harness/project-rpc.ts +29 -8
  400. package/src/harness/project-runtime.ts +4 -2
  401. package/src/harness/typescript-loader.ts +37 -0
  402. package/src/trace-viewer/public/app.js +6 -5
  403. package/src/trace-viewer/reader.mjs +42 -2
@@ -0,0 +1,11 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ let bootSession;
3
+ /** Cache only a verified UUID: a running Controller cannot survive a reboot. */
4
+ export function darwinBootSession() {
5
+ if (bootSession)
6
+ return bootSession;
7
+ const uuid = execFileSync('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], { encoding: 'utf8', timeout: 2_000 }).trim();
8
+ if (!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(uuid))
9
+ throw new Error('Invalid Darwin boot session UUID');
10
+ return bootSession = `darwin:${uuid.toLowerCase()}`;
11
+ }
@@ -2,9 +2,10 @@ import type { CreateRuntimeOptions, RecoverRuntimeOptions, Runtime } from './typ
2
2
  export type * from './session-types.js';
3
3
  export { createHarnessSession } from '../harness/project-harness.js';
4
4
  export type { Harness, HarnessContext, HarnessInput, HarnessInputHandler, HarnessInputPreparation, HarnessJson, HarnessStatusInfo, ProjectHarness, ProjectHarnessContext, ProjectHarnessResult, } from '../harness/project-harness.js';
5
- export type { HarnessAgentHandler, HarnessAgentReceipt, HarnessAgentRegistration, HarnessAgents, HarnessAnswer, HarnessAnswerReceipt, HarnessCapability, HarnessDescriptor, HarnessEvent, HarnessInputDescriptor, HarnessInputReceipt, HarnessLifetime, HarnessOperation, HarnessPhase, HarnessQuestion, HarnessQuestionKind, HarnessQuestionRequest, HarnessQuestionSource, HarnessRequest, HarnessDispatchRequest, HarnessResult, HarnessSession, HarnessSessionOptions, HarnessStartReceipt, HarnessState, HarnessStopReceipt, HarnessSubscriptionOptions, } from '../harness/harness-session-types.js';
5
+ export type { HarnessAgentHandler, HarnessAgentReceipt, HarnessAgentRegistration, HarnessAgents, HarnessAnswer, HarnessAnswerReceipt, HarnessCapability, HarnessDescriptor, HarnessEvent, HarnessInputDescriptor, HarnessInputReceipt, HarnessLifetime, HarnessOperation, HarnessPhase, HarnessQuestion, HarnessQuestionKind, HarnessQuestionRequest, HarnessQuestionSource, HarnessRequest, HarnessDispatchRequest, HarnessResult, HarnessSession, HarnessServices, HarnessSessionOptions, HarnessStartReceipt, HarnessState, HarnessStopReceipt, HarnessSubscriptionOptions, } from '../harness/harness-session-types.js';
6
6
  export { ProjectPreflightError } from '../harness/project-input.js';
7
7
  export { HarnessRpcClient } from '../harness/project-rpc-client.js';
8
+ export { runProjectRpc } from '../harness/project-rpc.js';
8
9
  export type { HarnessRpcClientOptions, HarnessRpcReady, HarnessRpcTransport } from '../harness/project-rpc-client.js';
9
10
  export { observeProjectRuntime, projectConfiguration, projectResult } from '../harness/project-runtime.js';
10
11
  export { runInput, type RunInputResult } from '../harness/run-input.js';
@@ -16,6 +17,7 @@ export { httpClient } from '../harness/http.js';
16
17
  export { checkGitProject, seedTeamRepository, seededCheckoutInstruction } from '../harness/project-git.js';
17
18
  export { initializeGitRepository, importGitTree, commitGitTree, isGitTreePath } from '../harness/git-tree.js';
18
19
  export { decodeFileSeed as decodeFileTree, snapshotFileSeed as snapshotFileTree, completeDigest as completeFileTreeDigest } from './files/core-file-seed.js';
20
+ export { resolveFilePolicy } from './file-policy.js';
19
21
  export { AnySwarmError } from '../errors.js';
20
22
  export { requestHttp } from '../protocol/http-request.js';
21
23
  export { stableStringify } from '../protocol/stable-json.js';
@@ -28,7 +30,7 @@ export { DEFAULT_WORKER_IMAGE, workerImageFor } from './worker-image.js';
28
30
  export { ServiceRegistry, serviceFromManifest, inProcessService, httpService, createInProcessAdapter, createHttpJsonAdapter, createServiceReplyAdapter } from './services.js';
29
31
  export { mcpService } from './mcp-service.js';
30
32
  export type { McpServiceOptions, McpHttpServiceOptions, McpStdioServiceOptions } from './mcp-service.js';
31
- export type { ServiceStateMetadata, ServiceStatePresentation } from './service-observation-types.js';
33
+ export type { ServiceLiveState, ServiceStateMetadata, ServiceStatePresentation, ServiceStateRead, ServiceStateSource } from './service-observation-types.js';
32
34
  export { managedProcessLifecycle } from './service-process.js';
33
35
  export type { ManagedProcessOptions } from './service-process.js';
34
36
  export type { ServiceLifecycle, ServiceLifecycleContext, ServiceStorage, ServiceResources } from './service-lifecycle-types.js';
@@ -20,7 +20,7 @@ import { createRedactor, createRunRecords, runtimeConfiguration } from './run-re
20
20
  import { createRuntimeManagement } from './runtime-management.js';
21
21
  import { claimOpenSandboxBackend, openOpenSandboxBackend } from './sandbox/opensandbox-backend.js';
22
22
  import { isOfficialWorkerImage, localWorkerSelector } from './worker-image.js';
23
- import { selectExecutorDriver } from './sandbox/executor-driver.js';
23
+ import { legacyImageExecutorVersion, selectExecutorDriver } from './sandbox/executor-driver.js';
24
24
  import { findExecutorEntry, executorFailure } from './sandbox/local-executor.js';
25
25
  import { prepareLocalWorker, workerFailure } from './sandbox/local-worker.js';
26
26
  import { loopbackLifecycle, resolveSandboxConnectionWithSources } from './sandbox/sandbox-connection.js';
@@ -30,6 +30,7 @@ import { registerServicePrivateValues, snapshotServiceRegistry } from './service
30
30
  export { createHarnessSession } from '../harness/project-harness.js';
31
31
  export { ProjectPreflightError } from '../harness/project-input.js';
32
32
  export { HarnessRpcClient } from '../harness/project-rpc-client.js';
33
+ export { runProjectRpc } from '../harness/project-rpc.js';
33
34
  export { observeProjectRuntime, projectConfiguration, projectResult } from '../harness/project-runtime.js';
34
35
  export { runInput } from '../harness/run-input.js';
35
36
  export { runWithReport } from '../harness/run-report.js';
@@ -40,6 +41,7 @@ export { httpClient } from '../harness/http.js';
40
41
  export { checkGitProject, seedTeamRepository, seededCheckoutInstruction } from '../harness/project-git.js';
41
42
  export { initializeGitRepository, importGitTree, commitGitTree, isGitTreePath } from '../harness/git-tree.js';
42
43
  export { decodeFileSeed as decodeFileTree, snapshotFileSeed as snapshotFileTree, completeDigest as completeFileTreeDigest } from './files/core-file-seed.js';
44
+ export { resolveFilePolicy } from './file-policy.js';
43
45
  export { AnySwarmError } from '../errors.js';
44
46
  export { requestHttp } from '../protocol/http-request.js';
45
47
  export { stableStringify } from '../protocol/stable-json.js';
@@ -137,7 +139,7 @@ function planRuntimeWorker(options, config, profiles, recoveryDirectory) {
137
139
  const configuredEntry = options.localWorker?.backendPath
138
140
  ? resolve(options.localWorker.backendPath) : localExecutor?.kind === kind ? localExecutor.entry : undefined;
139
141
  const requiredVersions = new Set(selectors.flatMap(selector => selector.version ? [selector.version] : []));
140
- if (typeof options.executor === 'object')
142
+ if (config.driver.version !== undefined)
141
143
  requiredVersions.add(config.driver.version);
142
144
  if (requiredVersions.size > 1)
143
145
  throw executorFailure('All local Worker selectors must match the selected installation version.');
@@ -147,7 +149,7 @@ function planRuntimeWorker(options, config, profiles, recoveryDirectory) {
147
149
  const entry = configuredEntry ?? await findExecutorEntry(kind);
148
150
  if (!entry)
149
151
  throw executorFailure(`No local ${kind} executable was found. Install it with npm and run the CLI from this SDK package with setup --backend ${kind}.`);
150
- return prepareLocalWorker({ kind, entry }, { progress, requiredVersion });
152
+ return prepareLocalWorker({ kind, entry }, { progress, requiredVersion: requiredVersion ?? (configuredEntry === localExecutor?.entry ? localExecutor?.version : undefined) });
151
153
  } };
152
154
  }
153
155
  function freezeProfileWorker(profile, config, worker) {
@@ -244,6 +246,11 @@ async function assembleRuntime(options, recovery) {
244
246
  for (const [id, profile] of profiles)
245
247
  profiles.set(id, freezeProfileWorker(profile, config, localWorker));
246
248
  }
249
+ else if (config.driver.version === undefined) {
250
+ const version = legacyImageExecutorVersion(config.driver.kind);
251
+ if (version !== undefined)
252
+ config = Object.freeze({ ...config, driver: selectExecutorDriver({ kind: config.driver.kind, version }) });
253
+ }
247
254
  if (options.persistence) {
248
255
  const { deploymentId, contract, retainForMs: duration = 900_000 } = options.persistence;
249
256
  if (!validId(deploymentId) || !validId(contract) || !Number.isSafeInteger(duration) || duration < 300_000 || duration > 3_600_000 ||
@@ -259,7 +266,7 @@ async function assembleRuntime(options, recovery) {
259
266
  }));
260
267
  const fingerprintInput = { contract, connectionFingerprint, callback: config.callback, limits, retainForMs,
261
268
  ...(options.hooks?.beforeCompact ? { beforeCompactTimeoutMs: options.hooks.beforeCompact.timeoutMs ?? 10_000 } : {}),
262
- models: modelConfig, modelGateway: config.modelGateway, executor: [config.driver.kind, config.driver.version],
269
+ models: modelConfig, modelGateway: config.modelGateway, executor: [config.driver.kind, config.driver.version ?? legacyImageExecutorVersion(config.driver.kind)],
263
270
  profiles: Object.fromEntries(profiles), services: [...registrations.values()].map(registration => registration.manifest).sort((a, b) => a.id.localeCompare(b.id)),
264
271
  files: config.filePolicy, requests: config.sandbox.resourceRequests, limitsSandbox: config.sandbox.resourceLimits };
265
272
  const configFingerprint = fingerprint(fingerprintInput);
@@ -1312,6 +1319,7 @@ async function assembleRuntime(options, recovery) {
1312
1319
  const wasClosing = closing;
1313
1320
  durable(owner => owner.beginClose());
1314
1321
  closing = true;
1322
+ management.cancelServiceStateReads();
1315
1323
  if (!closeWork) {
1316
1324
  for (const agent of agents.values())
1317
1325
  revoke(agent.info.id);
@@ -64,11 +64,11 @@ function mcpEndpoint(options) {
64
64
  } }),
65
65
  };
66
66
  }
67
- if (process.platform !== 'linux' || !isAbsolute(options.command) ||
67
+ if (!['linux', 'darwin'].includes(process.platform) || !isAbsolute(options.command) ||
68
68
  (options.args !== undefined && (!Array.isArray(options.args) || options.args.some(argument => typeof argument !== 'string'))) ||
69
69
  (options.cwd !== undefined && !isAbsolute(options.cwd)) ||
70
70
  (options.env !== undefined && Object.values(options.env).some(value => typeof value !== 'string'))) {
71
- throw new AnySwarmError('INVALID_CONTRACT', 'Managed MCP stdio requires Linux, an absolute executable and typed argv/environment');
71
+ throw new AnySwarmError('INVALID_CONTRACT', 'Managed MCP stdio requires Linux or macOS, an absolute executable and typed argv/environment');
72
72
  }
73
73
  const parameters = { command: options.command, args: [...options.args ?? []], cwd: options.cwd,
74
74
  env: Object.fromEntries(Object.entries(options.env ?? {}).sort(([a], [b]) => a.localeCompare(b))) };
@@ -38,6 +38,11 @@ export declare function createRuntimeManagement({ profiles, registrations, runti
38
38
  register: (input: RuntimeServiceRegistration) => Promise<RuntimeServiceDefinition>;
39
39
  get: (id: string) => RuntimeServiceDefinition | null;
40
40
  list: () => RuntimeServiceDefinition[];
41
+ listState: () => {
42
+ name: string;
43
+ supported: boolean;
44
+ }[];
45
+ readState: (name: string) => Promise<import("./service-observation-types.js").ServiceStateRead>;
41
46
  start: (input: ServiceRetirement) => Promise<RuntimeServiceDefinition>;
42
47
  stop: (input: ServiceRetirement) => Promise<RuntimeServiceDefinition>;
43
48
  restart: (input: ServiceRetirement) => Promise<RuntimeServiceDefinition>;
@@ -168,6 +173,7 @@ export declare function createRuntimeManagement({ profiles, registrations, runti
168
173
  retireAll: (timeoutMs: number) => Promise<void>;
169
174
  pendingServices: () => PendingCleanup[];
170
175
  knowsService: (id: string) => boolean;
176
+ cancelServiceStateReads: () => void;
171
177
  retiredExports: () => {
172
178
  path?: string;
173
179
  error?: ErrorInfo;
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { createServiceStateReader } from './service-live-state.js';
2
3
  import { createHash } from 'node:crypto';
3
4
  import { buildServiceRegistration, isJson, replaceServiceInterface, registerServicePrivateValues, snapshotServiceRegistration } from './services.js';
4
5
  import { validId } from './config.js';
@@ -35,6 +36,7 @@ export function createRuntimeManagement({ profiles, registrations, runtimeId, ru
35
36
  const requests = new Map();
36
37
  const serviceRequests = new Map();
37
38
  const services = new Map();
39
+ const stateReader = createServiceStateReader(redact);
38
40
  const unresolvedServices = new Map();
39
41
  const unresolvedDynamic = new Map();
40
42
  const remoteWrites = new Map();
@@ -156,6 +158,8 @@ export function createRuntimeManagement({ profiles, registrations, runtimeId, ru
156
158
  }
157
159
  catch (error) {
158
160
  registrations.delete(serviceId);
161
+ if (service.definition.instanceId)
162
+ stateReader.cancel(service.definition.instanceId);
159
163
  lifecycleChange(service, 'service.start', 'blocked', 'directory-change', {
160
164
  code: 'INVALID_CONTRACT', message: String(redact(error.message)), retryable: false,
161
165
  });
@@ -182,6 +186,8 @@ export function createRuntimeManagement({ profiles, registrations, runtimeId, ru
182
186
  const lifecycle = service.registration.lifecycle;
183
187
  lifecycleRequests.set(key, {});
184
188
  service.action = 'start';
189
+ if (service.definition.instanceId)
190
+ stateReader.reset(service.definition.instanceId);
185
191
  service.registration = { ...service.registration, instanceId: `${runtimeId}:${input.serviceId}:${randomUUID()}` };
186
192
  service.definition = { ...service.definition, instanceId: service.registration.instanceId };
187
193
  lifecycleChange(service, 'service.start', 'starting', input.requestId);
@@ -231,6 +237,8 @@ export function createRuntimeManagement({ profiles, registrations, runtimeId, ru
231
237
  throw problem('RECOVERY_BLOCKED', 'Original Service identity must be reconciled before stop');
232
238
  lifecycleRequests.set(key, { instanceId: service.definition.instanceId });
233
239
  registrations.delete(input.serviceId);
240
+ if (service.definition.instanceId)
241
+ stateReader.cancel(service.definition.instanceId);
234
242
  service.unwatch?.();
235
243
  service.unwatch = undefined;
236
244
  service.action = 'stop';
@@ -352,6 +360,18 @@ export function createRuntimeManagement({ profiles, registrations, runtimeId, ru
352
360
  function serviceList() {
353
361
  return [...new Set([...services.keys(), ...unresolvedServices.keys()])].map(id => serviceGet(id));
354
362
  }
363
+ function listServiceState() {
364
+ return [...services].map(([name, service]) => ({ name, supported: !!service.registration.adapter.readState }));
365
+ }
366
+ function readServiceState(name) {
367
+ const service = services.get(name);
368
+ const instanceId = service?.definition.instanceId;
369
+ return stateReader.read(service && instanceId ? {
370
+ instanceId,
371
+ readState: service.registration.adapter.readState,
372
+ ready: () => !isClosing() && service.definition.state === 'ready' && service.definition.instanceId === instanceId && registrations.has(name),
373
+ } : undefined);
374
+ }
355
375
  async function registerService(parameters) {
356
376
  const input = parameters && 'name' in parameters ? {
357
377
  requestId: parameters.requestId, actorId: parameters.actorId,
@@ -434,6 +454,8 @@ export function createRuntimeManagement({ profiles, registrations, runtimeId, ru
434
454
  if (service.work)
435
455
  return serviceGet(serviceId);
436
456
  registrations.delete(serviceId);
457
+ if (service.definition.instanceId)
458
+ stateReader.cancel(service.definition.instanceId);
437
459
  service.unwatch?.();
438
460
  service.unwatch = undefined;
439
461
  service.retirement = { requestId, caller };
@@ -711,12 +733,14 @@ export function createRuntimeManagement({ profiles, registrations, runtimeId, ru
711
733
  return {
712
734
  profiles: Object.freeze({ register: (input) => registerProfile(input), get: profileGet, list: profileList }),
713
735
  services: Object.freeze({ register: (input) => registerService(input), get: serviceGet, list: serviceList,
736
+ listState: listServiceState, readState: readServiceState,
714
737
  start: startService, stop: stopService, restart: restartService, health: serviceHealth,
715
738
  retire: (input) => retireService(input) }),
716
739
  access: Object.freeze({ get: accessGet,
717
740
  grant: (input) => mutateAccess('grant', input), revoke: (input) => mutateAccess('revoke', input) }),
718
741
  mutateAccess, initAccess, bridgeAccess, checkpoint, restore,
719
742
  recordRemoteWrite, prepareAll, retireAll, pendingServices, knowsService: (id) => services.has(id),
743
+ cancelServiceStateReads: () => stateReader.cancel(),
720
744
  retiredExports: () => ownedRetirements().flatMap(({ definition, exported }) => exported ? [{ serviceId: definition.id, ...exported }] : []),
721
745
  profileDigest: (id) => definitions.get(id)?.digest,
722
746
  snapshot: () => ({ sequence, profiles: profileList(), services: serviceList(), access: [...access.keys()].map(id => accessGet(id)) }),
@@ -5,9 +5,8 @@ type Model = ModelConfig;
5
5
  export interface ExecutorDriver {
6
6
  readonly kind: string;
7
7
  readonly name: string;
8
- readonly version: string;
8
+ readonly version?: string;
9
9
  readonly capabilities: ExecutorCapabilities;
10
- readonly compatibleVersions: readonly string[];
11
10
  readonly adapter?: ExecutorAdapter;
12
11
  readonly defaultMaxOutputTokens?: null;
13
12
  assertEnvironment?(environment: Readonly<Record<string, string>> | undefined): void;
@@ -20,6 +19,7 @@ export interface ExecutorDriver {
20
19
  model: Model;
21
20
  baseUrl: string;
22
21
  forkSession: boolean;
22
+ version: string;
23
23
  }): {
24
24
  command: 'pi';
25
25
  args: string[];
@@ -37,6 +37,8 @@ export interface ExecutorDriver {
37
37
  externalExecutor: ExecutorAdapter;
38
38
  };
39
39
  }
40
+ /** Preserve the contract for explicitly prepared deployments without a version pin. */
41
+ export declare function legacyImageExecutorVersion(kind: string): "0.172.0" | "1.3.0" | undefined;
40
42
  export declare function createPiExecutor({ version }?: {
41
43
  version?: string;
42
44
  }): BuiltinExecutorSelection;
@@ -10,8 +10,6 @@ const sharedCapabilities = {
10
10
  const pi = {
11
11
  kind: 'pi',
12
12
  name: 'Pi',
13
- version: '1.3.0',
14
- compatibleVersions: Object.freeze(['1.3.0', '1.4.0']),
15
13
  capabilities: Object.freeze({ ...sharedCapabilities, contextFork: true,
16
14
  session: Object.freeze({ configure: true, compact: true, abortRetry: true, clearQueue: true,
17
15
  state: true, stats: true, messages: true, context: true, beforeCompact: true }),
@@ -29,12 +27,9 @@ const pi = {
29
27
  '--append-system-prompt', '/workspace/runtime/profile-prompt.txt', '--provider', model.provider, '--model', model.model] };
30
28
  },
31
29
  };
32
- const codexVersion = '0.172.0';
33
30
  const codex = {
34
31
  kind: 'codex',
35
32
  name: 'Codex',
36
- version: codexVersion,
37
- compatibleVersions: Object.freeze([codexVersion]),
38
33
  defaultMaxOutputTokens: null,
39
34
  capabilities: Object.freeze({ ...sharedCapabilities, contextFork: false, steeringModes: Object.freeze(['all']) }),
40
35
  assertEnvironment(environment) {
@@ -45,25 +40,28 @@ const codex = {
45
40
  credentials(_model, _baseUrl, token) {
46
41
  return { environment: {}, secretEnvironment: { OPENAI_API_KEY: token } };
47
42
  },
48
- start({ model, baseUrl }) {
49
- return { command: 'codex', args: [], codex: { model: model.model, baseUrl, version: codexVersion } };
43
+ start({ model, baseUrl, version }) {
44
+ return { command: 'codex', args: [], codex: { model: model.model, baseUrl, version } };
50
45
  },
51
46
  };
52
47
  const drivers = { pi: Object.freeze(pi), codex: Object.freeze(codex) };
48
+ /** Preserve the contract for explicitly prepared deployments without a version pin. */
49
+ export function legacyImageExecutorVersion(kind) {
50
+ return kind === 'pi' ? '1.3.0' : kind === 'codex' ? '0.172.0' : undefined;
51
+ }
53
52
  function invalid(message) {
54
53
  throw Object.assign(new Error(message), { code: 'INVALID_CONTRACT' });
55
54
  }
56
- export function createPiExecutor({ version = pi.version } = {}) {
55
+ export function createPiExecutor({ version } = {}) {
57
56
  return builtinSelection('pi', version);
58
57
  }
59
- export function createCodexExecutor({ version = codex.version } = {}) {
58
+ export function createCodexExecutor({ version } = {}) {
60
59
  return builtinSelection('codex', version);
61
60
  }
62
61
  function builtinSelection(kind, version) {
63
- if (!drivers[kind].compatibleVersions.includes(version)) {
64
- invalid(`${kind} version ${JSON.stringify(version)} is incompatible; supported versions are ${drivers[kind].compatibleVersions.join(', ')}`);
65
- }
66
- return Object.freeze({ kind, version });
62
+ if (version !== undefined && !executorVersion(version))
63
+ invalid(`${kind} requires an exact executor version`);
64
+ return Object.freeze({ kind, ...(version === undefined ? {} : { version }) });
67
65
  }
68
66
  export function createExecutorAdapter(input) {
69
67
  if (!input || typeof input.kind !== 'string' || !/^[a-z][a-z0-9-]{0,47}$/.test(input.kind) || Object.hasOwn(drivers, input.kind) ||
@@ -86,7 +84,7 @@ export function selectExecutorDriver(executor = 'pi') {
86
84
  const input = executor;
87
85
  if (typeof input.kind === 'string' && Object.hasOwn(drivers, input.kind)) {
88
86
  const driver = drivers[input.kind];
89
- return Object.freeze({ ...driver, ...builtinSelection(input.kind, input.version ?? driver.version) });
87
+ return Object.freeze({ ...driver, ...builtinSelection(input.kind, input.version) });
90
88
  }
91
89
  const adapter = createExecutorAdapter(input);
92
90
  return Object.freeze({
@@ -2,12 +2,24 @@ import type { ExecutorKind } from '../backend-config.js';
2
2
  export type LocalExecutorSelection = {
3
3
  kind: ExecutorKind;
4
4
  entry: string;
5
+ version?: string;
5
6
  };
6
7
  export declare function executorFailure(message: string): Error & {
7
8
  code: string;
8
9
  };
9
- export declare function findExecutorEntry(kind: ExecutorKind): Promise<string | undefined>;
10
+ export declare function findExecutorEntry(kind: ExecutorKind, accepts?: (entry: string) => Promise<boolean>): Promise<string | undefined>;
10
11
  export declare function checkLocalExecutor(selection: LocalExecutorSelection, signal: AbortSignal): Promise<string>;
12
+ export declare function snapshotLinuxExecutor(selection: LocalExecutorSelection, destination: string, { image, platform, signal }: {
13
+ image: string;
14
+ platform: string;
15
+ signal: AbortSignal;
16
+ }): Promise<{
17
+ kind: ExecutorKind;
18
+ entry: string;
19
+ version: string;
20
+ digest: string;
21
+ guestEntry: string;
22
+ }>;
11
23
  export declare function snapshotLocalExecutor(selection: LocalExecutorSelection, destination: string, signal: AbortSignal): Promise<{
12
24
  kind: ExecutorKind;
13
25
  entry: string;
@@ -1,21 +1,22 @@
1
1
  import { execFile } from 'node:child_process';
2
- import { constants } from 'node:fs';
3
- import { access, mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
4
- import { tmpdir } from 'node:os';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { constants, createReadStream } from 'node:fs';
4
+ import { access, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
5
+ import { homedir, tmpdir } from 'node:os';
5
6
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
7
  import { promisify } from 'node:util';
7
- import { selectExecutorDriver } from './executor-driver.js';
8
+ import { executorVersion } from '../executor-adapter.js';
8
9
  const execute = promisify(execFile);
9
10
  const packageNames = { pi: '@earendil-works/pi-coding-agent', codex: '@openai/codex' };
10
11
  export function executorFailure(message) {
11
12
  return Object.assign(new Error(message), { code: 'LOCAL_EXECUTOR_UNAVAILABLE' });
12
13
  }
13
- export async function findExecutorEntry(kind) {
14
+ export async function findExecutorEntry(kind, accepts) {
14
15
  for (const base of (process.env.PATH ?? '').split(':')) {
15
16
  if (!isAbsolute(base))
16
17
  continue;
17
18
  const entry = join(base, kind);
18
- if (await access(entry, constants.X_OK).then(() => true, () => false))
19
+ if (await access(entry, constants.X_OK).then(() => true, () => false) && (!accepts || await accepts(entry)))
19
20
  return entry;
20
21
  }
21
22
  }
@@ -37,17 +38,15 @@ async function locatePackage(selection, signal) {
37
38
  while (directory !== dirname(directory) && !directory.endsWith(sep + 'node_modules' + sep + name)) {
38
39
  directory = dirname(directory);
39
40
  }
40
- if (!directory.endsWith(sep + 'node_modules' + sep + name))
41
+ const npm = directory.endsWith(sep + 'node_modules' + sep + name);
42
+ if (!npm && !(process.platform === 'darwin' && kind === 'codex' && basename(executable) === 'codex'))
41
43
  throw notSupported();
42
44
  const moduleRoot = dirname(dirname(directory));
43
- const metadata = await readPackage(directory).catch(() => { throw notSupported(); });
44
- const entry = metadata.bin?.[kind];
45
- if (metadata.name !== name || !entry || !below(directory, executable) || resolve(directory, entry) !== executable) {
46
- throw notSupported();
47
- }
48
- const compatible = selectExecutorDriver(kind).compatibleVersions;
49
- if (!metadata.version || !compatible.includes(metadata.version)) {
50
- throw executorFailure(`Selected ${kind} at ${selection.entry} reports package version ${metadata.version ?? 'unknown'}. This SDK supports ${compatible.join(', ')}.`);
45
+ const metadata = npm ? await readPackage(directory).catch(() => { throw notSupported(); }) : undefined;
46
+ if (metadata) {
47
+ const entry = metadata.bin?.[kind];
48
+ if (metadata.name !== name || !entry || !below(directory, executable) || resolve(directory, entry) !== executable)
49
+ throw notSupported();
51
50
  }
52
51
  const home = await mkdtemp(join(tmpdir(), 'anyswarm-executor-probe-'));
53
52
  try {
@@ -58,10 +57,15 @@ async function locatePackage(selection, signal) {
58
57
  signal.throwIfAborted();
59
58
  throw executorFailure(`Could not run ${kind} --version at ${selection.entry}. Check the installation and its dependencies.`);
60
59
  });
61
- const expected = kind === 'pi' ? metadata.version : `codex-cli ${metadata.version}`;
62
- if (stdout.trim() !== expected)
63
- throw executorFailure(`The executable at ${selection.entry} does not match its ${kind} package version ${metadata.version}.`);
64
- return { directory, moduleRoot, metadata, version: metadata.version, executable };
60
+ const reported = stdout.trim();
61
+ const version = kind === 'pi' ? reported : /^codex-cli (.+)$/.exec(reported)?.[1];
62
+ if (!executorVersion(version) || (metadata && version !== metadata.version)) {
63
+ throw executorFailure(`Could not verify the exact version of the selected ${kind} at ${selection.entry}.`);
64
+ }
65
+ if (selection.version !== undefined && selection.version !== version) {
66
+ throw executorFailure(`The selected ${kind} at ${selection.entry} is ${version}, but ${selection.version} was requested.`);
67
+ }
68
+ return { directory, moduleRoot, metadata, version, executable };
65
69
  }
66
70
  finally {
67
71
  await rm(home, { recursive: true, force: true });
@@ -87,9 +91,55 @@ async function resolveDependency(directory, moduleRoot, name) {
87
91
  return path;
88
92
  }
89
93
  const privateFiles = new Set(['.npmrc', '.ssh', '.git', '.env', 'auth.json']);
94
+ export async function snapshotLinuxExecutor(selection, destination, { image, platform, signal }) {
95
+ const { version } = await locatePackage(selection, signal);
96
+ const name = packageNames[selection.kind];
97
+ const container = `anyswarm-executor-${randomUUID()}`;
98
+ const cache = join(homedir(), '.cache', 'anyswarm', 'executor-npm', platform.replace('/', '-'));
99
+ await mkdir(destination, { recursive: true });
100
+ await mkdir(cache, { recursive: true, mode: 0o700 });
101
+ const cacheInfo = await lstat(cache);
102
+ if (!cacheInfo.isDirectory() || cacheInfo.uid !== process.getuid?.() || (cacheInfo.mode & 0o077) !== 0) {
103
+ throw executorFailure('The local executor npm cache must be an owner-only directory.');
104
+ }
105
+ try {
106
+ await execute('docker', ['run', '--rm', '--name', container, '--platform', platform,
107
+ '--mount', `type=bind,source=${await realpath(destination)},target=/out`,
108
+ '--mount', `type=bind,source=${await realpath(cache)},target=/npm-cache`, '--entrypoint', 'sh', image, '-eu', '-c', `
109
+ cd /tmp
110
+ npm install --prefix /tmp/executor --save-exact --omit=dev --ignore-scripts --no-bin-links \\
111
+ --cache /npm-cache --no-audit --no-fund --fetch-retries=1 --fetch-timeout=120000 --registry=https://registry.npmjs.org/ "$1"
112
+ node -e 'const pkg = require(process.argv[1]); const entry = pkg.bin[process.argv[3]]; if (pkg.version !== process.argv[2] || typeof entry !== "string") process.exit(1); process.stdout.write(entry);' "/tmp/executor/node_modules/$2/package.json" "$3" "$4" > /out/entry
113
+ tar --create --file=/out/program.tar --directory=/tmp/executor/node_modules --format=gnu \\
114
+ --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner --mode=u=rwX,go=rX --hard-dereference \\
115
+ --exclude=.package-lock.json .
116
+ `, 'prepare-executor', `${name}@${version}`, name, version, selection.kind], { signal, timeout: 600_000, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024 });
117
+ }
118
+ catch {
119
+ signal.throwIfAborted();
120
+ throw executorFailure(`Could not prepare ${name}@${version} for ${platform}. Check registry access from Docker and availability of the exact Linux package.`);
121
+ }
122
+ finally {
123
+ await execute('docker', ['rm', '-f', container], { timeout: 10_000 }).catch(() => { });
124
+ }
125
+ // Recheck the selected executable after Linux material generation, as on Linux.
126
+ if (await checkLocalExecutor(selection, signal) !== version)
127
+ throw executorFailure('The selected installation changed during preparation.');
128
+ const hash = createHash('sha256');
129
+ for await (const chunk of createReadStream(join(destination, 'program.tar'), { signal }))
130
+ hash.update(chunk);
131
+ const digest = hash.digest('hex');
132
+ await writeFile(join(destination, 'SHA256SUMS'), `${digest} program.tar\n`);
133
+ const entry = await readFile(join(destination, 'entry'), 'utf8');
134
+ if (!entry || isAbsolute(entry) || entry.split('/').includes('..'))
135
+ throw executorFailure('Linux executor package has an invalid executable entry.');
136
+ return { ...selection, version, digest, guestEntry: `node_modules/${name}/${entry}` };
137
+ }
90
138
  export async function snapshotLocalExecutor(selection, destination, signal) {
91
139
  const installation = await locatePackage(selection, signal);
92
140
  const { directory, moduleRoot, metadata, executable, version } = installation;
141
+ if (!metadata)
142
+ throw executorFailure('This platform requires an npm installation of the selected executor.');
93
143
  const packages = new Set();
94
144
  const files = [];
95
145
  await mkdir(destination, { recursive: true });
@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';
7
7
  import { promisify } from 'node:util';
8
8
  import { PACKAGE_VERSION, WORKER_PROTOCOL } from '../worker-image.js';
9
9
  import { fileProtocol } from '../files/core-file-seed.js';
10
- import { snapshotLocalExecutor, executorFailure } from './local-executor.js';
10
+ import { snapshotLinuxExecutor, snapshotLocalExecutor, executorFailure } from './local-executor.js';
11
11
  const execute = promisify(execFile);
12
12
  const sdkRoot = fileURLToPath(new URL('../../../..', import.meta.url));
13
13
  const imageId = /^sha256:[a-f0-9]{64}$/;
@@ -55,7 +55,7 @@ async function stageSdk(context, signal) {
55
55
  await copy(path);
56
56
  return hash.digest('hex');
57
57
  }
58
- async function inspect(reference, expected, signal) {
58
+ async function inspect(reference, expected, signal, platform) {
59
59
  const result = await execute('docker', ['image', 'inspect', reference], { signal, timeout: 10_000 }).catch(error => {
60
60
  signal.throwIfAborted();
61
61
  if (/No such image|not found/i.test(String(error.stderr)))
@@ -65,13 +65,18 @@ async function inspect(reference, expected, signal) {
65
65
  if (!result)
66
66
  return;
67
67
  const [image] = JSON.parse(result.stdout);
68
+ if (platform && `${image?.Os}/${image?.Architecture}` !== platform)
69
+ return;
68
70
  const labels = image?.Config?.Labels;
69
71
  if (imageId.test(image?.Id) && Object.entries(expected).every(([key, value]) => labels?.[label + key] === value))
70
72
  return image.Id;
71
73
  }
72
74
  export async function prepareLocalWorker(selection, { signal = AbortSignal.timeout(900_000), build = true, progress, requiredVersion } = {}) {
73
- if (process.platform !== 'linux')
74
- throw workerFailure('Local Worker preparation requires Linux and a same-host Docker engine.');
75
+ if (requiredVersion !== undefined)
76
+ selection = { ...selection, version: requiredVersion };
77
+ const darwin = process.platform === 'darwin';
78
+ if (!darwin && process.platform !== 'linux')
79
+ throw workerFailure('Local Worker preparation requires Linux or macOS with a local Docker engine.');
75
80
  await localDockerSocket(signal).catch(error => {
76
81
  signal.throwIfAborted();
77
82
  if (error.code === 'LOCAL_WORKER_UNAVAILABLE')
@@ -80,25 +85,31 @@ export async function prepareLocalWorker(selection, { signal = AbortSignal.timeo
80
85
  });
81
86
  const context = await mkdtemp(join(tmpdir(), 'anyswarm-worker-'));
82
87
  try {
83
- progress?.(`Checking the selected ${selection.kind} installation at ${selection.entry}`);
84
- const executor = await snapshotLocalExecutor(selection, join(context, 'executor'), signal).catch(error => {
88
+ const reportedPlatform = await execute('docker', ['info', '--format', '{{.OSType}}/{{.Architecture}}'], { signal, timeout: 10_000 })
89
+ .then(({ stdout }) => stdout.trim()).catch(() => {
85
90
  signal.throwIfAborted();
86
- if (error.code !== 'LOCAL_EXECUTOR_UNAVAILABLE')
87
- throw error;
88
- throw executorFailure(`SDK ${PACKAGE_VERSION}: ${error.message}`);
91
+ throw workerFailure('Docker is unavailable. Check access to the local Linux Docker engine.');
89
92
  });
90
- if (requiredVersion !== undefined && requiredVersion !== executor.version) {
91
- throw executorFailure(`This Runtime requests ${executor.kind} ${requiredVersion}, but the selected executable at ${executor.entry} is ${executor.version}.`);
93
+ const architecture = process.arch === 'x64' ? 'amd64' : process.arch;
94
+ if (!['arm64', 'amd64'].includes(architecture) || ![`linux/${architecture}`,
95
+ `linux/${architecture === 'amd64' ? 'x86_64' : 'aarch64'}`, `linux/${process.arch}`].includes(reportedPlatform)) {
96
+ throw workerFailure(`Docker platform ${reportedPlatform} does not match the native host architecture ${process.arch}.`);
92
97
  }
98
+ const platform = darwin ? `linux/${architecture}` : reportedPlatform;
93
99
  const sdkDigest = await stageSdk(context, signal);
94
- const platform = await execute('docker', ['info', '--format', '{{.OSType}}/{{.Architecture}}'], { signal, timeout: 10_000 })
95
- .then(({ stdout }) => stdout.trim()).catch(() => {
100
+ const dockerfile = join(context, 'deploy/worker/Dockerfile');
101
+ const nodeImage = /^ARG NODE_IMAGE=(\S+@sha256:[a-f0-9]{64})$/m.exec(await readFile(dockerfile, 'utf8'))?.[1];
102
+ if (darwin && !nodeImage)
103
+ throw workerFailure('Linux executor preparation requires a pinned Worker Node image.');
104
+ progress?.(`Checking the selected ${selection.kind} installation at ${selection.entry}`);
105
+ const destination = join(context, 'executor');
106
+ const executor = await (darwin ? snapshotLinuxExecutor(selection, destination, { image: nodeImage, platform, signal })
107
+ : snapshotLocalExecutor(selection, destination, signal)).catch(error => {
96
108
  signal.throwIfAborted();
97
- throw workerFailure('Docker is unavailable. Check access to the same-host Linux Docker engine.');
109
+ if (error.code !== 'LOCAL_EXECUTOR_UNAVAILABLE')
110
+ throw error;
111
+ throw executorFailure(`SDK ${PACKAGE_VERSION}: ${error.message}`);
98
112
  });
99
- if (!platform.startsWith('linux/') || ![process.arch, process.arch === 'x64' ? 'x86_64' : 'aarch64'].includes(platform.slice(6))) {
100
- throw workerFailure(`Docker platform ${platform} does not match the Linux host executor architecture ${process.arch}.`);
101
- }
102
113
  const fingerprint = createHash('sha256')
103
114
  .update(JSON.stringify([sdkDigest, executor.kind, executor.version, executor.digest, platform])).digest('hex');
104
115
  const reference = 'anyswarm-worker-local:' + fingerprint;
@@ -116,7 +127,7 @@ export async function prepareLocalWorker(selection, { signal = AbortSignal.timeo
116
127
  executorEntry: executor.entry, executorDigest: executor.digest,
117
128
  sdkVersion: PACKAGE_VERSION, sdkDigest, fingerprint,
118
129
  };
119
- const cached = await inspect(reference, verifiedLabels, signal);
130
+ const cached = await inspect(reference, verifiedLabels, signal, darwin ? platform : undefined);
120
131
  if (cached) {
121
132
  progress?.(`Reusing Worker ${reference} (${cached})`);
122
133
  return { ...identity, id: cached, source: 'cache' };
@@ -126,14 +137,14 @@ export async function prepareLocalWorker(selection, { signal = AbortSignal.timeo
126
137
  progress?.(`Building Worker ${reference} for SDK ${PACKAGE_VERSION} and ${executor.kind} ${executor.version}`);
127
138
  const resultFile = join(context, '.image-id');
128
139
  const args = [
129
- 'build', '--file', join(context, 'deploy/worker/Dockerfile'), '--tag', reference, '--iidfile', resultFile,
140
+ 'build', ...(darwin ? ['--platform', platform] : []), '--file', dockerfile, '--tag', reference, '--iidfile', resultFile,
130
141
  '--build-arg', `WORKER_EXECUTOR=${executor.kind}`, '--build-arg', `EXECUTOR_VERSION=${executor.version}`,
131
142
  '--build-arg', `EXECUTOR_ENTRY=${executor.guestEntry}`,
132
143
  ...Object.entries(verifiedLabels).flatMap(([key, value]) => ['--label', `${label}${key}=${value}`]),
133
144
  context,
134
145
  ];
135
146
  try {
136
- await execute('docker', args, { signal, timeout: 900_000, maxBuffer: 16 * 1024 * 1024 });
147
+ await execute('docker', args, { signal, timeout: 900_000, killSignal: 'SIGKILL', maxBuffer: 16 * 1024 * 1024 });
137
148
  }
138
149
  catch (error) {
139
150
  signal.throwIfAborted();
@@ -142,7 +153,7 @@ export async function prepareLocalWorker(selection, { signal = AbortSignal.timeo
142
153
  throw workerFailure(`Docker could not build ${reference}.${diagnostic ? ` ${diagnostic.slice(0, 500)}` : ''} Check build dependencies, Docker access and free disk space, then retry.`);
143
154
  }
144
155
  const built = (await readFile(resultFile, 'utf8')).trim();
145
- if (!imageId.test(built) || !await inspect(built, verifiedLabels, signal)) {
156
+ if (!imageId.test(built) || !await inspect(built, verifiedLabels, signal, darwin ? platform : undefined)) {
146
157
  throw workerFailure('Docker built a Worker whose identity does not match the SDK and executor materials.');
147
158
  }
148
159
  return { ...identity, id: built, source: 'build' };
@@ -60,6 +60,7 @@ interface BackendAgent {
60
60
  started?: boolean;
61
61
  executionEpoch?: number;
62
62
  sessionReady?: boolean;
63
+ executorVersion?: string;
63
64
  loadedResources?: readonly unknown[];
64
65
  activeMessageId?: string;
65
66
  sessionCommands?: Map<string, {
@@ -74,6 +75,7 @@ interface BackendAgent {
74
75
  decisions?: Set<string>;
75
76
  workerStartDispatched?: boolean;
76
77
  polling?: Promise<void>;
78
+ eventRead?: Promise<boolean>;
77
79
  submissions?: Map<string, InputSubmission>;
78
80
  executionStopped?: boolean;
79
81
  lease?: {