@anyswarm/core 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/README.md +11 -10
  2. package/deploy/worker/Dockerfile +12 -4
  3. package/dist/deploy/worker/Dockerfile +12 -4
  4. package/dist/examples/README.md +24 -12
  5. package/dist/examples/authoring/README.md +24 -0
  6. package/dist/examples/authoring/business.d.ts +2 -0
  7. package/dist/examples/authoring/business.js +4 -0
  8. package/dist/examples/authoring/config.d.ts +5 -0
  9. package/dist/examples/authoring/config.js +2 -0
  10. package/dist/examples/authoring/eject.json +5 -0
  11. package/dist/examples/authoring/harness.d.ts +4 -0
  12. package/dist/examples/authoring/harness.js +19 -0
  13. package/dist/examples/autoresearch/README.md +33 -0
  14. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +18 -0
  15. package/dist/examples/autoresearch/config.d.ts +51 -0
  16. package/dist/examples/autoresearch/config.js +57 -0
  17. package/dist/examples/autoresearch/demo.d.ts +11 -0
  18. package/dist/examples/autoresearch/demo.js +52 -0
  19. package/dist/examples/autoresearch/eject.json +15 -0
  20. package/dist/examples/autoresearch/frontiercs2.d.ts +87 -0
  21. package/dist/examples/autoresearch/frontiercs2.js +211 -0
  22. package/dist/examples/autoresearch/prepare.d.ts +95 -0
  23. package/dist/examples/autoresearch/prepare.js +257 -0
  24. package/dist/examples/autoresearch/process.d.ts +13 -0
  25. package/dist/examples/autoresearch/process.js +48 -0
  26. package/dist/examples/autoresearch/project.d.ts +115 -0
  27. package/dist/examples/autoresearch/project.js +410 -0
  28. package/dist/examples/autoresearch/research-service.d.ts +106 -0
  29. package/dist/examples/autoresearch/research-service.js +255 -0
  30. package/dist/examples/code/README.md +25 -0
  31. package/dist/examples/code/REQUIREMENTS.zh.md +11 -0
  32. package/dist/examples/code/candidate.d.ts +19 -0
  33. package/dist/examples/code/candidate.js +80 -0
  34. package/dist/examples/code/config.d.ts +32 -0
  35. package/dist/examples/code/config.js +18 -0
  36. package/dist/examples/code/eject.json +5 -0
  37. package/dist/examples/code/project.d.ts +3 -0
  38. package/dist/examples/code/project.js +605 -0
  39. package/dist/examples/code/prompts.d.ts +5 -0
  40. package/dist/examples/code/prompts.js +12 -0
  41. package/dist/examples/code/verification.d.ts +19 -0
  42. package/dist/examples/code/verification.js +268 -0
  43. package/dist/examples/code/worktree.d.ts +17 -0
  44. package/dist/examples/code/worktree.js +233 -0
  45. package/dist/examples/harness-session/README.md +3 -6
  46. package/dist/examples/lead-worker/harness/dynamic-scheduler.d.ts +2 -1
  47. package/dist/examples/lead-worker/harness/dynamic-scheduler.js +5 -2
  48. package/dist/examples/lead-worker/harness/index.d.ts +60 -0
  49. package/dist/examples/lead-worker/harness/index.js +77 -6
  50. package/dist/examples/lead-worker/project.js +2 -2
  51. package/dist/examples/lead-worker/services/board.d.ts +5 -0
  52. package/dist/examples/lead-worker/services/board.js +19 -1
  53. package/dist/examples/messages/README.md +5 -5
  54. package/dist/examples/messages/handoff.d.ts +2 -0
  55. package/dist/examples/messages/handoff.js +5 -1
  56. package/dist/examples/messages/project.js +52 -2
  57. package/dist/examples/notes/README.md +13 -18
  58. package/dist/examples/notes/project.js +67 -6
  59. package/dist/examples/peermesh/harness/router.js +3 -1
  60. package/dist/examples/peermesh/harness/team.d.ts +8 -0
  61. package/dist/examples/peermesh/harness/team.js +13 -0
  62. package/dist/examples/peermesh/project.js +22 -4
  63. package/dist/examples/services/agent-control/README.md +3 -3
  64. package/dist/examples/services/mathlib-search/Dockerfile +4 -2
  65. package/dist/examples/services/mathlib-search/README.md +1 -1
  66. package/dist/examples/services/mcp-managed/README.md +2 -2
  67. package/dist/examples/services/persistent-board/README.md +13 -3
  68. package/dist/examples/services/persistent-board/business.d.ts +7 -0
  69. package/dist/examples/services/persistent-board/business.js +7 -0
  70. package/dist/examples/services/persistent-board/index.js +10 -0
  71. package/dist/examples/services/persistent-board/live.d.ts +3 -0
  72. package/dist/examples/services/persistent-board/live.js +58 -0
  73. package/dist/examples/subagents/README.md +5 -5
  74. package/dist/examples/subagents/business.js +3 -1
  75. package/dist/examples/subagents/harness/controller.d.ts +15 -0
  76. package/dist/examples/subagents/harness/controller.js +181 -32
  77. package/dist/examples/subagents/project.d.ts +2 -0
  78. package/dist/examples/subagents/project.js +43 -34
  79. package/dist/examples/subagents/prompts/prompts.d.ts +1 -0
  80. package/dist/examples/subagents/prompts/prompts.js +3 -0
  81. package/dist/examples/subagents/services/collaboration-service.d.ts +3 -2
  82. package/dist/examples/subagents/services/collaboration-service.js +14 -2
  83. package/dist/examples/substrate/README.md +2 -2
  84. package/dist/examples/substrate/harness/index.d.ts +1 -1
  85. package/dist/examples/substrate/harness/index.js +77 -12
  86. package/dist/examples/substrate/project.js +4 -1
  87. package/dist/examples/super/README.md +40 -0
  88. package/dist/examples/super/actions.d.ts +95 -0
  89. package/dist/examples/super/actions.js +230 -0
  90. package/dist/examples/super/artifact.d.ts +4 -0
  91. package/dist/examples/super/artifact.js +51 -0
  92. package/dist/examples/super/config.d.ts +80 -0
  93. package/dist/examples/super/config.js +83 -0
  94. package/dist/examples/super/coordinator.d.ts +33 -0
  95. package/dist/examples/super/coordinator.js +151 -0
  96. package/dist/examples/super/daemon.d.ts +11 -0
  97. package/dist/examples/super/daemon.js +109 -0
  98. package/dist/examples/super/decisions.d.ts +8 -0
  99. package/dist/examples/super/decisions.js +52 -0
  100. package/dist/examples/super/eject.json +5 -0
  101. package/dist/examples/super/execution.d.ts +11 -0
  102. package/dist/examples/super/execution.js +136 -0
  103. package/dist/examples/super/github.d.ts +62 -0
  104. package/dist/examples/super/github.js +269 -0
  105. package/dist/examples/super/inbox.d.ts +162 -0
  106. package/dist/examples/super/inbox.js +284 -0
  107. package/dist/examples/super/location.d.ts +5 -0
  108. package/dist/examples/super/location.js +64 -0
  109. package/dist/examples/super/outbox.d.ts +5 -0
  110. package/dist/examples/super/outbox.js +103 -0
  111. package/dist/examples/super/project.d.ts +111 -0
  112. package/dist/examples/super/project.js +253 -0
  113. package/dist/examples/super/prompts.d.ts +3 -0
  114. package/dist/examples/super/prompts.js +25 -0
  115. package/dist/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  116. package/dist/examples/taskpool/harness/controller.d.ts +35 -6
  117. package/dist/examples/taskpool/harness/controller.js +73 -7
  118. package/dist/examples/taskpool/project.js +18 -2
  119. package/dist/scripts/anyswarm-applications.d.ts +19 -0
  120. package/dist/scripts/anyswarm-applications.js +19 -0
  121. package/dist/scripts/anyswarm-arguments.d.ts +35 -5
  122. package/dist/scripts/anyswarm-arguments.js +87 -23
  123. package/dist/scripts/anyswarm-author.d.ts +5 -0
  124. package/dist/scripts/anyswarm-author.js +24 -0
  125. package/dist/scripts/anyswarm-eject.d.ts +11 -0
  126. package/dist/scripts/anyswarm-eject.js +164 -0
  127. package/dist/scripts/anyswarm-harnesses.d.ts +2 -0
  128. package/dist/scripts/anyswarm-harnesses.js +31 -0
  129. package/dist/scripts/anyswarm-installation.js +19 -13
  130. package/dist/scripts/anyswarm-launch.d.ts +37 -0
  131. package/dist/scripts/anyswarm-launch.js +86 -0
  132. package/dist/scripts/anyswarm-project.d.ts +12 -2
  133. package/dist/scripts/anyswarm-project.js +121 -20
  134. package/dist/scripts/anyswarm-source-runner.d.ts +1 -0
  135. package/dist/scripts/anyswarm-source-runner.js +232 -0
  136. package/dist/scripts/anyswarm-tui-config.d.ts +36 -0
  137. package/dist/scripts/anyswarm-tui-config.js +189 -0
  138. package/dist/scripts/anyswarm-tui-session.d.ts +66 -0
  139. package/dist/scripts/anyswarm-tui-session.js +304 -0
  140. package/dist/scripts/anyswarm-tui-terminal.d.ts +41 -0
  141. package/dist/scripts/anyswarm-tui-terminal.js +154 -0
  142. package/dist/scripts/anyswarm-tui.d.ts +2 -0
  143. package/dist/scripts/anyswarm-tui.js +1012 -0
  144. package/dist/scripts/anyswarm.js +47 -2
  145. package/dist/scripts/build-provenance.json +1 -0
  146. package/dist/scripts/build.js +7 -1
  147. package/dist/scripts/generate-architecture-api.js +2 -0
  148. package/dist/scripts/generate-architecture-prompts.js +24 -2
  149. package/dist/scripts/local-environment.d.ts +6 -1
  150. package/dist/scripts/local-environment.js +52 -16
  151. package/dist/scripts/local-setup-smoke.js +3 -2
  152. package/dist/scripts/local-setup-worker.d.ts +1 -1
  153. package/dist/scripts/local-setup-worker.js +15 -6
  154. package/dist/scripts/local-setup.d.ts +2 -2
  155. package/dist/scripts/local-setup.js +72 -12
  156. package/dist/scripts/opensandbox-agent-worker.js +2 -2
  157. package/dist/scripts/pack-release.d.ts +1 -0
  158. package/dist/scripts/pack-release.js +63 -0
  159. package/dist/scripts/pi-session-bridge.js +11 -3
  160. package/dist/scripts/run-harness.js +3 -1
  161. package/dist/scripts/setup-bootstrap.js +43 -6
  162. package/dist/src/core/allocation-ledger.js +4 -3
  163. package/dist/src/core/host-identity.d.ts +2 -0
  164. package/dist/src/core/host-identity.js +11 -0
  165. package/dist/src/core/index.d.ts +4 -2
  166. package/dist/src/core/index.js +12 -4
  167. package/dist/src/core/mcp-service.js +2 -2
  168. package/dist/src/core/runtime-management.d.ts +6 -0
  169. package/dist/src/core/runtime-management.js +24 -0
  170. package/dist/src/core/sandbox/executor-driver.d.ts +4 -2
  171. package/dist/src/core/sandbox/executor-driver.js +12 -14
  172. package/dist/src/core/sandbox/local-executor.d.ts +13 -1
  173. package/dist/src/core/sandbox/local-executor.js +69 -19
  174. package/dist/src/core/sandbox/local-worker.js +32 -21
  175. package/dist/src/core/sandbox/opensandbox-backend.d.ts +2 -0
  176. package/dist/src/core/sandbox/opensandbox-backend.js +36 -11
  177. package/dist/src/core/sandbox/sandbox-connection.d.ts +2 -0
  178. package/dist/src/core/sandbox/sandbox-connection.js +14 -6
  179. package/dist/src/core/service-live-state.d.ts +14 -0
  180. package/dist/src/core/service-live-state.js +161 -0
  181. package/dist/src/core/service-observation-types.d.ts +21 -1
  182. package/dist/src/core/service-process.d.ts +1 -1
  183. package/dist/src/core/service-process.js +45 -4
  184. package/dist/src/core/service-types.d.ts +5 -1
  185. package/dist/src/core/services.d.ts +1 -1
  186. package/dist/src/core/services.js +8 -3
  187. package/dist/src/core/types.d.ts +3 -0
  188. package/dist/src/core/worker-image.js +3 -3
  189. package/dist/src/harness/harness-session-types.d.ts +10 -0
  190. package/dist/src/harness/harness-session.js +42 -5
  191. package/dist/src/harness/project-harness.d.ts +13 -1
  192. package/dist/src/harness/project-harness.js +36 -10
  193. package/dist/src/harness/project-input.js +81 -15
  194. package/dist/src/harness/project-rpc-client.d.ts +1 -0
  195. package/dist/src/harness/project-rpc-client.js +5 -0
  196. package/dist/src/harness/project-rpc.d.ts +8 -2
  197. package/dist/src/harness/project-rpc.js +31 -7
  198. package/dist/src/harness/project-runtime.js +3 -1
  199. package/dist/src/harness/typescript-loader.d.ts +2 -0
  200. package/dist/src/harness/typescript-loader.js +41 -0
  201. package/dist/src/trace-viewer/public/app.js +6 -5
  202. package/dist/src/trace-viewer/reader.mjs +42 -2
  203. package/docs/INDEX.md +3 -1
  204. package/docs/architecture/00-overview.md +1 -1
  205. package/docs/architecture/01-agent-core.md +1 -1
  206. package/docs/architecture/06-observability-experiments.md +1 -1
  207. package/docs/architecture/07-run-configuration.md +18 -12
  208. package/docs/architecture/08-prompts.md +22 -0
  209. package/docs/architecture/10-service-api-reference.md +53 -18
  210. package/docs/architecture/11-storage-reference.md +18 -1
  211. package/docs/architecture/12-code-coverage.md +148 -84
  212. package/docs/architecture/15-core-runtime.md +8 -0
  213. package/docs/architecture/16-pi-opensandbox-backend.md +5 -5
  214. package/docs/architecture/17-harness-reporting.md +1 -1
  215. package/docs/architecture/19-substrate-harness.md +28 -1
  216. package/docs/architecture/20-lead-worker-harness.md +34 -1
  217. package/docs/architecture/22-website.md +5 -3
  218. package/docs/architecture/23-project-harness.md +124 -5
  219. package/docs/architecture/24-runtime-recovery.md +10 -3
  220. package/docs/architecture/25-foreground-tui.md +51 -0
  221. package/docs/architecture/26-code.md +39 -0
  222. package/docs/architecture/27-personal.md +43 -0
  223. package/docs/architecture/28-autoresearch.md +31 -0
  224. package/docs/architecture/INDEX.md +4 -0
  225. package/docs/architecture/prompts/08-lead-worker-harness.md +4 -2
  226. package/docs/architecture/prompts/08-subagents-harness.md +21 -0
  227. package/docs/architecture/prompts/21-personal.md +44 -0
  228. package/docs/architecture/prompts/22-autoresearch.md +63 -0
  229. package/docs/architecture/prompts/26-code.md +55 -0
  230. package/docs/architecture/prompts/source-manifest.json +152 -33
  231. package/docs/architecture/source-map.json +489 -21
  232. package/docs/designs/core-harness/06-project-harness.md +13 -2
  233. package/docs/designs/core-harness/README.md +5 -0
  234. package/docs/en/agents.md +1 -1
  235. package/docs/en/build-your-harness.md +3 -5
  236. package/docs/en/changelog.md +13 -4
  237. package/docs/en/first-harness.md +8 -11
  238. package/docs/en/harnesses/lead-worker.md +1 -1
  239. package/docs/en/harnesses/peermesh.md +2 -2
  240. package/docs/en/harnesses/subagents.md +2 -2
  241. package/docs/en/harnesses/substrate.md +4 -4
  242. package/docs/en/harnesses/taskpool.md +2 -2
  243. package/docs/en/latest.md +12 -123
  244. package/docs/en/overview.md +1 -1
  245. package/docs/en/quickstart.md +40 -16
  246. package/docs/en/reference/api.md +14 -4
  247. package/docs/en/reference/cli.md +58 -14
  248. package/docs/en/runtime.md +2 -2
  249. package/docs/en/services.md +4 -0
  250. package/docs/third-party-notices.md +1 -0
  251. package/docs/workflows/development.md +17 -12
  252. package/docs/workflows/release-and-docs-versioning.md +76 -0
  253. package/docs/zh/agents.md +1 -1
  254. package/docs/zh/build-your-harness.md +3 -5
  255. package/docs/zh/changelog.md +13 -4
  256. package/docs/zh/first-harness.md +8 -11
  257. package/docs/zh/harnesses/lead-worker.md +1 -1
  258. package/docs/zh/harnesses/peermesh.md +2 -2
  259. package/docs/zh/harnesses/subagents.md +2 -2
  260. package/docs/zh/harnesses/substrate.md +4 -4
  261. package/docs/zh/harnesses/taskpool.md +2 -2
  262. package/docs/zh/latest.md +13 -124
  263. package/docs/zh/overview.md +1 -1
  264. package/docs/zh/quickstart.md +40 -16
  265. package/docs/zh/reference/api.md +14 -4
  266. package/docs/zh/reference/cli.md +58 -14
  267. package/docs/zh/runtime.md +2 -2
  268. package/docs/zh/services.md +4 -0
  269. package/examples/README.md +24 -12
  270. package/examples/authoring/README.md +24 -0
  271. package/examples/authoring/business.ts +4 -0
  272. package/examples/authoring/config.ts +2 -0
  273. package/examples/authoring/eject.json +5 -0
  274. package/examples/authoring/harness.ts +21 -0
  275. package/examples/autoresearch/README.md +33 -0
  276. package/examples/autoresearch/REQUIREMENTS.zh.md +18 -0
  277. package/examples/autoresearch/config.ts +90 -0
  278. package/examples/autoresearch/demo.ts +55 -0
  279. package/examples/autoresearch/eject.json +15 -0
  280. package/examples/autoresearch/frontiercs2.ts +237 -0
  281. package/examples/autoresearch/prepare.ts +267 -0
  282. package/examples/autoresearch/process.ts +50 -0
  283. package/examples/autoresearch/project.ts +397 -0
  284. package/examples/autoresearch/research-service.ts +302 -0
  285. package/examples/code/README.md +25 -0
  286. package/examples/code/REQUIREMENTS.zh.md +11 -0
  287. package/examples/code/candidate.ts +89 -0
  288. package/examples/code/config.ts +19 -0
  289. package/examples/code/eject.json +5 -0
  290. package/examples/code/project.ts +581 -0
  291. package/examples/code/prompts.ts +16 -0
  292. package/examples/code/verification.ts +239 -0
  293. package/examples/code/worktree.ts +188 -0
  294. package/examples/harness-session/README.md +3 -6
  295. package/examples/lead-worker/harness/dynamic-scheduler.ts +6 -3
  296. package/examples/lead-worker/harness/index.ts +61 -6
  297. package/examples/lead-worker/project.ts +2 -2
  298. package/examples/lead-worker/services/board.ts +14 -1
  299. package/examples/messages/README.md +5 -5
  300. package/examples/messages/handoff.ts +6 -2
  301. package/examples/messages/project.ts +47 -2
  302. package/examples/notes/README.md +13 -18
  303. package/examples/notes/project.ts +57 -9
  304. package/examples/peermesh/harness/router.ts +2 -2
  305. package/examples/peermesh/harness/team.ts +11 -0
  306. package/examples/peermesh/project.ts +19 -4
  307. package/examples/services/agent-control/README.md +3 -3
  308. package/examples/services/mathlib-search/Dockerfile +4 -2
  309. package/examples/services/mathlib-search/README.md +1 -1
  310. package/examples/services/mcp-managed/README.md +2 -2
  311. package/examples/services/persistent-board/README.md +13 -3
  312. package/examples/services/persistent-board/business.ts +10 -0
  313. package/examples/services/persistent-board/index.ts +10 -0
  314. package/examples/services/persistent-board/live.ts +54 -0
  315. package/examples/subagents/README.md +5 -5
  316. package/examples/subagents/business.ts +3 -1
  317. package/examples/subagents/harness/controller.ts +161 -29
  318. package/examples/subagents/project.ts +47 -33
  319. package/examples/subagents/prompts/prompts.ts +4 -0
  320. package/examples/subagents/services/collaboration-service.ts +14 -2
  321. package/examples/substrate/README.md +2 -2
  322. package/examples/substrate/harness/index.ts +67 -11
  323. package/examples/substrate/project.ts +5 -1
  324. package/examples/super/README.md +40 -0
  325. package/examples/super/actions.ts +196 -0
  326. package/examples/super/artifact.ts +56 -0
  327. package/examples/super/config.ts +95 -0
  328. package/examples/super/coordinator.ts +158 -0
  329. package/examples/super/daemon.ts +84 -0
  330. package/examples/super/decisions.ts +46 -0
  331. package/examples/super/eject.json +5 -0
  332. package/examples/super/execution.ts +131 -0
  333. package/examples/super/github.ts +242 -0
  334. package/examples/super/inbox.ts +306 -0
  335. package/examples/super/location.ts +54 -0
  336. package/examples/super/outbox.ts +97 -0
  337. package/examples/super/project.ts +227 -0
  338. package/examples/super/prompts.ts +27 -0
  339. package/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  340. package/examples/taskpool/harness/controller.ts +59 -7
  341. package/examples/taskpool/project.ts +18 -2
  342. package/npm-shrinkwrap.development.json +2199 -0
  343. package/npm-shrinkwrap.json +86 -1920
  344. package/package.development.json +92 -0
  345. package/package.json +13 -7
  346. package/scripts/anyswarm-applications.ts +39 -0
  347. package/scripts/anyswarm-arguments.ts +94 -28
  348. package/scripts/anyswarm-author.ts +25 -0
  349. package/scripts/anyswarm-eject.ts +145 -0
  350. package/scripts/anyswarm-harnesses.ts +27 -0
  351. package/scripts/anyswarm-installation.ts +19 -13
  352. package/scripts/anyswarm-launch.ts +108 -0
  353. package/scripts/anyswarm-project.ts +114 -21
  354. package/scripts/anyswarm-source-runner.ts +203 -0
  355. package/scripts/anyswarm-tui-config.ts +174 -0
  356. package/scripts/anyswarm-tui-session.ts +295 -0
  357. package/scripts/anyswarm-tui-terminal.ts +147 -0
  358. package/scripts/anyswarm-tui.ts +912 -0
  359. package/scripts/anyswarm.ts +43 -2
  360. package/scripts/build.ts +8 -1
  361. package/scripts/generate-architecture-api.ts +2 -0
  362. package/scripts/generate-architecture-prompts.ts +35 -2
  363. package/scripts/local-environment.ts +55 -17
  364. package/scripts/local-setup-smoke.ts +3 -2
  365. package/scripts/local-setup-worker.ts +17 -7
  366. package/scripts/local-setup.ts +66 -13
  367. package/scripts/opensandbox-agent-worker.ts +2 -2
  368. package/scripts/pack-release.ts +67 -0
  369. package/scripts/pi-session-bridge.ts +10 -2
  370. package/scripts/run-harness.ts +3 -1
  371. package/scripts/setup-bootstrap.ts +41 -6
  372. package/src/core/allocation-ledger.ts +5 -3
  373. package/src/core/host-identity.ts +11 -0
  374. package/src/core/index.ts +12 -6
  375. package/src/core/mcp-service.ts +2 -2
  376. package/src/core/runtime-management.ts +22 -0
  377. package/src/core/sandbox/executor-driver.ts +15 -18
  378. package/src/core/sandbox/local-executor.ts +65 -19
  379. package/src/core/sandbox/local-worker.ts +29 -21
  380. package/src/core/sandbox/opensandbox-backend.ts +36 -11
  381. package/src/core/sandbox/sandbox-connection.ts +14 -5
  382. package/src/core/service-live-state.ts +156 -0
  383. package/src/core/service-observation-types.ts +23 -1
  384. package/src/core/service-process.ts +36 -3
  385. package/src/core/service-types.ts +3 -1
  386. package/src/core/services.ts +8 -3
  387. package/src/core/types.ts +3 -0
  388. package/src/core/worker-image.ts +3 -3
  389. package/src/harness/harness-session-types.ts +13 -1
  390. package/src/harness/harness-session.ts +40 -7
  391. package/src/harness/project-harness.ts +36 -10
  392. package/src/harness/project-input.ts +73 -15
  393. package/src/harness/project-rpc-client.ts +5 -0
  394. package/src/harness/project-rpc.ts +29 -8
  395. package/src/harness/project-runtime.ts +2 -1
  396. package/src/harness/typescript-loader.ts +37 -0
  397. package/src/trace-viewer/public/app.js +6 -5
  398. package/src/trace-viewer/reader.mjs +42 -2
