@anyswarm/core 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (398) hide show
  1. package/README.md +11 -10
  2. package/deploy/worker/Dockerfile +12 -4
  3. package/dist/deploy/worker/Dockerfile +12 -4
  4. package/dist/examples/README.md +24 -12
  5. package/dist/examples/authoring/README.md +24 -0
  6. package/dist/examples/authoring/business.d.ts +2 -0
  7. package/dist/examples/authoring/business.js +4 -0
  8. package/dist/examples/authoring/config.d.ts +5 -0
  9. package/dist/examples/authoring/config.js +2 -0
  10. package/dist/examples/authoring/eject.json +5 -0
  11. package/dist/examples/authoring/harness.d.ts +4 -0
  12. package/dist/examples/authoring/harness.js +19 -0
  13. package/dist/examples/autoresearch/README.md +33 -0
  14. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +18 -0
  15. package/dist/examples/autoresearch/config.d.ts +51 -0
  16. package/dist/examples/autoresearch/config.js +57 -0
  17. package/dist/examples/autoresearch/demo.d.ts +11 -0
  18. package/dist/examples/autoresearch/demo.js +52 -0
  19. package/dist/examples/autoresearch/eject.json +15 -0
  20. package/dist/examples/autoresearch/frontiercs2.d.ts +87 -0
  21. package/dist/examples/autoresearch/frontiercs2.js +211 -0
  22. package/dist/examples/autoresearch/prepare.d.ts +95 -0
  23. package/dist/examples/autoresearch/prepare.js +257 -0
  24. package/dist/examples/autoresearch/process.d.ts +13 -0
  25. package/dist/examples/autoresearch/process.js +48 -0
  26. package/dist/examples/autoresearch/project.d.ts +115 -0
  27. package/dist/examples/autoresearch/project.js +410 -0
  28. package/dist/examples/autoresearch/research-service.d.ts +106 -0
  29. package/dist/examples/autoresearch/research-service.js +255 -0
  30. package/dist/examples/code/README.md +25 -0
  31. package/dist/examples/code/REQUIREMENTS.zh.md +11 -0
  32. package/dist/examples/code/candidate.d.ts +19 -0
  33. package/dist/examples/code/candidate.js +80 -0
  34. package/dist/examples/code/config.d.ts +32 -0
  35. package/dist/examples/code/config.js +18 -0
  36. package/dist/examples/code/eject.json +5 -0
  37. package/dist/examples/code/project.d.ts +3 -0
  38. package/dist/examples/code/project.js +605 -0
  39. package/dist/examples/code/prompts.d.ts +5 -0
  40. package/dist/examples/code/prompts.js +12 -0
  41. package/dist/examples/code/verification.d.ts +19 -0
  42. package/dist/examples/code/verification.js +268 -0
  43. package/dist/examples/code/worktree.d.ts +17 -0
  44. package/dist/examples/code/worktree.js +233 -0
  45. package/dist/examples/harness-session/README.md +3 -6
  46. package/dist/examples/lead-worker/harness/dynamic-scheduler.d.ts +2 -1
  47. package/dist/examples/lead-worker/harness/dynamic-scheduler.js +5 -2
  48. package/dist/examples/lead-worker/harness/index.d.ts +60 -0
  49. package/dist/examples/lead-worker/harness/index.js +77 -6
  50. package/dist/examples/lead-worker/project.js +2 -2
  51. package/dist/examples/lead-worker/services/board.d.ts +5 -0
  52. package/dist/examples/lead-worker/services/board.js +19 -1
  53. package/dist/examples/messages/README.md +5 -5
  54. package/dist/examples/messages/handoff.d.ts +2 -0
  55. package/dist/examples/messages/handoff.js +5 -1
  56. package/dist/examples/messages/project.js +52 -2
  57. package/dist/examples/notes/README.md +13 -18
  58. package/dist/examples/notes/project.js +67 -6
  59. package/dist/examples/peermesh/harness/router.js +3 -1
  60. package/dist/examples/peermesh/harness/team.d.ts +8 -0
  61. package/dist/examples/peermesh/harness/team.js +13 -0
  62. package/dist/examples/peermesh/project.js +22 -4
  63. package/dist/examples/services/agent-control/README.md +3 -3
  64. package/dist/examples/services/mathlib-search/Dockerfile +4 -2
  65. package/dist/examples/services/mathlib-search/README.md +1 -1
  66. package/dist/examples/services/mcp-managed/README.md +2 -2
  67. package/dist/examples/services/persistent-board/README.md +13 -3
  68. package/dist/examples/services/persistent-board/business.d.ts +7 -0
  69. package/dist/examples/services/persistent-board/business.js +7 -0
  70. package/dist/examples/services/persistent-board/index.js +10 -0
  71. package/dist/examples/services/persistent-board/live.d.ts +3 -0
  72. package/dist/examples/services/persistent-board/live.js +58 -0
  73. package/dist/examples/subagents/README.md +5 -5
  74. package/dist/examples/subagents/business.js +3 -1
  75. package/dist/examples/subagents/harness/controller.d.ts +15 -0
  76. package/dist/examples/subagents/harness/controller.js +181 -32
  77. package/dist/examples/subagents/project.d.ts +2 -0
  78. package/dist/examples/subagents/project.js +43 -34
  79. package/dist/examples/subagents/prompts/prompts.d.ts +1 -0
  80. package/dist/examples/subagents/prompts/prompts.js +3 -0
  81. package/dist/examples/subagents/services/collaboration-service.d.ts +3 -2
  82. package/dist/examples/subagents/services/collaboration-service.js +14 -2
  83. package/dist/examples/substrate/README.md +2 -2
  84. package/dist/examples/substrate/harness/index.d.ts +1 -1
  85. package/dist/examples/substrate/harness/index.js +77 -12
  86. package/dist/examples/substrate/project.js +4 -1
  87. package/dist/examples/super/README.md +40 -0
  88. package/dist/examples/super/actions.d.ts +95 -0
  89. package/dist/examples/super/actions.js +230 -0
  90. package/dist/examples/super/artifact.d.ts +4 -0
  91. package/dist/examples/super/artifact.js +51 -0
  92. package/dist/examples/super/config.d.ts +80 -0
  93. package/dist/examples/super/config.js +83 -0
  94. package/dist/examples/super/coordinator.d.ts +33 -0
  95. package/dist/examples/super/coordinator.js +151 -0
  96. package/dist/examples/super/daemon.d.ts +11 -0
  97. package/dist/examples/super/daemon.js +109 -0
  98. package/dist/examples/super/decisions.d.ts +8 -0
  99. package/dist/examples/super/decisions.js +52 -0
  100. package/dist/examples/super/eject.json +5 -0
  101. package/dist/examples/super/execution.d.ts +11 -0
  102. package/dist/examples/super/execution.js +136 -0
  103. package/dist/examples/super/github.d.ts +62 -0
  104. package/dist/examples/super/github.js +269 -0
  105. package/dist/examples/super/inbox.d.ts +162 -0
  106. package/dist/examples/super/inbox.js +284 -0
  107. package/dist/examples/super/location.d.ts +5 -0
  108. package/dist/examples/super/location.js +64 -0
  109. package/dist/examples/super/outbox.d.ts +5 -0
  110. package/dist/examples/super/outbox.js +103 -0
  111. package/dist/examples/super/project.d.ts +111 -0
  112. package/dist/examples/super/project.js +253 -0
  113. package/dist/examples/super/prompts.d.ts +3 -0
  114. package/dist/examples/super/prompts.js +25 -0
  115. package/dist/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  116. package/dist/examples/taskpool/harness/controller.d.ts +35 -6
  117. package/dist/examples/taskpool/harness/controller.js +73 -7
  118. package/dist/examples/taskpool/project.js +18 -2
  119. package/dist/scripts/anyswarm-applications.d.ts +19 -0
  120. package/dist/scripts/anyswarm-applications.js +19 -0
  121. package/dist/scripts/anyswarm-arguments.d.ts +35 -5
  122. package/dist/scripts/anyswarm-arguments.js +87 -23
  123. package/dist/scripts/anyswarm-author.d.ts +5 -0
  124. package/dist/scripts/anyswarm-author.js +24 -0
  125. package/dist/scripts/anyswarm-eject.d.ts +11 -0
  126. package/dist/scripts/anyswarm-eject.js +164 -0
  127. package/dist/scripts/anyswarm-harnesses.d.ts +2 -0
  128. package/dist/scripts/anyswarm-harnesses.js +31 -0
  129. package/dist/scripts/anyswarm-installation.js +19 -13
  130. package/dist/scripts/anyswarm-launch.d.ts +37 -0
  131. package/dist/scripts/anyswarm-launch.js +86 -0
  132. package/dist/scripts/anyswarm-project.d.ts +12 -2
  133. package/dist/scripts/anyswarm-project.js +121 -20
  134. package/dist/scripts/anyswarm-source-runner.d.ts +1 -0
  135. package/dist/scripts/anyswarm-source-runner.js +232 -0
  136. package/dist/scripts/anyswarm-tui-config.d.ts +36 -0
  137. package/dist/scripts/anyswarm-tui-config.js +189 -0
  138. package/dist/scripts/anyswarm-tui-session.d.ts +66 -0
  139. package/dist/scripts/anyswarm-tui-session.js +304 -0
  140. package/dist/scripts/anyswarm-tui-terminal.d.ts +41 -0
  141. package/dist/scripts/anyswarm-tui-terminal.js +154 -0
  142. package/dist/scripts/anyswarm-tui.d.ts +2 -0
  143. package/dist/scripts/anyswarm-tui.js +1012 -0
  144. package/dist/scripts/anyswarm.js +47 -2
  145. package/dist/scripts/build-provenance.json +1 -0
  146. package/dist/scripts/build.js +7 -1
  147. package/dist/scripts/generate-architecture-api.js +2 -0
  148. package/dist/scripts/generate-architecture-prompts.js +24 -2
  149. package/dist/scripts/local-environment.d.ts +6 -1
  150. package/dist/scripts/local-environment.js +52 -16
  151. package/dist/scripts/local-setup-smoke.js +3 -2
  152. package/dist/scripts/local-setup-worker.d.ts +1 -1
  153. package/dist/scripts/local-setup-worker.js +15 -6
  154. package/dist/scripts/local-setup.d.ts +2 -2
  155. package/dist/scripts/local-setup.js +72 -12
  156. package/dist/scripts/opensandbox-agent-worker.js +2 -2
  157. package/dist/scripts/pack-release.d.ts +1 -0
  158. package/dist/scripts/pack-release.js +63 -0
  159. package/dist/scripts/pi-session-bridge.js +11 -3
  160. package/dist/scripts/run-harness.js +3 -1
  161. package/dist/scripts/setup-bootstrap.js +43 -6
  162. package/dist/src/core/allocation-ledger.js +4 -3
  163. package/dist/src/core/host-identity.d.ts +2 -0
  164. package/dist/src/core/host-identity.js +11 -0
  165. package/dist/src/core/index.d.ts +4 -2
  166. package/dist/src/core/index.js +12 -4
  167. package/dist/src/core/mcp-service.js +2 -2
  168. package/dist/src/core/runtime-management.d.ts +6 -0
  169. package/dist/src/core/runtime-management.js +24 -0
  170. package/dist/src/core/sandbox/executor-driver.d.ts +4 -2
  171. package/dist/src/core/sandbox/executor-driver.js +12 -14
  172. package/dist/src/core/sandbox/local-executor.d.ts +13 -1
  173. package/dist/src/core/sandbox/local-executor.js +69 -19
  174. package/dist/src/core/sandbox/local-worker.js +32 -21
  175. package/dist/src/core/sandbox/opensandbox-backend.d.ts +2 -0
  176. package/dist/src/core/sandbox/opensandbox-backend.js +36 -11
  177. package/dist/src/core/sandbox/sandbox-connection.d.ts +2 -0
  178. package/dist/src/core/sandbox/sandbox-connection.js +14 -6
  179. package/dist/src/core/service-live-state.d.ts +14 -0
  180. package/dist/src/core/service-live-state.js +161 -0
  181. package/dist/src/core/service-observation-types.d.ts +21 -1
  182. package/dist/src/core/service-process.d.ts +1 -1
  183. package/dist/src/core/service-process.js +45 -4
  184. package/dist/src/core/service-types.d.ts +5 -1
  185. package/dist/src/core/services.d.ts +1 -1
  186. package/dist/src/core/services.js +8 -3
  187. package/dist/src/core/types.d.ts +3 -0
  188. package/dist/src/core/worker-image.js +3 -3
  189. package/dist/src/harness/harness-session-types.d.ts +10 -0
  190. package/dist/src/harness/harness-session.js +42 -5
  191. package/dist/src/harness/project-harness.d.ts +13 -1
  192. package/dist/src/harness/project-harness.js +36 -10
  193. package/dist/src/harness/project-input.js +81 -15
  194. package/dist/src/harness/project-rpc-client.d.ts +1 -0
  195. package/dist/src/harness/project-rpc-client.js +5 -0
  196. package/dist/src/harness/project-rpc.d.ts +8 -2
  197. package/dist/src/harness/project-rpc.js +31 -7
  198. package/dist/src/harness/project-runtime.js +3 -1
  199. package/dist/src/harness/typescript-loader.d.ts +2 -0
  200. package/dist/src/harness/typescript-loader.js +41 -0
  201. package/dist/src/trace-viewer/public/app.js +6 -5
  202. package/dist/src/trace-viewer/reader.mjs +42 -2
  203. package/docs/INDEX.md +3 -1
  204. package/docs/architecture/00-overview.md +1 -1
  205. package/docs/architecture/01-agent-core.md +1 -1
  206. package/docs/architecture/06-observability-experiments.md +1 -1
  207. package/docs/architecture/07-run-configuration.md +18 -12
  208. package/docs/architecture/08-prompts.md +22 -0
  209. package/docs/architecture/10-service-api-reference.md +53 -18
  210. package/docs/architecture/11-storage-reference.md +18 -1
  211. package/docs/architecture/12-code-coverage.md +148 -84
  212. package/docs/architecture/15-core-runtime.md +8 -0
  213. package/docs/architecture/16-pi-opensandbox-backend.md +5 -5
  214. package/docs/architecture/17-harness-reporting.md +1 -1
  215. package/docs/architecture/19-substrate-harness.md +28 -1
  216. package/docs/architecture/20-lead-worker-harness.md +34 -1
  217. package/docs/architecture/22-website.md +5 -3
  218. package/docs/architecture/23-project-harness.md +124 -5
  219. package/docs/architecture/24-runtime-recovery.md +10 -3
  220. package/docs/architecture/25-foreground-tui.md +51 -0
  221. package/docs/architecture/26-code.md +39 -0
  222. package/docs/architecture/27-personal.md +43 -0
  223. package/docs/architecture/28-autoresearch.md +31 -0
  224. package/docs/architecture/INDEX.md +4 -0
  225. package/docs/architecture/prompts/08-lead-worker-harness.md +4 -2
  226. package/docs/architecture/prompts/08-subagents-harness.md +21 -0
  227. package/docs/architecture/prompts/21-personal.md +44 -0
  228. package/docs/architecture/prompts/22-autoresearch.md +63 -0
  229. package/docs/architecture/prompts/26-code.md +55 -0
  230. package/docs/architecture/prompts/source-manifest.json +152 -33
  231. package/docs/architecture/source-map.json +489 -21
  232. package/docs/designs/core-harness/06-project-harness.md +13 -2
  233. package/docs/designs/core-harness/README.md +5 -0
  234. package/docs/en/agents.md +1 -1
  235. package/docs/en/build-your-harness.md +3 -5
  236. package/docs/en/changelog.md +13 -4
  237. package/docs/en/first-harness.md +8 -11
  238. package/docs/en/harnesses/lead-worker.md +1 -1
  239. package/docs/en/harnesses/peermesh.md +2 -2
  240. package/docs/en/harnesses/subagents.md +2 -2
  241. package/docs/en/harnesses/substrate.md +4 -4
  242. package/docs/en/harnesses/taskpool.md +2 -2
  243. package/docs/en/latest.md +12 -123
  244. package/docs/en/overview.md +1 -1
  245. package/docs/en/quickstart.md +40 -16
  246. package/docs/en/reference/api.md +14 -4
  247. package/docs/en/reference/cli.md +58 -14
  248. package/docs/en/runtime.md +2 -2
  249. package/docs/en/services.md +4 -0
  250. package/docs/third-party-notices.md +1 -0
  251. package/docs/workflows/development.md +17 -12
  252. package/docs/workflows/release-and-docs-versioning.md +76 -0
  253. package/docs/zh/agents.md +1 -1
  254. package/docs/zh/build-your-harness.md +3 -5
  255. package/docs/zh/changelog.md +13 -4
  256. package/docs/zh/first-harness.md +8 -11
  257. package/docs/zh/harnesses/lead-worker.md +1 -1
  258. package/docs/zh/harnesses/peermesh.md +2 -2
  259. package/docs/zh/harnesses/subagents.md +2 -2
  260. package/docs/zh/harnesses/substrate.md +4 -4
  261. package/docs/zh/harnesses/taskpool.md +2 -2
  262. package/docs/zh/latest.md +13 -124
  263. package/docs/zh/overview.md +1 -1
  264. package/docs/zh/quickstart.md +40 -16
  265. package/docs/zh/reference/api.md +14 -4
  266. package/docs/zh/reference/cli.md +58 -14
  267. package/docs/zh/runtime.md +2 -2
  268. package/docs/zh/services.md +4 -0
  269. package/examples/README.md +24 -12
  270. package/examples/authoring/README.md +24 -0
  271. package/examples/authoring/business.ts +4 -0
  272. package/examples/authoring/config.ts +2 -0
  273. package/examples/authoring/eject.json +5 -0
  274. package/examples/authoring/harness.ts +21 -0
  275. package/examples/autoresearch/README.md +33 -0
  276. package/examples/autoresearch/REQUIREMENTS.zh.md +18 -0
  277. package/examples/autoresearch/config.ts +90 -0
  278. package/examples/autoresearch/demo.ts +55 -0
  279. package/examples/autoresearch/eject.json +15 -0
  280. package/examples/autoresearch/frontiercs2.ts +237 -0
  281. package/examples/autoresearch/prepare.ts +267 -0
  282. package/examples/autoresearch/process.ts +50 -0
  283. package/examples/autoresearch/project.ts +397 -0
  284. package/examples/autoresearch/research-service.ts +302 -0
  285. package/examples/code/README.md +25 -0
  286. package/examples/code/REQUIREMENTS.zh.md +11 -0
  287. package/examples/code/candidate.ts +89 -0
  288. package/examples/code/config.ts +19 -0
  289. package/examples/code/eject.json +5 -0
  290. package/examples/code/project.ts +581 -0
  291. package/examples/code/prompts.ts +16 -0
  292. package/examples/code/verification.ts +239 -0
  293. package/examples/code/worktree.ts +188 -0
  294. package/examples/harness-session/README.md +3 -6
  295. package/examples/lead-worker/harness/dynamic-scheduler.ts +6 -3
  296. package/examples/lead-worker/harness/index.ts +61 -6
  297. package/examples/lead-worker/project.ts +2 -2
  298. package/examples/lead-worker/services/board.ts +14 -1
  299. package/examples/messages/README.md +5 -5
  300. package/examples/messages/handoff.ts +6 -2
  301. package/examples/messages/project.ts +47 -2
  302. package/examples/notes/README.md +13 -18
  303. package/examples/notes/project.ts +57 -9
  304. package/examples/peermesh/harness/router.ts +2 -2
  305. package/examples/peermesh/harness/team.ts +11 -0
  306. package/examples/peermesh/project.ts +19 -4
  307. package/examples/services/agent-control/README.md +3 -3
  308. package/examples/services/mathlib-search/Dockerfile +4 -2
  309. package/examples/services/mathlib-search/README.md +1 -1
  310. package/examples/services/mcp-managed/README.md +2 -2
  311. package/examples/services/persistent-board/README.md +13 -3
  312. package/examples/services/persistent-board/business.ts +10 -0
  313. package/examples/services/persistent-board/index.ts +10 -0
  314. package/examples/services/persistent-board/live.ts +54 -0
  315. package/examples/subagents/README.md +5 -5
  316. package/examples/subagents/business.ts +3 -1
  317. package/examples/subagents/harness/controller.ts +161 -29
  318. package/examples/subagents/project.ts +47 -33
  319. package/examples/subagents/prompts/prompts.ts +4 -0
  320. package/examples/subagents/services/collaboration-service.ts +14 -2
  321. package/examples/substrate/README.md +2 -2
  322. package/examples/substrate/harness/index.ts +67 -11
  323. package/examples/substrate/project.ts +5 -1
  324. package/examples/super/README.md +40 -0
  325. package/examples/super/actions.ts +196 -0
  326. package/examples/super/artifact.ts +56 -0
  327. package/examples/super/config.ts +95 -0
  328. package/examples/super/coordinator.ts +158 -0
  329. package/examples/super/daemon.ts +84 -0
  330. package/examples/super/decisions.ts +46 -0
  331. package/examples/super/eject.json +5 -0
  332. package/examples/super/execution.ts +131 -0
  333. package/examples/super/github.ts +242 -0
  334. package/examples/super/inbox.ts +306 -0
  335. package/examples/super/location.ts +54 -0
  336. package/examples/super/outbox.ts +97 -0
  337. package/examples/super/project.ts +227 -0
  338. package/examples/super/prompts.ts +27 -0
  339. package/examples/taskpool/deploy/service-hosts/Dockerfile +4 -2
  340. package/examples/taskpool/harness/controller.ts +59 -7
  341. package/examples/taskpool/project.ts +18 -2
  342. package/npm-shrinkwrap.development.json +2199 -0
  343. package/npm-shrinkwrap.json +86 -1920
  344. package/package.development.json +92 -0
  345. package/package.json +13 -7
  346. package/scripts/anyswarm-applications.ts +39 -0
  347. package/scripts/anyswarm-arguments.ts +94 -28
  348. package/scripts/anyswarm-author.ts +25 -0
  349. package/scripts/anyswarm-eject.ts +145 -0
  350. package/scripts/anyswarm-harnesses.ts +27 -0
  351. package/scripts/anyswarm-installation.ts +19 -13
  352. package/scripts/anyswarm-launch.ts +108 -0
  353. package/scripts/anyswarm-project.ts +114 -21
  354. package/scripts/anyswarm-source-runner.ts +203 -0
  355. package/scripts/anyswarm-tui-config.ts +174 -0
  356. package/scripts/anyswarm-tui-session.ts +295 -0
  357. package/scripts/anyswarm-tui-terminal.ts +147 -0
  358. package/scripts/anyswarm-tui.ts +912 -0
  359. package/scripts/anyswarm.ts +43 -2
  360. package/scripts/build.ts +8 -1
  361. package/scripts/generate-architecture-api.ts +2 -0
  362. package/scripts/generate-architecture-prompts.ts +35 -2
  363. package/scripts/local-environment.ts +55 -17
  364. package/scripts/local-setup-smoke.ts +3 -2
  365. package/scripts/local-setup-worker.ts +17 -7
  366. package/scripts/local-setup.ts +66 -13
  367. package/scripts/opensandbox-agent-worker.ts +2 -2
  368. package/scripts/pack-release.ts +67 -0
  369. package/scripts/pi-session-bridge.ts +10 -2
  370. package/scripts/run-harness.ts +3 -1
  371. package/scripts/setup-bootstrap.ts +41 -6
  372. package/src/core/allocation-ledger.ts +5 -3
  373. package/src/core/host-identity.ts +11 -0
  374. package/src/core/index.ts +12 -6
  375. package/src/core/mcp-service.ts +2 -2
  376. package/src/core/runtime-management.ts +22 -0
  377. package/src/core/sandbox/executor-driver.ts +15 -18
  378. package/src/core/sandbox/local-executor.ts +65 -19
  379. package/src/core/sandbox/local-worker.ts +29 -21
  380. package/src/core/sandbox/opensandbox-backend.ts +36 -11
  381. package/src/core/sandbox/sandbox-connection.ts +14 -5
  382. package/src/core/service-live-state.ts +156 -0
  383. package/src/core/service-observation-types.ts +23 -1
  384. package/src/core/service-process.ts +36 -3
  385. package/src/core/service-types.ts +3 -1
  386. package/src/core/services.ts +8 -3
  387. package/src/core/types.ts +3 -0
  388. package/src/core/worker-image.ts +3 -3
  389. package/src/harness/harness-session-types.ts +13 -1
  390. package/src/harness/harness-session.ts +40 -7
  391. package/src/harness/project-harness.ts +36 -10
  392. package/src/harness/project-input.ts +73 -15
  393. package/src/harness/project-rpc-client.ts +5 -0
  394. package/src/harness/project-rpc.ts +29 -8
  395. package/src/harness/project-runtime.ts +2 -1
  396. package/src/harness/typescript-loader.ts +37 -0
  397. package/src/trace-viewer/public/app.js +6 -5
  398. package/src/trace-viewer/reader.mjs +42 -2
