@anyswarm/core 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (403) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +21 -13
  3. package/deploy/worker/Dockerfile +12 -4
  4. package/dist/deploy/worker/Dockerfile +12 -4
  5. package/dist/examples/README.md +35 -12
  6. package/dist/examples/authoring/README.md +24 -0
  7. package/dist/examples/authoring/business.d.ts +2 -0
  8. package/dist/examples/authoring/business.js +4 -0
  9. package/dist/examples/authoring/config.d.ts +5 -0
  10. package/dist/examples/authoring/config.js +2 -0
  11. package/dist/examples/authoring/eject.json +5 -0
  12. package/dist/examples/authoring/harness.d.ts +4 -0
  13. package/dist/examples/authoring/harness.js +19 -0
  14. package/dist/examples/autoresearch/README.md +40 -0
  15. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +11 -0
  16. package/dist/examples/autoresearch/config.d.ts +51 -0
  17. package/dist/examples/autoresearch/config.js +57 -0
  18. package/dist/examples/autoresearch/demo.d.ts +11 -0
  19. package/dist/examples/autoresearch/demo.js +52 -0
  20. package/dist/examples/autoresearch/eject.json +17 -0
  21. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -0
  22. package/dist/examples/autoresearch/frontiercs2-config.js +3 -0
  23. package/dist/examples/autoresearch/frontiercs2.d.ts +87 -0
  24. package/dist/examples/autoresearch/frontiercs2.js +211 -0
  25. package/dist/examples/autoresearch/prepare-demo.d.ts +1 -0
  26. package/dist/examples/autoresearch/prepare-demo.js +15 -0
  27. package/dist/examples/autoresearch/prepare.d.ts +95 -0
  28. package/dist/examples/autoresearch/prepare.js +257 -0
  29. package/dist/examples/autoresearch/process.d.ts +13 -0
  30. package/dist/examples/autoresearch/process.js +48 -0
  31. package/dist/examples/autoresearch/project.d.ts +21 -0
  32. package/dist/examples/autoresearch/project.js +392 -0
  33. package/dist/examples/autoresearch/research-service.d.ts +106 -0
  34. package/dist/examples/autoresearch/research-service.js +255 -0
  35. package/dist/examples/code/README.md +33 -0
  36. package/dist/examples/code/REQUIREMENTS.zh.md +11 -0
  37. package/dist/examples/code/candidate.d.ts +19 -0
  38. package/dist/examples/code/candidate.js +80 -0
  39. package/dist/examples/code/config.d.ts +32 -0
  40. package/dist/examples/code/config.js +18 -0
  41. package/dist/examples/code/eject.json +5 -0
  42. package/dist/examples/code/project.d.ts +3 -0
  43. package/dist/examples/code/project.js +605 -0
  44. package/dist/examples/code/prompts.d.ts +5 -0
  45. package/dist/examples/code/prompts.js +12 -0
  46. package/dist/examples/code/verification.d.ts +19 -0
  47. package/dist/examples/code/verification.js +268 -0
  48. package/dist/examples/code/worktree.d.ts +17 -0
  49. package/dist/examples/code/worktree.js +233 -0
  50. package/dist/examples/harness-session/README.md +3 -6
  51. package/dist/examples/lead-worker/harness/dynamic-scheduler.d.ts +2 -1
  52. package/dist/examples/lead-worker/harness/dynamic-scheduler.js +5 -2
  53. package/dist/examples/lead-worker/harness/index.d.ts +60 -0
  54. package/dist/examples/lead-worker/harness/index.js +77 -6
  55. package/dist/examples/lead-worker/project.js +2 -2
  56. package/dist/examples/lead-worker/services/board.d.ts +5 -0
  57. package/dist/examples/lead-worker/services/board.js +19 -1
  58. package/dist/examples/messages/README.md +5 -5
  59. package/dist/examples/messages/handoff.d.ts +2 -0
  60. package/dist/examples/messages/handoff.js +5 -1
  61. package/dist/examples/messages/project.js +52 -2
  62. package/dist/examples/notes/README.md +13 -18
  63. package/dist/examples/notes/project.js +67 -6
  64. package/dist/examples/peermesh/harness/router.js +3 -1
  65. package/dist/examples/peermesh/harness/team.d.ts +8 -0
  66. package/dist/examples/peermesh/harness/team.js +13 -0
  67. package/dist/examples/peermesh/project.js +22 -4
  68. package/dist/examples/services/agent-control/README.md +3 -3
  69. package/dist/examples/services/mathlib-search/Dockerfile +4 -2
  70. package/dist/examples/services/mathlib-search/README.md +1 -1
  71. package/dist/examples/services/mcp-managed/README.md +2 -2
  72. package/dist/examples/services/persistent-board/README.md +16 -3
  73. package/dist/examples/services/persistent-board/business.d.ts +7 -0
  74. package/dist/examples/services/persistent-board/business.js +7 -0
  75. package/dist/examples/services/persistent-board/index.js +10 -0
  76. package/dist/examples/services/persistent-board/live.d.ts +3 -0
  77. package/dist/examples/services/persistent-board/live.js +58 -0
  78. package/dist/examples/subagents/README.md +5 -5
  79. package/dist/examples/subagents/business.js +3 -1
  80. package/dist/examples/subagents/config.js +3 -3
  81. package/dist/examples/subagents/harness/controller.d.ts +15 -0
  82. package/dist/examples/subagents/harness/controller.js +181 -32
  83. package/dist/examples/subagents/project.d.ts +2 -0
  84. package/dist/examples/subagents/project.js +43 -34
  85. package/dist/examples/subagents/prompts/prompts.d.ts +1 -0
  86. package/dist/examples/subagents/prompts/prompts.js +3 -0
  87. package/dist/examples/subagents/services/collaboration-service.d.ts +3 -2
  88. package/dist/examples/subagents/services/collaboration-service.js +14 -2
  89. package/dist/examples/substrate/README.md +2 -2
  90. package/dist/examples/substrate/harness/index.d.ts +1 -1
  91. package/dist/examples/substrate/harness/index.js +77 -12
  92. package/dist/examples/substrate/project.js +4 -1
  93. package/dist/examples/super/README.md +52 -0
  94. package/dist/examples/super/actions.d.ts +95 -0
  95. package/dist/examples/super/actions.js +230 -0
  96. package/dist/examples/super/artifact.d.ts +4 -0
  97. package/dist/examples/super/artifact.js +51 -0
  98. package/dist/examples/super/config.d.ts +80 -0
  99. package/dist/examples/super/config.js +83 -0
  100. package/dist/examples/super/coordinator.d.ts +33 -0
  101. package/dist/examples/super/coordinator.js +151 -0
  102. package/dist/examples/super/daemon.d.ts +11 -0
  103. package/dist/examples/super/daemon.js +109 -0
  104. package/dist/examples/super/decisions.d.ts +8 -0
  105. package/dist/examples/super/decisions.js +52 -0
  106. package/dist/examples/super/eject.json +5 -0
  107. package/dist/examples/super/execution.d.ts +11 -0
  108. package/dist/examples/super/execution.js +136 -0
  109. package/dist/examples/super/github.d.ts +62 -0
  110. package/dist/examples/super/github.js +269 -0
  111. package/dist/examples/super/inbox.d.ts +162 -0
  112. package/dist/examples/super/inbox.js +284 -0
  113. package/dist/examples/super/location.d.ts +5 -0
  114. package/dist/examples/super/location.js +64 -0
  115. package/dist/examples/super/operator.d.ts +1 -0
  116. package/dist/examples/super/operator.js +31 -0
  117. package/dist/examples/super/outbox.d.ts +5 -0
  118. package/dist/examples/super/outbox.js +103 -0
  119. package/dist/examples/super/project.d.ts +4 -0
  120. package/dist/examples/super/project.js +251 -0
  121. package/dist/examples/super/prompts.d.ts +3 -0
  122. package/dist/examples/super/prompts.js +25 -0
  123. package/dist/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  124. package/dist/examples/taskpool/harness/controller.d.ts +35 -6
  125. package/dist/examples/taskpool/harness/controller.js +73 -7
  126. package/dist/examples/taskpool/project.js +18 -2
  127. package/dist/scripts/anyswarm-arguments.d.ts +18 -6
  128. package/dist/scripts/anyswarm-arguments.js +88 -52
  129. package/dist/scripts/anyswarm-author.d.ts +5 -0
  130. package/dist/scripts/anyswarm-author.js +24 -0
  131. package/dist/scripts/anyswarm-eject.d.ts +11 -0
  132. package/dist/scripts/anyswarm-eject.js +164 -0
  133. package/dist/scripts/anyswarm-harnesses.d.ts +1 -0
  134. package/dist/scripts/anyswarm-harnesses.js +10 -0
  135. package/dist/scripts/anyswarm-installation.d.ts +7 -40
  136. package/dist/scripts/anyswarm-installation.js +17 -285
  137. package/dist/scripts/anyswarm-launch.d.ts +7 -0
  138. package/dist/scripts/anyswarm-launch.js +37 -0
  139. package/dist/scripts/anyswarm-progress.d.ts +6 -0
  140. package/dist/scripts/anyswarm-progress.js +102 -0
  141. package/dist/scripts/anyswarm-project.d.ts +3 -1
  142. package/dist/scripts/anyswarm-project.js +49 -35
  143. package/dist/scripts/anyswarm-source-runner.d.ts +1 -0
  144. package/dist/scripts/anyswarm-source-runner.js +200 -0
  145. package/dist/scripts/anyswarm.js +28 -3
  146. package/dist/scripts/build-provenance.json +1 -0
  147. package/dist/scripts/build.js +7 -1
  148. package/dist/scripts/generate-architecture-api.js +2 -0
  149. package/dist/scripts/generate-architecture-prompts.js +24 -2
  150. package/dist/scripts/local-environment.d.ts +13 -2
  151. package/dist/scripts/local-environment.js +111 -28
  152. package/dist/scripts/local-setup-smoke.js +3 -2
  153. package/dist/scripts/local-setup-worker.d.ts +1 -1
  154. package/dist/scripts/local-setup-worker.js +15 -6
  155. package/dist/scripts/local-setup.d.ts +5 -2
  156. package/dist/scripts/local-setup.js +167 -79
  157. package/dist/scripts/opensandbox-agent-worker.js +2 -2
  158. package/dist/scripts/pack-release.d.ts +1 -0
  159. package/dist/scripts/pack-release.js +66 -0
  160. package/dist/scripts/pi-session-bridge.js +11 -3
  161. package/dist/scripts/run-harness.js +3 -1
  162. package/dist/scripts/setup-bootstrap.js +43 -6
  163. package/dist/src/core/allocation-ledger.js +4 -3
  164. package/dist/src/core/host-identity.d.ts +2 -0
  165. package/dist/src/core/host-identity.js +11 -0
  166. package/dist/src/core/index.d.ts +4 -2
  167. package/dist/src/core/index.js +12 -4
  168. package/dist/src/core/mcp-service.js +2 -2
  169. package/dist/src/core/runtime-management.d.ts +6 -0
  170. package/dist/src/core/runtime-management.js +24 -0
  171. package/dist/src/core/sandbox/executor-driver.d.ts +4 -2
  172. package/dist/src/core/sandbox/executor-driver.js +12 -14
  173. package/dist/src/core/sandbox/local-executor.d.ts +13 -1
  174. package/dist/src/core/sandbox/local-executor.js +69 -19
  175. package/dist/src/core/sandbox/local-worker.js +32 -21
  176. package/dist/src/core/sandbox/opensandbox-backend.d.ts +2 -0
  177. package/dist/src/core/sandbox/opensandbox-backend.js +36 -11
  178. package/dist/src/core/sandbox/sandbox-connection.d.ts +2 -0
  179. package/dist/src/core/sandbox/sandbox-connection.js +14 -6
  180. package/dist/src/core/service-live-state.d.ts +14 -0
  181. package/dist/src/core/service-live-state.js +161 -0
  182. package/dist/src/core/service-observation-types.d.ts +21 -1
  183. package/dist/src/core/service-process.d.ts +1 -1
  184. package/dist/src/core/service-process.js +45 -4
  185. package/dist/src/core/service-types.d.ts +5 -1
  186. package/dist/src/core/services.d.ts +1 -1
  187. package/dist/src/core/services.js +8 -3
  188. package/dist/src/core/types.d.ts +3 -0
  189. package/dist/src/core/worker-image.js +3 -3
  190. package/dist/src/harness/harness-session-types.d.ts +10 -0
  191. package/dist/src/harness/harness-session.js +42 -5
  192. package/dist/src/harness/project-harness.d.ts +14 -1
  193. package/dist/src/harness/project-harness.js +38 -12
  194. package/dist/src/harness/project-input.js +81 -15
  195. package/dist/src/harness/project-rpc-client.d.ts +1 -0
  196. package/dist/src/harness/project-rpc-client.js +5 -0
  197. package/dist/src/harness/project-rpc.d.ts +8 -2
  198. package/dist/src/harness/project-rpc.js +31 -7
  199. package/dist/src/harness/project-runtime.js +6 -2
  200. package/dist/src/harness/typescript-loader.d.ts +2 -0
  201. package/dist/src/harness/typescript-loader.js +41 -0
  202. package/dist/src/trace-viewer/public/app.js +6 -5
  203. package/dist/src/trace-viewer/reader.mjs +42 -2
  204. package/docs/INDEX.md +5 -2
  205. package/docs/architecture/00-overview.md +1 -1
  206. package/docs/architecture/01-agent-core.md +1 -1
  207. package/docs/architecture/04-services.md +1 -1
  208. package/docs/architecture/06-observability-experiments.md +1 -1
  209. package/docs/architecture/07-run-configuration.md +38 -18
  210. package/docs/architecture/08-prompts.md +22 -0
  211. package/docs/architecture/10-service-api-reference.md +53 -18
  212. package/docs/architecture/11-storage-reference.md +18 -1
  213. package/docs/architecture/12-code-coverage.md +152 -89
  214. package/docs/architecture/15-core-runtime.md +8 -0
  215. package/docs/architecture/16-pi-opensandbox-backend.md +5 -5
  216. package/docs/architecture/17-harness-reporting.md +1 -1
  217. package/docs/architecture/19-substrate-harness.md +28 -1
  218. package/docs/architecture/20-lead-worker-harness.md +34 -1
  219. package/docs/architecture/22-website.md +5 -6
  220. package/docs/architecture/23-project-harness.md +152 -8
  221. package/docs/architecture/24-runtime-recovery.md +10 -3
  222. package/docs/architecture/26-code.md +54 -0
  223. package/docs/architecture/27-personal.md +58 -0
  224. package/docs/architecture/28-autoresearch.md +43 -0
  225. package/docs/architecture/INDEX.md +3 -0
  226. package/docs/architecture/prompts/08-lead-worker-harness.md +4 -2
  227. package/docs/architecture/prompts/08-subagents-harness.md +21 -0
  228. package/docs/architecture/prompts/21-personal.md +44 -0
  229. package/docs/architecture/prompts/22-autoresearch.md +63 -0
  230. package/docs/architecture/prompts/26-code.md +55 -0
  231. package/docs/architecture/prompts/source-manifest.json +152 -33
  232. package/docs/architecture/source-map.json +473 -25
  233. package/docs/designs/core-harness/01-core.md +2 -2
  234. package/docs/designs/core-harness/06-project-harness.md +13 -2
  235. package/docs/designs/core-harness/README.md +7 -2
  236. package/docs/en/agents.md +1 -1
  237. package/docs/en/build-your-harness.md +3 -5
  238. package/docs/en/changelog.md +20 -4
  239. package/docs/en/first-harness.md +9 -12
  240. package/docs/en/harnesses/lead-worker.md +1 -1
  241. package/docs/en/harnesses/peermesh.md +2 -2
  242. package/docs/en/harnesses/subagents.md +2 -2
  243. package/docs/en/harnesses/substrate.md +4 -4
  244. package/docs/en/harnesses/taskpool.md +2 -2
  245. package/docs/en/latest.md +14 -121
  246. package/docs/en/overview.md +1 -1
  247. package/docs/en/quickstart.md +42 -39
  248. package/docs/en/reference/api.md +14 -4
  249. package/docs/en/reference/cli.md +53 -47
  250. package/docs/en/runtime.md +2 -2
  251. package/docs/en/sandbox.md +3 -3
  252. package/docs/en/services.md +4 -0
  253. package/docs/operations/trace-viewer.md +1 -1
  254. package/docs/workflows/development.md +28 -21
  255. package/docs/workflows/release-and-docs-versioning.md +77 -0
  256. package/docs/workflows/release-cli-acceptance.md +85 -0
  257. package/docs/zh/agents.md +1 -1
  258. package/docs/zh/build-your-harness.md +3 -5
  259. package/docs/zh/changelog.md +20 -4
  260. package/docs/zh/first-harness.md +9 -12
  261. package/docs/zh/harnesses/lead-worker.md +1 -1
  262. package/docs/zh/harnesses/peermesh.md +2 -2
  263. package/docs/zh/harnesses/subagents.md +2 -2
  264. package/docs/zh/harnesses/substrate.md +4 -4
  265. package/docs/zh/harnesses/taskpool.md +2 -2
  266. package/docs/zh/latest.md +15 -122
  267. package/docs/zh/overview.md +1 -1
  268. package/docs/zh/quickstart.md +42 -39
  269. package/docs/zh/reference/api.md +14 -4
  270. package/docs/zh/reference/cli.md +24 -40
  271. package/docs/zh/runtime.md +2 -2
  272. package/docs/zh/sandbox.md +3 -3
  273. package/docs/zh/services.md +4 -0
  274. package/examples/README.md +35 -12
  275. package/examples/authoring/README.md +24 -0
  276. package/examples/authoring/business.ts +4 -0
  277. package/examples/authoring/config.ts +2 -0
  278. package/examples/authoring/eject.json +5 -0
  279. package/examples/authoring/harness.ts +21 -0
  280. package/examples/autoresearch/README.md +40 -0
  281. package/examples/autoresearch/REQUIREMENTS.zh.md +11 -0
  282. package/examples/autoresearch/config.ts +90 -0
  283. package/examples/autoresearch/demo.ts +55 -0
  284. package/examples/autoresearch/eject.json +17 -0
  285. package/examples/autoresearch/frontiercs2-config.ts +4 -0
  286. package/examples/autoresearch/frontiercs2.ts +237 -0
  287. package/examples/autoresearch/prepare-demo.ts +15 -0
  288. package/examples/autoresearch/prepare.ts +267 -0
  289. package/examples/autoresearch/process.ts +50 -0
  290. package/examples/autoresearch/project.ts +380 -0
  291. package/examples/autoresearch/research-service.ts +302 -0
  292. package/examples/code/README.md +33 -0
  293. package/examples/code/REQUIREMENTS.zh.md +11 -0
  294. package/examples/code/candidate.ts +89 -0
  295. package/examples/code/config.ts +19 -0
  296. package/examples/code/eject.json +5 -0
  297. package/examples/code/project.ts +581 -0
  298. package/examples/code/prompts.ts +16 -0
  299. package/examples/code/verification.ts +239 -0
  300. package/examples/code/worktree.ts +188 -0
  301. package/examples/harness-session/README.md +3 -6
  302. package/examples/lead-worker/harness/dynamic-scheduler.ts +6 -3
  303. package/examples/lead-worker/harness/index.ts +61 -6
  304. package/examples/lead-worker/project.ts +2 -2
  305. package/examples/lead-worker/services/board.ts +14 -1
  306. package/examples/messages/README.md +5 -5
  307. package/examples/messages/handoff.ts +6 -2
  308. package/examples/messages/project.ts +47 -2
  309. package/examples/notes/README.md +13 -18
  310. package/examples/notes/project.ts +57 -9
  311. package/examples/peermesh/harness/router.ts +2 -2
  312. package/examples/peermesh/harness/team.ts +11 -0
  313. package/examples/peermesh/project.ts +19 -4
  314. package/examples/services/agent-control/README.md +3 -3
  315. package/examples/services/mathlib-search/Dockerfile +4 -2
  316. package/examples/services/mathlib-search/README.md +1 -1
  317. package/examples/services/mcp-managed/README.md +2 -2
  318. package/examples/services/persistent-board/README.md +16 -3
  319. package/examples/services/persistent-board/business.ts +10 -0
  320. package/examples/services/persistent-board/index.ts +10 -0
  321. package/examples/services/persistent-board/live.ts +54 -0
  322. package/examples/subagents/README.md +5 -5
  323. package/examples/subagents/business.ts +3 -1
  324. package/examples/subagents/config.ts +4 -3
  325. package/examples/subagents/harness/controller.ts +161 -29
  326. package/examples/subagents/project.ts +47 -33
  327. package/examples/subagents/prompts/prompts.ts +4 -0
  328. package/examples/subagents/services/collaboration-service.ts +14 -2
  329. package/examples/substrate/README.md +2 -2
  330. package/examples/substrate/harness/index.ts +67 -11
  331. package/examples/substrate/project.ts +5 -1
  332. package/examples/super/README.md +52 -0
  333. package/examples/super/actions.ts +196 -0
  334. package/examples/super/artifact.ts +56 -0
  335. package/examples/super/config.ts +95 -0
  336. package/examples/super/coordinator.ts +158 -0
  337. package/examples/super/daemon.ts +84 -0
  338. package/examples/super/decisions.ts +46 -0
  339. package/examples/super/eject.json +5 -0
  340. package/examples/super/execution.ts +131 -0
  341. package/examples/super/github.ts +242 -0
  342. package/examples/super/inbox.ts +306 -0
  343. package/examples/super/location.ts +54 -0
  344. package/examples/super/operator.ts +28 -0
  345. package/examples/super/outbox.ts +97 -0
  346. package/examples/super/project.ts +225 -0
  347. package/examples/super/prompts.ts +27 -0
  348. package/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  349. package/examples/taskpool/harness/controller.ts +59 -7
  350. package/examples/taskpool/project.ts +18 -2
  351. package/npm-shrinkwrap.development.json +700 -0
  352. package/npm-shrinkwrap.json +95 -1969
  353. package/package.development.json +88 -0
  354. package/package.json +11 -8
  355. package/scripts/anyswarm-arguments.ts +91 -54
  356. package/scripts/anyswarm-author.ts +25 -0
  357. package/scripts/anyswarm-eject.ts +145 -0
  358. package/scripts/anyswarm-harnesses.ts +10 -0
  359. package/scripts/anyswarm-installation.ts +18 -288
  360. package/scripts/anyswarm-launch.ts +36 -0
  361. package/scripts/anyswarm-progress.ts +95 -0
  362. package/scripts/anyswarm-project.ts +35 -34
  363. package/scripts/anyswarm-source-runner.ts +176 -0
  364. package/scripts/anyswarm.ts +24 -3
  365. package/scripts/build.ts +8 -1
  366. package/scripts/generate-architecture-api.ts +2 -0
  367. package/scripts/generate-architecture-prompts.ts +35 -2
  368. package/scripts/local-environment.ts +117 -28
  369. package/scripts/local-setup-smoke.ts +3 -2
  370. package/scripts/local-setup-worker.ts +17 -7
  371. package/scripts/local-setup.ts +166 -73
  372. package/scripts/opensandbox-agent-worker.ts +2 -2
  373. package/scripts/pack-release.ts +70 -0
  374. package/scripts/pi-session-bridge.ts +10 -2
  375. package/scripts/run-harness.ts +3 -1
  376. package/scripts/setup-bootstrap.ts +41 -6
  377. package/src/core/allocation-ledger.ts +5 -3
  378. package/src/core/host-identity.ts +11 -0
  379. package/src/core/index.ts +12 -6
  380. package/src/core/mcp-service.ts +2 -2
  381. package/src/core/runtime-management.ts +22 -0
  382. package/src/core/sandbox/executor-driver.ts +15 -18
  383. package/src/core/sandbox/local-executor.ts +65 -19
  384. package/src/core/sandbox/local-worker.ts +29 -21
  385. package/src/core/sandbox/opensandbox-backend.ts +36 -11
  386. package/src/core/sandbox/sandbox-connection.ts +14 -5
  387. package/src/core/service-live-state.ts +156 -0
  388. package/src/core/service-observation-types.ts +23 -1
  389. package/src/core/service-process.ts +36 -3
  390. package/src/core/service-types.ts +3 -1
  391. package/src/core/services.ts +8 -3
  392. package/src/core/types.ts +3 -0
  393. package/src/core/worker-image.ts +3 -3
  394. package/src/harness/harness-session-types.ts +13 -1
  395. package/src/harness/harness-session.ts +40 -7
  396. package/src/harness/project-harness.ts +38 -12
  397. package/src/harness/project-input.ts +73 -15
  398. package/src/harness/project-rpc-client.ts +5 -0
  399. package/src/harness/project-rpc.ts +29 -8
  400. package/src/harness/project-runtime.ts +4 -2
  401. package/src/harness/typescript-loader.ts +37 -0
  402. package/src/trace-viewer/public/app.js +6 -5
  403. package/src/trace-viewer/reader.mjs +42 -2
