@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
@@ -1,4 +1,4 @@
1
- import { ServiceRegistry, createRuntime, runInput, createInputAdmission, ProjectPreflightError, runWithReport } from '@anyswarm/core';
1
+ import { ServiceRegistry, createRuntime, getExecutorCapabilities, runInput, createInputAdmission, ProjectPreflightError, runWithReport } from '@anyswarm/core';
2
2
  import { join } from 'node:path';
3
3
  import { createSubstrateService } from '../services/substrate.js';
4
4
 
@@ -23,16 +23,58 @@ export function substratePeerProfile({ image, model = 'default', exportLimit = 2
23
23
 
24
24
  /** Fixed no-Task pool. Harness owns content and drivers; Core owns all Agents. */
25
25
  export async function runSubstrate({ sandbox, executor, models, connection, filePolicy, runId, image, outputDir, question, model = 'default', poolSize = 3, maxRounds = 2,
26
- workTimeoutMs = 120_000, turnTimeoutMs = 30_000, closeTimeoutMs = 30_000, files, onRuntime, beforeCycle, onReady, onCycle, onPeerStop, questionForCycle, maxConcurrentInputs }: any, signal: any, run = runWithReport) {
26
+ workTimeoutMs = 120_000, turnTimeoutMs = 30_000, closeTimeoutMs = 30_000, files, onRuntime, beforeCycle, onReady, onCycle, onPeerStop, onControl, questionForCycle, maxConcurrentInputs }: any, signal: any, run = runWithReport) {
27
27
  if (typeof outputDir !== 'string' || !outputDir || typeof question !== 'string' || !question.trim() || Buffer.byteLength(question) > 8192 ||
28
28
  typeof image !== 'string' || !image || !Number.isSafeInteger(maxRounds) || maxRounds < 2 || maxRounds > 32 ||
29
29
  ![workTimeoutMs, turnTimeoutMs, closeTimeoutMs].every(finite) || (signal !== undefined && !(signal instanceof AbortSignal)) ||
30
30
  (maxConcurrentInputs !== undefined && (!Number.isSafeInteger(maxConcurrentInputs) || maxConcurrentInputs < 1 || maxConcurrentInputs > poolSize)) ||
31
- [onRuntime, beforeCycle, onReady, onCycle, onPeerStop, questionForCycle].some((hook: any) => hook !== undefined && typeof hook !== 'function')) throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Substrate requires a question, image, output directory, two to 32 rounds, finite waits and an optional trusted host lifecycle functions');
31
+ [onRuntime, beforeCycle, onReady, onCycle, onPeerStop, onControl, questionForCycle].some((hook: any) => hook !== undefined && typeof hook !== 'function')) throw new ProjectPreflightError('INVALID_RUN_CONFIGURATION', 'Substrate requires a question, image, output directory, two to 32 rounds, finite waits and an optional trusted host lifecycle functions');
32
32
  const substrate = createSubstrateService({ databasePath: join(outputDir, 'substrate.sqlite'), runId, poolSize });
33
33
  const services = new ServiceRegistry();
34
34
  services.register('substrate', substrate.service);
35
35
  const peers: any[] = [], events: any[] = [];
36
+ const memberSignals = new Map<string, AbortController>();
37
+ const heldMembers = new Map<string, ReturnType<typeof Promise.withResolvers<void>>>();
38
+ async function memberReady(peer: any) {
39
+ if (peer.held && !peer.stopped) {
40
+ let waiting = heldMembers.get(peer.agentId);
41
+ if (!waiting) heldMembers.set(peer.agentId, waiting = Promise.withResolvers<void>());
42
+ await waitFor(waiting.promise, workSignal);
43
+ }
44
+ return !peer.stopped;
45
+ }
46
+ const memberControls = {
47
+ capabilities: {
48
+ send: { supported: getExecutorCapabilities(executor ?? 'pi').activeSteer, text: true, modes: ['steer'] },
49
+ interrupt: { supported: getExecutorCapabilities(executor ?? 'pi').queuedInputCancellation },
50
+ stop: { supported: true },
51
+ },
52
+ handlers: {
53
+ send(agentId: string, payload: any, request: any) {
54
+ const { input, options } = payload;
55
+ return runtime.send(agentId, input, { ...options, requestId: request.operationId });
56
+ },
57
+ async interrupt(agentId: string, _payload: any, request: any) {
58
+ const peer = peers.find(peer => peer.agentId === agentId);
59
+ peer.held = true;
60
+ peer.interventions.push({ kind: 'interrupt', requestId: request.requestId });
61
+ const core = await runtime.interrupt(agentId, { requestId: request.operationId });
62
+ onControl?.({ agentId, kind: 'interrupt', receipt: core, snapshot: substrate.snapshot() });
63
+ return { core, harnessEffects: { held: true, rescheduled: false } };
64
+ },
65
+ async stop(agentId: string, payload: any, request: any) {
66
+ const peer = peers.find(peer => peer.agentId === agentId);
67
+ peer.stopped = true;
68
+ memberSignals.get(agentId)?.abort();
69
+ peer.interventions.push({ kind: 'stop', requestId: request.requestId });
70
+ heldMembers.get(agentId)?.resolve();
71
+ substrate.retirePeer(agentId);
72
+ const core = await runtime.stop(agentId, { requestId: request.operationId, reason: payload?.reason });
73
+ onControl?.({ agentId, kind: 'stop', receipt: core, snapshot: substrate.snapshot() });
74
+ return { core, harnessEffects: { stopped: true, rescheduled: false } };
75
+ },
76
+ },
77
+ };
36
78
  const evidence = () => ({ peers, events, substrate: substrate.snapshot(), databasePath: join(outputDir, 'substrate.sqlite'),
37
79
  policy: { poolSize, maxRounds, workTimeoutMs, turnTimeoutMs, closeTimeoutMs, replacement: false,
38
80
  ranking: 'token occurrences descending, incoming references descending, stable address ascending', maxSearchResults: 8 } });
@@ -69,27 +111,31 @@ export async function runSubstrate({ sandbox, executor, models, connection, file
69
111
  substrate.bindRuntime(core.id);
70
112
  const unsubscribe = core.onEvent((event: any) => events.push({ agentId: event.agentId, seq: events.length + 1, type: event.type, ...(event.outcome ? { outcome: event.outcome } : {}) }));
71
113
  try {
72
- onRuntime?.(core);
114
+ onRuntime?.(core, memberControls);
73
115
  for (let index = 0; index < poolSize; index++) {
74
116
  remaining();
75
117
  const agent = await waitFor(core.spawn({ requestId: `peer:${index}`, profile: 'peer', files: files ?? {
76
118
  'question.txt': { data: question, encoding: 'utf8' },
77
119
  } }), workSignal);
78
120
  remaining(); substrate.bindPeer(agent.id);
79
- peers.push({ index, agentId: agent.id, turns: [], failure: null, stop: null });
121
+ memberSignals.set(agent.id, new AbortController());
122
+ peers.push({ index, agentId: agent.id, turns: [], failure: null, stop: null, held: false, stopped: false, interventions: [] });
80
123
  }
81
124
  if (onReady) await waitFor(Promise.resolve().then(() => onReady({ runtime:core, peerIds:peers.map((peer: any)=>peer.agentId), snapshot:substrate.snapshot() })),workSignal);
82
125
  remaining();
83
126
  await Promise.all(peers.map(async (peer: any) => {
127
+ const peerSignal = AbortSignal.any([workSignal, memberSignals.get(peer.agentId)!.signal]);
84
128
  try {
85
129
  for (let round = 0; round < maxRounds; round++) {
130
+ if (!await memberReady(peer)) break;
86
131
  if (beforeCycle) {
87
132
  remaining();
88
- await waitFor(Promise.resolve().then(() => beforeCycle({ peerIndex: peer.index, agentId: peer.agentId, round, signal: workSignal })), workSignal);
133
+ await waitFor(Promise.resolve().then(() => beforeCycle({ peerIndex: peer.index, agentId: peer.agentId, round, signal: peerSignal })), peerSignal);
89
134
  remaining();
135
+ if (!await memberReady(peer)) break;
90
136
  }
91
137
  const cycleQuestion = questionForCycle ? await waitFor(Promise.resolve().then(() =>
92
- questionForCycle({ peerIndex: peer.index, agentId: peer.agentId, round, signal: workSignal })), workSignal) : question;
138
+ questionForCycle({ peerIndex: peer.index, agentId: peer.agentId, round, signal: peerSignal })), peerSignal) : question;
93
139
  if (typeof cycleQuestion !== 'string' || !cycleQuestion.trim() || Buffer.byteLength(cycleQuestion) > 8192) throw fail('SUBSTRATE_QUESTION_INVALID');
94
140
  const requestId = `${peer.agentId}:cycle:${round}`;
95
141
  const turn: any = { requestId, round, attempts: [] }; peer.turns.push(turn);
@@ -109,14 +155,22 @@ export async function runSubstrate({ sandbox, executor, models, connection, file
109
155
  const left = Math.floor(turnDeadline - performance.now());
110
156
  if(left < 1) throw fail('SUBSTRATE_CORRECTION_WINDOW_CLOSED');
111
157
  return runInput(core, peer.agentId, text,
112
- { requestId: currentRequestId, timeoutMs: Math.min(left, remaining()), signal: workSignal });
158
+ { requestId: currentRequestId, timeoutMs: Math.min(left, remaining()), signal: peerSignal,
159
+ beforeSend() { if (peer.held || peer.stopped) throw fail('SUBSTRATE_MEMBER_HELD'); } });
113
160
  };
114
- const receipt = await (admission ? admission.run(sendInput) : sendInput());
161
+ let receipt;
162
+ try { receipt = await (admission ? admission.run(sendInput) : sendInput()); }
163
+ catch (error) {
164
+ if (!peer.held && !peer.stopped) throw error;
165
+ turn.outcome = peer.stopped ? 'user-stopped' : 'user-interrupted';
166
+ await memberReady(peer);
167
+ break;
168
+ }
115
169
  const observed: any = { requestId: currentRequestId, inputId: receipt.inputId,
116
170
  outcome: receipt.settled.outcome, attempt };
117
171
  turn.attempts.push(observed); Object.assign(turn, { inputId: observed.inputId, outcome: observed.outcome });
118
172
  const decision = onCycle ? await waitFor(Promise.resolve().then(() => onCycle({ peerIndex: peer.index,
119
- agentId: peer.agentId, round, attempt, requestId: currentRequestId, result: receipt, beforeSnapshot, snapshot: substrate.snapshot(), signal: workSignal, deadlineAtMs: turnDeadline })), workSignal) : undefined;
173
+ agentId: peer.agentId, round, attempt, requestId: currentRequestId, result: receipt, beforeSnapshot, snapshot: substrate.snapshot(), signal: peerSignal, deadlineAtMs: turnDeadline })), peerSignal) : undefined;
120
174
  if (decision?.correction === undefined) break;
121
175
  if (typeof decision.correction !== 'string' || !decision.correction.trim() || Buffer.byteLength(decision.correction) > 4096 ||
122
176
  !finite(decision.timeoutMs)) throw fail('SUBSTRATE_CORRECTION_INVALID');
@@ -126,8 +180,9 @@ export async function runSubstrate({ sandbox, executor, models, connection, file
126
180
  attempt++;
127
181
  }
128
182
  }
183
+ await memberReady(peer);
129
184
  } catch (error: any) {
130
- peer.failure = { code: error.code ?? 'PEER_WORK_FAILED', ...(error.requestId ? { requestId: error.requestId } : {}),
185
+ if (!peer.stopped) peer.failure = { code: error.code ?? 'PEER_WORK_FAILED', ...(error.requestId ? { requestId: error.requestId } : {}),
131
186
  ...(error.inputId ? { inputId: error.inputId } : {}), ...(error.receipt ? { receipt: error.receipt } : {}) };
132
187
  } finally {
133
188
  substrate.retirePeer(peer.agentId);
@@ -141,6 +196,7 @@ export async function runSubstrate({ sandbox, executor, models, connection, file
141
196
  }));
142
197
  if (workSignal.aborted || Date.now() >= deadlineAt) throw fail('SUBSTRATE_WORK_ABORTED');
143
198
  if (peers.some((peer: any) => peer.failure)) throw fail('SUBSTRATE_PEERS_FAILED');
199
+ if (peers.some((peer: any) => peer.interventions.length)) throw fail('SUBSTRATE_USER_INTERVENTION');
144
200
  return { peerIds: peers.map((peer: any) => peer.agentId), completedRounds: peers.map((peer: any) => peer.turns.length) };
145
201
  } finally { workClosed = true; clearTimeout(timer); unsubscribe(); }
146
202
  },
@@ -35,13 +35,17 @@ const substrate = {
35
35
  const result = await runSubstrate({
36
36
  sandbox: sandboxHandle, executor: configuration.executor, connection, filePolicy: configuration.filePolicy, models, image, model, poolSize, maxRounds, workTimeoutMs, turnTimeoutMs, closeTimeoutMs,
37
37
  runId: context.runId, outputDir: context.outputDir, question: context.input.prompt, files: context.initial.files,
38
- onRuntime: (runtime: Parameters<typeof observeProjectRuntime>[0]) => { observation = observeProjectRuntime(runtime, context, () => business); },
38
+ onRuntime: (runtime: Parameters<typeof observeProjectRuntime>[0], controls: Parameters<typeof observeProjectRuntime>[3]) => {
39
+ observation = observeProjectRuntime(runtime, context, () => business, controls);
40
+ },
39
41
  onReady: ({ peerIds, snapshot }: { peerIds: string[]; snapshot: unknown }) => {
40
42
  progress({ stage: 'running', peerIds, publication: snapshot });
41
43
  context.markRunning();
42
44
  },
43
45
  onCycle: ({ agentId, round, attempt, snapshot }: { agentId: string; round: number; attempt: number; snapshot: unknown }) =>
44
46
  progress({ stage: 'cycle', agentId, round, attempt, publication: snapshot }),
47
+ onControl: (event: { agentId: string; kind: string; receipt: unknown; snapshot: unknown }) =>
48
+ progress({ stage: 'owner-intervention', ...event }),
45
49
  onPeerStop: ({ agentId, receipt, snapshot }: { agentId: string; receipt: unknown; snapshot: unknown }) =>
46
50
  progress({ stage: 'peer-stopped', agentId, receipt, publication: snapshot }),
47
51
  }, context.signal, context.runWithRuntime);
@@ -0,0 +1,40 @@
1
+ # Personal
2
+
3
+ Personal receives GitHub Issue and linked PR requests in the background. The user and GitHub inbox address a Router, which assigns scoped Pi Workers and a read-only Reviewer as needed. See [the full Personal requirements](https://github.com/AnySwarm/anyswarm/pull/320).
4
+
5
+ ## Connect and start
6
+
7
+ Use Node.js 22.19 or later, Git and an existing Pi/OpenSandbox connection. Run `anys setup --backend pi` for host setup. This candidate's end-to-end acceptance uses Linux. Set `ANYSWARM_MODEL_URL` to the full Responses endpoint and `ANYSWARM_MODEL_ID` to the model ID. Optional `ANYSWARM_MODEL_PROVIDER`, `ANYSWARM_MODEL_TOKEN` and `ANYSWARM_MODEL_HEADERS_JSON` follow the model provider. For a reasoning model outside the built-in model catalog, set `ANYSWARM_MODEL_REASONING=true`. Keep credentials in the host environment or credential manager.
8
+
9
+ Open `anys`, enter `/super`, then use the composer:
10
+
11
+ ```text
12
+ /setup --repo owner/project --path README.md
13
+ /start
14
+ /jobs
15
+ ```
16
+
17
+ For scripts, use the same actions through `anys -u super --cmd`, for example `anys -u super --cmd '/jobs #123'`. `/setup` infers the repository from a GitHub `origin` when available and defaults to the authenticated GitHub login and `README.md`. Use repeated `--user` or `--path` to allow other logins or up to eight existing UTF-8 files. Set `ANYSWARM_SUPER_GITHUB_TOKEN` or use an existing GitHub CLI login. Allow Issues and Pull requests read/write for conversations and Contents read for files. Creating or updating a Draft PR also needs Contents and Pull requests write.
18
+
19
+ `/setup` reports the verified GitHub identity, repository, comments and requested files. It validates the local Pi and model configuration and gives the fix for an invalid setting. GitHub reply and PR writes stay unverified until the corresponding operations succeed. `/start` initializes the Runtime. A real work item verifies Worker and model connectivity. `/jobs` and `/logs` show the most recent background failure stage and its repair hint.
20
+
21
+ ## Work with the Router
22
+
23
+ Post `/super Update the installation instructions` on an Issue in scope or enter `/ask #123 Update the installation instructions` in the composer. GitHub follows the original Issue or its bound Draft PR. In the terminal, `@router #123 Add a Linux example` sends a follow-up through the same inbox. Use `#<issue>` or an unambiguous work ID prefix in place of `#123` for an existing work item.
24
+
25
+ When the Router asks a question, use `/answer #123 <text>` or answer its decision card. Personal sends the verified patch and Reviewer findings to the local approval card. Use `/approve #123` to let the host publish this patch and post a follow-up receipt. `/reject #123 [reason]` records the rejection locally. Use `--publish` at setup if you want automatic publication for the configured repository. `/jobs [work]` shows the artifact, decisions and reply receipts. `/stop-work <work>` stops a single work item.
26
+
27
+ Type `q` or `/quit` to detach. Use `/stop` to stop the daemon and `/logs` for its log path. `/trace` opens the Trace Viewer at the attached Personal instance's Runtime records. Every Runtime has a bounded model request budget.
28
+
29
+ State is keyed by the launch directory and lives under `$XDG_STATE_HOME/anyswarm/personal` or `~/.local/state/anyswarm/personal`. To reuse state across launch directories, set `ANYSWARM_SUPER_STATE_DIR` to the same absolute, private path. Stop an older candidate before starting a new version against its state. A restart retains tasks, verified artifacts, decisions and pending replies. Unknown GitHub mutations are reconciled by identity. Personal reads a newly linked PR's comments even if it has already advanced the repository cursor during recovery. The original Sandbox can require cleanup after a crash. Same-host recovery uses the original Worker-reachable address and `ANYSWARM_SUPER_CALLBACK_PORT` when set.
30
+
31
+ ## Edit your copy
32
+
33
+ ```sh
34
+ anys eject super --dir ./personal-src
35
+ cd ./personal-src
36
+ npm install
37
+ npm run start
38
+ ```
39
+
40
+ The SDK-bound export includes the TypeScript Harness, Slash Actions and GitHub adapter. `npm run start` opens the shared terminal with the exported module. The same module can run in a foreground process with `anys run ./project.ts --prompt 'Run Personal GitHub inbox'`. The exported and installed daemons use the same state lock. The export contains the application sources and SDK provenance.
@@ -0,0 +1,196 @@
1
+ import { execFileSync, spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { closeSync, constants, existsSync, openSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { setTimeout as pause } from 'node:timers/promises';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { parseArgs } from 'node:util';
8
+ import type { Harness } from '@anyswarm/core';
9
+ import { defaults, inspectBackendConfiguration, type PersonalStartupFailure } from './config.js';
10
+ import { observe, serve } from './daemon.js';
11
+ import { GitHub, githubToken, safePath } from './github.js';
12
+ import { openInbox } from './inbox.js';
13
+ import { loadSettings, lockPersonalState, privateDirectory, stateDirectory } from './location.js';
14
+
15
+ type ActionContext = { args: string; cwd: string; signal: AbortSignal };
16
+
17
+ async function probe(cwd: string, shutdown: AbortSignal) {
18
+ const signal = AbortSignal.any([shutdown, AbortSignal.timeout(1000)]);
19
+ return observe({ cwd, signal }).catch(() => undefined);
20
+ }
21
+
22
+ async function setup(args: string, cwd: string, directory: string, shutdown: AbortSignal) {
23
+ const { values } = parseArgs({ args: args.split(/\s+/).filter(Boolean), options: {
24
+ repo: { type: 'string' }, user: { type: 'string', multiple: true }, path: { type: 'string', multiple: true },
25
+ publish: { type: 'boolean' }, 'poll-ms': { type: 'string' },
26
+ } });
27
+ let guessed: string | undefined;
28
+ try {
29
+ const remote = execFileSync('git', ['remote', 'get-url', 'origin'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
30
+ guessed = /^(?:https:\/\/github\.com\/|git@github\.com:)([^/]+\/[^/]+?)(?:\.git)?$/.exec(remote)?.[1];
31
+ } catch { /* A local Git checkout is optional. */ }
32
+ const repository = values.repo ?? guessed;
33
+ if (!repository) return 'Configure GitHub with /setup --repo owner/repo [--path README.md] [--user login] [--publish].';
34
+ const paths = values.path?.length ? [...new Set(values.path)] : ['README.md'];
35
+ const publish = values.publish ?? false;
36
+ if (paths.length > 8 || paths.some(path => !safePath(path) || path === 'personal-output.patch')) {
37
+ throw new Error('Select 1–8 existing text files using repository-relative paths without dot directories.');
38
+ }
39
+ const pollMs = Number(values['poll-ms'] ?? defaults.pollMs);
40
+ if (!Number.isSafeInteger(pollMs) || pollMs < 2000 || pollMs > 300_000) throw new Error('Polling interval must be 2000–300000 ms.');
41
+ const signal = AbortSignal.any([shutdown, AbortSignal.timeout(60_000)]);
42
+ const github = new GitHub(repository, githubToken());
43
+ const { account, repo } = await github.inspect(signal);
44
+ const users = [...new Set((values.user ?? [account]).map(user => user.toLowerCase()))];
45
+ if (!users.length || users.length > 20 || users.some(user => !/^[a-z0-9][a-z0-9-]{0,38}$/.test(user))) {
46
+ throw new Error('Set 1–20 valid GitHub user logins.');
47
+ }
48
+ if (publish && repo.permissions?.push === false) throw new Error('The authenticated GitHub account needs write access for --publish.');
49
+ const head = await github.head(signal);
50
+ await Promise.all(paths.map(path => github.file(path, head.sha, signal)));
51
+ const release = lockPersonalState(directory);
52
+ try {
53
+ const existing = await observe({ cwd, signal });
54
+ if (existing) { existing.close(); throw new Error('Stop Personal before replacing its settings.'); }
55
+ const file = join(directory, 'settings.json');
56
+ const before = existsSync(file) ? loadSettings(directory) : undefined;
57
+ if (before && existsSync(join(directory, 'personal.sqlite')) &&
58
+ (JSON.stringify([...before.paths].sort()) !== JSON.stringify([...paths].sort()) ||
59
+ before.account.toLowerCase() !== account.toLowerCase() ||
60
+ JSON.stringify([...before.users].sort()) !== JSON.stringify([...users].sort()))) {
61
+ throw new Error('This state has work under a different account, requester list or file scope. Choose a new state directory for the changed scope.');
62
+ }
63
+ if (before && before.repository.toLowerCase() !== repository.toLowerCase()) {
64
+ throw new Error('This state is associated with another GitHub repository. Choose a new state directory.');
65
+ }
66
+ const temporary = join(directory, 'settings.' + randomUUID() + '.tmp');
67
+ try {
68
+ writeFileSync(temporary, JSON.stringify({
69
+ repository: repo.full_name, account, paths, users, publish, pollMs, since: before?.since ?? new Date().toISOString(),
70
+ }) + '\n', { flag: 'wx', mode: 0o600 });
71
+ renameSync(temporary, file);
72
+ } finally { if (existsSync(temporary)) unlinkSync(temporary); }
73
+ } finally { release(); }
74
+ const backend = inspectBackendConfiguration(join(directory, 'runs'));
75
+ return { configured: true, source: 'GitHub', account, repository: repo.full_name, users, paths, publish, backend,
76
+ connection: 'repository and comment read verified',
77
+ github: { repositoryRead: 'verified', commentRead: 'verified', contentRead: 'verified', replyWrite: 'unverified',
78
+ publicationWrite: repo.permissions?.push === false ? 'repository-push-denied' : 'unverified' },
79
+ requiredPermissions: publish ? 'Issues and Pull requests: read/write; Contents: read/write'
80
+ : 'Issues and Pull requests: read/write; Contents: read',
81
+ verification: 'After the backend configuration is valid, /start initializes the Runtime. A real work item verifies Worker, model and reply connectivity. An approved publication verifies PR write access.' };
82
+ }
83
+
84
+ function directoryFor(cwd: string) {
85
+ const directory = stateDirectory(cwd);
86
+ privateDirectory(directory);
87
+ return directory;
88
+ }
89
+
90
+ function lastStartupFailure(directory: string) {
91
+ const inbox = existsSync(join(directory, 'personal.sqlite')) ? openInbox(directory, true) : undefined;
92
+ try { return inbox?.get<PersonalStartupFailure | null>('startupFailure') ?? undefined; }
93
+ finally { inbox?.close(); }
94
+ }
95
+
96
+ async function start(cwd: string, directory: string, signal: AbortSignal) {
97
+ const settings = loadSettings(directory);
98
+ const previous = await probe(cwd, signal);
99
+ if (previous) { previous.close(); return { state: 'already_running', repository: settings.repository }; }
100
+ signal.throwIfAborted();
101
+ const backend = inspectBackendConfiguration(join(directory, 'runs'));
102
+ if (backend.configuration === 'invalid') throw new Error(backend.hint);
103
+ githubToken();
104
+ const launchId = randomUUID();
105
+ const log = openSync(join(directory, 'daemon.log'), constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
106
+ let failure = false;
107
+ let exited = false;
108
+ try {
109
+ const cli = fileURLToPath(new URL('../../scripts/anyswarm.js', import.meta.resolve('@anyswarm/core')));
110
+ const project = fileURLToPath(new URL('./project.js', import.meta.url));
111
+ const entry = existsSync(project) ? project : fileURLToPath(new URL('./project.ts', import.meta.url));
112
+ const child = spawn(process.execPath, [cli, '-u', entry, '--cmd', '/serve'], {
113
+ cwd, detached: true, stdio: ['ignore', log, log],
114
+ env: { ...process.env, ANYSWARM_PERSONAL_DAEMON: '1', ANYSWARM_SUPER_STATE_DIR: directory, ANYSWARM_PERSONAL_LAUNCH: launchId },
115
+ });
116
+ child.on('error', () => { failure = true; });
117
+ child.on('exit', () => { exited = true; });
118
+ child.unref();
119
+ } finally { closeSync(log); }
120
+ for (let attempt = 0; !failure && !exited && attempt < 80; attempt++) {
121
+ signal.throwIfAborted();
122
+ const client = await probe(cwd, signal);
123
+ if (client) {
124
+ try {
125
+ const state = await client.session.getState();
126
+ if (state.phase === 'running') return { state: 'running', repository: settings.repository, account: settings.account, runId: state.runId };
127
+ if (state.phase === 'finished') break;
128
+ } catch {
129
+ // The daemon may finish and close its observer between attach and getState.
130
+ signal.throwIfAborted();
131
+ } finally { client.close(); }
132
+ }
133
+ await pause(250, undefined, { signal });
134
+ }
135
+ const diagnostic = lastStartupFailure(directory);
136
+ if (diagnostic?.launchId === launchId) throw new Error(`${diagnostic.phase}: ${diagnostic.hint}`);
137
+ if (failure) throw new Error('Personal could not launch its background process. Check the Node installation and /logs.');
138
+ throw new Error('Personal did not become ready. Use /jobs and /logs for diagnostics.');
139
+ }
140
+
141
+ async function jobs({ args, cwd, signal }: ActionContext) {
142
+ const directory = directoryFor(cwd);
143
+ const settings = loadSettings(directory);
144
+ const client = await probe(cwd, signal);
145
+ try {
146
+ const state = await client?.session.getState();
147
+ const inbox = existsSync(join(directory, 'personal.sqlite')) ? openInbox(directory, true) : undefined;
148
+ try {
149
+ const status = inbox?.status(64, args || undefined);
150
+ if (args && !status?.jobs.length) throw new Error('No Personal work found for that work ID or Issue.');
151
+ return { state: state?.phase ?? 'stopped', settings, runId: state?.runId,
152
+ live: args ? undefined : state?.business, ...status, cleanup: inbox?.get('cleanup'),
153
+ startupFailure: inbox?.get('startupFailure') ?? undefined, log: join(directory, 'daemon.log') };
154
+ } finally { inbox?.close(); }
155
+ } finally { client?.close(); }
156
+ }
157
+
158
+ async function send(command: string, { args, cwd, signal }: ActionContext) {
159
+ const client = await probe(cwd, signal);
160
+ if (!client) {
161
+ signal.throwIfAborted();
162
+ if (command === 'stop') return { state: 'stopped', verification: 'Use /jobs for the last cleanup receipt.' };
163
+ throw new Error('Start Personal with /start first.');
164
+ }
165
+ try {
166
+ const request = { requestId: randomUUID() };
167
+ if (command === 'stop') {
168
+ if (args) throw new Error('Use /stop to stop Personal or /stop-work <work> to stop one work item.');
169
+ const completion = client.session.completion;
170
+ const receipt = await client.session.stop({ ...request, reason: 'owner_stop' });
171
+ const result = await completion;
172
+ return { state: 'stopped', receipt, cleanup: result?.cleanup ?? { status: 'pending' } };
173
+ }
174
+ const receipt = await client.session.input(`/${command} ${args}`, request);
175
+ return receipt;
176
+ } finally { client.close(); }
177
+ }
178
+
179
+ export function personalActions(definition: Harness) {
180
+ const commands = ['ask', 'answer', 'stop-work', 'approve', 'reject', 'stop'] as const;
181
+ return {
182
+ setup: ({ args, cwd, signal }: ActionContext) => setup(args, cwd, directoryFor(cwd), signal),
183
+ start: ({ args, cwd, signal }: ActionContext) => {
184
+ if (args) throw new Error('Use /start without arguments.');
185
+ return start(cwd, directoryFor(cwd), signal);
186
+ },
187
+ jobs,
188
+ logs: ({ cwd }: ActionContext) => {
189
+ const directory = directoryFor(cwd);
190
+ return { log: join(directory, 'daemon.log'), startupFailure: lastStartupFailure(directory) };
191
+ },
192
+ ...Object.fromEntries(commands.map(command => [command, (context: ActionContext) => send(command, context)])),
193
+ ...(process.env.ANYSWARM_PERSONAL_DAEMON === '1' && { serve: ({ cwd, signal }: ActionContext) =>
194
+ serve(definition, directoryFor(cwd), cwd, signal) }),
195
+ };
196
+ }
@@ -0,0 +1,56 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { mkdir, mkdtemp, rm, writeFile, rename } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ import type { GitHub } from './github.js';
6
+ import { digest } from './inbox.js';
7
+ import type { WorkProject } from './coordinator.js';
8
+ import type { PersonalSettings } from './config.js';
9
+
10
+ const exec = promisify(execFile);
11
+
12
+ export function githubProject(directory: string, github: GitHub, settings: PersonalSettings): WorkProject {
13
+ return {
14
+ async baseline(entry, signal) {
15
+ const base = entry.job.last?.base ?? (await github.head(signal)).sha;
16
+ const files = Object.fromEntries(await Promise.all(settings.paths.map(async path =>
17
+ [path, await github.file(path, base, signal)])));
18
+ return { base, files };
19
+ },
20
+ async export(entry, baseline, files) {
21
+ const root = join(directory, 'artifacts');
22
+ await mkdir(root, { recursive: true, mode: 0o700 });
23
+ const scratch = await mkdtemp(join(root, '.stage-'));
24
+ const env = {
25
+ PATH: process.env.PATH, LANG: 'C', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null',
26
+ };
27
+ const git = async (...args: string[]) => (await exec('git', ['-c', 'core.autocrlf=false', ...args],
28
+ { cwd: scratch, env, timeout: 10_000, maxBuffer: 8 * 1024 * 1024 })).stdout;
29
+ async function write(tree: Record<string, string>) {
30
+ for (const [path, text] of Object.entries(tree)) {
31
+ const target = join(scratch, path);
32
+ await mkdir(dirname(target), { recursive: true, mode: 0o700 });
33
+ await writeFile(target, text, { mode: 0o600 });
34
+ }
35
+ }
36
+ try {
37
+ await git('init', '-q');
38
+ await write(baseline.files);
39
+ await git('add', '--', ...settings.paths);
40
+ await write(files);
41
+ await git('diff', '--check');
42
+ const diff = await git('diff', '--no-ext-diff', '--no-textconv', '--binary');
43
+ const summary = (await git('diff', '--no-ext-diff', '--no-textconv', '--stat')).trim();
44
+ const name = digest(entry.input.id).slice(0, 24) + '.patch';
45
+ const patch = join(root, name);
46
+ await writeFile(join(scratch, 'personal-output.patch'), diff, { mode: 0o600 });
47
+ if (diff) await git('apply', '--cached', '--check', '--', 'personal-output.patch');
48
+ await rename(join(scratch, 'personal-output.patch'), patch);
49
+ return { base: baseline.base, files, patch, sha256: digest(diff), summary,
50
+ checks: ['git diff --check: passed', ...(diff ? ['git apply --check against pinned base: passed'] : ['Patch is empty against pinned base.'])] };
51
+ } finally {
52
+ await rm(scratch, { recursive: true, force: true });
53
+ }
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,95 @@
1
+ import { createSandbox, resolveSandboxConnection, workerImageFor, type CreateRuntimeOptions } from '@anyswarm/core';
2
+
3
+ export interface PersonalSettings {
4
+ repository: string;
5
+ account: string;
6
+ users: string[];
7
+ paths: string[];
8
+ publish: boolean;
9
+ pollMs: number;
10
+ since: string;
11
+ }
12
+
13
+ export type PersonalStartupFailure = {
14
+ phase: 'github-identity' | 'backend-configuration' | 'runtime-initialization' | 'processing';
15
+ code: string;
16
+ hint: string;
17
+ launchId?: string;
18
+ };
19
+
20
+ export const defaults = { pollMs: 15_000, maxWork: 2, maxTurns: 8, fileBytes: 128 * 1024 };
21
+
22
+ export class PersonalConfigurationError extends Error {
23
+ constructor(readonly code: string, hint: string) { super(hint); }
24
+ }
25
+
26
+ export function backendDiagnostic(error: unknown) {
27
+ if (error instanceof PersonalConfigurationError) return { code: error.code, hint: error.message };
28
+ return { code: 'PERSONAL_BACKEND_CONFIG_INVALID', hint: 'Review the Pi and OpenSandbox configuration with anys doctor. Select Pi with anys setup --backend pi.' };
29
+ }
30
+
31
+ export function runtimeOptions(outputDir: string) {
32
+ if (process.env.ANYSWARM_EXECUTOR && process.env.ANYSWARM_EXECUTOR !== 'pi') {
33
+ throw new PersonalConfigurationError('PERSONAL_PI_REQUIRED', 'Personal requires Pi. Run anys setup --backend pi and select Pi in ANYSWARM_EXECUTOR.');
34
+ }
35
+ const { image, executor: configured, advertiseHost, publicUrl, endpointSource: _source, ...sandbox } =
36
+ resolveSandboxConnection({}, 'SUPER');
37
+ const executor = process.env.ANYSWARM_EXECUTOR ?? configured ?? 'pi';
38
+ if (executor !== 'pi') throw new PersonalConfigurationError('PERSONAL_PI_REQUIRED', 'Personal requires Pi. Run anys setup --backend pi.');
39
+ const url = process.env.ANYSWARM_MODEL_URL;
40
+ const model = process.env.ANYSWARM_MODEL_ID;
41
+ if (!url || !model) throw new PersonalConfigurationError('PERSONAL_MODEL_CONFIG_MISSING',
42
+ 'Set ANYSWARM_MODEL_URL and ANYSWARM_MODEL_ID using your existing backend settings.');
43
+ const endpoint = URL.parse(url);
44
+ if (!endpoint || !['http:', 'https:'].includes(endpoint.protocol)) {
45
+ throw new PersonalConfigurationError('PERSONAL_MODEL_URL_INVALID', 'Set ANYSWARM_MODEL_URL to the full HTTP or HTTPS Responses endpoint.');
46
+ }
47
+ const provider = process.env.ANYSWARM_MODEL_PROVIDER ?? 'openai';
48
+ const reasoning = process.env.ANYSWARM_MODEL_REASONING;
49
+ if (reasoning !== undefined && reasoning !== 'true' && reasoning !== 'false') {
50
+ throw new PersonalConfigurationError('PERSONAL_MODEL_REASONING_INVALID', 'ANYSWARM_MODEL_REASONING must be true or false.');
51
+ }
52
+ const capabilities = reasoning === undefined ? undefined : {
53
+ contextWindow: 64_000, maxOutputTokens: 3072, tools: true, reasoning: reasoning === 'true',
54
+ };
55
+ const token = process.env.ANYSWARM_MODEL_TOKEN;
56
+ let extra: unknown = {};
57
+ try { if (process.env.ANYSWARM_MODEL_HEADERS_JSON) extra = JSON.parse(process.env.ANYSWARM_MODEL_HEADERS_JSON); }
58
+ catch { extra = null; }
59
+ if (!extra || typeof extra !== 'object' || Array.isArray(extra) ||
60
+ Object.values(extra).some(value => typeof value !== 'string')) {
61
+ throw new PersonalConfigurationError('PERSONAL_MODEL_HEADERS_INVALID', 'ANYSWARM_MODEL_HEADERS_JSON must be a JSON object of strings.');
62
+ }
63
+ const headers: Record<string, string> = { ...extra, ...(token && { authorization: `Bearer ${token}` }) };
64
+ const bindPort = process.env.ANYSWARM_SUPER_CALLBACK_PORT === undefined ? undefined : Number(process.env.ANYSWARM_SUPER_CALLBACK_PORT);
65
+ const host = process.env.ANYSWARM_ADVERTISE_HOST ?? advertiseHost;
66
+ if (bindPort !== undefined && (!host || publicUrl || !Number.isInteger(bindPort) || bindPort < 1024 || bindPort > 65535)) {
67
+ throw new PersonalConfigurationError('PERSONAL_CALLBACK_CONFIG_INVALID',
68
+ 'Durable cleanup requires a fixed callback port and a Worker-reachable ANYSWARM_ADVERTISE_HOST.');
69
+ }
70
+ return {
71
+ options: {
72
+ executor, sandbox: createSandbox(sandbox), outputDir,
73
+ connection: {
74
+ advertiseHost: host,
75
+ publicUrl: bindPort ? `http://${host}:${bindPort}` : publicUrl,
76
+ ...(bindPort && { bindPort, bindHost: host }),
77
+ modelGateway: { requestTimeoutMs: 90_000, maxOutputTokens: 3072, maxRequests: 80 },
78
+ },
79
+ models: { default: { provider, model, capabilities,
80
+ upstream: { url, headers } } },
81
+ ...(bindPort && { persistence: { deploymentId: 'personal-super-v1', contract: 'personal-super-v1' } }),
82
+ } satisfies Omit<CreateRuntimeOptions, 'profiles' | 'maxAgents' | 'services'>,
83
+ image: image ?? workerImageFor(executor),
84
+ };
85
+ }
86
+
87
+ export function inspectBackendConfiguration(outputDir: string) {
88
+ try {
89
+ runtimeOptions(outputDir);
90
+ return { configuration: 'valid', executor: 'pi', connectivity: 'unverified' } as const;
91
+ } catch (error) {
92
+ return { configuration: 'invalid', connectivity: 'unverified', ...backendDiagnostic(error) } as const;
93
+ }
94
+ }
95
+ export default defaults;