@@ -0,0 +1,174 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { lstat, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, extname, isAbsolute, join, resolve } from 'node:path';
6
+ import { loadAnySwarmConfig } from '../src/core/sandbox/sandbox-connection.js';
7
+ import { selectExecutorDriver } from '../src/core/sandbox/executor-driver.js';
8
+ import { builtinConfiguration, builtins } from './anyswarm-harnesses.js';
9
+ import { runLocalCommand } from './local-setup.js';
10
+
11
+ type Builtin = keyof typeof builtins;
12
+ type Budget = { key: string; max: number };
13
+ const timerMax = 2_147_483_647;
14
+ const runtimeBudgets = [
15
+ { key: 'workTimeoutMs', max: timerMax },
16
+ { key: 'closeTimeoutMs', max: timerMax },
17
+ ];
18
+ const budgets: Record<string, readonly Budget[]> = {
19
+ subagents: [...runtimeBudgets, { key: 'questionTimeoutMs', max: 120_000 }],
20
+ taskpool: runtimeBudgets,
21
+ peermesh: [{ key: 'durationMs', max: 86_400_000 }],
22
+ substrate: [...runtimeBudgets, { key: 'turnTimeoutMs', max: timerMax }],
23
+ 'lead-worker': [runtimeBudgets[0], { key: 'closeTimeoutMs', max: 60_000 },
24
+ { key: 'turnTimeoutMs', max: timerMax }],
25
+ notes: [{ key: 'turnTimeoutMs', max: timerMax }, runtimeBudgets[1]],
26
+ messages: [{ key: 'workTimeoutMs', max: timerMax },
27
+ { key: 'cleanupTimeoutMs', max: timerMax }],
28
+ };
29
+
30
+ function builtin(name: string): name is Builtin {
31
+ return Object.hasOwn(builtins, name);
32
+ }
33
+
34
+ export function terminalObject(value: unknown): Record<string, unknown> {
35
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
36
+ }
37
+
38
+ const preferencesPath = () => resolve(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'anyswarm', 'launcher.json');
39
+ type ConfigurationChoice = { path?: string; source: string };
40
+ type Preference = { version: 1; harness: string; configPath: string };
41
+
42
+ async function readPreference(path: string): Promise<Preference | undefined> {
43
+ let handle;
44
+ try {
45
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
46
+ } catch (error) {
47
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
48
+ throw error;
49
+ }
50
+ try {
51
+ const file = await handle.stat();
52
+ if (!file.isFile() || file.size > 8192 || (file.mode & 0o077) !== 0 ||
53
+ (process.getuid && file.uid !== process.getuid())) throw new Error('Launcher preferences must be an owner-only file');
54
+ const data = Buffer.alloc(8193);
55
+ const { bytesRead } = await handle.read(data, 0, data.length, 0);
56
+ if (bytesRead > 8192) throw new Error('Launcher preferences exceed 8 KiB');
57
+ const pref = terminalObject(JSON.parse(data.subarray(0, bytesRead).toString('utf8')));
58
+ if (pref.version !== 1 || typeof pref.harness !== 'string' || typeof pref.configPath !== 'string' ||
59
+ !isAbsolute(pref.configPath) || Object.keys(pref).length !== 3) {
60
+ throw new Error('Invalid launcher preferences. Select a trusted configuration or forget the saved preference.');
61
+ }
62
+ return pref as Preference;
63
+ } finally { await handle.close(); }
64
+ }
65
+
66
+ export class LauncherConfiguration {
67
+ readonly workspace: string;
68
+ readonly preferencePath = preferencesPath();
69
+ readonly isBuiltin: boolean;
70
+ source = 'environment';
71
+ path?: string;
72
+ preference?: Preference;
73
+ preferenceError?: string;
74
+ error?: string;
75
+ configuration?: Record<string, unknown>;
76
+ diagnostics?: Awaited<ReturnType<typeof runLocalCommand>>;
77
+ private choice?: ConfigurationChoice;
78
+
79
+ constructor(readonly harness: string, readonly specifier: string, readonly launchDirectory: string, cwd?: string, path?: string, choice?: ConfigurationChoice) {
80
+ this.workspace = resolve(launchDirectory, cwd ?? '.');
81
+ this.isBuiltin = builtin(specifier);
82
+ this.choice = choice ?? (path ? { path: resolve(launchDirectory, path), source: '--config' } : undefined);
83
+ }
84
+
85
+ selectedChoice() { return this.choice; }
86
+
87
+ async refresh() {
88
+ this.diagnostics = undefined;
89
+ this.preference = undefined;
90
+ this.preferenceError = undefined;
91
+ this.configuration = undefined;
92
+ this.error = undefined;
93
+ try { this.preference = await readPreference(this.preferencePath); }
94
+ catch { this.preferenceError = 'Cannot use launcher preferences. Select a trusted configuration or forget the preference.'; }
95
+ const remembered = this.preference?.harness === this.harness ? this.preference : undefined;
96
+ this.path = this.choice ? this.choice.path : remembered?.configPath;
97
+ this.source = this.choice?.source ?? (remembered ? 'remembered' : this.isBuiltin ? 'environment' : 'Harness defaults');
98
+ if (!this.choice && this.preferenceError) {
99
+ this.error = this.preferenceError;
100
+ return;
101
+ }
102
+ try {
103
+ if (this.path && !['.ts', '.mts', '.cts', '.mjs', '.js'].includes(extname(this.path))) {
104
+ this.error = 'Choose an explicit trusted TypeScript or ESM module.';
105
+ return;
106
+ }
107
+ const value = this.path ? await loadAnySwarmConfig(this.path)
108
+ : builtin(this.specifier) ? await builtinConfiguration(this.specifier) : undefined;
109
+ if (value === undefined && !this.path) return;
110
+ if (value === null || Array.isArray(value) || typeof value !== 'object' ||
111
+ ['cwd', 'prompt', 'input', 'workload'].some(field => Object.hasOwn(value, field))) {
112
+ this.error = 'The configuration must export an object without cwd, prompt, input or workload fields.';
113
+ return;
114
+ }
115
+ this.configuration = { ...value };
116
+ if (Object.hasOwn(budgets, this.specifier)) this.validateRuntime();
117
+ } catch (error) {
118
+ const requirements = /^Set ([A-Z0-9_]+(?: or [A-Z0-9_]+)*) /.exec(error instanceof Error ? error.message : '');
119
+ this.error = !this.path && requirements ? 'Set ' + requirements[1] : this.path
120
+ ? 'Could not load the trusted module. Check its path, exported configuration and adjacent .env.'
121
+ : 'Set the model endpoint and Sandbox connection environment, or select a trusted configuration.';
122
+ }
123
+ }
124
+
125
+ private validateRuntime() {
126
+ const config = this.configuration!;
127
+ if (!config.sandbox || !config.models || typeof config.image !== 'string' || !config.image) {
128
+ this.error = 'This Harness requires sandbox, models and a Worker image. Use /config to select a trusted configuration or run setup.';
129
+ return;
130
+ }
131
+ try { selectExecutorDriver(config.executor as Parameters<typeof selectExecutorDriver>[0]); }
132
+ catch { this.error = 'The selected executor is not configured. Run anys setup --backend pi or --backend codex.'; }
133
+ const invalid = budgets[this.specifier].find(({ key, max }) => {
134
+ const value = config[key];
135
+ return value !== undefined && (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > max);
136
+ });
137
+ if (invalid && !this.error) this.error = invalid.key + ' must be between 1 and ' + invalid.max + ' ms.';
138
+ }
139
+
140
+ select(path: string) {
141
+ this.choice = path.trim() ? { path: resolve(this.launchDirectory, path.trim()), source: 'selected for this launch' } :
142
+ { source: this.isBuiltin ? 'environment (selected)' : 'Harness defaults (selected)' };
143
+ return this.refresh();
144
+ }
145
+
146
+ async remember() {
147
+ if (!this.path || !this.configuration || this.error) throw new Error('Select a valid trusted configuration first.');
148
+ await mkdir(dirname(this.preferencePath), { recursive: true, mode: 0o700 });
149
+ const preference = { version: 1, harness: this.harness, configPath: this.path } as const;
150
+ const temporary = this.preferencePath + '.' + randomUUID();
151
+ try {
152
+ await writeFile(temporary, JSON.stringify(preference) + '\n', { mode: 0o600, flag: 'wx' });
153
+ await rename(temporary, this.preferencePath);
154
+ this.preference = preference;
155
+ this.preferenceError = undefined;
156
+ } finally { await rm(temporary, { force: true }); }
157
+ }
158
+
159
+ async forget() {
160
+ if (await lstat(this.preferencePath).then(() => true, error => {
161
+ if (error.code !== 'ENOENT') throw error;
162
+ return false;
163
+ })) await rm(this.preferencePath);
164
+ await this.refresh();
165
+ }
166
+
167
+ async diagnose(prepare: boolean, signal: AbortSignal, progress: (message: string) => void, backend?: 'pi' | 'codex') {
168
+ if (this.path && !this.configuration) throw new Error('Fix the selected configuration before using setup or doctor.');
169
+ const command = prepare ? { command: 'setup' as const, configPath: this.path, backend } : { command: 'doctor' as const, smoke: false, configPath: this.path };
170
+ const report = await runLocalCommand(command, signal, progress);
171
+ if (prepare && report.ok && !this.path) await this.refresh();
172
+ this.diagnostics = report;
173
+ }
174
+ }
@@ -0,0 +1,295 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import type { HarnessEvent, HarnessQuestion, HarnessRequest, HarnessResult, HarnessSession, HarnessState } from '../src/harness/project-harness.js';
4
+ import { terminalObject } from './anyswarm-tui-config.js';
5
+
6
+ function unresolvedHarnessReceipt(value: unknown): boolean {
7
+ const receipt = terminalObject(value);
8
+ const core = terminalObject(receipt.core ?? receipt.result);
9
+ return receipt.status === 'unknown' || core.status === 'unknown' || receipt.disposition === 'unknown' || core.disposition === 'unknown' || core.cleanup === 'pending' || terminalObject(receipt.harnessEffects).status === 'pending';
10
+ }
11
+
12
+ const messageLimit = 96;
13
+ const activityLimit = 100;
14
+ const contentLimit = 16_384;
15
+ const maxPending = 64;
16
+ const readTimeoutMs = 8_000;
17
+
18
+ type Message = {
19
+ order: number;
20
+ agentId: string;
21
+ id: string;
22
+ role: string;
23
+ blocks: Map<number, string>;
24
+ hidden: boolean;
25
+ complete: boolean;
26
+ truncated: boolean;
27
+ };
28
+
29
+ type Activity = { order: number; agentId: string; event: string; summary?: string };
30
+ type Mutation = {
31
+ payload: unknown;
32
+ request: HarnessRequest;
33
+ send: (request: HarnessRequest) => Promise<unknown>;
34
+ status: 'pending' | 'unknown' | 'confirmed' | 'failed';
35
+ receipt?: unknown;
36
+ };
37
+
38
+ export function formatSessionError(error: unknown) {
39
+ const { code, message } = terminalObject(error);
40
+ const detail = typeof message === 'string' ? message.slice(0, 1024) : 'The request failed.';
41
+ return typeof code === 'string' ? code + ' ' + detail : detail;
42
+ }
43
+
44
+ function boundedMap<K, V>(map: Map<K, V>, key: K, value: V, max: number) {
45
+ map.set(key, value);
46
+ if (map.size > max) map.delete(map.keys().next().value!);
47
+ }
48
+
49
+ function messageText(message: Record<string, unknown>) {
50
+ if (typeof message.content === 'string') return message.content.slice(0, contentLimit);
51
+ if (!Array.isArray(message.content)) return '';
52
+ let text = '';
53
+ for (const part of message.content.slice(0, 64)) {
54
+ const { type, text: block, name } = terminalObject(part);
55
+ if (type === 'text' && typeof block === 'string') text += block;
56
+ if (type === 'toolCall' && typeof name === 'string') text += '\nTool ' + name;
57
+ if (text.length >= contentLimit) break;
58
+ }
59
+ return text.slice(0, contentLimit);
60
+ }
61
+
62
+ export class TerminalSession {
63
+ state?: HarnessState;
64
+ revision = 0;
65
+ result?: HarnessResult;
66
+ readonly questions = new Map<string, HarnessQuestion>();
67
+ readonly messages = new Map<string, Message>();
68
+ readonly activity = new Map<string, Activity>();
69
+ readonly operations = new Map<string, Mutation>();
70
+ readonly observations = new Map<string, { pending: boolean; result?: unknown; error?: string }>();
71
+ subscribing = true;
72
+ observationLost = false;
73
+ workerHistoryLost = false;
74
+ runtimeObservationLost = false;
75
+ truncated = false;
76
+ lastError?: string;
77
+ private unsubscribe?: () => void;
78
+ private resubscribe?: ReturnType<typeof setTimeout>;
79
+ private closed = false;
80
+ private anonymousActivity = 0;
81
+ private reading = 0;
82
+
83
+ constructor(readonly session: HarnessSession, private readonly update: () => void) {
84
+ this.subscribe();
85
+ }
86
+
87
+ close() {
88
+ this.closed = true;
89
+ clearTimeout(this.resubscribe);
90
+ this.unsubscribe?.();
91
+ }
92
+
93
+ private subscribe() {
94
+ this.unsubscribe = this.session.onEvent(event => {
95
+ if (this.closed) return;
96
+ try { this.consume(event); }
97
+ catch (error) { this.subscriptionFailed(error); }
98
+ this.update();
99
+ }, { initialSnapshot: true, onError: error => this.subscriptionFailed(error) });
100
+ }
101
+
102
+ private subscriptionFailed(error: unknown) {
103
+ if (this.closed) return;
104
+ this.subscribing = true;
105
+ this.observationLost = true;
106
+ this.lastError = formatSessionError(error);
107
+ this.update();
108
+ if (this.resubscribe) return;
109
+ this.resubscribe = setTimeout(() => {
110
+ this.resubscribe = undefined;
111
+ this.unsubscribe?.();
112
+ try { this.subscribe(); }
113
+ catch (error) { this.subscriptionFailed(error); }
114
+ }, 250);
115
+ this.resubscribe.unref();
116
+ }
117
+
118
+ consume(event: HarnessEvent) {
119
+ switch (event.type) {
120
+ case 'snapshot':
121
+ case 'state':
122
+ if (this.state?.phase !== event.state.phase) {
123
+ this.revision++;
124
+ this.rememberActivity('', 'Run', { phase: event.state.phase });
125
+ }
126
+ this.state = event.state;
127
+ this.truncated ||= event.state.snapshotTruncated === true;
128
+ if (event.type === 'snapshot') {
129
+ this.subscribing = false;
130
+ this.messages.clear();
131
+ this.questions.clear();
132
+ for (const message of event.state.output) this.restoreMessage(message);
133
+ }
134
+ for (const question of event.state.questions) boundedMap(this.questions, question.questionId, question, 96);
135
+ if (event.state.result) this.result = event.state.result;
136
+ break;
137
+ case 'question':
138
+ boundedMap(this.questions, event.question.questionId, event.question, 96);
139
+ break;
140
+ case 'result':
141
+ this.result = event.result;
142
+ for (const question of event.result.questions ?? []) boundedMap(this.questions, question.questionId, question, 96);
143
+ break;
144
+ case 'event':
145
+ this.revision++;
146
+ this.observe(event.event);
147
+ break;
148
+ case 'operation':
149
+ for (const operation of this.operations.values()) {
150
+ if (operation.request.requestId === event.requestId && operation.status !== 'pending') {
151
+ operation.receipt = event.result;
152
+ operation.status = unresolvedHarnessReceipt(event.result) ? 'unknown' : 'confirmed';
153
+ }
154
+ }
155
+ break;
156
+ }
157
+ }
158
+
159
+ private restoreMessage(value: unknown) {
160
+ const record = terminalObject(value);
161
+ if (typeof record.messageId !== 'string' || typeof record.agentId !== 'string') return;
162
+ const message = this.message(record.agentId, record.messageId);
163
+ if (record.complete) this.finishMessage(message, record.message);
164
+ else if (Array.isArray(record.blocks)) {
165
+ for (const entry of record.blocks.slice(0, 64)) {
166
+ if (Array.isArray(entry) && Number.isSafeInteger(entry[0]) && typeof entry[1] === 'string') {
167
+ message.blocks.set(entry[0], entry[1].slice(-contentLimit));
168
+ }
169
+ }
170
+ } else if (typeof record.text === 'string') message.blocks.set(0, record.text.slice(-contentLimit));
171
+ message.truncated ||= record.truncated === true;
172
+ }
173
+
174
+ private message(agentId: string, id: string) {
175
+ const key = JSON.stringify([agentId, id]);
176
+ let current = this.messages.get(key);
177
+ if (!current) {
178
+ if (this.messages.size >= messageLimit) this.truncated = true;
179
+ current = { order: this.revision, agentId, id, role: 'assistant', blocks: new Map(), hidden: false, complete: false, truncated: false };
180
+ boundedMap(this.messages, key, current, messageLimit);
181
+ }
182
+ return current;
183
+ }
184
+
185
+ private finishMessage(message: Message, raw: unknown) {
186
+ const final = terminalObject(raw);
187
+ message.complete = true;
188
+ message.hidden = final.display === false;
189
+ message.role = typeof final.role === 'string' ? final.role : message.role;
190
+ if (final.truncated === true) {
191
+ message.truncated = true;
192
+ return;
193
+ }
194
+ message.blocks.clear();
195
+ if (!message.hidden) message.blocks.set(0, messageText(final));
196
+ }
197
+
198
+ private observe(raw: unknown) {
199
+ const item = terminalObject(raw);
200
+ const event = item.kind === 'agent' ? terminalObject(item.event) : item;
201
+ const author = event.agentId ?? event.agent ?? event.role;
202
+ const agentId = typeof author === 'string' ? author : '';
203
+ const eventName = String(event.type ?? item.kind ?? 'event');
204
+ if (event.type === 'subscriberGap') this.runtimeObservationLost = true;
205
+ if (event.type === 'error' &&
206
+ /worker event history has a gap/i.test(String(terminalObject(event.error).message))) this.workerHistoryLost = true;
207
+ if (event.type !== 'session') {
208
+ if (!['output', 'workerProbe'].includes(eventName)) this.rememberActivity(agentId, eventName, typeof raw === 'string' ? { text: raw } : event);
209
+ return;
210
+ }
211
+ const session = terminalObject(event.event);
212
+ const name = String(session.type ?? 'event');
213
+ if (typeof session.messageId === 'string') {
214
+ const message = this.message(agentId, session.messageId);
215
+ if (name === 'messageStart') {
216
+ if (typeof session.role === 'string') message.role = session.role;
217
+ message.hidden = session.display === false;
218
+ }
219
+ if (name === 'messageEnd') this.finishMessage(message, session.message);
220
+ if (name === 'textDelta' && !message.complete && typeof session.delta === 'string') {
221
+ const index = Number.isSafeInteger(session.blockIndex) ? Number(session.blockIndex) : 0;
222
+ const text = (message.blocks.get(index) ?? '') + session.delta;
223
+ message.truncated ||= text.length > contentLimit || message.blocks.size >= 64;
224
+ boundedMap(message.blocks, index, text.slice(-contentLimit), 64);
225
+ }
226
+ return;
227
+ }
228
+ this.rememberActivity(agentId, name, session);
229
+ }
230
+
231
+ private rememberActivity(agentId: string, event: string, detail: Record<string, unknown>) {
232
+ const toolKey = typeof detail.toolCallId === 'string' ? JSON.stringify([agentId, detail.toolCallId]) : undefined;
233
+ const text = [detail.summary, detail.message, detail.text, detail.toolName, detail.phase, detail.state, detail.status]
234
+ .find((value): value is string => typeof value === 'string');
235
+ const summary = text?.slice(0, 1024).replace(/\s+/g, ' ').slice(0, 280);
236
+ boundedMap(this.activity, toolKey ?? String(this.anonymousActivity++), {
237
+ order: this.revision, agentId, event: event.slice(0, 128), summary,
238
+ }, activityLimit);
239
+ }
240
+
241
+ async mutate(key: string, payload: unknown, send: (request: HarnessRequest) => Promise<unknown>) {
242
+ const previous = this.operations.get(key);
243
+ if (previous?.status === 'pending') return;
244
+ const retry = previous?.status === 'unknown' && isDeepStrictEqual(previous.payload, payload);
245
+ const preservePrevious = !retry && previous?.status === 'unknown';
246
+ if ((!this.operations.has(key) || preservePrevious) && this.operations.size >= maxPending) {
247
+ const settled = [...this.operations].find(([, item]) => item.status === 'confirmed' || item.status === 'failed');
248
+ if (!settled) throw new Error('Operation limit reached. Resolve an unknown operation before sending more.');
249
+ this.operations.delete(settled[0]);
250
+ }
251
+ if (preservePrevious) this.operations.set(key + ':' + previous.request.requestId, previous);
252
+ const operation: Mutation = retry ? previous : { payload, request: { requestId: randomUUID() }, send, status: 'pending' };
253
+ operation.status = 'pending';
254
+ this.operations.set(key, operation);
255
+ this.update();
256
+ try {
257
+ const receipt = await operation.send(operation.request);
258
+ operation.receipt = receipt;
259
+ operation.status = unresolvedHarnessReceipt(receipt) ? 'unknown' : 'confirmed';
260
+ return receipt;
261
+ } catch (error) {
262
+ const { code } = terminalObject(error);
263
+ operation.status = ['RPC_TIMEOUT', 'RPC_DISCONNECTED', 'OPERATION_UNKNOWN'].includes(String(code)) ? 'unknown' : 'failed';
264
+ operation.receipt = formatSessionError(error);
265
+ throw error;
266
+ } finally { if (!this.closed) this.update(); }
267
+ }
268
+
269
+ retry(key: string) {
270
+ const operation = this.operations.get(key);
271
+ if (operation?.status !== 'unknown') return;
272
+ return this.mutate(key, operation.payload, operation.send);
273
+ }
274
+
275
+ async read(key: string, query: () => Promise<unknown>) {
276
+ if (this.observations.get(key)?.pending || this.reading >= 4) return;
277
+ this.reading++;
278
+ boundedMap(this.observations, key, { pending: true }, 20);
279
+ this.update();
280
+ let timer: ReturnType<typeof setTimeout> | undefined;
281
+ const running = Promise.resolve().then(query);
282
+ void running.finally(() => { this.reading--; }).catch(() => {});
283
+ try {
284
+ const result = await Promise.race([running, new Promise<never>((_, reject) => {
285
+ timer = setTimeout(() => reject(new Error('Read timed out')), readTimeoutMs);
286
+ })]);
287
+ boundedMap(this.observations, key, { pending: false, result }, 20);
288
+ } catch (error) {
289
+ boundedMap(this.observations, key, { pending: false, error: formatSessionError(error) }, 20);
290
+ } finally {
291
+ clearTimeout(timer);
292
+ if (!this.closed) this.update();
293
+ }
294
+ }
295
+ }
@@ -0,0 +1,147 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ import { StdinBuffer, stripTerminalSequences, type Terminal } from '@earendil-works/pi-tui';
3
+
4
+ const beginPaste = '\x1b[200~';
5
+ const endPaste = '\x1b[201~';
6
+ const maxPasteBytes = 262_144;
7
+
8
+ export function terminalText(value: string) {
9
+ return stripTerminalSequences(value).replace(/\r\n?/g, '\n').replace(/\t/g, ' ')
10
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '');
11
+ }
12
+
13
+ export class AnySwarmTerminal implements Terminal {
14
+ readonly kittyProtocolActive = false;
15
+ private readonly input = process.stdin;
16
+ private readonly stdout = process.stdout;
17
+ private readonly transport = this.stdout.write.bind(this.stdout);
18
+ private readonly decoder = new StringDecoder('utf8');
19
+ private readonly keys = new StdinBuffer();
20
+ private resize?: () => void;
21
+ private inputCallback?: (data: string) => void;
22
+ private raw?: boolean;
23
+ private paused = true;
24
+ private partial = '';
25
+ private partialTimer?: ReturnType<typeof setTimeout>;
26
+
27
+ enableRawMode() {
28
+ if (this.raw !== undefined) return;
29
+ const previous = this.input.isRaw;
30
+ this.paused = this.input.isPaused();
31
+ this.input.setRawMode(true);
32
+ this.raw = previous;
33
+ }
34
+
35
+ get enabled() { return this.raw !== undefined; }
36
+ private paste?: string[];
37
+ private pasteBytes = 0;
38
+ private surrogate = '';
39
+
40
+ constructor(private readonly pasteRejected: () => void) {
41
+ this.keys.on('data', key => {
42
+ if (/^[\uD800-\uDBFF]$/.test(key)) {
43
+ this.surrogate = key;
44
+ return;
45
+ }
46
+ if (this.surrogate && /^[\uDC00-\uDFFF]$/.test(key)) key = this.surrogate + key;
47
+ this.surrogate = '';
48
+ this.inputCallback?.(key);
49
+ });
50
+ }
51
+
52
+ start(onInput: (data: string) => void, onResize: () => void) {
53
+ this.enableRawMode();
54
+ this.inputCallback = onInput;
55
+ this.resize = onResize;
56
+ this.input.on('data', this.data);
57
+ this.stdout.on('resize', onResize);
58
+ this.write('\x1b[?2004h');
59
+ this.input.resume();
60
+ }
61
+
62
+ stop() {
63
+ if (this.raw === undefined) return;
64
+ const previous = this.raw;
65
+ this.raw = undefined;
66
+ this.inputCallback = undefined;
67
+ this.input.off('data', this.data);
68
+ if (this.resize) this.stdout.off('resize', this.resize);
69
+ this.keys.destroy();
70
+ clearTimeout(this.partialTimer);
71
+ try { this.input.setRawMode(previous); }
72
+ finally {
73
+ if (this.paused || this.input.listenerCount('data') === 0) this.input.pause();
74
+ this.write('\x1b[?2004l\x1b[?25h');
75
+ }
76
+ }
77
+
78
+ // Keep just the possible delimiter suffix in memory while a paste is open.
79
+ // An oversize paste is discarded through its closing delimiter, including embedded keys.
80
+ private data = (chunk: Buffer | string) => {
81
+ clearTimeout(this.partialTimer);
82
+ let remaining = this.partial + (typeof chunk === 'string' ? chunk : this.decoder.write(chunk));
83
+ this.partial = '';
84
+ while (remaining) {
85
+ const delimiter = this.paste ? endPaste : beginPaste;
86
+ const index = remaining.indexOf(delimiter);
87
+ let end = index;
88
+ if (index < 0) {
89
+ end = remaining.length;
90
+ for (let size = Math.min(delimiter.length - 1, remaining.length); size > 0; size--) {
91
+ if (remaining.endsWith(delimiter.slice(0, size))) {
92
+ this.partial = remaining.slice(-size);
93
+ end -= size;
94
+ break;
95
+ }
96
+ }
97
+ }
98
+ const content = remaining.slice(0, end);
99
+ if (this.paste) {
100
+ this.pasteBytes += Buffer.byteLength(content);
101
+ if (this.pasteBytes <= maxPasteBytes) this.paste.push(content);
102
+ if (index >= 0) {
103
+ const pasted = this.paste;
104
+ this.paste = undefined;
105
+ if (this.pasteBytes > maxPasteBytes) this.pasteRejected();
106
+ else this.inputCallback?.(beginPaste + terminalText(pasted.join('')) + endPaste);
107
+ }
108
+ } else {
109
+ // The key buffer owns lone Escape and ordinary terminal key sequences.
110
+ if (content) this.keys.process(content);
111
+ if (index >= 0) {
112
+ this.paste = [];
113
+ this.pasteBytes = 0;
114
+ }
115
+ }
116
+ remaining = index >= 0 ? remaining.slice(index + delimiter.length) : '';
117
+ }
118
+ if (this.partial && !this.paste) {
119
+ this.partialTimer = setTimeout(() => {
120
+ const pending = this.partial;
121
+ this.partial = '';
122
+ this.keys.process(pending);
123
+ }, 30);
124
+ this.partialTimer.unref();
125
+ }
126
+ if (this.keys.getBuffer().length > 4096) this.keys.clear();
127
+ };
128
+
129
+ get columns() { return this.stdout.columns || 80; }
130
+ get rows() { return this.stdout.rows || 24; }
131
+ write(data: string) {
132
+ if (this.stdout.writableLength > 512 * 1024) throw new Error('Terminal output is not draining');
133
+ this.transport(data);
134
+ }
135
+ restoreDisplay() { this.transport('\x1b[?2026l\x1b[?2004l\x1b[?7h\x1b[?1049l\x1b[0m\x1b[?25h'); }
136
+ drained() { return new Promise<void>((resolve, reject) => this.transport('', error => error ? reject(error) : resolve())); }
137
+ async drainInput() {}
138
+ moveBy(lines: number) { if (lines) this.write('\x1b[' + Math.abs(lines) + (lines < 0 ? 'A' : 'B')); }
139
+ hideCursor() { this.write('\x1b[?25l'); }
140
+ showCursor() { this.write('\x1b[?25h'); }
141
+ clearLine() { this.write('\x1b[2K'); }
142
+ clearFromCursor() { this.write('\x1b[J'); }
143
+ clearScreen() { this.write('\x1b[2J\x1b[H'); }
144
+ setTitle() {}
145
+ setProgress() {}
146
+ setProgramStatus() {}
147
+ }