@@ -0,0 +1,156 @@
1
+ import type { ServiceLiveState, ServiceStatePresentation, ServiceStateRead } from './service-observation-types.js';
2
+ import type { JsonValue, ServiceAdapter } from './service-types.js';
3
+
4
+ const timeoutMs = 1_000;
5
+ const maxBytes = 64 * 1024;
6
+ const maxConcurrentReads = 8;
7
+
8
+ type Source = { instanceId: string; readState?: ServiceAdapter['readState']; ready(): boolean };
9
+ type PendingRead = { result: Promise<ServiceStateRead>; cancel(): void };
10
+
11
+ /** Detach from provider objects and bound the work before redaction or serialization. */
12
+ function copyJson(value: unknown): JsonValue {
13
+ let allowance = maxBytes;
14
+ function spend(bytes: number) {
15
+ allowance -= bytes;
16
+ if (allowance < 0) throw new Error('Service state exceeds its size limit');
17
+ }
18
+ function visit(value: unknown, depth: number): JsonValue {
19
+ spend(1);
20
+ if (depth > 32) throw new Error('Service state exceeds its depth limit');
21
+ if (typeof value === 'string') {
22
+ spend(value.length);
23
+ return value;
24
+ }
25
+ if (value === null || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) return value;
26
+ if (!value || typeof value !== 'object') throw new Error('Service state is not JSON');
27
+ if (Array.isArray(value)) {
28
+ if (value.length > allowance) throw new Error('Service state exceeds its size limit');
29
+ return Array.from({ length: value.length }, (_, index) => visit(data(value, String(index)), depth + 1));
30
+ }
31
+ const prototype = Object.getPrototypeOf(value);
32
+ if (prototype !== Object.prototype && prototype !== null) throw new Error('Service state is not a plain JSON object');
33
+ const entries: [string, JsonValue][] = [];
34
+ for (const key in value) {
35
+ if (!Object.hasOwn(value, key)) continue;
36
+ spend(key.length + 1);
37
+ entries.push([key, visit(data(value, key), depth + 1)]);
38
+ }
39
+ return Object.fromEntries(entries);
40
+ }
41
+ return visit(value, 0);
42
+ }
43
+
44
+ function data(value: object, key: string): unknown {
45
+ const entry = Object.getOwnPropertyDescriptor(value, key);
46
+ if (!entry || !Object.hasOwn(entry, 'value')) throw new Error('Service state requires own data properties');
47
+ return entry.value;
48
+ }
49
+
50
+ function record(value: unknown): value is Record<string, unknown> {
51
+ return !!value && typeof value === 'object' && !Array.isArray(value);
52
+ }
53
+
54
+ function pointer(value: unknown): value is string {
55
+ return typeof value === 'string' && value.length <= 512 && /^(?:\/(?:[^~/]|~[01])*)*$/.test(value);
56
+ }
57
+
58
+ function label(value: unknown): value is string {
59
+ return typeof value === 'string' && value.length > 0 && value.length <= 128;
60
+ }
61
+
62
+ function fields(value: unknown): value is ServiceStatePresentation['summary'] {
63
+ return Array.isArray(value) && value.length <= 16 && value.every(field =>
64
+ record(field) && Object.keys(field).every(key => key === 'label' || key === 'path') && label(field.label) && pointer(field.path));
65
+ }
66
+
67
+ function presentationIsValid(value: unknown): value is ServiceStatePresentation {
68
+ return record(value) && Object.keys(value).every(key => key === 'summary' || key === 'tables') &&
69
+ (value.summary === undefined || fields(value.summary)) &&
70
+ (value.tables === undefined || (Array.isArray(value.tables) && value.tables.length <= 4 && value.tables.every(table =>
71
+ record(table) && Object.keys(table).every(key => ['title', 'path', 'columns'].includes(key)) &&
72
+ label(table.title) && pointer(table.path) && fields(table.columns))));
73
+ }
74
+
75
+ function capture(sample: ServiceLiveState, redact: (value: unknown) => unknown): ServiceLiveState {
76
+ if (!record(sample)) throw new Error('Service state must provide a capture record');
77
+ const capturedAt = data(sample, 'capturedAt');
78
+ const revision = Object.hasOwn(sample, 'revision') ? data(sample, 'revision') : undefined;
79
+ const presentation = Object.hasOwn(sample, 'presentation') ? data(sample, 'presentation') : undefined;
80
+ const plain = copyJson({ state: data(sample, 'state'), capturedAt,
81
+ ...(revision === undefined ? {} : { revision }),
82
+ ...(presentation === undefined ? {} : { presentation }) });
83
+ if (!record(plain) || !Object.hasOwn(plain, 'state') || typeof plain.capturedAt !== 'string' ||
84
+ !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?(?:Z|[+-]\d\d:\d\d)$/.test(plain.capturedAt) ||
85
+ !Number.isFinite(Date.parse(plain.capturedAt)) ||
86
+ (plain.revision !== undefined && !label(plain.revision)) ||
87
+ (plain.presentation !== undefined && !presentationIsValid(plain.presentation))) {
88
+ throw new Error('Service state has invalid data or presentation');
89
+ }
90
+ const safe = redact({
91
+ state: plain.state,
92
+ ...(plain.revision === undefined ? {} : { revision: plain.revision }),
93
+ ...(plain.presentation === undefined ? {} : { presentation: plain.presentation }),
94
+ }) as Omit<ServiceLiveState, 'capturedAt'>;
95
+ const result = { ...safe, capturedAt: new Date(plain.capturedAt).toISOString() };
96
+ if (Buffer.byteLength(JSON.stringify(result)) > maxBytes) throw new Error('Service state exceeds its size limit');
97
+ return result;
98
+ }
99
+
100
+ /** One bounded read per Service, with a separate capacity budget from business work. */
101
+ export function createServiceStateReader(redact: (value: unknown) => unknown) {
102
+ const pending = new Map<string, PendingRead>();
103
+ const timestamps = new Map<string, string>();
104
+ function failed(source: Source | undefined, status: Exclude<ServiceStateRead['status'], 'available'>, reason: string): ServiceStateRead {
105
+ const capturedAt = source && timestamps.get(source.instanceId);
106
+ return { status, reason, ...(capturedAt ? { capturedAt } : {}) };
107
+ }
108
+ return {
109
+ cancel(instanceId?: string) {
110
+ if (instanceId !== undefined) pending.get(instanceId)?.cancel();
111
+ else for (const read of pending.values()) read.cancel();
112
+ },
113
+ reset(instanceId: string) {
114
+ pending.get(instanceId)?.cancel();
115
+ timestamps.delete(instanceId);
116
+ },
117
+ async read(source: Source | undefined): Promise<ServiceStateRead> {
118
+ if (!source?.ready()) return failed(source, 'unavailable', 'Service is not ready');
119
+ const { instanceId, readState } = source;
120
+ if (!readState) return failed(source, 'unsupported', 'Service does not provide live state');
121
+ const prior = pending.get(instanceId);
122
+ if (prior) return structuredClone(await prior.result);
123
+ if (pending.size >= maxConcurrentReads) return failed(source, 'unavailable', 'Service state reader is busy');
124
+ const controller = new AbortController();
125
+ const reply = Promise.withResolvers<ServiceStateRead>();
126
+ let timer: NodeJS.Timeout;
127
+ function abort(status: 'timeout' | 'unavailable', reason: string) {
128
+ clearTimeout(timer);
129
+ controller.abort();
130
+ reply.resolve(failed(source, status, reason));
131
+ }
132
+ timer = setTimeout(() => abort('timeout', 'Service state read timed out'), timeoutMs);
133
+ pending.set(instanceId, { result: reply.promise, cancel: () => abort('unavailable', 'Service is not ready') });
134
+ async function perform() {
135
+ let result: ServiceStateRead;
136
+ try {
137
+ const raw = await readState!({ signal: controller.signal });
138
+ if (controller.signal.aborted) return;
139
+ if (!source!.ready()) return abort('unavailable', 'Service is not ready');
140
+ const sample = capture(raw, redact);
141
+ timestamps.set(instanceId, sample.capturedAt);
142
+ result = { ...sample, status: 'available' };
143
+ } catch {
144
+ if (controller.signal.aborted) return;
145
+ result = failed(source, 'error', 'Service state read failed');
146
+ } finally {
147
+ clearTimeout(timer);
148
+ pending.delete(instanceId);
149
+ }
150
+ reply.resolve(result);
151
+ }
152
+ void perform();
153
+ return structuredClone(await reply.promise);
154
+ },
155
+ };
156
+ }
@@ -1,4 +1,6 @@
1
- /** Data-only display hints evaluated against an exported JSON state using JSON Pointer. */
1
+ import type { JsonValue } from './service-types.js';
2
+
3
+ /** Data-only display hints evaluated against a JSON state using JSON Pointer. */
2
4
  export interface ServiceStatePresentation {
3
5
  summary?: readonly { label: string; path: string }[];
4
6
  tables?: readonly {
@@ -15,3 +17,23 @@ export interface ServiceStateMetadata {
15
17
  description?: string;
16
18
  presentation?: ServiceStatePresentation;
17
19
  }
20
+
21
+ /** Explicit public projection produced by a running Service. */
22
+ export interface ServiceLiveState {
23
+ readonly state: JsonValue;
24
+ readonly capturedAt: string;
25
+ readonly revision?: string;
26
+ readonly presentation?: ServiceStatePresentation;
27
+ }
28
+
29
+ export interface ServiceStateSource {
30
+ readonly name: string;
31
+ readonly supported: boolean;
32
+ }
33
+
34
+ export type ServiceStateRead = (ServiceLiveState & { readonly status: 'available' }) | {
35
+ readonly status: 'unsupported' | 'timeout' | 'error' | 'unavailable';
36
+ readonly reason: string;
37
+ /** Last successful capture by this Service instance, when available. */
38
+ readonly capturedAt?: string;
39
+ };
@@ -1,7 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { spawn, type ChildProcess } from 'node:child_process';
2
+ import { execFile, spawn, type ChildProcess } from 'node:child_process';
3
3
  import { readFile, access } from 'node:fs/promises';
4
4
  import { isAbsolute, resolve } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { darwinBootSession } from './host-identity.js';
5
7
  import type { JsonValue } from './service-types.js';
6
8
  import type { ServiceLifecycle, ServiceLifecycleContext, ServiceStorage, ServiceResources } from './service-lifecycle-types.js';
7
9
 
@@ -19,7 +21,38 @@ export interface ManagedProcessOptions {
19
21
 
20
22
  export type ProcessIdentity = { pid: number; startTime: string; bootId: string };
21
23
 
24
+ const execute = promisify(execFile);
25
+
26
+ async function darwinProcessIdentity(pid: number): Promise<ProcessIdentity | undefined> {
27
+ // The system JavaScript Objective-C bridge can query libproc without a
28
+ // build toolchain. PROC_PIDTBSDINFO (3) returns the 136-byte proc_bsdinfo.
29
+ const { stdout } = await execute('/usr/bin/osascript', ['-l', 'JavaScript', '-e', `
30
+ ObjC.import('Foundation');
31
+ ObjC.bindFunction('proc_pidinfo', ['int', ['int', 'int', 'uint64', 'void *', 'int']]);
32
+ function run(argv) {
33
+ const data = $.NSMutableData.dataWithLength(136);
34
+ const size = $.proc_pidinfo(Number(argv[0]), 3, 0, data.mutableBytes, 136);
35
+ return size === 136 ? ObjC.unwrap(data.base64EncodedStringWithOptions(0)) : 'unavailable';
36
+ }
37
+ `, '--', String(pid)], { timeout: 2_000, maxBuffer: 4096, env: { PATH: '/usr/bin:/bin' } });
38
+ if (stdout.trim() === 'unavailable') {
39
+ // An inaccessible process is not confirmed absent and must not be replaced.
40
+ try { process.kill(pid, 0); }
41
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ESRCH') return undefined; }
42
+ throw new Error('Managed process identity cannot be verified');
43
+ }
44
+ const data = Buffer.from(stdout.trim(), 'base64');
45
+ if (data.length !== 136 || data.readUInt32LE(12) !== pid) throw new Error('Invalid managed process identity');
46
+ if (data.readUInt32LE(4) === 5) return undefined; // SZOMB
47
+ const seconds = data.readBigUInt64LE(120);
48
+ const microseconds = data.readBigUInt64LE(128);
49
+ if (seconds === 0n || microseconds >= 1_000_000n) throw new Error('Invalid managed process start time');
50
+ return { pid, startTime: `${seconds}.${microseconds.toString().padStart(6, '0')}`, bootId: darwinBootSession() };
51
+ }
52
+
22
53
  export async function processIdentity(pid: number): Promise<ProcessIdentity | undefined> {
54
+ if (!Number.isSafeInteger(pid) || pid < 1 || pid > 0x7fffffff) throw new Error('Invalid managed process PID');
55
+ if (process.platform === 'darwin') return darwinProcessIdentity(pid);
23
56
  const stat = await readFile(`/proc/${pid}/stat`, 'utf8').catch(error => {
24
57
  const code = (error as NodeJS.ErrnoException).code;
25
58
  // Linux can remove the process between opening stat and reading it.
@@ -58,7 +91,7 @@ function resourceIdentity(context: ServiceLifecycleContext): ProcessIdentity | u
58
91
  return resource as ProcessIdentity;
59
92
  }
60
93
 
61
- /** Linux same-host process ownership with argv execution and PID reuse protection. */
94
+ /** Same-host process ownership with argv execution and PID reuse protection. */
62
95
  export function managedProcessLifecycle(options: ManagedProcessOptions): ServiceLifecycle {
63
96
  options = { ...options, args: [...options.args ?? []], cwd: resolve(options.cwd ?? process.cwd()),
64
97
  env: Object.fromEntries(Object.entries({ ...process.env, ...options.env }).filter((entry): entry is [string, string] => entry[1] !== undefined).sort(([a], [b]) => a.localeCompare(b))),
@@ -73,7 +106,7 @@ export function managedProcessLifecycle(options: ManagedProcessOptions): Service
73
106
  return {
74
107
  ownership: 'managed', implementationId: options.implementationId, configurationFingerprint, storage: options.storage, resources: options.resources,
75
108
  validate(resources) {
76
- if (process.platform !== 'linux') throw new Error('Managed process identity requires Linux /proc');
109
+ if (process.platform !== 'linux' && process.platform !== 'darwin') throw new Error('Managed process identity requires Linux or macOS');
77
110
  if (!isAbsolute(options.command) || !options.implementationId) throw new Error('Managed process requires an absolute executable and implementation ID');
78
111
  if (resources && Object.keys(resources).length) throw new Error('This process backend does not enforce CPU or memory limits');
79
112
  },
@@ -1,4 +1,4 @@
1
- import type { ServiceStateMetadata } from './service-observation-types.js';
1
+ import type { ServiceLiveState, ServiceStateMetadata } from './service-observation-types.js';
2
2
  import type { ServiceLifecycle } from './service-lifecycle-types.js';
3
3
 
4
4
  export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
@@ -102,6 +102,8 @@ export interface ServiceAdapter {
102
102
  invokeReply?(request: ServiceRequest): ServiceReply | Promise<ServiceReply>;
103
103
  /** Host confirmation that an uncertain HTTP write cannot continue to change remote state. */
104
104
  confirmQuiescent?(options: { signal: AbortSignal }): boolean | Promise<boolean>;
105
+ /** Optional host-only read of an explicitly public, bounded projection while ready. */
106
+ readState?(options: { signal: AbortSignal }): ServiceLiveState | Promise<ServiceLiveState>;
105
107
  /** Optional bounded host-only snapshot called during retirement or Runtime close. */
106
108
  exportState?(options: { signal: AbortSignal }): JsonValue | Promise<JsonValue>;
107
109
  /** Optional public capture facts and declarative display hints for that exact export. */
@@ -290,13 +290,14 @@ function captureLifecycle(lifecycle: ServiceLifecycle): ServiceLifecycle {
290
290
 
291
291
  function captureRegistration({ adapter, lifecycle, ...registration }: ServiceRegistration): Readonly<ServiceRegistration> {
292
292
  if (!adapter || typeof adapter.invoke !== 'function') invalid('Service adapter requires invoke(request)');
293
- for (const hook of ['invokeReply', 'exportStateMetadata'] as const) {
293
+ for (const hook of ['invokeReply', 'readState', 'exportStateMetadata'] as const) {
294
294
  if (adapter[hook] !== undefined && typeof adapter[hook] !== 'function') invalid(`Service ${hook} must be a function`);
295
295
  }
296
296
  if (adapter.exportState !== undefined && typeof adapter.exportState !== 'function') invalid('Service exportState must be a function');
297
297
  if (adapter.confirmQuiescent !== undefined && typeof adapter.confirmQuiescent !== 'function') invalid('Service confirmQuiescent must be a function');
298
298
  const captured = Object.freeze({ invoke: adapter.invoke.bind(adapter),
299
299
  ...(adapter.invokeReply ? { invokeReply: adapter.invokeReply.bind(adapter) } : {}),
300
+ ...(adapter.readState ? { readState: adapter.readState.bind(adapter) } : {}),
300
301
  ...(adapter.exportStateMetadata ? { exportStateMetadata: adapter.exportStateMetadata.bind(adapter) } : {}),
301
302
  ...(adapter.exportState ? { exportState: adapter.exportState.bind(adapter) } : {}),
302
303
  ...(adapter.confirmQuiescent ? { confirmQuiescent: adapter.confirmQuiescent.bind(adapter) } : {}) });
@@ -526,15 +527,19 @@ export async function invokeService(registration: ServiceRegistration, invocatio
526
527
 
527
528
  export type ServiceHandler = (input: JsonValue, context: ServiceRequest) => JsonValue | Promise<JsonValue>;
528
529
 
529
- export function inProcessService(definition: ServiceInterface, handlers: Readonly<Record<string, ServiceHandler>>): ServiceDefinition {
530
+ export function inProcessService(definition: ServiceInterface, handlers: Readonly<Record<string, ServiceHandler>>,
531
+ observation?: Pick<ServiceAdapter, 'readState'>): ServiceDefinition {
530
532
  if (!record(handlers) || !record(definition?.operations) ||
531
533
  Object.keys(handlers).length !== Object.keys(definition.operations).length ||
532
534
  Object.keys(definition.operations).some(operation => !Object.hasOwn(handlers, operation) || typeof handlers[operation] !== 'function')) {
533
535
  invalid('In-process Service requires exactly one handler for each operation');
534
536
  }
535
537
  const snapshot = Object.freeze({ ...handlers });
538
+ const readState = observation?.readState;
539
+ if (readState !== undefined && typeof readState !== 'function') invalid('Service readState must be a function');
536
540
  return { interface: definition, provider: 'in-process', create: () => ({
537
- adapter: { invoke: request => snapshot[request.capability.operation](request.input, request) },
541
+ adapter: { invoke: request => snapshot[request.capability.operation](request.input, request),
542
+ ...(readState ? { readState: readState.bind(observation) } : {}) },
538
543
  }) };
539
544
  }
540
545
 
package/src/core/types.ts CHANGED
@@ -4,6 +4,7 @@ import type { ExecutorSelection } from './executor-adapter.js';
4
4
  import type { FilePolicy } from './file-policy.js';
5
5
  import type { ServiceRegistration, ServiceRegistry } from './services.js';
6
6
  import type { ServiceStorage, ServiceResources } from './service-lifecycle-types.js';
7
+ import type { ServiceStateRead, ServiceStateSource } from './service-observation-types.js';
7
8
  import type { JsonValue, ServiceDefinition, ServiceToolMode, ServiceManifest } from './service-types.js';
8
9
 
9
10
  import type { AgentSessionConfig, ContextInput, ContextInputReceipt, ContextSendOptions, RuntimeHooks, RuntimeSession, SessionEvent } from './session-types.js';
@@ -424,6 +425,8 @@ export interface Runtime {
424
425
  register(input: RuntimeServiceRegistration): Promise<RuntimeServiceDefinition>;
425
426
  get(id: string): RuntimeServiceDefinition | null;
426
427
  list(): readonly RuntimeServiceDefinition[];
428
+ listState(): readonly ServiceStateSource[];
429
+ readState(serviceId: string): Promise<ServiceStateRead>;
427
430
  start(input: ServiceRetirement): Promise<RuntimeServiceDefinition>;
428
431
  stop(input: ServiceRetirement): Promise<RuntimeServiceDefinition>;
429
432
  restart(input: ServiceRetirement): Promise<RuntimeServiceDefinition>;
@@ -16,7 +16,7 @@ function readPackageVersion(): string {
16
16
  // Try the compiled dist/src/core -> package root path next.
17
17
  }
18
18
  }
19
- return '0.5.0';
19
+ return '0.5.1';
20
20
  }
21
21
 
22
22
  export const PACKAGE_VERSION = readPackageVersion();
@@ -27,14 +27,14 @@ export const DEFAULT_WORKER_IMAGE = 'anyswarm-worker-local:default';
27
27
  export function workerImageFor(executor: ExecutorSelection | string = 'pi'): string {
28
28
  const driver = selectExecutorDriver(executor);
29
29
  return driver.adapter?.image ?? `anyswarm-worker-local:${driver.kind}${
30
- typeof executor === 'object' && 'version' in executor ? `-${driver.version}` : ''
30
+ driver.version === undefined ? '' : `-${driver.version}`
31
31
  }`;
32
32
  }
33
33
 
34
34
  export function localWorkerSelector(image: string) {
35
35
  if (image === DEFAULT_WORKER_IMAGE) return {};
36
36
  if (typeof image !== 'string') return;
37
- const match = /^anyswarm-worker-local:(pi|codex)(?:-(\d+\.\d+\.\d+))?$/.exec(image);
37
+ const match = /^anyswarm-worker-local:(pi|codex)(?:-(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?))?$/.exec(image);
38
38
  if (match) return { kind: match[1] as 'pi' | 'codex', version: match[2] };
39
39
  }
40
40
 
@@ -1,6 +1,7 @@
1
1
  import type { Runtime, InputReceipt, ConditionalInputReceipt, InterruptReceipt, StopReceipt, SendOptions, ErrorDiagnostic } from '../core/types.js';
2
2
  import type { AgentSessionPatch, AgentSessionState, AgentSessionStats, AgentSessionMessages, ContextInput, ContextSendOptions, ContextInputReceipt, SessionControlReceipt } from '../core/session-types.js';
3
3
  import type { HarnessInput, HarnessJson, Harness } from './project-harness.js';
4
+ import type { ServiceStateRead, ServiceStateSource } from '../core/service-observation-types.js';
4
5
 
5
6
  export type HarnessLifetime = 'task' | 'interactive';
6
7
  export type HarnessRequest = Readonly<{ requestId: string }>;
@@ -19,7 +20,13 @@ export type HarnessCapability = Readonly<{
19
20
  text?: boolean;
20
21
  context?: boolean;
21
22
  }>;
22
- export type HarnessInputDescriptor = Readonly<{ description?: string; schema?: HarnessJson; targets?: HarnessJson }>;
23
+ export type HarnessInputDescriptor = Readonly<{
24
+ description?: string;
25
+ schema?: HarnessJson;
26
+ targets?: HarnessJson;
27
+ /** Terminal slash commands or explicit @mentions routed as Harness input. */
28
+ commands?: readonly string[];
29
+ }>;
23
30
  export type HarnessDescriptor = Readonly<{
24
31
  id: string;
25
32
  apiVersion: 1;
@@ -141,6 +148,10 @@ export interface HarnessAgents {
141
148
  interrupt(agentId: string, request: HarnessRequest): Promise<HarnessAgentReceipt<InterruptReceipt>>;
142
149
  stop(agentId: string, options: HarnessRequest & { reason?: string }): Promise<HarnessAgentReceipt<StopReceipt>>;
143
150
  }
151
+ export interface HarnessServices {
152
+ list(): Promise<readonly (ServiceStateSource & { readonly runtimeId: string })[]>;
153
+ read(runtimeId: string, name: string): Promise<ServiceStateRead>;
154
+ }
144
155
  export interface HarnessSession {
145
156
  describe(): Promise<HarnessDescriptor>;
146
157
  start(input: HarnessInput, request: HarnessRequest): Promise<HarnessStartReceipt>;
@@ -149,6 +160,7 @@ export interface HarnessSession {
149
160
  getState(): Promise<HarnessState>;
150
161
  onEvent(handler: (event: HarnessEvent) => void, options?: HarnessSubscriptionOptions): () => void;
151
162
  readonly agents: HarnessAgents;
163
+ readonly services: HarnessServices;
152
164
  stop(request: HarnessRequest & { reason?: string }): Promise<HarnessStopReceipt>;
153
165
  readonly completion: Promise<HarnessResult> | undefined;
154
166
  }
@@ -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';
@@ -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);
@@ -278,9 +295,17 @@ export function createProjectHost(definition: ProjectHarness, options: StartupOp
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 {