@@ -0,0 +1,242 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { defaults, PersonalConfigurationError, type PersonalSettings } from './config.js';
3
+ import { digest, type Delivery, type Entry, type Inbox } from './inbox.js';
4
+
5
+ const ownerName = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/;
6
+ const repositoryName = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9_.-]{1,100}$/;
7
+ const markerPrefix = '<!-- anys-super:';
8
+ const routePrefix = /^\/super\s+/i;
9
+ const sha = /^[a-f0-9]{40}$/;
10
+
11
+ export function safePath(path: string) {
12
+ return path.length <= 180 && path.split('/').every(part => /^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(part));
13
+ }
14
+ export function githubToken() {
15
+ const configured = process.env.ANYSWARM_SUPER_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN;
16
+ if (configured) return configured;
17
+ try {
18
+ const token = execFileSync('gh', ['auth', 'token', '--hostname', 'github.com'], {
19
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000,
20
+ }).trim();
21
+ if (token) return token;
22
+ } catch { /* Refuse an unavailable gh credential below. */ }
23
+ throw new PersonalConfigurationError('PERSONAL_GITHUB_CREDENTIAL_MISSING',
24
+ 'Set ANYSWARM_SUPER_GITHUB_TOKEN or run gh auth login --hostname github.com.');
25
+ }
26
+ export class GitHubApiError extends Error {
27
+ constructor(readonly status: number, readonly permission: string | null, readonly permissionDenied = false) {
28
+ super(`GitHub returned HTTP ${status}${permission ? ` (endpoint permissions: ${permission})` : ''}`);
29
+ }
30
+ }
31
+ type Comment = { id: number; issue_url: string; html_url: string; body: string; created_at: string; updated_at: string;
32
+ user: { login: string; type: string } | null };
33
+ type Pull = { number: number; html_url: string; body: string | null };
34
+ type Ref = { object: { sha: string } };
35
+ type Commit = { commit: { message: string } };
36
+ type Repo = { full_name: string; default_branch: string; permissions?: { push?: boolean } };
37
+ const encode = encodeURIComponent;
38
+
39
+ export class GitHub {
40
+ readonly #base: string;
41
+ readonly #owner: string;
42
+ #lastPullRead = 0;
43
+ constructor(readonly repository: string, private readonly token: string) {
44
+ if (!repositoryName.test(repository)) throw new Error('Use an owner/repository GitHub name.');
45
+ this.#base = '/repos/' + repository;
46
+ this.#owner = repository.split('/')[0]!;
47
+ }
48
+
49
+ private async request<T>(path: string, signal: AbortSignal, body?: unknown): Promise<{ data: T; next: string | null }> {
50
+ const url = new URL(path, 'https://api.github.com');
51
+ if (url.origin !== 'https://api.github.com') throw new Error('Unexpected GitHub pagination host');
52
+ const response = await fetch(url, {
53
+ method: body === undefined ? 'GET' : 'POST', signal: AbortSignal.any([signal, AbortSignal.timeout(20_000)]),
54
+ redirect: 'error',
55
+ headers: { authorization: `Bearer ${this.token}`, accept: 'application/vnd.github+json',
56
+ 'content-type': 'application/json', 'user-agent': 'anyswarm-personal' },
57
+ ...(body !== undefined && { body: JSON.stringify(body) }),
58
+ });
59
+ if (!response.ok) {
60
+ await response.body?.cancel();
61
+ throw new GitHubApiError(response.status, response.headers.get('x-accepted-github-permissions'),
62
+ response.status === 401 || (response.status === 403 && response.headers.get('x-ratelimit-remaining') !== '0'
63
+ && !response.headers.has('retry-after')));
64
+ }
65
+ const next = response.headers.get('link')?.match(/<([^>]+)>; rel="next"/)?.[1] ?? null;
66
+ return { data: await response.json() as T, next };
67
+ }
68
+ private async get<T>(path: string, signal: AbortSignal, body?: unknown) {
69
+ return (await this.request<T>(path, signal, body)).data;
70
+ }
71
+ private async list<T>(path: string, signal: AbortSignal) {
72
+ const items: T[] = [];
73
+ let cursor: string | null = path;
74
+ for (let page = 0; cursor && page < 20; page++) {
75
+ const { data, next }: { data: T[]; next: string | null } = await this.request(cursor, signal);
76
+ items.push(...data);
77
+ cursor = next;
78
+ }
79
+ if (cursor) throw new Error('GitHub returned more than 20 pages; narrow the source scope.');
80
+ return items;
81
+ }
82
+ private async optional<T>(path: string, signal: AbortSignal): Promise<T | undefined> {
83
+ try { return await this.get<T>(path, signal); }
84
+ catch (error) {
85
+ if (error instanceof GitHubApiError && error.status === 404) return;
86
+ throw error;
87
+ }
88
+ }
89
+ async inspect(signal: AbortSignal) {
90
+ const [account, repo] = await Promise.all([
91
+ this.get<{ login: string }>('/user', signal), this.get<Repo>(this.#base, signal),
92
+ this.get<Comment[]>(this.#base + '/issues/comments?per_page=1', signal),
93
+ ]);
94
+ if (!ownerName.test(account.login)) throw new Error('GitHub did not return a usable account.');
95
+ return { account: account.login, repo };
96
+ }
97
+ private admitComments(comments: readonly Comment[], settings: PersonalSettings, inbox: Inbox, pull?: number) {
98
+ for (const comment of comments) {
99
+ if (Date.parse(comment.created_at) < Date.parse(settings.since) || !comment.user ||
100
+ !settings.users.includes(comment.user.login.toLowerCase()) || comment.user.type !== 'User' ||
101
+ comment.body.includes(markerPrefix)) continue;
102
+ const match = /^https:\/\/api\.github\.com\/repos\/([^/]+\/[^/]+)\/issues\/(\d+)$/.exec(comment.issue_url);
103
+ if (!match || match[1]!.toLowerCase() !== settings.repository.toLowerCase()) continue;
104
+ const thread = Number(match[2]);
105
+ const kind = new URL(comment.html_url).pathname.includes('/pull/') ? 'pull' : 'issue';
106
+ const existing = inbox.topic(thread, kind);
107
+ if (pull !== undefined && (kind !== 'pull' || thread !== pull)) continue;
108
+ if (pull === undefined && kind === 'pull' && existing?.readPullFeedback) continue;
109
+ if (!existing && (kind === 'pull' || !routePrefix.test(comment.body))) continue;
110
+ const text = comment.body.replace(routePrefix, '').trim();
111
+ if (!text || Buffer.byteLength(text) > 16_384) continue;
112
+ const admission = inbox.accept({ id: 'github:' + comment.id, thread, kind, author: comment.user.login, text });
113
+ if (admission.state === 'capacity') throw new Error('Personal inbox is full; pending work must finish before advancing the source cursor.');
114
+ }
115
+ }
116
+ async poll(settings: PersonalSettings, inbox: Inbox, signal: AbortSignal) {
117
+ let readError: unknown;
118
+ for (const pull of inbox.unreadPulls(this.#lastPullRead)) {
119
+ signal.throwIfAborted();
120
+ this.#lastPullRead = pull;
121
+ try {
122
+ const comments = await this.list<Comment>(this.#base + `/issues/${pull}/comments?per_page=100&since=` + encode(settings.since), signal);
123
+ this.admitComments(comments, settings, inbox, pull);
124
+ inbox.finishPullRead(pull);
125
+ } catch (error) { readError ??= error; }
126
+ }
127
+ const mark = inbox.get<string>('githubCursor') ?? settings.since;
128
+ const overlap = new Date(Date.parse(mark) - 2000).toISOString();
129
+ const comments = await this.list<Comment>(this.#base + '/issues/comments?per_page=100&sort=updated&direction=asc&since=' + encode(overlap), signal);
130
+ this.admitComments(comments, settings, inbox);
131
+ let cursor = mark;
132
+ for (const comment of comments) if (comment.updated_at > cursor) cursor = comment.updated_at;
133
+ inbox.put('githubCursor', cursor);
134
+ if (readError) throw readError;
135
+ return new Date().toISOString();
136
+ }
137
+ async issue(number: number, signal: AbortSignal) {
138
+ if (!Number.isSafeInteger(number) || number < 1) return false;
139
+ const issue = await this.optional<{ number: number; pull_request?: unknown }>(this.#base + '/issues/' + number, signal);
140
+ return issue?.number === number && !issue.pull_request;
141
+ }
142
+ async head(signal: AbortSignal) {
143
+ const repo = await this.get<Repo>(this.#base, signal);
144
+ const ref = await this.get<Ref>(this.#base + '/git/ref/heads/' + encode(repo.default_branch), signal);
145
+ return { name: repo.default_branch, sha: ref.object.sha };
146
+ }
147
+ async file(path: string, revision: string, signal: AbortSignal) {
148
+ if (!safePath(path) || !sha.test(revision)) throw new Error('Invalid approved file identity');
149
+ const commit = await this.get<{ tree: { sha: string } }>(this.#base + '/git/commits/' + revision, signal);
150
+ let current = commit.tree.sha;
151
+ const parts = path.split('/');
152
+ for (const [index, name] of parts.entries()) {
153
+ const tree = await this.get<{ tree: { type: string; path: string; mode: string; sha: string; size?: number }[] }>(
154
+ this.#base + '/git/trees/' + current, signal);
155
+ const node = tree.tree.find(item => item.path === name);
156
+ const last = index === parts.length - 1;
157
+ if (!node || (last ? node.type !== 'blob' || node.mode !== '100644' : node.type !== 'tree')) {
158
+ throw new Error(`Allowlisted file is missing or is not a regular non-executable file: ${path}`);
159
+ }
160
+ if (node.size !== undefined && node.size > defaults.fileBytes) throw new Error(`Allowlisted file exceeds the size limit: ${path}`);
161
+ current = node.sha;
162
+ }
163
+ const blob = await this.get<{ content: string; encoding: string; size: number }>(this.#base + '/git/blobs/' + current, signal);
164
+ if (blob.encoding !== 'base64' || blob.size > defaults.fileBytes) throw new Error(`Unsupported blob: ${path}`);
165
+ const bytes = Buffer.from(blob.content, 'base64');
166
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
167
+ if (text.includes('\0')) throw new Error(`Allowlisted file is not text: ${path}`);
168
+ return text;
169
+ }
170
+ async reconcile(step: NonNullable<Delivery['checkpoint']>, entry: Entry, signal: AbortSignal) {
171
+ const delivery = entry.delivery!;
172
+ const branch = delivery.branch!;
173
+ const ref = await this.optional<Ref>(this.#base + '/git/ref/heads/' + encode(branch), signal);
174
+ if (!ref) return;
175
+ if (step === 'branch') return ref.object.sha === delivery.artifact!.base ? ref : undefined;
176
+ if (step === 'commit') {
177
+ const commit = await this.get<Commit>(this.#base + '/commits/' + ref.object.sha, signal);
178
+ return commit.commit.message.includes(commitMarker(entry)) ? ref : undefined;
179
+ }
180
+ return this.findPull(entry, signal);
181
+ }
182
+ private async findPull(entry: Entry, signal: AbortSignal) {
183
+ const matches = await this.list<Pull>(this.#base + '/pulls?state=all&head=' + encode(this.#owner + ':' + entry.delivery!.branch), signal);
184
+ return matches.find(pull => pull.body?.includes(pullMarker(entry)));
185
+ }
186
+ async writeBranch(branch: string, base: string, signal: AbortSignal) {
187
+ return this.get<Ref>(this.#base + '/git/refs', signal, { ref: 'refs/heads/' + branch, sha: base });
188
+ }
189
+ async writeCommit(entry: Entry, signal: AbortSignal) {
190
+ const delivery = entry.delivery!;
191
+ const expectedHeadOid = entry.job.commit ?? delivery.artifact!.base;
192
+ const result = await this.get<{ data?: { createCommitOnBranch: { commit: { oid: string } } }; errors?: { type?: string }[] }>('/graphql', signal, {
193
+ query: 'mutation($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid } } }',
194
+ variables: { input: {
195
+ branch: { repositoryNameWithOwner: this.repository, branchName: delivery.branch! },
196
+ expectedHeadOid, message: { headline: `Personal: update for issue #${entry.job.thread}`, body: commitMarker(entry) },
197
+ fileChanges: { additions: Object.entries(delivery.artifact!.files).map(([path, text]) =>
198
+ ({ path, contents: Buffer.from(text).toString('base64') })) },
199
+ } },
200
+ });
201
+ if (result.errors?.some(error => error.type === 'FORBIDDEN')) {
202
+ throw new GitHubApiError(403, 'Contents: write', true);
203
+ }
204
+ const oid = result.data?.createCommitOnBranch?.commit?.oid;
205
+ if (!oid || !sha.test(oid)) throw new Error('GitHub could not confirm the commit');
206
+ return { object: { sha: oid } };
207
+ }
208
+ async writePull(entry: Entry, signal: AbortSignal) {
209
+ const { name } = await this.head(signal);
210
+ return this.get<Pull>(this.#base + '/pulls', signal, {
211
+ draft: true, head: entry.delivery!.branch, base: name,
212
+ title: `Personal work for #${entry.job.thread}`,
213
+ body: `Work requested in #${entry.job.thread}.\n\n${pullMarker(entry)}`,
214
+ });
215
+ }
216
+ private commentPath(entry: Entry) {
217
+ return this.#base + '/issues/' + entry.input.thread + '/comments';
218
+ }
219
+ async findReply(entry: Entry, account: string, signal: AbortSignal) {
220
+ const marker = replyMarker(entry);
221
+ const comments = await this.list<Comment>(this.commentPath(entry) + '?per_page=100', signal);
222
+ return comments.find(comment => comment.user?.login.toLowerCase() === account.toLowerCase() && comment.body.includes(marker))?.html_url;
223
+ }
224
+ async writeReply(entry: Entry, signal: AbortSignal) {
225
+ const delivery = entry.delivery!;
226
+ const artifact = delivery.artifact;
227
+ const proof = artifact ? [
228
+ '', delivery.url ? `Draft PR: ${delivery.url}` : 'Patch saved locally. Use /jobs in Personal for its path.',
229
+ ...artifact.checks, `Patch SHA-256: ${artifact.sha256}`,
230
+ ...(delivery.publish === 'approval' ? ['Publishing is awaiting authorization.'] : []),
231
+ ] : [];
232
+ const result = await this.get<Comment>(this.commentPath(entry), signal, {
233
+ body: [delivery.text, ...proof, '', replyMarker(entry)].join('\n'),
234
+ });
235
+ if (!result.html_url) throw new Error('GitHub did not return a comment receipt');
236
+ return result.html_url;
237
+ }
238
+ }
239
+
240
+ const commitMarker = (entry: Entry) => 'anys-super-event:' + digest(entry.input.id).slice(0, 24);
241
+ const pullMarker = (entry: Entry) => markerPrefix + 'job:' + entry.job.id + ' -->';
242
+ const replyMarker = (entry: Entry) => markerPrefix + 'reply:' + digest(entry.input.id + (entry.delivery?.replyVersion ? ':' + entry.delivery.replyVersion : '')).slice(0, 24) + ' -->';
@@ -0,0 +1,306 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { join } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+
5
+ export const digest = (bytes: string | Buffer) => createHash('sha256').update(bytes).digest('hex');
6
+ export type Inbound = {
7
+ id: string;
8
+ thread: number;
9
+ kind: 'issue' | 'pull';
10
+ author: string;
11
+ text: string;
12
+ };
13
+ export type Artifact = {
14
+ base: string;
15
+ files: Record<string, string>;
16
+ patch: string;
17
+ sha256: string;
18
+ checks: string[];
19
+ summary?: string;
20
+ review?: string;
21
+ };
22
+ export type Delivery = {
23
+ text: string;
24
+ result: 'completed' | 'failed' | 'waiting';
25
+ question?: string;
26
+ artifact?: Artifact;
27
+ branch?: string;
28
+ branchConfirmed?: boolean;
29
+ pull?: number;
30
+ commit?: string;
31
+ url?: string;
32
+ comment?: string;
33
+ originalComment?: string;
34
+ replyVersion?: 'publication';
35
+ checkpoint?: 'branch' | 'commit' | 'pull';
36
+ publish?: 'queued' | 'sending' | 'confirmed' | 'approval' | 'rejected' | 'unknown';
37
+ ownerApproved?: boolean;
38
+ rejectionReason?: string;
39
+ reply: 'queued' | 'sending' | 'confirmed' | 'unknown';
40
+ };
41
+ type State = 'queued' | 'working' | 'prepared' | 'unknown' | 'delivered' | 'failed' | 'stopped';
42
+ type Job = { id: string; thread: number; last?: Artifact; branch?: string; pull?: number; readPullFeedback?: boolean; commit?: string; question?: string };
43
+ type PriorTurn = { request: string; response?: string; result?: Delivery['result'] };
44
+ export type Entry = { job: Job; input: Inbound; state: State; delivery?: Delivery; problem?: string; history?: PriorTurn[] };
45
+ type Row = { seq: number; job: string; input: string; state: State; delivery: string | null; problem: string | null };
46
+ type JobRow = { id: string; thread: number; data: string };
47
+ type Admission = { id: string; job?: string; state: State | 'conflict' | 'unbound' | 'capacity'; duplicate?: boolean };
48
+
49
+ export const PERSONAL_SCHEMA_SQL = `
50
+ PRAGMA journal_mode = WAL;
51
+ PRAGMA synchronous = FULL;
52
+ CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, thread INTEGER UNIQUE NOT NULL, pull INTEGER UNIQUE, data TEXT NOT NULL);
53
+ CREATE TABLE IF NOT EXISTS events (
54
+ seq INTEGER PRIMARY KEY, id TEXT UNIQUE NOT NULL, job TEXT NOT NULL, hash TEXT NOT NULL,
55
+ input TEXT NOT NULL, state TEXT NOT NULL, delivery TEXT, problem TEXT
56
+ );
57
+ CREATE INDEX IF NOT EXISTS events_queue ON events (job, state, seq);
58
+ CREATE TABLE IF NOT EXISTS conflicts (id TEXT PRIMARY KEY, detected TEXT NOT NULL);
59
+ CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, data TEXT NOT NULL);
60
+ `;
61
+
62
+ export function openInbox(directory: string, readOnly = false) {
63
+ const db = new DatabaseSync(join(directory, 'personal.sqlite'), { readOnly });
64
+ db.exec('PRAGMA busy_timeout = 3000');
65
+ if (!readOnly) db.exec(PERSONAL_SCHEMA_SQL);
66
+ const event = db.prepare('SELECT * FROM events WHERE id = ?');
67
+ const job = db.prepare('SELECT * FROM jobs WHERE id = ?');
68
+ const serial = (row: JobRow): Job => ({ id: row.id, thread: row.thread, ...JSON.parse(row.data) });
69
+ const lookup = (id: string) => {
70
+ const row = job.get(id) as JobRow | undefined;
71
+ return row && serial(row);
72
+ };
73
+ const load = (row: Row): Entry => ({
74
+ job: lookup(row.job)!, input: JSON.parse(row.input), state: row.state,
75
+ ...(row.delivery && { delivery: JSON.parse(row.delivery) }),
76
+ ...(row.problem && { problem: row.problem }),
77
+ });
78
+ const next = db.prepare(`SELECT q.* FROM events q WHERE q.state = 'queued' AND q.job NOT IN (SELECT value FROM json_each(?)) AND NOT EXISTS (
79
+ SELECT 1 FROM events p WHERE p.job = q.job AND
80
+ (p.state IN ('working', 'prepared', 'unknown') OR (p.state = 'queued' AND p.seq < q.seq))
81
+ ) ORDER BY q.seq LIMIT 1`);
82
+ function change(id: string, from: State, to: State, delivery?: Delivery, problem?: string) {
83
+ return db.prepare(`UPDATE events SET state = ?, delivery = coalesce(?, delivery), problem = ?
84
+ WHERE id = ? AND state = ?`).run(to, delivery ? JSON.stringify(delivery) : null, problem ?? null, id, from).changes === 1;
85
+ }
86
+ function transaction<T>(fn: () => T): T {
87
+ db.exec('BEGIN IMMEDIATE');
88
+ try {
89
+ const result = fn();
90
+ db.exec('COMMIT');
91
+ return result;
92
+ } catch (error) {
93
+ db.exec('ROLLBACK');
94
+ throw error;
95
+ }
96
+ }
97
+ function saveJob(value: Job) {
98
+ const { id, thread: _thread, ...data } = value;
99
+ db.prepare('UPDATE jobs SET pull = ?, data = ? WHERE id = ?').run(value.pull ?? null, JSON.stringify(data), id);
100
+ }
101
+ const latestArtifact = db.prepare(`SELECT * FROM events WHERE job = ? AND json_type(delivery, '$.artifact') = 'object'
102
+ ORDER BY seq DESC LIMIT 1`);
103
+ const busy = db.prepare(`SELECT 1 FROM events WHERE job = ? AND state IN ('working', 'prepared', 'unknown') LIMIT 1`);
104
+ function queuePublication(entry: Entry, ownerApproved: boolean) {
105
+ const delivery = entry.delivery!;
106
+ const queued = {
107
+ ...delivery, ownerApproved: ownerApproved || delivery.ownerApproved, originalComment: delivery.originalComment ?? delivery.comment, comment: undefined,
108
+ checkpoint: undefined, publish: 'queued', reply: 'queued', replyVersion: 'publication',
109
+ } as const;
110
+ return change(entry.input.id, 'delivered', 'prepared', queued) ? queued : undefined;
111
+ }
112
+ return {
113
+ topic(thread: number, kind: Inbound['kind']) {
114
+ const row = db.prepare(kind === 'pull' ? 'SELECT * FROM jobs WHERE pull = ?' : 'SELECT * FROM jobs WHERE thread = ?')
115
+ .get(thread) as JobRow | undefined;
116
+ return row && serial(row);
117
+ },
118
+ resolveWork(selector: string | number) {
119
+ if (typeof selector === 'number') return this.topic(selector, 'issue');
120
+ if (/^#[1-9][0-9]{0,14}$/.test(selector)) return this.topic(Number(selector.slice(1)), 'issue');
121
+ if (!/^[a-f0-9]{1,16}$/i.test(selector)) throw new Error('Use #<issue> or a work ID prefix.');
122
+ const prefix = selector.toLowerCase();
123
+ const exact = lookup(prefix);
124
+ if (exact) return exact;
125
+ const rows = db.prepare('SELECT * FROM jobs WHERE id GLOB ? LIMIT 2').all(prefix + '*') as JobRow[];
126
+ if (rows.length > 1) throw new Error('Ambiguous work ID. Use a longer prefix from /jobs.');
127
+ return rows[0] && serial(rows[0]);
128
+ },
129
+ accept(input: Inbound): Admission {
130
+ const json = JSON.stringify(input);
131
+ const hash = digest(JSON.stringify([input.thread, input.kind, input.author, input.text]));
132
+ return transaction(() => {
133
+ const previous = event.get(input.id) as (Row & { hash: string }) | undefined;
134
+ if (previous) {
135
+ if (previous.hash === hash) return { id: input.id, job: previous.job, state: previous.state, duplicate: true };
136
+ db.prepare('INSERT OR IGNORE INTO conflicts VALUES (?, ?)').run(input.id, new Date().toISOString());
137
+ return { id: input.id, job: previous.job, state: 'conflict' };
138
+ }
139
+ const bound = this.topic(input.thread, input.kind);
140
+ if (!bound && input.kind === 'pull') return { id: input.id, state: 'unbound' };
141
+ const count = db.prepare("SELECT count(*) AS n FROM events WHERE state IN ('queued','working','prepared','unknown')").get()!;
142
+ if (Number(count.n) >= 128) return { id: input.id, state: 'capacity' };
143
+ const id = bound?.id ?? digest(String(input.thread)).slice(0, 16);
144
+ if (!bound) db.prepare("INSERT INTO jobs (id, thread, data) VALUES (?, ?, '{}')").run(id, input.thread);
145
+ db.prepare("INSERT INTO events (id, job, hash, input, state) VALUES (?, ?, ?, ?, 'queued')").run(input.id, id, hash, json);
146
+ return { id: input.id, job: id, state: 'queued' };
147
+ });
148
+ },
149
+ claim(exclude: readonly string[] = []): Entry | undefined {
150
+ return transaction(() => {
151
+ const row = next.get(JSON.stringify(exclude)) as Row | undefined;
152
+ if (!row) return;
153
+ const entry = load(row);
154
+ if (!change(entry.input.id, 'queued', 'working')) throw new Error('Could not claim the queued request');
155
+ const history = (db.prepare(`SELECT seq, input, delivery FROM events WHERE seq IN (
156
+ SELECT seq FROM (SELECT seq FROM events WHERE job = ? AND seq < ? AND state = 'delivered' ORDER BY seq DESC LIMIT 6)
157
+ UNION
158
+ SELECT min(seq) FROM events WHERE job = ? AND seq < ?
159
+ ) ORDER BY seq`).all(entry.job.id, row.seq, entry.job.id, row.seq) as Pick<Row, 'seq' | 'input' | 'delivery'>[]).map((row, index) => {
160
+ const previous = JSON.parse(row.input) as Inbound;
161
+ const output = row.delivery ? JSON.parse(row.delivery) as Delivery : undefined;
162
+ return { request: index === 0 ? previous.text : previous.text.slice(0, 1600), response: output?.text.slice(0, 1600), result: output?.result };
163
+ });
164
+ return { ...entry, state: 'working', history };
165
+ });
166
+ },
167
+ recover() {
168
+ transaction(() => {
169
+ db.prepare("UPDATE events SET state = 'queued', problem = 'rebuilding_after_restart' WHERE state = 'working'").run();
170
+ if (!this.get('githubPullReadVersion')) {
171
+ db.prepare("UPDATE jobs SET data = json_set(data, '$.readPullFeedback', json('true')) WHERE pull IS NOT NULL").run();
172
+ this.put('githubPullReadVersion', 1);
173
+ }
174
+ });
175
+ },
176
+ unreadPulls(after: number) {
177
+ return (db.prepare(`SELECT pull FROM jobs WHERE json_extract(data, '$.readPullFeedback') = 1
178
+ ORDER BY pull <= ?, pull LIMIT 4`).all(after) as { pull: number }[]).map(({ pull }) => pull);
179
+ },
180
+ finishPullRead(pull: number) {
181
+ db.prepare("UPDATE jobs SET data = json_remove(data, '$.readPullFeedback') WHERE pull = ?").run(pull);
182
+ },
183
+ prepare(entry: Entry, delivery: Delivery) {
184
+ return transaction(() => {
185
+ if (!change(entry.input.id, 'working', 'prepared', delivery)) return false;
186
+ const value = lookup(entry.job.id)!;
187
+ value.question = delivery.question;
188
+ if (delivery.artifact) value.last = delivery.artifact;
189
+ saveJob(value);
190
+ return true;
191
+ });
192
+ },
193
+ resumeApproved() {
194
+ return transaction(() => {
195
+ const rows = db.prepare(`SELECT e.* FROM events e WHERE e.state = 'delivered' AND
196
+ json_extract(e.delivery, '$.publish') = 'approval' AND NOT EXISTS (
197
+ SELECT 1 FROM events newer WHERE newer.job = e.job AND newer.seq > e.seq AND
198
+ json_type(newer.delivery, '$.artifact') = 'object'
199
+ )`).all() as Row[];
200
+ for (const row of rows) if (!busy.get(row.job)) queuePublication(load(row), false);
201
+ });
202
+ },
203
+ decidePublication(work: string, approve: boolean, rejectionReason?: string, expectedEvent?: string) {
204
+ return transaction(() => {
205
+ const row = latestArtifact.get(work) as Row | undefined;
206
+ if (!row || row.state !== 'delivered' || busy.get(work)) return;
207
+ const entry = load(row);
208
+ const delivery = entry.delivery!;
209
+ if (delivery.publish !== 'approval' || (expectedEvent && expectedEvent !== entry.input.id)) return;
210
+ if (approve) return queuePublication(entry, true);
211
+ const rejected = { ...delivery, publish: 'rejected', rejectionReason } as const;
212
+ if (!change(entry.input.id, 'delivered', 'delivered', rejected)) return;
213
+ const prior = db.prepare(`SELECT delivery FROM events WHERE job = ? AND seq < ?
214
+ AND json_extract(delivery, '$.publish') = 'confirmed' ORDER BY seq DESC LIMIT 1`).get(work, row.seq);
215
+ entry.job.last = prior ? (JSON.parse(String(prior.delivery)) as Delivery).artifact : undefined;
216
+ saveJob(entry.job);
217
+ return rejected;
218
+ });
219
+ },
220
+ decisions(limit = 8) {
221
+ const waiting = db.prepare(`SELECT * FROM events e WHERE e.state IN ('prepared', 'delivered') AND e.seq = (
222
+ SELECT max(seq) FROM events WHERE job = e.job AND delivery IS NOT NULL
223
+ ) AND EXISTS (SELECT 1 FROM jobs j WHERE j.id = e.job AND json_extract(j.data, '$.question') IS NOT NULL)
224
+ ORDER BY seq DESC LIMIT ?`).all(limit) as Row[];
225
+ const approvals = db.prepare(`SELECT * FROM events e WHERE e.state = 'delivered' AND json_extract(e.delivery, '$.publish') = 'approval'
226
+ AND e.seq = (SELECT max(seq) FROM events WHERE job = e.job AND json_type(delivery, '$.artifact') = 'object')
227
+ ORDER BY seq DESC LIMIT ?`).all(limit) as Row[];
228
+ return [...waiting.map(load).filter(entry => Boolean(entry.delivery?.question) && !busy.get(entry.job.id))
229
+ .map(entry => ({ kind: 'question' as const, entry })),
230
+ ...approvals.map(load).filter(entry => !busy.get(entry.job.id)).map(entry => ({ kind: 'publication' as const, entry }))];
231
+ },
232
+ pending() {
233
+ return (db.prepare("SELECT * FROM events WHERE state IN ('prepared','unknown') AND delivery IS NOT NULL ORDER BY seq LIMIT 128")
234
+ .all() as Row[]).map(load);
235
+ },
236
+ setDelivery(entry: Entry, delivery: Delivery, state: State = 'prepared', problem?: string) {
237
+ return transaction(() => {
238
+ if (!change(entry.input.id, entry.state, state, delivery, problem)) return false;
239
+ if (delivery.branchConfirmed || delivery.pull || delivery.commit) {
240
+ const value = lookup(entry.job.id)!;
241
+ if (delivery.branchConfirmed) value.branch = delivery.branch ?? value.branch;
242
+ if (delivery.pull && delivery.pull !== value.pull) value.readPullFeedback = true;
243
+ value.pull = delivery.pull ?? value.pull;
244
+ value.commit = delivery.commit ?? value.commit;
245
+ saveJob(value);
246
+ }
247
+ entry.state = state;
248
+ entry.delivery = delivery;
249
+ return true;
250
+ });
251
+ },
252
+ work(id: string) {
253
+ return lookup(id);
254
+ },
255
+ stop(id: string) {
256
+ return transaction(() => {
257
+ const value = lookup(id);
258
+ if (!value) return 0;
259
+ const waiting = Boolean(value.question);
260
+ if (waiting) {
261
+ value.question = undefined;
262
+ saveJob(value);
263
+ }
264
+ const changed = db.prepare(`UPDATE events SET state = 'stopped', problem = 'owner_stopped'
265
+ WHERE job = ? AND (state IN ('queued','working') OR
266
+ (state = 'prepared' AND json_extract(delivery, '$.reply') = 'queued' AND
267
+ coalesce(json_extract(delivery, '$.publish'), '') IN ('', 'queued', 'approval')))`).run(id).changes;
268
+ return Number(changed) + Number(waiting);
269
+ });
270
+ },
271
+ get<T>(key: string): T | undefined {
272
+ const row = db.prepare('SELECT data FROM metadata WHERE key = ?').get(key);
273
+ return row && JSON.parse(String(row.data)) as T;
274
+ },
275
+ put(key: string, data: unknown) {
276
+ db.prepare('INSERT INTO metadata VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET data = excluded.data').run(key, JSON.stringify(data));
277
+ },
278
+ status(limit = 64, work?: string | number) {
279
+ const selected = work === undefined ? undefined : this.resolveWork(work)?.id;
280
+ const filter = work === undefined ? null : selected ?? '';
281
+ const events = (db.prepare(`SELECT * FROM events WHERE (? IS NULL OR job = ?) ORDER BY
282
+ state IN ('working','prepared','unknown','queued') DESC, seq DESC LIMIT ?`).all(filter, filter, limit) as Row[]).map(load);
283
+ const jobs = (db.prepare(`SELECT j.* FROM jobs j WHERE (? IS NULL OR j.id = ?) ORDER BY
284
+ (json_extract(j.data, '$.question') IS NOT NULL OR EXISTS (
285
+ SELECT 1 FROM events e WHERE e.job = j.id AND (e.state IN ('working','prepared','unknown','queued') OR
286
+ (json_extract(e.delivery, '$.publish') = 'approval' AND e.seq = (
287
+ SELECT max(seq) FROM events WHERE job = j.id AND json_type(delivery, '$.artifact') = 'object'
288
+ )))
289
+ )) DESC, j.rowid DESC LIMIT ?`).all(filter, filter, limit) as JobRow[]).map(row => {
290
+ const item = serial(row);
291
+ return { id: item.id, issue: item.thread, pull: item.pull, branch: item.branch, waiting: item.question,
292
+ artifact: item.last && { patch: item.last.patch, sha256: item.last.sha256, checks: item.last.checks, summary: item.last.summary, review: item.last.review } };
293
+ });
294
+ return {
295
+ jobs, events: events.map(({ job: item, input, state, delivery, problem }) => ({
296
+ id: input.id, job: item.id, thread: input.thread, state, problem,
297
+ result: delivery?.result, publish: delivery?.publish, reply: delivery?.reply, comment: delivery?.comment, originalComment: delivery?.originalComment, url: delivery?.url, rejectionReason: delivery?.rejectionReason,
298
+ })),
299
+ conflicts: db.prepare('SELECT id, detected FROM conflicts ORDER BY rowid DESC LIMIT 32').all(),
300
+ };
301
+ },
302
+ close: () => db.close(),
303
+ };
304
+ }
305
+
306
+ export type Inbox = ReturnType<typeof openInbox>;
@@ -0,0 +1,54 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { constants, lstatSync, openSync, closeSync, readFileSync, mkdirSync, statSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { digest } from './inbox.js';
6
+ import type { PersonalSettings } from './config.js';
7
+
8
+ export function stateDirectory(cwd: string) {
9
+ const root = process.env.ANYSWARM_SUPER_STATE_DIR ??
10
+ join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'anyswarm', 'personal', digest(resolve(cwd)).slice(0, 20));
11
+ if (!isAbsolute(root)) throw new Error('ANYSWARM_SUPER_STATE_DIR must be an absolute path.');
12
+ if (Buffer.byteLength(join(root, 'rpc')) >= 104) {
13
+ throw new Error('Set ANYSWARM_SUPER_STATE_DIR to a shorter absolute directory for the local socket.');
14
+ }
15
+ return root;
16
+ }
17
+
18
+ export function privateDirectory(root: string) {
19
+ mkdirSync(root, { recursive: true, mode: 0o700 });
20
+ const stat = lstatSync(root);
21
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) {
22
+ throw new Error('Personal state must be a private directory owned by the current user (chmod 700).');
23
+ }
24
+ const parent = statSync(dirname(root));
25
+ if (!parent.isDirectory() || ((parent.mode & 0o022) !== 0 && (parent.mode & 0o1000) === 0)) {
26
+ throw new Error('Personal state needs a private or sticky parent directory.');
27
+ }
28
+ }
29
+ export function loadSettings(root: string): PersonalSettings {
30
+ try {
31
+ const fd = openSync(join(root, 'settings.json'), constants.O_RDONLY | constants.O_NOFOLLOW);
32
+ try { return JSON.parse(readFileSync(fd, 'utf8')); }
33
+ finally { closeSync(fd); }
34
+ } catch {
35
+ throw new Error('Run anyswarm run ./operator.ts setup --repo owner/repo.');
36
+ }
37
+ }
38
+
39
+ // Keep ownership in a separate rollback-journal database so Inbox readers and writes remain independent.
40
+ export function lockPersonalState(root: string) {
41
+ const path = join(root, 'daemon.lock.sqlite');
42
+ try { closeSync(openSync(path, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL, 0o600)); }
43
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; }
44
+ if (!lstatSync(path).isFile()) throw new Error('Personal state lock must be an owner-only regular file.');
45
+ const db = new DatabaseSync(path);
46
+ try {
47
+ db.exec('PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE');
48
+ } catch (error) {
49
+ db.close();
50
+ if ((error as { errcode?: number }).errcode === 5) throw new Error('Another Personal process owns this state directory. Stop it before replacing the settings or starting another Run.');
51
+ throw error;
52
+ }
53
+ return () => db.close();
54
+ }
@@ -0,0 +1,28 @@
1
+ import { personalActions } from './actions.js';
2
+ import personal from './project.js';
3
+
4
+ const actions = personalActions(personal);
5
+ const [command, ...args] = process.argv.slice(2);
6
+ if (!command || !Object.hasOwn(actions, command)) {
7
+ console.error('Usage: anyswarm run ./operator.ts setup|start|jobs|logs|ask|answer|approve|reject|stop-work|stop [arguments]');
8
+ process.exitCode = 2;
9
+ } else {
10
+ const controller = new AbortController();
11
+ const interrupt = (signal: NodeJS.Signals) => {
12
+ process.exitCode = signal === 'SIGINT' ? 130 : 143;
13
+ controller.abort();
14
+ };
15
+ process.on('SIGINT', interrupt).on('SIGTERM', interrupt);
16
+ try {
17
+ const action = actions[command as keyof typeof actions]!;
18
+ const result = await action({ args: args.join(' '), cwd: process.cwd(), signal: controller.signal });
19
+ if (result !== undefined) console.log(JSON.stringify(result));
20
+ } catch (error) {
21
+ if (!controller.signal.aborted) {
22
+ console.error(error instanceof Error ? error.message : 'Personal command failed.');
23
+ process.exitCode = 1;
24
+ }
25
+ } finally {
26
+ process.off('SIGINT', interrupt).off('SIGTERM', interrupt);
27
+ }
28
+ }