@stateset/sandbox-cli 1.0.6 → 3.4.0

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 (431) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/LICENSE +22 -0
  3. package/README.md +940 -6
  4. package/dist/client.d.ts +789 -10
  5. package/dist/client.d.ts.map +1 -1
  6. package/dist/client.js +694 -12
  7. package/dist/client.js.map +1 -1
  8. package/dist/commands/alias.d.ts +5 -0
  9. package/dist/commands/alias.d.ts.map +1 -0
  10. package/dist/commands/alias.js +131 -0
  11. package/dist/commands/alias.js.map +1 -0
  12. package/dist/commands/api-key.d.ts +3 -0
  13. package/dist/commands/api-key.d.ts.map +1 -0
  14. package/dist/commands/api-key.js +119 -0
  15. package/dist/commands/api-key.js.map +1 -0
  16. package/dist/commands/artifact.d.ts.map +1 -1
  17. package/dist/commands/artifact.js +105 -46
  18. package/dist/commands/artifact.js.map +1 -1
  19. package/dist/commands/audit.d.ts +3 -0
  20. package/dist/commands/audit.d.ts.map +1 -0
  21. package/dist/commands/audit.js +191 -0
  22. package/dist/commands/audit.js.map +1 -0
  23. package/dist/commands/auth.d.ts +3 -0
  24. package/dist/commands/auth.d.ts.map +1 -0
  25. package/dist/commands/auth.js +126 -0
  26. package/dist/commands/auth.js.map +1 -0
  27. package/dist/commands/benchmark.d.ts +3 -0
  28. package/dist/commands/benchmark.d.ts.map +1 -0
  29. package/dist/commands/benchmark.js +166 -0
  30. package/dist/commands/benchmark.js.map +1 -0
  31. package/dist/commands/billing.d.ts +3 -0
  32. package/dist/commands/billing.d.ts.map +1 -0
  33. package/dist/commands/billing.js +139 -0
  34. package/dist/commands/billing.js.map +1 -0
  35. package/dist/commands/checkpoint.d.ts.map +1 -1
  36. package/dist/commands/checkpoint.js +105 -48
  37. package/dist/commands/checkpoint.js.map +1 -1
  38. package/dist/commands/completion.d.ts +3 -0
  39. package/dist/commands/completion.d.ts.map +1 -0
  40. package/dist/commands/completion.js +134 -0
  41. package/dist/commands/completion.js.map +1 -0
  42. package/dist/commands/computer-use.d.ts +3 -0
  43. package/dist/commands/computer-use.d.ts.map +1 -0
  44. package/dist/commands/computer-use.js +124 -0
  45. package/dist/commands/computer-use.js.map +1 -0
  46. package/dist/commands/config.d.ts.map +1 -1
  47. package/dist/commands/config.js +2 -1
  48. package/dist/commands/config.js.map +1 -1
  49. package/dist/commands/context.d.ts +3 -0
  50. package/dist/commands/context.d.ts.map +1 -0
  51. package/dist/commands/context.js +98 -0
  52. package/dist/commands/context.js.map +1 -0
  53. package/dist/commands/cp.d.ts +3 -0
  54. package/dist/commands/cp.d.ts.map +1 -0
  55. package/dist/commands/cp.js +165 -0
  56. package/dist/commands/cp.js.map +1 -0
  57. package/dist/commands/deploy.d.ts +3 -0
  58. package/dist/commands/deploy.d.ts.map +1 -1
  59. package/dist/commands/deploy.js +68 -20
  60. package/dist/commands/deploy.js.map +1 -1
  61. package/dist/commands/diff.d.ts +3 -0
  62. package/dist/commands/diff.d.ts.map +1 -0
  63. package/dist/commands/diff.js +186 -0
  64. package/dist/commands/diff.js.map +1 -0
  65. package/dist/commands/doctor.d.ts +30 -0
  66. package/dist/commands/doctor.d.ts.map +1 -1
  67. package/dist/commands/doctor.js +177 -207
  68. package/dist/commands/doctor.js.map +1 -1
  69. package/dist/commands/egress.d.ts +3 -0
  70. package/dist/commands/egress.d.ts.map +1 -0
  71. package/dist/commands/egress.js +155 -0
  72. package/dist/commands/egress.js.map +1 -0
  73. package/dist/commands/env.d.ts +3 -0
  74. package/dist/commands/env.d.ts.map +1 -0
  75. package/dist/commands/env.js +169 -0
  76. package/dist/commands/env.js.map +1 -0
  77. package/dist/commands/governance.d.ts +47 -0
  78. package/dist/commands/governance.d.ts.map +1 -0
  79. package/dist/commands/governance.js +345 -0
  80. package/dist/commands/governance.js.map +1 -0
  81. package/dist/commands/grade.d.ts +41 -0
  82. package/dist/commands/grade.d.ts.map +1 -1
  83. package/dist/commands/grade.js +255 -160
  84. package/dist/commands/grade.js.map +1 -1
  85. package/dist/commands/history.d.ts +4 -0
  86. package/dist/commands/history.d.ts.map +1 -0
  87. package/dist/commands/history.js +157 -0
  88. package/dist/commands/history.js.map +1 -0
  89. package/dist/commands/images.d.ts +8 -0
  90. package/dist/commands/images.d.ts.map +1 -0
  91. package/dist/commands/images.js +145 -0
  92. package/dist/commands/images.js.map +1 -0
  93. package/dist/commands/info.d.ts +3 -0
  94. package/dist/commands/info.d.ts.map +1 -0
  95. package/dist/commands/info.js +86 -0
  96. package/dist/commands/info.js.map +1 -0
  97. package/dist/commands/init.d.ts +3 -0
  98. package/dist/commands/init.d.ts.map +1 -0
  99. package/dist/commands/init.js +185 -0
  100. package/dist/commands/init.js.map +1 -0
  101. package/dist/commands/logs.d.ts +3 -0
  102. package/dist/commands/logs.d.ts.map +1 -0
  103. package/dist/commands/logs.js +129 -0
  104. package/dist/commands/logs.js.map +1 -0
  105. package/dist/commands/mcp.d.ts +3 -0
  106. package/dist/commands/mcp.d.ts.map +1 -0
  107. package/dist/commands/mcp.js +141 -0
  108. package/dist/commands/mcp.js.map +1 -0
  109. package/dist/commands/open.d.ts +3 -0
  110. package/dist/commands/open.d.ts.map +1 -0
  111. package/dist/commands/open.js +96 -0
  112. package/dist/commands/open.js.map +1 -0
  113. package/dist/commands/platform-status.d.ts +25 -5
  114. package/dist/commands/platform-status.d.ts.map +1 -1
  115. package/dist/commands/platform-status.js +199 -149
  116. package/dist/commands/platform-status.js.map +1 -1
  117. package/dist/commands/plugin.d.ts +5 -0
  118. package/dist/commands/plugin.d.ts.map +1 -0
  119. package/dist/commands/plugin.js +126 -0
  120. package/dist/commands/plugin.js.map +1 -0
  121. package/dist/commands/pool.d.ts.map +1 -1
  122. package/dist/commands/pool.js +52 -66
  123. package/dist/commands/pool.js.map +1 -1
  124. package/dist/commands/profile.d.ts +3 -0
  125. package/dist/commands/profile.d.ts.map +1 -0
  126. package/dist/commands/profile.js +107 -0
  127. package/dist/commands/profile.js.map +1 -0
  128. package/dist/commands/repl.d.ts +3 -0
  129. package/dist/commands/repl.d.ts.map +1 -0
  130. package/dist/commands/repl.js +390 -0
  131. package/dist/commands/repl.js.map +1 -0
  132. package/dist/commands/run.d.ts +3 -0
  133. package/dist/commands/run.d.ts.map +1 -0
  134. package/dist/commands/run.js +154 -0
  135. package/dist/commands/run.js.map +1 -0
  136. package/dist/commands/sandbox-processes.d.ts +27 -0
  137. package/dist/commands/sandbox-processes.d.ts.map +1 -0
  138. package/dist/commands/sandbox-processes.js +195 -0
  139. package/dist/commands/sandbox-processes.js.map +1 -0
  140. package/dist/commands/sandbox.d.ts.map +1 -1
  141. package/dist/commands/sandbox.js +562 -108
  142. package/dist/commands/sandbox.js.map +1 -1
  143. package/dist/commands/secret.d.ts +3 -0
  144. package/dist/commands/secret.d.ts.map +1 -0
  145. package/dist/commands/secret.js +128 -0
  146. package/dist/commands/secret.js.map +1 -0
  147. package/dist/commands/session.d.ts.map +1 -1
  148. package/dist/commands/session.js +285 -52
  149. package/dist/commands/session.js.map +1 -1
  150. package/dist/commands/snapshot.d.ts +3 -0
  151. package/dist/commands/snapshot.d.ts.map +1 -0
  152. package/dist/commands/snapshot.js +253 -0
  153. package/dist/commands/snapshot.js.map +1 -0
  154. package/dist/commands/ssh.d.ts +5 -0
  155. package/dist/commands/ssh.d.ts.map +1 -0
  156. package/dist/commands/ssh.js +154 -0
  157. package/dist/commands/ssh.js.map +1 -0
  158. package/dist/commands/swarm.d.ts +12 -0
  159. package/dist/commands/swarm.d.ts.map +1 -0
  160. package/dist/commands/swarm.js +288 -0
  161. package/dist/commands/swarm.js.map +1 -0
  162. package/dist/commands/template.d.ts +3 -0
  163. package/dist/commands/template.d.ts.map +1 -0
  164. package/dist/commands/template.js +102 -0
  165. package/dist/commands/template.js.map +1 -0
  166. package/dist/commands/terminal.d.ts +55 -0
  167. package/dist/commands/terminal.d.ts.map +1 -0
  168. package/dist/commands/terminal.js +438 -0
  169. package/dist/commands/terminal.js.map +1 -0
  170. package/dist/commands/top.d.ts +3 -0
  171. package/dist/commands/top.d.ts.map +1 -0
  172. package/dist/commands/top.js +116 -0
  173. package/dist/commands/top.js.map +1 -0
  174. package/dist/commands/tunnel.d.ts.map +1 -1
  175. package/dist/commands/tunnel.js +73 -26
  176. package/dist/commands/tunnel.js.map +1 -1
  177. package/dist/commands/update.d.ts +3 -0
  178. package/dist/commands/update.d.ts.map +1 -0
  179. package/dist/commands/update.js +51 -0
  180. package/dist/commands/update.js.map +1 -0
  181. package/dist/commands/wait.d.ts +3 -0
  182. package/dist/commands/wait.d.ts.map +1 -0
  183. package/dist/commands/wait.js +64 -0
  184. package/dist/commands/wait.js.map +1 -0
  185. package/dist/commands/webhook.d.ts +3 -0
  186. package/dist/commands/webhook.d.ts.map +1 -0
  187. package/dist/commands/webhook.js +169 -0
  188. package/dist/commands/webhook.js.map +1 -0
  189. package/dist/commands/workbench.d.ts +138 -0
  190. package/dist/commands/workbench.d.ts.map +1 -0
  191. package/dist/commands/workbench.js +531 -0
  192. package/dist/commands/workbench.js.map +1 -0
  193. package/dist/config.d.ts +14 -6
  194. package/dist/config.d.ts.map +1 -1
  195. package/dist/config.js +109 -16
  196. package/dist/config.js.map +1 -1
  197. package/dist/index.js +169 -11
  198. package/dist/index.js.map +1 -1
  199. package/dist/sandboxctl.d.ts +3 -0
  200. package/dist/sandboxctl.d.ts.map +1 -0
  201. package/dist/sandboxctl.js +37 -0
  202. package/dist/sandboxctl.js.map +1 -0
  203. package/dist/utils/context.d.ts +23 -0
  204. package/dist/utils/context.d.ts.map +1 -0
  205. package/dist/utils/context.js +48 -0
  206. package/dist/utils/context.js.map +1 -0
  207. package/dist/utils/credentials.d.ts +8 -0
  208. package/dist/utils/credentials.d.ts.map +1 -0
  209. package/dist/utils/credentials.js +120 -0
  210. package/dist/utils/credentials.js.map +1 -0
  211. package/dist/utils/dry-run.d.ts +4 -0
  212. package/dist/utils/dry-run.d.ts.map +1 -0
  213. package/dist/utils/dry-run.js +24 -0
  214. package/dist/utils/dry-run.js.map +1 -0
  215. package/dist/utils/egress-policy.d.ts +31 -0
  216. package/dist/utils/egress-policy.d.ts.map +1 -0
  217. package/dist/utils/egress-policy.js +83 -0
  218. package/dist/utils/egress-policy.js.map +1 -0
  219. package/dist/utils/errors.d.ts +53 -0
  220. package/dist/utils/errors.d.ts.map +1 -0
  221. package/dist/utils/errors.js +278 -0
  222. package/dist/utils/errors.js.map +1 -0
  223. package/dist/utils/file-content.d.ts +10 -0
  224. package/dist/utils/file-content.d.ts.map +1 -0
  225. package/dist/utils/file-content.js +14 -0
  226. package/dist/utils/file-content.js.map +1 -0
  227. package/dist/utils/grade-target.d.ts +12 -0
  228. package/dist/utils/grade-target.d.ts.map +1 -0
  229. package/dist/utils/grade-target.js +106 -0
  230. package/dist/utils/grade-target.js.map +1 -0
  231. package/dist/utils/health-report.d.ts +18 -0
  232. package/dist/utils/health-report.d.ts.map +1 -0
  233. package/dist/utils/health-report.js +43 -0
  234. package/dist/utils/health-report.js.map +1 -0
  235. package/dist/utils/output.d.ts +20 -0
  236. package/dist/utils/output.d.ts.map +1 -0
  237. package/dist/utils/output.js +123 -0
  238. package/dist/utils/output.js.map +1 -0
  239. package/dist/utils/plugins.d.ts +17 -0
  240. package/dist/utils/plugins.d.ts.map +1 -0
  241. package/dist/utils/plugins.js +57 -0
  242. package/dist/utils/plugins.js.map +1 -0
  243. package/dist/utils/resource-class.d.ts +12 -0
  244. package/dist/utils/resource-class.d.ts.map +1 -0
  245. package/dist/utils/resource-class.js +17 -0
  246. package/dist/utils/resource-class.js.map +1 -0
  247. package/dist/utils/shutdown.d.ts +14 -0
  248. package/dist/utils/shutdown.d.ts.map +1 -0
  249. package/dist/utils/shutdown.js +54 -0
  250. package/dist/utils/shutdown.js.map +1 -0
  251. package/dist/utils/swarm-plan.d.ts +69 -0
  252. package/dist/utils/swarm-plan.d.ts.map +1 -0
  253. package/dist/utils/swarm-plan.js +321 -0
  254. package/dist/utils/swarm-plan.js.map +1 -0
  255. package/dist/utils/template-create.d.ts +36 -0
  256. package/dist/utils/template-create.d.ts.map +1 -0
  257. package/dist/utils/template-create.js +116 -0
  258. package/dist/utils/template-create.js.map +1 -0
  259. package/dist/utils/tty.d.ts +44 -0
  260. package/dist/utils/tty.d.ts.map +1 -0
  261. package/dist/utils/tty.js +93 -0
  262. package/dist/utils/tty.js.map +1 -0
  263. package/dist/utils/warnings.d.ts +4 -0
  264. package/dist/utils/warnings.d.ts.map +1 -0
  265. package/dist/utils/warnings.js +22 -0
  266. package/dist/utils/warnings.js.map +1 -0
  267. package/dist/utils/watch.d.ts +7 -0
  268. package/dist/utils/watch.d.ts.map +1 -0
  269. package/dist/utils/watch.js +55 -0
  270. package/dist/utils/watch.js.map +1 -0
  271. package/dist/workbench/actions.d.ts +26 -0
  272. package/dist/workbench/actions.d.ts.map +1 -0
  273. package/dist/workbench/actions.js +39 -0
  274. package/dist/workbench/actions.js.map +1 -0
  275. package/dist/workbench/agent-chat.d.ts +71 -0
  276. package/dist/workbench/agent-chat.d.ts.map +1 -0
  277. package/dist/workbench/agent-chat.js +223 -0
  278. package/dist/workbench/agent-chat.js.map +1 -0
  279. package/dist/workbench/agents.d.ts +96 -0
  280. package/dist/workbench/agents.d.ts.map +1 -0
  281. package/dist/workbench/agents.js +370 -0
  282. package/dist/workbench/agents.js.map +1 -0
  283. package/dist/workbench/batch-uploads.d.ts +36 -0
  284. package/dist/workbench/batch-uploads.d.ts.map +1 -0
  285. package/dist/workbench/batch-uploads.js +154 -0
  286. package/dist/workbench/batch-uploads.js.map +1 -0
  287. package/dist/workbench/commands.d.ts +6 -0
  288. package/dist/workbench/commands.d.ts.map +1 -0
  289. package/dist/workbench/commands.js +517 -0
  290. package/dist/workbench/commands.js.map +1 -0
  291. package/dist/workbench/connection-failure.d.ts +9 -0
  292. package/dist/workbench/connection-failure.d.ts.map +1 -0
  293. package/dist/workbench/connection-failure.js +27 -0
  294. package/dist/workbench/connection-failure.js.map +1 -0
  295. package/dist/workbench/connection.d.ts +4 -0
  296. package/dist/workbench/connection.d.ts.map +1 -0
  297. package/dist/workbench/connection.js +28 -0
  298. package/dist/workbench/connection.js.map +1 -0
  299. package/dist/workbench/creation.d.ts +22 -0
  300. package/dist/workbench/creation.d.ts.map +1 -0
  301. package/dist/workbench/creation.js +102 -0
  302. package/dist/workbench/creation.js.map +1 -0
  303. package/dist/workbench/credits.d.ts +11 -0
  304. package/dist/workbench/credits.d.ts.map +1 -0
  305. package/dist/workbench/credits.js +132 -0
  306. package/dist/workbench/credits.js.map +1 -0
  307. package/dist/workbench/docker.d.ts +18 -0
  308. package/dist/workbench/docker.d.ts.map +1 -0
  309. package/dist/workbench/docker.js +207 -0
  310. package/dist/workbench/docker.js.map +1 -0
  311. package/dist/workbench/execution.d.ts +14 -0
  312. package/dist/workbench/execution.d.ts.map +1 -0
  313. package/dist/workbench/execution.js +24 -0
  314. package/dist/workbench/execution.js.map +1 -0
  315. package/dist/workbench/files.d.ts +51 -0
  316. package/dist/workbench/files.d.ts.map +1 -0
  317. package/dist/workbench/files.js +80 -0
  318. package/dist/workbench/files.js.map +1 -0
  319. package/dist/workbench/history.d.ts +34 -0
  320. package/dist/workbench/history.d.ts.map +1 -0
  321. package/dist/workbench/history.js +50 -0
  322. package/dist/workbench/history.js.map +1 -0
  323. package/dist/workbench/input-batch-commands.d.ts +6 -0
  324. package/dist/workbench/input-batch-commands.d.ts.map +1 -0
  325. package/dist/workbench/input-batch-commands.js +41 -0
  326. package/dist/workbench/input-batch-commands.js.map +1 -0
  327. package/dist/workbench/kitty-diacritics.d.ts +2 -0
  328. package/dist/workbench/kitty-diacritics.d.ts.map +1 -0
  329. package/dist/workbench/kitty-diacritics.js +22 -0
  330. package/dist/workbench/kitty-diacritics.js.map +1 -0
  331. package/dist/workbench/kitty-graphics.d.ts +59 -0
  332. package/dist/workbench/kitty-graphics.d.ts.map +1 -0
  333. package/dist/workbench/kitty-graphics.js +263 -0
  334. package/dist/workbench/kitty-graphics.js.map +1 -0
  335. package/dist/workbench/live-execution.d.ts +51 -0
  336. package/dist/workbench/live-execution.d.ts.map +1 -0
  337. package/dist/workbench/live-execution.js +222 -0
  338. package/dist/workbench/live-execution.js.map +1 -0
  339. package/dist/workbench/model.d.ts +110 -0
  340. package/dist/workbench/model.d.ts.map +1 -0
  341. package/dist/workbench/model.js +249 -0
  342. package/dist/workbench/model.js.map +1 -0
  343. package/dist/workbench/overview.d.ts +11 -0
  344. package/dist/workbench/overview.d.ts.map +1 -0
  345. package/dist/workbench/overview.js +92 -0
  346. package/dist/workbench/overview.js.map +1 -0
  347. package/dist/workbench/png.d.ts +10 -0
  348. package/dist/workbench/png.d.ts.map +1 -0
  349. package/dist/workbench/png.js +51 -0
  350. package/dist/workbench/png.js.map +1 -0
  351. package/dist/workbench/python-task.d.ts +21 -0
  352. package/dist/workbench/python-task.d.ts.map +1 -0
  353. package/dist/workbench/python-task.js +52 -0
  354. package/dist/workbench/python-task.js.map +1 -0
  355. package/dist/workbench/registry-commands.d.ts +8 -0
  356. package/dist/workbench/registry-commands.d.ts.map +1 -0
  357. package/dist/workbench/registry-commands.js +93 -0
  358. package/dist/workbench/registry-commands.js.map +1 -0
  359. package/dist/workbench/registry.d.ts +76 -0
  360. package/dist/workbench/registry.d.ts.map +1 -0
  361. package/dist/workbench/registry.js +353 -0
  362. package/dist/workbench/registry.js.map +1 -0
  363. package/dist/workbench/renderer.d.ts +6 -0
  364. package/dist/workbench/renderer.d.ts.map +1 -0
  365. package/dist/workbench/renderer.js +18 -0
  366. package/dist/workbench/renderer.js.map +1 -0
  367. package/dist/workbench/results.d.ts +15 -0
  368. package/dist/workbench/results.d.ts.map +1 -0
  369. package/dist/workbench/results.js +29 -0
  370. package/dist/workbench/results.js.map +1 -0
  371. package/dist/workbench/task-archive.d.ts +23 -0
  372. package/dist/workbench/task-archive.d.ts.map +1 -0
  373. package/dist/workbench/task-archive.js +56 -0
  374. package/dist/workbench/task-archive.js.map +1 -0
  375. package/dist/workbench/task-board.d.ts +26 -0
  376. package/dist/workbench/task-board.d.ts.map +1 -0
  377. package/dist/workbench/task-board.js +43 -0
  378. package/dist/workbench/task-board.js.map +1 -0
  379. package/dist/workbench/task-monitor.d.ts +35 -0
  380. package/dist/workbench/task-monitor.d.ts.map +1 -0
  381. package/dist/workbench/task-monitor.js +176 -0
  382. package/dist/workbench/task-monitor.js.map +1 -0
  383. package/dist/workbench/tasks.d.ts +93 -0
  384. package/dist/workbench/tasks.d.ts.map +1 -0
  385. package/dist/workbench/tasks.js +195 -0
  386. package/dist/workbench/tasks.js.map +1 -0
  387. package/dist/workbench/terminal.d.ts +82 -0
  388. package/dist/workbench/terminal.d.ts.map +1 -0
  389. package/dist/workbench/terminal.js +2607 -0
  390. package/dist/workbench/terminal.js.map +1 -0
  391. package/dist/workbench/text.d.ts +10 -0
  392. package/dist/workbench/text.d.ts.map +1 -0
  393. package/dist/workbench/text.js +72 -0
  394. package/dist/workbench/text.js.map +1 -0
  395. package/dist/workbench/uploads.d.ts +12 -0
  396. package/dist/workbench/uploads.d.ts.map +1 -0
  397. package/dist/workbench/uploads.js +16 -0
  398. package/dist/workbench/uploads.js.map +1 -0
  399. package/dist/workbench/worker-launch.d.ts +10 -0
  400. package/dist/workbench/worker-launch.d.ts.map +1 -0
  401. package/dist/workbench/worker-launch.js +30 -0
  402. package/dist/workbench/worker-launch.js.map +1 -0
  403. package/dist/workbench/worker-monitor.d.ts +33 -0
  404. package/dist/workbench/worker-monitor.d.ts.map +1 -0
  405. package/dist/workbench/worker-monitor.js +142 -0
  406. package/dist/workbench/worker-monitor.js.map +1 -0
  407. package/dist/workbench/worker-output.d.ts +8 -0
  408. package/dist/workbench/worker-output.d.ts.map +1 -0
  409. package/dist/workbench/worker-output.js +32 -0
  410. package/dist/workbench/worker-output.js.map +1 -0
  411. package/dist/workbench/worker-result.d.ts +29 -0
  412. package/dist/workbench/worker-result.d.ts.map +1 -0
  413. package/dist/workbench/worker-result.js +85 -0
  414. package/dist/workbench/worker-result.js.map +1 -0
  415. package/dist/workbench/workers.d.ts +49 -0
  416. package/dist/workbench/workers.d.ts.map +1 -0
  417. package/dist/workbench/workers.js +53 -0
  418. package/dist/workbench/workers.js.map +1 -0
  419. package/package.json +38 -17
  420. package/dist/__tests__/client.test.d.ts +0 -2
  421. package/dist/__tests__/client.test.d.ts.map +0 -1
  422. package/dist/__tests__/client.test.js +0 -198
  423. package/dist/__tests__/client.test.js.map +0 -1
  424. package/dist/__tests__/config.test.d.ts +0 -2
  425. package/dist/__tests__/config.test.d.ts.map +0 -1
  426. package/dist/__tests__/config.test.js +0 -74
  427. package/dist/__tests__/config.test.js.map +0 -1
  428. package/dist/__tests__/utils-cli.test.d.ts +0 -2
  429. package/dist/__tests__/utils-cli.test.d.ts.map +0 -1
  430. package/dist/__tests__/utils-cli.test.js +0 -35
  431. package/dist/__tests__/utils-cli.test.js.map +0 -1
@@ -0,0 +1,2607 @@
1
+ import { TerminalRenderer } from './renderer.js';
2
+ import { backspaceText, clipCells, limitText, padCells, printableInput, wrapCells } from './text.js';
3
+ import { emitKeypressEvents } from 'node:readline';
4
+ import { PassThrough } from 'node:stream';
5
+ import { KittyGraphics } from './kitty-graphics.js';
6
+ import { getShutdownManager } from '../utils/shutdown.js';
7
+ import { sandboxRow, terminalText, stripTerminalStyles } from './model.js';
8
+ import { creditAmountCents, creditPurchaseUrl, subscriptionUrl } from './credits.js';
9
+ import { COMMAND_LIMIT, commandReceipt } from './execution.js';
10
+ import { creationDraft, creationLines, creationRequest, creationTextFields, creationFieldLimit, resourceClasses, inferenceProviders } from './creation.js';
11
+ import { overviewLines, shortId, timeLeft } from './overview.js';
12
+ import { filterActions, workbenchActions } from './actions.js';
13
+ import { agentCell, agentColumns, agentDetailLines, agentLines, agentSummary } from './agents.js';
14
+ import { connectionLines, snapshotStale } from './connection.js';
15
+ import { randomUUID } from 'node:crypto';
16
+ import { workerLines, workerRow } from './workers.js';
17
+ import { executionReceipt, executionRow, historyLines } from './history.js';
18
+ import { workerResultLines } from './worker-result.js';
19
+ import { WorkerMonitor, workerRefreshStatus } from './worker-monitor.js';
20
+ import { workerLaunchDraft, workerLaunchLines, workerLaunchRequest } from './worker-launch.js';
21
+ import { LiveExecution } from './live-execution.js';
22
+ import { PYTHON_LIMIT, PYTHON_EXAMPLE, pythonTask, preparePythonTask, pythonLines } from './python-task.js';
23
+ import { FILE_LIMIT, workspacePath, fileRows, filesLines, filePreview, decodeFile, downloadDestination, downloadFile } from './files.js';
24
+ import { posix } from 'node:path';
25
+ import { delegationDraft, delegationFields, editDelegation, delegationInput, planDelegation, delegationLines, taskBoardLines } from './tasks.js';
26
+ import { readTaskResultArtifact, TaskResultCollectionError } from '@stateset/sandbox-sdk/node';
27
+ import { resultLines } from './results.js';
28
+ import { taskArchive, readTaskArchive, taskArchiveLines } from './task-archive.js';
29
+ import { uploadLines } from './uploads.js';
30
+ import { BatchUploadController, batchUploadLines } from './batch-uploads.js';
31
+ import { taskViewModes, reconcileTaskSelection, hasTaskFilters, clearTaskFilters, validateTaskFocus } from './task-board.js';
32
+ import { chatLines, chatStatus, chatRequests, beginChatControl, chatReceiptTargets, markChatReceiptAttempt, observeChatReceipt, restoreChatDraft, discardChatDraft } from './agent-chat.js';
33
+ import { TaskMonitor, taskRefreshStatus } from './task-monitor.js';
34
+ import { RegistryController, registryView, registryLines } from './registry.js';
35
+ import { AgentChatInputError, AgentChatSendError, AgentChatInputCapabilityError } from '@stateset/sandbox-sdk/node';
36
+ const help = [
37
+ 'NAVIGATE',
38
+ 'F2 or :: searchable actions with availability explanations',
39
+ 'Action menu: type to filter, arrows to choose, Enter opens, Esc returns.',
40
+ 'Server task registry: F2 then registry; u from a private task; metadata and grants only',
41
+ 'c: connection diagnostics, snapshot age and full refresh errors',
42
+ 'g: launch a prepared agent command as a supervised worker (hosted API)',
43
+ 'Worker launch: Tab chooses command, recovery name and runtime; Enter reviews.',
44
+ 'w: workers; Enter reads logs, v opens outcome and output, d reviews stop',
45
+ 'Worker results: l opens logs, r refreshes, Esc returns; tasks keep running.',
46
+ 'h: recover execution history and saved receipts without rerunning',
47
+ 'i: Python code interpreter; edit source, name and runtime; Enter reviews',
48
+ 'f: workspace files and artifacts; Enter previews, d reviews download',
49
+ 'PNG previews: v toggles inline image / full details; --graphics off uses text only.',
50
+ 'Workspace files: u uploads one input; i prepares/recovers a multi-file input batch',
51
+ 'm: agent task board across sandboxes; Enter inspects a saved task',
52
+ 'Task board: / finds tasks, t filters observed states, p shows a parent family, a clears',
53
+ 'l: delegate a named task to a prepared agent; Tab selects task fields',
54
+ 'Task detail: c collect artifacts, b saved bundles, v result, f files, g child, d stop',
55
+ 'Task board: b opens saved results for up to 16 visible tasks; Enter verifies files.',
56
+ 'Task detail: s opens a prepared conversation; i composes, x reviews interrupting its turn',
57
+ 'Agent chat: b opens saved bundles offline; f opens task files; Esc returns to chat.',
58
+ 'j/k or Up/Down: select a sandbox',
59
+ 'PageUp/PageDown: move one page; Home/End: first/last',
60
+ '/: search IDs, statuses, agent names and creating Herdr panes',
61
+ 'Enter: apply search or open selected sandbox details',
62
+ 'Esc: cancel search, clear filter or return to the list',
63
+ '?: open this help; r: refresh shared state',
64
+ 'a: open session activity for all sandboxes',
65
+ 'o: overview of statuses, running allocations and upcoming expiries',
66
+ 'v: agents recorded under --agents directories, by fleet, with phase, branch and pull request',
67
+ 'Workbenches of the current repository (stateset workbench up) are recorded without --agents.',
68
+ 'AGENT and PHASE columns come from those records; Enter adds task, objective, cost and errors.',
69
+ '* marks likely duplicates: agents still working under matching names; details name the pair.',
70
+ 't: cycle list sort: ID, expiry, status, newest; selection stays pinned',
71
+ 'TIME LEFT: ! warns at 2 minutes; due awaits backend status.',
72
+ 'b: buy prepaid credits through your browser and Stripe',
73
+ 's: start or reactivate a subscription in owner billing',
74
+ '',
75
+ 'SANDBOX ACTIONS (from the list)',
76
+ 'n: choose CPU, memory and lifetime; Enter reviews, y creates',
77
+ 'Creation form: Tab/Up/Down selects; type replaces; Ctrl+U clears.',
78
+ 'p/u: pause/resume; e: extend the selected sandbox',
79
+ 'd: stop the selected full ID; y confirms, Esc cancels',
80
+ 'x: run a shell command in the selected running sandbox',
81
+ 'Type or paste; Enter reviews, y runs; Ctrl+U clears input.',
82
+ 'Output streams live; z reviews cancellation; r recovers a saved receipt.',
83
+ 'Esc leaves the run active. j/k scroll; x edits another command after completion.',
84
+ 'Read-only mode disables all mutations.',
85
+ 'Failed refreshes retain stale rows and disable lifecycle actions.',
86
+ '',
87
+ 'SHARED WORKSPACE',
88
+ 'Other agents use sandboxctl JSON commands in their own panes.',
89
+ 'Local Docker rows show the creating Herdr pane when available.',
90
+ 'q or Ctrl+C: quit; sandboxes and submitted actions stay alive.',
91
+ ];
92
+ function pageSize(height) {
93
+ return Math.max(1, Math.min(200, height) - 8);
94
+ }
95
+ /** The list and the agents screen keep one row for the note about skipped agent records. */
96
+ function noteRows(model, view, height) {
97
+ return model.agents.note && height >= 10 && (!view.screen || view.screen === 'list' || view.screen === 'agents') ? 1 : 0;
98
+ }
99
+ /** The only styling in a frame, added after cleaning so that none of it comes from data. */
100
+ function dim(line) { return line ? `\x1b[2m${line}\x1b[22m` : line; }
101
+ function availableActions(model, options, id, now = Date.now()) {
102
+ return workbenchActions({ row: model.rows.find(row => row.id === id), busy: model.busy,
103
+ readOnly: options.readOnly, backend: options.backend || 'api', connected: Boolean(model.lastUpdated),
104
+ stale: snapshotStale(model, options.intervalMs, now), workers: Boolean(model.api.processes), history: Boolean(model.api.executions),
105
+ python: Boolean(model.api.executeStream && model.api.mkdir && model.api.writeFile), files: Boolean(model.api.listFiles && model.api.readFile), tasks: Boolean(model.api.tasks), registry: Boolean(model.api.taskRegistry), inputBatches: Boolean(model.api.inputBatches) });
106
+ }
107
+ function canEditCommand(model, options, id, now = Date.now()) {
108
+ return !model.busy && !options.readOnly && !snapshotStale(model, options.intervalMs, now)
109
+ && model.rows.some(row => row.id === id && row.status === 'running');
110
+ }
111
+ function screenContent(model, options, width, view, now = Date.now()) {
112
+ const row = view.detailId ? model.rows.find(row => row.id === view.detailId) : model.selected;
113
+ const actions = filterActions(availableActions(model, options, view.actionTarget, now), view.actionQuery);
114
+ const selectedAction = actions.find(action => action.id === view.actionSelected) || actions[0];
115
+ const content = view.screen === 'taskRegistry' && view.registry ? registryLines(view.registry, Boolean(options.readOnly))
116
+ : view.screen === 'inputBatch' && view.inputBatch ? batchUploadLines(view.inputBatch, Boolean(options.readOnly))
117
+ : view.screen === 'upload' && view.upload ? uploadLines(view.upload)
118
+ : view.screen === 'agentChat' && view.chat ? chatLines(view.chat, Boolean(options.readOnly))
119
+ : view.screen === 'delegate' && view.delegation ? delegationLines(view.delegation)
120
+ : view.screen === 'taskResults' && view.results ? resultLines(view.results)
121
+ : view.screen === 'taskArchive' && view.archive ? taskArchiveLines(view.archive)
122
+ : (view.screen === 'tasks' || view.screen === 'task') && view.tasks ? taskBoardLines(view.tasks, view.screen === 'task', width)
123
+ : view.screen === 'files' && view.files ? filesLines(view.files)
124
+ : (view.screen === 'history' || view.screen === 'receipt') && view.history ? historyLines(view.history, view.screen === 'receipt')
125
+ : view.screen === 'workerResult' && view.workers ? [
126
+ ...(view.workers.error ? [`STALE / unavailable: ${view.workers.error}`] : []),
127
+ ...workerResultLines(view.workers.result, view.workers.sandboxId, view.workers.resultId, view.workers.resultUpdatedAt),
128
+ ]
129
+ : (view.screen === 'workers' || view.screen === 'workerLogs') && view.workers ? [...workerLines(view.workers, view.screen === 'workerLogs'), model.message]
130
+ : view.screen === 'actions' ? [
131
+ 'ACTIONS', `Target: ${view.actionTarget || 'none selected'}`, `Find: ${view.actionQuery || ''}_`,
132
+ 'Type to filter; arrows select; Enter opens an action.',
133
+ ...(actions.length ? actions.flatMap(action => [
134
+ `${action.id === selectedAction?.id ? '> ' : ' '}[${action.key}] ${action.label}`,
135
+ ...(action.reason ? [` Unavailable: ${action.reason}`] : []),
136
+ ]) : ['No matching actions. Ctrl+U clears the filter.']),
137
+ view.actionMessage || '',
138
+ ] : view.screen === 'connection' ? connectionLines(model, options.intervalMs, now)
139
+ : view.screen === 'overview' ? overviewLines(model.rows, now)
140
+ : view.screen === 'agents' ? agentLines(model.agents, model.rows, Boolean(model.lastUpdated) && !model.error, width)
141
+ : view.screen === 'create' && view.creation
142
+ ? creationLines(view.creation, options.createOptions, options.backend || 'api', Boolean(view.creationReview))
143
+ : view.screen === 'command' && view.commandMode === 'spawn' && view.workerLaunch ? [
144
+ ...workerLaunchLines(view.command || '', view.workerLaunch, Boolean(view.commandReview)),
145
+ `Sandbox: ${view.commandId}`, view.commandMessage || '',
146
+ ] : view.screen === 'command' && view.commandMode === 'python' && view.workerLaunch && (view.commandEditing || view.commandReview) ? [
147
+ ...pythonLines(view.command || '', view.workerLaunch, Boolean(view.commandReview), view.python),
148
+ `Sandbox: ${view.commandId}`, view.commandMessage || '',
149
+ ] : view.screen === 'command' ? [
150
+ view.commandMode === 'python' ? 'PYTHON TASK RESULT' : 'RUN COMMAND', `Sandbox: ${view.commandId}`,
151
+ ...(view.commandMode === 'python' && view.python ? [`Python task: ${view.python.name} | ${view.python.id}`, `Artifacts: ${view.python.directory}`]
152
+ : [model.api.executeStream ? 'Runs sh -lc inside this sandbox. Output streams live.' : 'Runs sh -lc inside this sandbox. Output appears after completion.']),
153
+ ...(view.commandEditing ? [`Type or paste a command (max ${COMMAND_LIMIT} characters). Enter reviews; Ctrl+U clears.`,
154
+ ...`$ ${view.command || ''}_`.split('\n')]
155
+ : [view.commandMode === 'python' ? `Source: ${view.python?.source}` : `$ ${view.command || ''}`]),
156
+ view.commandMessage || '',
157
+ ...(view.commandResult ? [
158
+ view.commandResult.status,
159
+ ...(view.commandResult.executionId ? [`Execution: ${view.commandResult.executionId}`] : []),
160
+ ...(view.commandResult.truncated ? ['Output truncated (server limit or 64 KiB per stream).'] : []),
161
+ 'STDOUT', ...(view.commandResult.stdout || '(empty)').split(/\r?\n/),
162
+ 'STDERR', ...(view.commandResult.stderr || '(empty)').split(/\r?\n/),
163
+ ] : []),
164
+ ] : view.screen === 'subscription' ? [
165
+ 'SUBSCRIPTION',
166
+ ...(options.billing ? [
167
+ options.readOnly ? 'Read-only: subscription actions are disabled.' : 'Enter reviews opening subscription plans in your browser.',
168
+ 'Sign in as the owner and verify the organization.',
169
+ 'Select a plan and review recurring fees plus usage before confirming.',
170
+ 'Cancelling: use Reactivate Subscription before the period ends.',
171
+ 'Canceled: start a new subscription; existing credits do not restart it.',
172
+ 'Opening this page does not change your plan or submit payment.',
173
+ view.subscriptionMessage || '',
174
+ ...(view.subscriptionUrl ? ['Subscription link (o opens it again):', view.subscriptionUrl] : []),
175
+ ] : ['Local Docker sandboxes do not require a subscription.']),
176
+ ] : view.screen === 'billing' ? [
177
+ 'BUY CREDITS',
178
+ ...(options.billing ? [
179
+ `USD amount: $${view.creditAmount ?? '25'}${view.creditEditing ? '_' : ''}`,
180
+ 'Type an amount ($5-$2,000); Enter reviews it.',
181
+ options.readOnly ? 'Read-only: purchases are disabled.' : 'Payment is completed in your browser.',
182
+ 'Sign in as the owner and verify the organization before paying.',
183
+ 'Stripe confirms payment before credits are applied.',
184
+ 'Credits fund an active metered subscription; they do not change your plan.',
185
+ 'Need a subscription? Press s to review plans or reactivate.',
186
+ 'Return here after payment; r refreshes sandboxes.',
187
+ view.creditMessage || '',
188
+ ...(view.creditUrl ? ['Billing link (o opens it again):', view.creditUrl] : []),
189
+ ] : ['Local Docker sandboxes do not require credits.']),
190
+ ] : view.screen === 'activity' ? [
191
+ 'ACTIVITY | all sandboxes',
192
+ 'Current session; newest first; last 100 observations.',
193
+ ...(model.activity.length ? model.activity.map(event => `${event.at.toISOString()} | ${event.message}`)
194
+ : ['Waiting for the first observation...']),
195
+ ] : view.screen === 'help' ? help : row ? [
196
+ `ID: ${row.id}`, `Status: ${row.status}`, `CPU: ${row.cpus || '-'}`,
197
+ `Memory: ${row.memory || '-'}`, `Created: ${row.createdAt || '-'}`,
198
+ `Expires: ${row.expiresAt || '-'}`, `Time left: ${timeLeft(row, now)}`, `Backend: ${row.backend || 'api'}`,
199
+ `Creating Herdr pane: ${row.origin || '-'}`,
200
+ ...agentDetailLines(model.agents, row.id),
201
+ ] : ['Selected sandbox is no longer available. Esc returns to the list.'];
202
+ // Wrap before slicing so full IDs and pane names remain inspectable in splits.
203
+ const plain = stripTerminalStyles(content.join('\n'));
204
+ return (options.redact?.(plain) ?? plain).split('\n').flatMap(line => {
205
+ const safe = terminalText(line);
206
+ return wrapCells(safe, width);
207
+ });
208
+ }
209
+ export function dashboardLines(model, options, width, height, confirmation, view = {}, now = Date.now()) {
210
+ width = Math.max(1, Math.min(500, width - 1));
211
+ height = Math.max(1, Math.min(200, height));
212
+ const clean = (text) => {
213
+ const plain = stripTerminalStyles(text);
214
+ return clipCells(terminalText(options.redact?.(plain) ?? plain), width);
215
+ };
216
+ const baseTitle = `STATESET SANDBOX${options.readOnly ? ' [read only]' : ''}`;
217
+ const running = model.rows.filter(row => row.status.toLowerCase() === 'running').length;
218
+ const title = `${baseTitle}${!view.screen || view.screen === 'list' ? ` | ${running} running/${model.rows.length} total | sort:${model.sortMode}${model.agents.duplicates.size ? ` | dup:${model.agents.duplicates.size}` : ''}` : ''}`;
219
+ if (height < 8 || width < 24)
220
+ return [title, 'Resize to at least 25x8', 'q quits; sandboxes stay alive'].slice(0, height).map(clean);
221
+ const status = model.readRetryAt > now ? `STALE / rate limited: API reads resume in ${Math.ceil((model.readRetryAt - now) / 1000)}s`
222
+ : model.error
223
+ ? `STALE / unavailable: ${model.error}`
224
+ : snapshotStale(model, options.intervalMs, now) ? 'STALE: refresh delayed. Press c for connection diagnostics.'
225
+ : model.lastUpdated ? `Updated ${model.lastUpdated.toISOString()} | ${model.rows.length} sandboxes` : 'Connecting...';
226
+ const agents = model.agents;
227
+ const note = noteRows(model, view, height);
228
+ // With agent columns the wide layout needs more room beside CPU and memory.
229
+ const compact = width < 60 || (agents.bySandbox.size > 0 && width < 64);
230
+ const rows = model.visibleRows;
231
+ const search = view.searching ? `Search: /${model.filter}_ Enter:apply Esc:cancel`
232
+ : model.filter ? `Filter: ${model.filter} | ${rows.length}/${model.rows.length} matches | Esc:clear` : undefined;
233
+ if (view.screen && view.screen !== 'list') {
234
+ const wrapped = screenContent(model, options, width, view, now);
235
+ const room = height - 5 - note;
236
+ const offset = Math.max(0, Math.min(view.scroll || 0, Math.max(0, wrapped.length - room)));
237
+ const lines = [title, options.label, status, ...wrapped.slice(offset, offset + room)];
238
+ while (lines.length < height - 2 - note)
239
+ lines.push('');
240
+ if (note)
241
+ lines.push(agents.note);
242
+ const actionReason = view.screen === 'actions' ? view.actionMessage
243
+ || filterActions(availableActions(model, options, view.actionTarget, now), view.actionQuery)
244
+ .find(action => action.id === view.actionSelected)?.reason : undefined;
245
+ lines.push(confirmation || actionReason || ((view.screen === 'history' || view.screen === 'receipt') && view.history?.error) || (view.screen === 'create' && view.creation?.error)
246
+ || (view.screen === 'delegate' && view.delegation?.error)
247
+ || ((view.screen === 'tasks' || view.screen === 'task') && view.tasks?.refreshQueued && !model.busy ? taskRefreshStatus(view.tasks) : '')
248
+ || ((view.screen === 'tasks' || view.screen === 'task') && view.tasks?.error)
249
+ || (view.screen === 'task' && view.tasks?.rows.find(row => row.task.task_id === view.tasks?.detailId)?.error)
250
+ || (view.screen === 'taskResults' && view.results?.error)
251
+ || (view.screen === 'taskRegistry' && view.registry ? view.registry.loading ? 'Reading task registry...' : view.registry.error || view.registry.notice : '')
252
+ || (view.screen === 'inputBatch' && view.inputBatch ? view.inputBatch.loading ? 'Reading input receipt...'
253
+ : view.inputBatch.uploading ? `Input files verified: ${view.inputBatch.progress || 0}/${view.inputBatch.plan?.files.length || 0}` : view.inputBatch.message : '')
254
+ || ((view.screen === 'task' || view.screen === 'tasks') && model.busy ? `BUSY: ${model.message}` : '')
255
+ || ((view.screen === 'task' || view.screen === 'tasks') && view.tasks ? taskRefreshStatus(view.tasks) : '')
256
+ || ((view.screen === 'workers' || view.screen === 'workerLogs' || view.screen === 'workerResult') && (view.workers?.error || model.busy) ? model.busy ? `BUSY: ${model.message}` : view.workers?.error : '')
257
+ || ((view.screen === 'workers' || view.screen === 'workerLogs' || view.screen === 'workerResult') && view.workers ? workerRefreshStatus(view.workers) : '')
258
+ || (view.screen === 'command' && model.busy ? view.live?.receipt.phase === 'finished'
259
+ ? 'BUSY: command request settling; wait to edit.' : 'BUSY: command in progress.' : '')
260
+ || (view.screen === 'command' ? view.commandMessage : '')
261
+ || (view.screen === 'agentChat' && view.chat ? chatStatus(view.chat, model.busy) : '')
262
+ || `${view.screen.toUpperCase()} | ${offset + 1}-${Math.min(offset + room, wrapped.length)}/${wrapped.length}`);
263
+ lines.push(confirmation ? 'y:confirm Esc:cancel' : view.screen === 'delegate' ? 'Tab:field Enter:review Esc:back Ctrl+U:clear Ctrl+C:quit'
264
+ : view.screen === 'tasks' ? view.tasks?.searching ? 'Enter:apply Esc:cancel Ctrl+U:clear Ctrl+C:quit' : 'Enter:inspect b:archive /:find t:state p:family a:all r:refresh Esc:back q:quit'
265
+ : view.screen === 'task' ? 's:chat u:registry c:collect b:bundles v:result f:files g:child d:stop Esc:tasks q:quit'
266
+ : view.screen === 'taskRegistry' ? view.registry?.detailId ? 'p:register g:grant d:revoke j/k:grant r:refresh Esc:back q:quit' : 'Enter:inspect n:next b:previous f:family a:all r:refresh Esc:back q:quit'
267
+ : view.screen === 'agentChat' ? view.chat?.editing ? 'Enter:send Ctrl+B:bundles Ctrl+F:files Esc:cancel Ctrl+U:clear Ctrl+C:quit'
268
+ : view.chat?.controls ? options.readOnly ? 'j/k:select Enter:receipt r:refresh Esc:chat q:quit'
269
+ : 'j/k:select Enter:receipt d:restore Del:forget r:refresh Esc:chat q:quit'
270
+ : 'i:message x:interrupt z:finish c:requests b:saved f:files r:read Esc:task q:quit'
271
+ : view.screen === 'taskResults' ? 'Enter:open j/k:select r:refresh Esc:back q:quit'
272
+ : view.screen === 'taskArchive' ? 'Enter:verify j/k:select r:refresh Esc:tasks q:quit'
273
+ : view.screen === 'upload' ? view.upload?.attempted ? 'v:verify Enter:new plan Esc:files Ctrl+C:quit' : 'Enter:review Ctrl+U:clear Esc:files Ctrl+C:quit'
274
+ : view.screen === 'inputBatch' ? 'Enter:prepare c:review upload v:inspect g:delegate n:new Esc:back Ctrl+C:quit'
275
+ : view.screen === 'files' ? 'Enter:open d:download u:upload i:input batch Backspace:parent r:refresh Esc:back q:quit' : view.screen === 'workers' ? 'Enter:logs v:result g:launch d:stop r:refresh Esc:back q:quit'
276
+ : view.screen === 'workerResult' ? 'l:logs r:refresh j/k:scroll Esc:workers q:quit'
277
+ : view.screen === 'workerLogs' ? 'v:result r:refresh j/k:scroll Esc:workers q:quit'
278
+ : view.screen === 'actions' ? 'Enter:open Esc:back Ctrl+U:clear Ctrl+C:quit' : view.screen === 'create' ? 'Tab:field Enter:review Esc:back Ctrl+C:quit' : view.screen === 'command'
279
+ ? view.commandEditing ? view.commandMode !== 'exec' ? 'Tab:field Enter:review Esc:back Ctrl+C:quit' : 'Enter:review Esc:back Ctrl+C:quit'
280
+ : `z:cancel r:receipt f:files${canEditCommand(model, options, view.commandId, now) ? ' x:edit' : ''} h:history Esc:back q:quit`
281
+ : 'F2:actions Esc:back j/k:scroll q:quit');
282
+ return lines.map((line, index) => note && index === height - 3 ? dim(clean(line)) : clean(line));
283
+ }
284
+ const idWidth = compact ? width - 21 : width - 40;
285
+ const split = agents.bySandbox.size ? agentColumns(idWidth) : { id: idWidth, name: 0, phase: 0 };
286
+ const idHeading = split.name ? `${'ID'.padEnd(split.id)} ${'AGENT'.padEnd(split.name)} ${compact ? 'PHASE' : 'PHASE'.padEnd(split.phase)}` : compact ? 'ID' : 'ID'.padEnd(idWidth);
287
+ const heading = compact ? ` STATUS TIME LEFT ${idHeading}` : ` ${idHeading} ${'STATUS'.padEnd(11)} ${'CPU'.padEnd(5)} ${'MEMORY'.padEnd(8)} TIME LEFT`;
288
+ const lines = [title, options.label, status, search || heading];
289
+ if (height === 8)
290
+ lines.pop();
291
+ const room = Math.max(1, height - lines.length - 4 - note);
292
+ const selected = rows.findIndex(row => row.id === model.selectedId);
293
+ const start = Math.max(0, selected - room + 1);
294
+ for (const row of rows.slice(start, start + room)) {
295
+ const prefix = row.id === model.selectedId ? '> ' : ' ';
296
+ const cell = (value, size) => padCells(clean(value), size);
297
+ // The name is cut to its column; the ID keeps both ends in what is left.
298
+ const id = split.name ? `${shortId(row.id, split.id).padEnd(split.id)} ${cell(agentCell(agents, row.id, split.name), split.name)} ${cell(agents.bySandbox.get(row.id)?.[0]?.phase || '-', split.phase)}`
299
+ : compact ? shortId(row.id, idWidth) : shortId(row.id, idWidth).padEnd(idWidth);
300
+ lines.push(compact
301
+ ? `${prefix}${cell(row.status, 9)} ${cell(timeLeft(row, now), 8)} ${id}`
302
+ : `${prefix}${id} ${cell(row.status, 11)} ${cell(row.cpus || '-', 5)} ${cell(row.memory || '-', 8)} ${timeLeft(row, now)}`);
303
+ }
304
+ if (!rows.length)
305
+ lines.push(model.filter ? 'No matches. Esc clears search.' : model.lastUpdated
306
+ ? options.readOnly ? 'No sandboxes.' : 'No sandboxes. Press n to create.' : 'Waiting for backend...');
307
+ while (lines.length < height - 4 - note)
308
+ lines.push('');
309
+ if (note)
310
+ lines.push(agents.note);
311
+ const row = model.selected;
312
+ const agent = row ? agentSummary(agents, row.id) : '';
313
+ lines.push(row ? `${row.id} | ${agent ? `${agent} | ` : ''}CPU ${row.cpus || '-'} | RAM ${row.memory || '-'} | ${row.status}` : 'Nothing selected');
314
+ lines.push(confirmation ? `${confirmation} [y] confirm / [Esc] cancel` : view.searching ? search : model.busy ? `BUSY: ${model.message}` : model.message);
315
+ lines.push(confirmation ? 'y:confirm Esc:cancel' : options.readOnly ? 'F2:actions m:tasks v:agents j/k:select r:refresh c:connection' : 'F2:actions m:tasks v:agents l:delegate n:new x:exec i:python g:agent');
316
+ lines.push(view.searching ? 'Enter:apply Esc:cancel Ctrl+C:quit' : 'q:quit /:search Enter:details o:overview t:sort ?:help r:refresh a:activity');
317
+ return lines.slice(0, height).map((line, index) => note && index === height - 5 ? dim(clean(line)) : clean(line));
318
+ }
319
+ /** No terminal reset or subprocess panes: works in a Herdr/tmux split. */
320
+ export async function runDashboard(model, options, input = process.stdin, output = process.stdout) {
321
+ if (!input.isTTY || !output.isTTY || typeof input.setRawMode !== 'function') {
322
+ throw new Error('The dashboard requires a terminal. Use sandboxctl status --json from agents or pipes.');
323
+ }
324
+ validateTaskFocus(options);
325
+ const registryFocus = Boolean(options.registryFocus || options.registryRootTaskId);
326
+ if (options.registryRootTaskId !== undefined && !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(options.registryRootTaskId))
327
+ throw new Error('Registry startup requires an exact server family UUID.');
328
+ if (registryFocus && (options.taskId || options.taskFamily))
329
+ throw new Error('Choose registry, task or family startup focus.');
330
+ if (registryFocus && !model.api.taskRegistry)
331
+ throw new Error('Server registry requires the updated hosted API client.');
332
+ if ((options.taskId !== undefined || options.taskFamily !== undefined) && !model.api.tasks)
333
+ throw new Error('Task focus requires the hosted API task journal.');
334
+ const manager = getShutdownManager();
335
+ const wasRaw = input.isRaw;
336
+ const wasPaused = input.isPaused();
337
+ const wasFlowing = input.readableFlowing;
338
+ let closed = false;
339
+ let pending;
340
+ let pasting = false;
341
+ let pasted = '';
342
+ const view = { screen: registryFocus ? 'taskRegistry' : options.taskId ? 'task' : options.taskFamily ? 'tasks' : 'list', scroll: 0,
343
+ ...(registryFocus ? { registry: { ...registryView('list'), rootTaskId: options.registryRootTaskId } } : {}),
344
+ ...(options.taskId || options.taskFamily ? { tasks: { rows: [], detailId: options.taskId, selectedId: options.taskId, family: options.taskFamily } } : {}) };
345
+ const chatViews = new Map();
346
+ let searchBefore = '';
347
+ let timer;
348
+ let clockTimer;
349
+ let outputTimer;
350
+ let finish;
351
+ const done = new Promise(resolve => { finish = resolve; });
352
+ const renderer = new TerminalRenderer();
353
+ const imageKeys = new PassThrough();
354
+ let graphics;
355
+ const imagePreview = () => view.screen === 'files' ? view.files?.preview : view.screen === 'taskResults' ? view.results?.preview : undefined;
356
+ let taskMonitor;
357
+ let workerMonitor;
358
+ let registryController;
359
+ let batchController;
360
+ let queuedChat;
361
+ const chatObservers = new Map();
362
+ const observeChat = (current) => {
363
+ const controller = new AbortController();
364
+ chatObservers.set(controller, current);
365
+ return { signal: controller.signal, active: () => !controller.signal.aborted && current(),
366
+ close: () => { chatObservers.delete(controller); } };
367
+ };
368
+ const chatContextChanged = () => {
369
+ for (const [controller, current] of chatObservers)
370
+ if (!current()) {
371
+ controller.abort();
372
+ chatObservers.delete(controller);
373
+ }
374
+ if (queuedChat && (closed || view.screen !== 'agentChat' || view.chat !== queuedChat)) {
375
+ queuedChat.refreshQueued = false;
376
+ queuedChat = undefined;
377
+ }
378
+ };
379
+ const draw = () => {
380
+ if (closed)
381
+ return;
382
+ if (view.screen === 'tasks' && view.tasks)
383
+ reconcileTaskSelection(view.tasks);
384
+ taskMonitor?.contextChanged();
385
+ workerMonitor?.contextChanged();
386
+ registryController?.contextChanged();
387
+ batchController?.contextChanged();
388
+ chatContextChanged();
389
+ if (view.screen !== 'list') {
390
+ const width = Math.max(1, Math.min(500, (output.columns || 80) - 1));
391
+ const room = Math.max(1, Math.min(200, output.rows || 24) - 5 - noteRows(model, view, Math.min(200, output.rows || 24)));
392
+ const end = Math.max(0, screenContent(model, options, width, view).length - room);
393
+ view.scroll = ((view.screen === 'command' && view.commandEditing && (view.commandMode === 'exec' || view.workerLaunch?.field === 0))
394
+ || (view.screen === 'agentChat' && view.chat?.follow)) && !pending ? end : Math.max(0, Math.min(view.scroll || 0, end));
395
+ if ((view.screen === 'create' || view.screen === 'actions' || view.screen === 'workers' || view.screen === 'history' || view.screen === 'tasks' || view.screen === 'taskArchive' || view.screen === 'delegate' || view.screen === 'taskResults' && !view.results?.preview || view.screen === 'files' && !view.files?.preview
396
+ || view.screen === 'taskRegistry' || view.screen === 'command' && view.commandMode !== 'exec' && view.commandEditing && view.workerLaunch?.field !== 0) && !pending) {
397
+ const content = screenContent(model, options, width, view);
398
+ const focus = view.screen === 'taskRegistry' && view.registry?.form ? content.findIndex(line => line.startsWith('> Principal:') || line.startsWith('> Role:'))
399
+ : view.screen === 'tasks' && view.tasks?.searching ? content.findIndex(line => line.startsWith('Find tasks:'))
400
+ : content.findIndex(line => line.startsWith('> ') || (view.screen === 'actions' && line.startsWith('No matching actions.')));
401
+ if (focus >= 0)
402
+ view.scroll = Math.max(0, Math.min(focus, Math.max(view.scroll || 0, focus - room + 2)));
403
+ }
404
+ }
405
+ let lines = dashboardLines(model, options, output.columns || 80, output.rows || 24, pending?.label, view);
406
+ const preview = imagePreview();
407
+ const image = preview?.image && view.imageDetailsKey !== preview.sha256 && !pending
408
+ && (output.rows || 24) >= 14 && (output.columns || 80) >= 25 ? preview.image : undefined;
409
+ const width = Math.max(1, Math.min(200, (output.columns || 80) - 1));
410
+ const height = Math.min(200, output.rows || 24);
411
+ const area = { top: 8, columns: width, rows: Math.min(64, Math.max(1, height - 10)) };
412
+ graphics?.setTarget(image, preview?.sha256 || '', area);
413
+ const useImageFrame = Boolean(image && graphics?.active);
414
+ if (useImageFrame && preview && graphics) {
415
+ const clean = (value) => clipCells(terminalText(options.redact?.(stripTerminalStyles(value)) ?? stripTerminalStyles(value)), width);
416
+ lines = [...lines.slice(0, 3).map(clean), 'ARTIFACT PREVIEW | PNG', clean(`File: ${preview.path}`),
417
+ clean(`${image.width} x ${image.height} | ${preview.size} bytes | SHA-256 ${preview.sha256.slice(0, 16)}...`), '', ...Array(area.rows).fill('')];
418
+ while (lines.length < height - 3)
419
+ lines.push('');
420
+ lines.push(clean(graphics.status), clean(`v:details${view.screen === 'files' ? ' d:download' : ''} Esc:back q:quit | resize to fit`), clean('Read-only preview. Validate task artifacts separately.'));
421
+ }
422
+ else if (image && graphics && lines.length > 2)
423
+ lines[lines.length - 2] = clipCells(graphics.status, Math.max(1, (output.columns || 80) - 1));
424
+ const screen = `${view.screen || 'list'}:${Boolean(pending)}:${Boolean(view.files?.preview)}:${Boolean(view.results?.preview)}:${Boolean(view.results?.bundle)}:${Boolean(view.commandEditing)}:${preview?.sha256 || ''}:${useImageFrame}`;
425
+ const patch = renderer.render(lines, output.columns || 80, output.rows || 24, screen);
426
+ if (patch)
427
+ output.write(patch);
428
+ if (useImageFrame && patch)
429
+ output.write(graphics.paint());
430
+ };
431
+ graphics = new KittyGraphics({ mode: options.graphics || 'auto', tmux: Boolean(process.env.TMUX),
432
+ write: text => output.write(text), keys: bytes => imageKeys.write(bytes), changed: draw });
433
+ const imageData = (bytes) => graphics.input.feed(Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes));
434
+ const imageKeypress = (text, key) => input.emit('keypress', text, key);
435
+ workerMonitor = new WorkerMonitor({
436
+ context: () => !closed && view.workers && (view.screen === 'workers' || view.screen === 'workerLogs' || view.screen === 'workerResult')
437
+ ? { state: view.workers, screen: view.screen } : undefined,
438
+ api: () => model.api.processes, read: request => model.read(request), changed: draw,
439
+ });
440
+ const refreshWorkers = () => workerMonitor.refresh();
441
+ let historyRead;
442
+ const refreshHistory = () => {
443
+ if (historyRead)
444
+ return historyRead;
445
+ const state = view.history;
446
+ const api = model.api.executions;
447
+ if (!state || !api || (view.screen !== 'history' && view.screen !== 'receipt'))
448
+ return Promise.resolve();
449
+ historyRead = (async () => {
450
+ try {
451
+ const rows = (await model.read(() => api.list(state.sandboxId))).map(executionRow);
452
+ if (view.history !== state || closed)
453
+ return;
454
+ state.rows = rows;
455
+ state.updatedAt = new Date();
456
+ if (view.screen !== 'receipt' && !rows.some(row => row.id === state.selectedId))
457
+ state.selectedId = rows[0]?.id;
458
+ const receiptId = state.receiptId;
459
+ if (view.screen === 'receipt' && receiptId) {
460
+ const receipt = executionReceipt(await model.read(() => api.get(state.sandboxId, receiptId)));
461
+ if (view.history !== state || state.receiptId !== receiptId || closed)
462
+ return;
463
+ if (receipt.id !== receiptId)
464
+ throw new Error('Execution receipt identity mismatch.');
465
+ state.receipt = receipt;
466
+ }
467
+ state.error = undefined;
468
+ }
469
+ catch (error) {
470
+ if (view.history === state && !closed)
471
+ state.error = error instanceof Error ? error.message : 'History refresh failed';
472
+ }
473
+ })().finally(() => { historyRead = undefined; draw(); });
474
+ return historyRead;
475
+ };
476
+ const fileApi = () => {
477
+ if (!model.api.listFiles || !model.api.readFile)
478
+ throw new Error('Workspace file support is unavailable.');
479
+ return { listFiles: (...args) => model.api.listFiles(...args), readFile: (...args) => model.api.readFile(...args) };
480
+ };
481
+ let fileRead;
482
+ let filePreviewRead;
483
+ const refreshFiles = () => {
484
+ if (fileRead)
485
+ return fileRead;
486
+ const state = view.files;
487
+ if (view.screen !== 'files' || !state)
488
+ return Promise.resolve();
489
+ const directory = state.directory;
490
+ fileRead = (async () => {
491
+ try {
492
+ const rows = fileRows(await model.read(() => fileApi().listFiles(state.sandboxId, directory)), directory);
493
+ if (closed || view.files !== state || state.directory !== directory)
494
+ return;
495
+ state.rows = rows;
496
+ state.updatedAt = new Date();
497
+ state.error = undefined;
498
+ if (!rows.some(row => row.path === state.selectedPath))
499
+ state.selectedPath = rows[0]?.path;
500
+ }
501
+ catch (error) {
502
+ if (view.files === state && state.directory === directory && !closed)
503
+ state.error = error instanceof Error ? error.message : 'File listing failed';
504
+ }
505
+ })().finally(() => { fileRead = undefined; draw(); if (!closed && view.screen === 'files' && view.files?.directory !== directory)
506
+ void refreshFiles(); });
507
+ return fileRead;
508
+ };
509
+ taskMonitor = new TaskMonitor({
510
+ context: () => !closed && view.tasks && (view.screen === 'tasks' || view.screen === 'task')
511
+ ? { state: view.tasks, detail: view.screen === 'task' } : undefined,
512
+ api: () => model.api.tasks, read: request => model.read(request), retryAt: () => model.readRetryAt, changed: draw,
513
+ });
514
+ const refreshTasks = (retrySelected = false, queueIfBusy = retrySelected) => taskMonitor.refresh(retrySelected, queueIfBusy);
515
+ registryController = new RegistryController(model, () => !closed && view.screen === 'taskRegistry' ? view.registry : undefined, draw, Boolean(options.readOnly));
516
+ const openRegistry = (state) => {
517
+ if (!model.api.taskRegistry) {
518
+ model.message = 'Server registry requires the updated hosted API client.';
519
+ if (view.tasks)
520
+ view.tasks.error = model.message;
521
+ return;
522
+ }
523
+ view.registry = state;
524
+ view.screen = 'taskRegistry';
525
+ view.scroll = 0;
526
+ void registryController.refresh(state);
527
+ };
528
+ const reviewRegistry = (state, plan) => {
529
+ const reviewed = structuredClone(plan);
530
+ state.review = reviewed;
531
+ state.notice = undefined;
532
+ view.scroll = 0;
533
+ pending = { label: `Confirm registry ${plan.operation} for ${plan.operation === 'register' ? plan.taskId : 'family ' + plan.rootTaskId}?`,
534
+ run: async () => { state.review = undefined; await registryController.apply(state, reviewed); } };
535
+ };
536
+ batchController = new BatchUploadController(model.api.inputBatches, () => !closed && view.screen === 'inputBatch' ? view.inputBatch : undefined, draw, state => {
537
+ if (closed || options.readOnly || snapshotStale(model, options.intervalMs)
538
+ || model.rows.find(row => row.id === state.sandboxId)?.status !== 'running')
539
+ throw new Error('Refresh a running sandbox before uploading. Read-only mode disables uploads.');
540
+ });
541
+ let chatRead;
542
+ let lastChatRead = 0;
543
+ const refreshChat = (force = false) => {
544
+ const state = view.chat, api = model.api.chats;
545
+ if (closed || view.screen !== 'agentChat' || !state || !api)
546
+ return Promise.resolve();
547
+ if (chatRead) {
548
+ if (force) {
549
+ if (queuedChat && queuedChat !== state)
550
+ queuedChat.refreshQueued = false;
551
+ queuedChat = state;
552
+ state.refreshQueued = true;
553
+ }
554
+ return chatRead;
555
+ }
556
+ if (!force && Date.now() - lastChatRead < Math.max(5000, options.intervalMs))
557
+ return Promise.resolve();
558
+ const scope = observeChat(() => !closed && view.screen === 'agentChat' && view.chat === state);
559
+ const observing = scope.active;
560
+ lastChatRead = Date.now();
561
+ state.checkingReceipts = Boolean(state.pendingRequests?.length);
562
+ chatRead = (async () => {
563
+ try {
564
+ const snapshot = await model.read(async () => observing() ? api.inspect(state.taskId, scope.signal) : undefined);
565
+ if (!snapshot || !observing())
566
+ return;
567
+ state.snapshot = snapshot;
568
+ state.error = undefined;
569
+ if (state.controls && !chatRequests(state).some(request => request.request_id === state.controls.selectedId)) {
570
+ state.controls.selectedId = chatRequests(state)[0]?.request_id;
571
+ state.controls.receipt = undefined;
572
+ state.controls.error = undefined;
573
+ }
574
+ const targets = chatReceiptTargets(state);
575
+ state.checkingReceipts = targets.length > 0;
576
+ draw();
577
+ for (const target of targets) {
578
+ if (!observing())
579
+ return;
580
+ try {
581
+ const receipt = await model.read(async () => observing() && markChatReceiptAttempt(state, target)
582
+ ? api.receipt(state.taskId, target.request_id, target.sha256, scope.signal) : undefined);
583
+ if (!observing())
584
+ return;
585
+ if (!receipt)
586
+ continue;
587
+ observeChatReceipt(state, receipt);
588
+ }
589
+ catch (error) {
590
+ if (!observing())
591
+ return;
592
+ // A worker may not have consumed stdin yet. Saved anchors also
593
+ // outlive its recent-request window, so absence is still pending.
594
+ if (error && typeof error === 'object' && 'status' in error && error.status === 404) {
595
+ if (state.receiptErrorRequestId === target.request_id) {
596
+ state.receiptError = undefined;
597
+ state.receiptErrorRequestId = undefined;
598
+ }
599
+ }
600
+ else {
601
+ state.receiptError = error instanceof Error ? error.message : 'Request receipt unavailable';
602
+ state.receiptErrorRequestId = target.request_id;
603
+ }
604
+ }
605
+ }
606
+ if (observing()) {
607
+ if (state.receipt)
608
+ observeChatReceipt(state, state.receipt);
609
+ for (const held of state.heldDrafts || [])
610
+ if (restoreChatDraft(state, held.request_id))
611
+ break;
612
+ }
613
+ }
614
+ catch (error) {
615
+ if (observing())
616
+ state.error = error instanceof Error ? error.message : 'Agent conversation unavailable';
617
+ }
618
+ })().finally(() => {
619
+ scope.close();
620
+ state.checkingReceipts = false;
621
+ chatRead = undefined;
622
+ const next = queuedChat;
623
+ queuedChat = undefined;
624
+ if (next)
625
+ next.refreshQueued = false;
626
+ if (next && !closed && view.screen === 'agentChat' && view.chat === next)
627
+ void refreshChat(true);
628
+ draw();
629
+ });
630
+ return chatRead;
631
+ };
632
+ const refresh = async () => { await model.refresh(); await refreshWorkers(); await refreshHistory(); await refreshFiles(); await refreshTasks(); await refreshChat(); draw(); };
633
+ let resultRead;
634
+ let resultPlanning = false;
635
+ const openBundles = (taskId, selectedId, returnTo = 'task') => {
636
+ if (!model.api.taskResults) {
637
+ if (returnTo === 'agentChat' && view.chat)
638
+ view.chat.notice = 'Saved task results require the updated hosted client.';
639
+ else if (view.tasks)
640
+ view.tasks.error = 'Task result collection requires the updated hosted client.';
641
+ return;
642
+ }
643
+ const state = { taskId, rows: [], selectedId, artifactIndex: 0, loading: true, returnTo };
644
+ view.results = state;
645
+ view.screen = 'taskResults';
646
+ view.scroll = 0;
647
+ // Local reads have their own queue so a stalled remote poll cannot block archived results.
648
+ resultRead = (async () => {
649
+ try {
650
+ state.rows = await model.api.taskResults.list(taskId);
651
+ if (closed || view.results !== state)
652
+ return;
653
+ state.selectedId ||= state.rows[0]?.collection_id;
654
+ if (selectedId)
655
+ state.bundle = await model.api.taskResults.get(taskId, selectedId);
656
+ }
657
+ catch (error) {
658
+ state.error = error instanceof Error ? error.message : 'Saved result read failed';
659
+ }
660
+ finally {
661
+ state.loading = false;
662
+ if (view.results === state)
663
+ resultRead = undefined;
664
+ draw();
665
+ }
666
+ })();
667
+ draw();
668
+ };
669
+ const openChatFiles = (state) => {
670
+ const task = state.snapshot?.task;
671
+ if (!model.api.listFiles || !model.api.readFile)
672
+ state.notice = 'Task files require the updated hosted client.';
673
+ else if (!task || task.task_id !== state.taskId)
674
+ state.notice = 'Refresh the task identity before opening its files. Saved bundles remain available with b.';
675
+ else {
676
+ view.files = { sandboxId: task.sandbox_id, directory: task.artifact_dir, rows: [], returnTo: 'agentChat' };
677
+ view.screen = 'files';
678
+ view.scroll = 0;
679
+ void refreshFiles();
680
+ }
681
+ };
682
+ const openArchive = (state) => {
683
+ const api = model.api.taskResults;
684
+ if (!api) {
685
+ if (view.tasks)
686
+ view.tasks.error = 'Saved task results require the updated hosted client.';
687
+ return;
688
+ }
689
+ if (view.tasks)
690
+ view.tasks.error = undefined;
691
+ view.archive = state;
692
+ view.screen = 'taskArchive';
693
+ view.scroll = 0;
694
+ void readTaskArchive(state, api, () => !closed && view.archive === state
695
+ && (view.screen === 'taskArchive' || view.screen === 'taskResults' && view.results?.returnTo === 'taskArchive'), draw);
696
+ draw();
697
+ };
698
+ const cleanup = () => {
699
+ if (closed)
700
+ return;
701
+ closed = true;
702
+ taskMonitor?.contextChanged();
703
+ workerMonitor?.contextChanged();
704
+ chatContextChanged();
705
+ if (timer)
706
+ clearInterval(timer);
707
+ if (clockTimer)
708
+ clearInterval(clockTimer);
709
+ if (outputTimer)
710
+ clearTimeout(outputTimer);
711
+ view.live?.stopWatching();
712
+ registryController?.stop();
713
+ batchController?.stop();
714
+ graphics?.close();
715
+ input.removeListener('data', imageData);
716
+ imageKeys.removeListener('keypress', imageKeypress);
717
+ imageKeys.destroy();
718
+ input.removeListener('keypress', keypress);
719
+ output.removeListener('resize', draw);
720
+ manager.deregister('sandbox-dashboard');
721
+ try {
722
+ input.setRawMode(Boolean(wasRaw));
723
+ }
724
+ finally {
725
+ if (wasPaused || wasFlowing !== true)
726
+ input.pause();
727
+ output.write('\x1b[?2004l\x1b[?25h\x1b[?1049l');
728
+ finish();
729
+ }
730
+ };
731
+ const mutate = (label, action, completed) => {
732
+ const work = model.mutate(label, action, completed);
733
+ draw();
734
+ void work.finally(draw);
735
+ };
736
+ const scroll = (name) => {
737
+ if (name === 'down' || name === 'j')
738
+ view.scroll = (view.scroll || 0) + 1;
739
+ if (name === 'up' || name === 'k')
740
+ view.scroll = Math.max(0, (view.scroll || 0) - 1);
741
+ if (name === 'pagedown')
742
+ view.scroll = (view.scroll || 0) + pageSize(output.rows || 24);
743
+ if (name === 'pageup')
744
+ view.scroll = Math.max(0, (view.scroll || 0) - pageSize(output.rows || 24));
745
+ if (name === 'home')
746
+ view.scroll = 0;
747
+ if (name === 'end')
748
+ view.scroll = Number.MAX_SAFE_INTEGER;
749
+ };
750
+ const performAction = (actionId, id) => {
751
+ const action = availableActions(model, options, id).find(action => action.id === actionId);
752
+ if (action.reason) {
753
+ model.message = `${action.label} unavailable: ${action.reason}`;
754
+ view.actionMessage = model.message;
755
+ if ((view.screen === 'task' || view.screen === 'tasks') && view.tasks)
756
+ view.tasks.error = model.message;
757
+ return;
758
+ }
759
+ if (actionId === 'refresh') {
760
+ void refresh();
761
+ return;
762
+ }
763
+ const screens = { overview: 'overview', activity: 'activity', connection: 'connection', credits: 'billing', subscription: 'subscription', help: 'help', agents: 'agents' };
764
+ if (actionId in screens) {
765
+ view.screen = screens[actionId];
766
+ view.scroll = 0;
767
+ return;
768
+ }
769
+ if (actionId === 'details') {
770
+ view.screen = 'details';
771
+ view.detailId = id;
772
+ view.scroll = 0;
773
+ return;
774
+ }
775
+ if (actionId === 'workers') {
776
+ if (view.workers?.sandboxId !== id)
777
+ view.workers = { sandboxId: id, rows: [] };
778
+ view.screen = 'workers';
779
+ view.scroll = 0;
780
+ void refreshWorkers();
781
+ return;
782
+ }
783
+ if (actionId === 'tasks') {
784
+ view.tasks ||= { rows: [] };
785
+ view.screen = 'tasks';
786
+ view.scroll = 0;
787
+ void refreshTasks();
788
+ return;
789
+ }
790
+ if (actionId === 'registry') {
791
+ openRegistry(registryView(view.screen === 'tasks' || view.screen === 'task' ? view.screen : 'list'));
792
+ return;
793
+ }
794
+ if (actionId === 'inputBatches') {
795
+ view.inputBatch = { sandboxId: id, query: '' };
796
+ view.screen = 'inputBatch';
797
+ view.scroll = 0;
798
+ return;
799
+ }
800
+ if (actionId === 'delegate') {
801
+ view.delegation = delegationDraft(id);
802
+ view.screen = 'delegate';
803
+ view.scroll = 0;
804
+ return;
805
+ }
806
+ if (actionId === 'history') {
807
+ if (view.history?.sandboxId !== id)
808
+ view.history = { sandboxId: id, rows: [] };
809
+ view.screen = 'history';
810
+ view.scroll = 0;
811
+ void refreshHistory();
812
+ return;
813
+ }
814
+ if (actionId === 'files') {
815
+ if (view.screen === 'command' && view.commandMode === 'python' && view.python && view.commandId === id) {
816
+ view.files = { sandboxId: id, directory: view.python.directory, rows: [] };
817
+ }
818
+ else if (view.screen === 'receipt' && view.history && view.history.sandboxId === id && view.history.receipt?.workingDir) {
819
+ try {
820
+ view.files = { sandboxId: id, directory: workspacePath(view.history.receipt.workingDir), rows: [] };
821
+ }
822
+ catch {
823
+ view.files = { sandboxId: id, directory: '/workspace', rows: [] };
824
+ }
825
+ }
826
+ else if (view.files?.sandboxId !== id)
827
+ view.files = { sandboxId: id, directory: '/workspace', rows: [] };
828
+ view.screen = 'files';
829
+ view.scroll = 0;
830
+ void refreshFiles();
831
+ return;
832
+ }
833
+ if (actionId === 'create') {
834
+ view.creation ||= creationDraft(options.createOptions);
835
+ view.creation.field = 0;
836
+ view.creation.replace = true;
837
+ view.creation.error = undefined;
838
+ view.creationReview = false;
839
+ view.screen = 'create';
840
+ view.scroll = 0;
841
+ }
842
+ if (actionId === 'execute' || actionId === 'launch' || actionId === 'interpret') {
843
+ const mode = actionId === 'launch' ? 'spawn' : actionId === 'interpret' ? 'python' : 'exec';
844
+ const same = view.commandId === id && view.commandMode === mode;
845
+ view.screen = 'command';
846
+ view.commandId = id;
847
+ view.scroll = 0;
848
+ view.commandMode = mode;
849
+ if (!same) {
850
+ view.live?.stopWatching();
851
+ view.live = undefined;
852
+ view.command = mode === 'python' ? PYTHON_EXAMPLE : '';
853
+ view.python = undefined;
854
+ view.commandResult = undefined;
855
+ view.commandMessage = '';
856
+ }
857
+ if (mode === 'spawn' && (!same || !view.workerLaunch || !view.commandEditing))
858
+ view.workerLaunch = workerLaunchDraft(`worker-${randomUUID()}`);
859
+ if (mode === 'python' && (!same || !view.workerLaunch))
860
+ view.workerLaunch = { ...workerLaunchDraft('Python analysis'), timeout: '60' };
861
+ if (mode !== 'exec' && view.workerLaunch) {
862
+ view.workerLaunch.field = 0;
863
+ view.workerLaunch.replace = false;
864
+ }
865
+ view.commandReview = false;
866
+ view.commandEditing = !same || (!view.commandResult && !view.commandMessage);
867
+ }
868
+ if (actionId === 'stop')
869
+ pending = { label: `Stop ${id}?`, run: async () => {
870
+ if (snapshotStale(model, options.intervalMs))
871
+ throw new Error('Refresh successfully before stopping the sandbox.');
872
+ const result = await model.api.stop(id);
873
+ if (!result.success)
874
+ throw new Error('Stop was not acknowledged');
875
+ } };
876
+ if (actionId === 'pause')
877
+ mutate(`Pause ${id}`, () => model.api.pause(id, { wait: false }));
878
+ if (actionId === 'resume')
879
+ mutate(`Resume ${id}`, () => model.api.resume(id, { wait: false }));
880
+ if (actionId === 'extend')
881
+ mutate(`Extend ${id} +${options.extendSeconds}s`, () => model.api.extend(id, options.extendSeconds));
882
+ };
883
+ const deliverChat = async (state, plan) => {
884
+ if (closed || options.readOnly || !model.api.chats)
885
+ throw new Error('Messaging is unavailable.');
886
+ beginChatControl(state, plan);
887
+ state.inputFailure = undefined;
888
+ state.request = { task_id: state.taskId, request_id: plan.request_id, sha256: plan.sha256 };
889
+ state.receipt = undefined;
890
+ state.receiptError = undefined;
891
+ state.receiptErrorRequestId = undefined;
892
+ state.uncertainRequestId = undefined;
893
+ state.notice = 'Sending one control request; delivery is not automatically retried.';
894
+ try {
895
+ await model.api.chats.send(plan, () => !closed);
896
+ state.notice = undefined;
897
+ if (plan.op === 'message' && state.draft === plan.text)
898
+ state.draft = '';
899
+ state.editing = false;
900
+ }
901
+ catch (error) {
902
+ state.editing = false;
903
+ if (error instanceof AgentChatInputError)
904
+ state.inputFailure = error.path;
905
+ if (error instanceof AgentChatSendError) {
906
+ state.uncertainRequestId = plan.request_id;
907
+ // A lost transport acknowledgement must not leave a ready-to-resend
908
+ // copy in the composer. Retain text privately until a receipt resolves it.
909
+ if (plan.op === 'message' && state.draft === plan.text)
910
+ state.draft = '';
911
+ }
912
+ else {
913
+ state.request = undefined;
914
+ state.receipt = undefined;
915
+ state.heldDrafts = state.heldDrafts?.filter(draft => draft.request_id !== plan.request_id);
916
+ state.pendingRequests = state.pendingRequests?.filter(request => request.request_id !== plan.request_id || request.sha256 !== plan.sha256);
917
+ }
918
+ state.notice = error instanceof AgentChatSendError ? `${error.message} Intent: ${error.intent_path}` : error instanceof Error ? error.message : 'Message failed.';
919
+ throw error;
920
+ }
921
+ finally {
922
+ state.sending = false;
923
+ void refreshChat(true);
924
+ }
925
+ };
926
+ const keypress = (text, key = {}) => {
927
+ if (key.name === 'paste-start') {
928
+ pasting = true;
929
+ pasted = '';
930
+ return;
931
+ }
932
+ if (key.name === 'paste-end') {
933
+ if (pasting && view.screen === 'inputBatch' && view.inputBatch && !view.inputBatch.plan && !view.inputBatch.loading && !pending) {
934
+ if (printableInput(pasted) && view.inputBatch.query.length + pasted.length <= 4096)
935
+ view.inputBatch.query += pasted;
936
+ else
937
+ view.inputBatch.message = 'Paste one manifest path or one UUID and hash; input unchanged.';
938
+ }
939
+ if (pasting && view.screen === 'taskRegistry' && view.registry?.form && !pending) {
940
+ const state = view.registry, form = state.form;
941
+ if (form.field === 0 && /^[a-f0-9:-]*$/.test(pasted) && form.principal.length + pasted.length <= 43) {
942
+ form.principal += pasted;
943
+ state.notice = undefined;
944
+ }
945
+ else if (form.field === 1 && ['viewer', 'operator'].includes(pasted)) {
946
+ form.role = pasted;
947
+ state.notice = undefined;
948
+ }
949
+ else
950
+ state.notice = 'Paste one UUID principal or one role; form unchanged.';
951
+ }
952
+ if (pasting && view.screen === 'agentChat' && view.chat?.editing && !pending && !view.chat.sending) {
953
+ const message = view.chat.draft + pasted.replace(/[\r\n\t]/g, ' ');
954
+ if (printableInput(message) && message.length <= 4096 && Buffer.byteLength(message) <= 8192) {
955
+ view.chat.draft = message;
956
+ view.chat.notice = undefined;
957
+ }
958
+ else
959
+ view.chat.notice = 'Message limit: 4096 characters / 8192 UTF-8 bytes, without controls; draft unchanged.';
960
+ }
961
+ if (pasting && view.screen === 'tasks' && view.tasks?.searching) {
962
+ view.tasks.query = limitText((view.tasks.query || '') + pasted, 200);
963
+ view.tasks.notice = undefined;
964
+ }
965
+ if (pasting && view.screen === 'upload' && view.upload && !view.upload.planning && !view.upload.plan && !pending) {
966
+ if (printableInput(pasted) && view.upload.source.length + pasted.length <= 4096) {
967
+ view.upload.source += pasted;
968
+ view.upload.message = undefined;
969
+ }
970
+ else
971
+ view.upload.message = 'Paste one file path up to 4096 characters without controls; input unchanged.';
972
+ }
973
+ if (pasting && view.searching)
974
+ model.setFilter(limitText(model.filter + pasted, 200));
975
+ if (pasting && view.screen === 'delegate' && view.delegation && !pending)
976
+ editDelegation(view.delegation, pasted);
977
+ if (pasting && view.screen === 'command' && view.commandEditing && !pending) {
978
+ const draft = view.commandMode !== 'exec' ? view.workerLaunch : undefined;
979
+ if (draft && draft.field > 0) {
980
+ const field = draft.field === 1 ? 'name' : 'timeout';
981
+ const limit = draft.field === 1 ? 128 : 8;
982
+ const value = (draft.replace ? '' : draft[field]) + pasted;
983
+ if (printableInput(pasted) && value.length <= limit) {
984
+ draft[field] = value;
985
+ draft.replace = false;
986
+ view.commandMessage = '';
987
+ }
988
+ else
989
+ view.commandMessage = `Paste one name or runtime value up to ${limit} characters without controls; input unchanged.`;
990
+ }
991
+ else {
992
+ const limit = view.commandMode === 'python' ? PYTHON_LIMIT : COMMAND_LIMIT;
993
+ // Normalize once: readline may deliver CR and LF in separate events.
994
+ const normalized = pasted.replace(/\r\n?/g, '\n').replace(/\t/g, view.commandMode === 'python' ? ' ' : ' ');
995
+ const value = (view.command || '') + normalized;
996
+ if (value.length <= limit && printableInput(normalized.replace(/\n/g, ''))) {
997
+ view.command = value;
998
+ view.commandMessage = '';
999
+ }
1000
+ else
1001
+ view.commandMessage = `Input unchanged: maximum ${limit} characters; only printable text and newlines are allowed.`;
1002
+ }
1003
+ }
1004
+ if (pasting && view.screen === 'create' && view.creation && !pending && creationTextFields[view.creation.field]) {
1005
+ const draft = view.creation;
1006
+ const field = creationTextFields[draft.field];
1007
+ const limit = creationFieldLimit(draft.field);
1008
+ if (field && /^[\x20-\x7e]*$/.test(pasted) && pasted.length <= limit) {
1009
+ draft[field] = ((draft.replace ? '' : draft[field]) + pasted).slice(0, limit);
1010
+ draft.replace = false;
1011
+ draft.error = undefined;
1012
+ }
1013
+ else
1014
+ draft.error = `Paste one value at a time (up to ${limit} characters).`;
1015
+ }
1016
+ if (pasting && view.screen === 'actions' && !pending) {
1017
+ view.actionQuery = ((view.actionQuery || '') + pasted).slice(0, 100);
1018
+ view.actionSelected = undefined;
1019
+ view.actionMessage = '';
1020
+ }
1021
+ pasting = false;
1022
+ pasted = '';
1023
+ draw();
1024
+ return;
1025
+ }
1026
+ if (pasting) {
1027
+ if (view.screen === 'taskRegistry' && view.registry?.form && text) {
1028
+ pasted = (pasted + text).slice(0, 44);
1029
+ }
1030
+ else if (view.screen === 'agentChat' && view.chat?.editing && text) {
1031
+ pasted = (pasted + text).slice(0, 4097);
1032
+ }
1033
+ else if ((view.screen === 'upload' || view.screen === 'inputBatch') && text) {
1034
+ pasted = (pasted + text).slice(0, 4097);
1035
+ }
1036
+ else if ((view.searching || view.screen === 'tasks' && view.tasks?.searching) && text) {
1037
+ const normalized = text.replace(/[\r\n\t]/g, ' ');
1038
+ if (printableInput(normalized))
1039
+ pasted = limitText(pasted + normalized, 200);
1040
+ }
1041
+ else if (view.screen === 'delegate' && view.delegation && !pending && text) {
1042
+ pasted = (pasted + text).slice(0, delegationFields[view.delegation.field].limit + 1);
1043
+ }
1044
+ else if (view.screen === 'command' && view.commandEditing && !pending && text) {
1045
+ if (view.commandMode !== 'exec' && view.workerLaunch && view.workerLaunch.field > 0)
1046
+ pasted = (pasted + text).slice(0, 129);
1047
+ else {
1048
+ // CRLF normalization can halve the raw length. Keep twice the limit
1049
+ // plus a sentinel: an overflowing buffer must still fail after normalization.
1050
+ pasted = (pasted + text).slice(0, 2 * (view.commandMode === 'python' ? PYTHON_LIMIT : COMMAND_LIMIT) + 1);
1051
+ }
1052
+ }
1053
+ else if (view.screen === 'create' && !pending && text) {
1054
+ pasted = (pasted + text).slice(0, creationFieldLimit(view.creation?.field ?? 0) + 1);
1055
+ }
1056
+ else if (view.screen === 'actions' && text) {
1057
+ pasted = (pasted + text.replace(/[\r\n\t]/g, ' ').replace(/[^\x20-\x7e]/g, '')).slice(0, 100);
1058
+ }
1059
+ return;
1060
+ }
1061
+ if (key.ctrl && key.name === 'c') {
1062
+ cleanup();
1063
+ return;
1064
+ }
1065
+ if (view.screen === 'taskRegistry' && view.registry?.form && !pending) {
1066
+ const state = view.registry, form = state.form;
1067
+ if (key.name === 'escape')
1068
+ state.form = undefined;
1069
+ else if (key.ctrl && key.name === 'u')
1070
+ form.principal = '';
1071
+ else if (key.name === 'tab' || key.name === 'up' || key.name === 'down')
1072
+ form.field = 1 - form.field;
1073
+ else if (key.name === 'left' || key.name === 'right' || text === ' ' && form.field === 1)
1074
+ form.role = form.role === 'viewer' ? 'operator' : 'viewer';
1075
+ else if (key.name === 'backspace' && form.field === 0)
1076
+ form.principal = form.principal.slice(0, -1);
1077
+ else if (key.name === 'return') {
1078
+ try {
1079
+ reviewRegistry(state, registryController.access(state, 'grant', form.principal, form.role));
1080
+ }
1081
+ catch (error) {
1082
+ state.notice = error instanceof Error ? error.message : 'Grant review failed.';
1083
+ }
1084
+ }
1085
+ else if (!key.ctrl && !key.meta && form.field === 0 && text && /^[a-f0-9:-]+$/.test(text))
1086
+ form.principal = (form.principal + text).slice(0, 43);
1087
+ draw();
1088
+ return;
1089
+ }
1090
+ if (view.screen === 'agentChat' && view.chat?.editing && !pending) {
1091
+ const state = view.chat, api = model.api.chats;
1092
+ if (key.name === 'escape') {
1093
+ state.editing = false;
1094
+ state.draft = '';
1095
+ }
1096
+ else if (key.ctrl && ['b', 'f'].includes(key.name || '') && !state.sending) {
1097
+ state.editing = false;
1098
+ if (key.name === 'b')
1099
+ openBundles(state.taskId, undefined, 'agentChat');
1100
+ else
1101
+ openChatFiles(state);
1102
+ }
1103
+ else if (!options.readOnly && !state.sending) {
1104
+ if (key.ctrl && key.name === 'u')
1105
+ state.draft = '';
1106
+ else if (key.name === 'backspace')
1107
+ state.draft = backspaceText(state.draft);
1108
+ else if (key.name === 'return' && !model.busy && state.draft.trim() && api) {
1109
+ const draft = state.draft;
1110
+ state.sending = true;
1111
+ mutate('Send agent message', async () => {
1112
+ try {
1113
+ const plan = await api.plan(state.taskId, draft);
1114
+ await deliverChat(state, plan);
1115
+ }
1116
+ catch (error) {
1117
+ if (error instanceof AgentChatInputCapabilityError)
1118
+ state.editing = false;
1119
+ state.notice = error instanceof Error ? error.message : 'Message planning failed; nothing was sent.';
1120
+ }
1121
+ finally {
1122
+ state.sending = false;
1123
+ }
1124
+ });
1125
+ }
1126
+ else if (!key.ctrl && !key.meta && text && printableInput(text)) {
1127
+ const message = state.draft + text;
1128
+ if (message.length <= 4096 && Buffer.byteLength(message) <= 8192) {
1129
+ state.draft = message;
1130
+ state.notice = undefined;
1131
+ }
1132
+ else
1133
+ state.notice = 'Message limit: 4096 characters / 8192 UTF-8 bytes; draft unchanged.';
1134
+ }
1135
+ }
1136
+ draw();
1137
+ return;
1138
+ }
1139
+ if (view.screen === 'tasks' && view.tasks?.searching) {
1140
+ const state = view.tasks;
1141
+ if (key.name === 'escape') {
1142
+ state.query = state.searchBefore;
1143
+ state.selectedId = state.searchSelectedBefore;
1144
+ state.searching = false;
1145
+ }
1146
+ else if (key.name === 'return')
1147
+ state.searching = false;
1148
+ else if (key.ctrl && key.name === 'u')
1149
+ state.query = '';
1150
+ else if (key.name === 'backspace')
1151
+ state.query = backspaceText(state.query || '');
1152
+ else if (!key.ctrl && !key.meta && text && printableInput(text))
1153
+ state.query = limitText((state.query || '') + text, 200);
1154
+ state.notice = undefined;
1155
+ view.scroll = 0;
1156
+ draw();
1157
+ return;
1158
+ }
1159
+ if (view.screen === 'inputBatch' && view.inputBatch && !pending) {
1160
+ const state = view.inputBatch;
1161
+ const handle = (work) => { void work.catch(error => { if (!closed && view.inputBatch === state && view.screen === 'inputBatch')
1162
+ state.message = error instanceof Error ? error.message : 'Input batch operation failed.'; }).finally(draw); };
1163
+ if (key.name === 'escape') {
1164
+ view.screen = view.files ? 'files' : 'list';
1165
+ view.scroll = 0;
1166
+ }
1167
+ else if (state.loading || state.uploading || model.busy)
1168
+ scroll(key.name);
1169
+ else if (state.plan) {
1170
+ if (key.name === 'v')
1171
+ handle(batchController.inspect(state));
1172
+ else if (key.name === 'c') {
1173
+ try {
1174
+ const pinned = batchController.review(state);
1175
+ view.scroll = 0;
1176
+ pending = { label: 'Upload only never-attempted files in this reviewed batch?', run: () => batchController.upload(state, pinned) };
1177
+ }
1178
+ catch (error) {
1179
+ state.message = error instanceof Error ? error.message : 'Input review failed.';
1180
+ }
1181
+ }
1182
+ else if (key.name === 'g') {
1183
+ if (!state.observation?.integrity_verified || state.observation.batch_id !== state.plan.batch_id || state.observation.manifest_sha256 !== state.plan.manifest_sha256)
1184
+ state.message = 'Verify this batch before attaching it to an agent task.';
1185
+ else {
1186
+ const before = view.delegation;
1187
+ performAction('delegate', state.plan.sandbox_id);
1188
+ if (view.delegation && view.delegation !== before) {
1189
+ view.delegation.inputBatch = state.plan.batch_id;
1190
+ view.delegation.inputSha256 = state.plan.manifest_sha256;
1191
+ }
1192
+ else
1193
+ state.message = model.message;
1194
+ }
1195
+ }
1196
+ else if (key.name === 'n') {
1197
+ view.inputBatch = { sandboxId: state.sandboxId, query: '' };
1198
+ view.scroll = 0;
1199
+ }
1200
+ else
1201
+ scroll(key.name);
1202
+ }
1203
+ else if (key.name === 'return')
1204
+ handle(batchController.prepare(state, Boolean(options.readOnly)));
1205
+ else if (key.ctrl && key.name === 'u')
1206
+ state.query = '';
1207
+ else if (key.name === 'backspace')
1208
+ state.query = backspaceText(state.query);
1209
+ else if (!key.ctrl && !key.meta && text && printableInput(text))
1210
+ state.query = limitText(state.query + text, 4096);
1211
+ draw();
1212
+ return;
1213
+ }
1214
+ if (view.screen === 'upload' && view.upload && !pending) {
1215
+ const state = view.upload;
1216
+ const api = model.api.inputs;
1217
+ const showInput = (path) => {
1218
+ if (closed || view.upload !== state || view.screen !== 'upload')
1219
+ return;
1220
+ view.files = { sandboxId: state.sandboxId, directory: posix.dirname(path), selectedPath: path, rows: [], message: `Input verified | SHA-256: ${state.plan?.sha256}` };
1221
+ view.screen = 'files';
1222
+ view.scroll = 0;
1223
+ void refreshFiles();
1224
+ };
1225
+ if (key.name === 'escape') {
1226
+ view.screen = 'files';
1227
+ view.scroll = 0;
1228
+ }
1229
+ else if (model.busy)
1230
+ scroll(key.name);
1231
+ else if (state.attempted && state.plan) {
1232
+ if (key.name === 'v' && api && !model.busy && !state.planning) {
1233
+ state.planning = true;
1234
+ state.message = 'Verifying remote bytes; no upload is repeated.';
1235
+ void api.verify(state.plan).then(receipt => showInput(receipt.remote_path))
1236
+ .catch(error => { state.message = error instanceof Error ? error.message : 'Input verification failed'; })
1237
+ .finally(() => { state.planning = false; draw(); });
1238
+ }
1239
+ else if (key.name === 'return' && !state.planning) {
1240
+ state.plan = undefined;
1241
+ state.attempted = false;
1242
+ state.message = 'Review a new destination before another upload.';
1243
+ }
1244
+ else
1245
+ scroll(key.name);
1246
+ }
1247
+ else if (!state.planning) {
1248
+ if (key.ctrl && key.name === 'u') {
1249
+ state.source = '';
1250
+ state.message = undefined;
1251
+ }
1252
+ else if (key.name === 'backspace')
1253
+ state.source = backspaceText(state.source);
1254
+ else if (key.name === 'return' && api && !model.busy) {
1255
+ state.planning = true;
1256
+ state.message = undefined;
1257
+ void api.plan(state.sandboxId, state.source).then(plan => {
1258
+ if (closed || view.screen !== 'upload' || view.upload !== state)
1259
+ return;
1260
+ state.plan = plan;
1261
+ view.scroll = 0;
1262
+ pending = { label: 'Upload this reviewed file to the new workspace directory?', run: async () => {
1263
+ state.attempted = true;
1264
+ state.uploading = true;
1265
+ state.message = 'Uploading and verifying remote bytes...';
1266
+ try {
1267
+ if (options.readOnly || snapshotStale(model, options.intervalMs) || model.rows.find(row => row.id === state.sandboxId)?.status !== 'running')
1268
+ throw new Error('Refresh a running sandbox before uploading.');
1269
+ const receipt = await api.upload(plan, () => !closed);
1270
+ showInput(receipt.remote_path);
1271
+ }
1272
+ catch (error) {
1273
+ state.message = `${error instanceof Error ? error.message : 'Upload failed'} Destination: ${plan.remote_path}`;
1274
+ throw error;
1275
+ }
1276
+ finally {
1277
+ state.uploading = false;
1278
+ }
1279
+ } };
1280
+ }).catch(error => { state.message = error instanceof Error ? error.message : 'Input review failed'; })
1281
+ .finally(() => { state.planning = false; draw(); });
1282
+ }
1283
+ else if (!key.ctrl && !key.meta && text && printableInput(text)) {
1284
+ if (state.source.length + text.length <= 4096) {
1285
+ state.source += text;
1286
+ state.message = undefined;
1287
+ }
1288
+ else
1289
+ state.message = 'Input unchanged: maximum 4096 characters.';
1290
+ }
1291
+ }
1292
+ draw();
1293
+ return;
1294
+ }
1295
+ if (view.searching) {
1296
+ if (key.name === 'escape') {
1297
+ model.setFilter(searchBefore);
1298
+ view.searching = false;
1299
+ }
1300
+ else if (key.name === 'return')
1301
+ view.searching = false;
1302
+ else if (key.ctrl && key.name === 'u')
1303
+ model.setFilter('');
1304
+ else if (key.name === 'backspace')
1305
+ model.setFilter(backspaceText(model.filter));
1306
+ else if (!key.ctrl && !key.meta && text && printableInput(text)) {
1307
+ model.setFilter(limitText(model.filter + text, 200));
1308
+ }
1309
+ draw();
1310
+ return;
1311
+ }
1312
+ if (view.screen === 'actions' && !pending) {
1313
+ const actions = filterActions(availableActions(model, options, view.actionTarget), view.actionQuery);
1314
+ const index = Math.max(0, actions.findIndex(action => action.id === view.actionSelected));
1315
+ if (key.name === 'escape' || key.name === 'f2')
1316
+ view.screen = view.actionReturn || 'list';
1317
+ else if (key.name === 'return' && actions[index]) {
1318
+ const action = actions[index];
1319
+ if (action.reason)
1320
+ view.actionMessage = action.reason;
1321
+ else {
1322
+ view.screen = view.actionReturn || 'list';
1323
+ performAction(action.id, view.actionTarget);
1324
+ }
1325
+ }
1326
+ else if (['up', 'down', 'home', 'end', 'pageup', 'pagedown'].includes(key.name || '')) {
1327
+ const delta = key.name === 'pageup' || key.name === 'pagedown' ? pageSize(output.rows || 24) : 1;
1328
+ const next = key.name === 'home' ? 0 : key.name === 'end' ? actions.length - 1 : index + (key.name === 'up' || key.name === 'pageup' ? -delta : delta);
1329
+ view.actionSelected = actions[Math.max(0, Math.min(actions.length - 1, next))]?.id;
1330
+ view.actionMessage = '';
1331
+ }
1332
+ else if (key.ctrl && key.name === 'u') {
1333
+ view.actionQuery = '';
1334
+ view.actionSelected = undefined;
1335
+ view.actionMessage = '';
1336
+ }
1337
+ else if (key.name === 'backspace') {
1338
+ view.actionQuery = (view.actionQuery || '').slice(0, -1);
1339
+ view.actionSelected = undefined;
1340
+ view.actionMessage = '';
1341
+ }
1342
+ else if (!key.ctrl && !key.meta && text && /^[\x20-\x7e]+$/.test(text)) {
1343
+ view.actionQuery = ((view.actionQuery || '') + text).slice(0, 100);
1344
+ view.actionSelected = undefined;
1345
+ view.actionMessage = '';
1346
+ }
1347
+ draw();
1348
+ return;
1349
+ }
1350
+ if (view.screen === 'create' && view.creation && !pending) {
1351
+ const draft = view.creation;
1352
+ const field = creationTextFields[draft.field];
1353
+ const count = options.backend === 'docker' ? 3 : creationTextFields.length;
1354
+ if (key.name === 'escape')
1355
+ view.screen = 'list';
1356
+ else if (key.name === 'tab' || key.name === 'up' || key.name === 'down') {
1357
+ const delta = key.name === 'up' || (key.name === 'tab' && key.shift) ? -1 : 1;
1358
+ draft.field = (draft.field + delta + count) % count;
1359
+ draft.replace = true;
1360
+ }
1361
+ else if (draft.field === 3 && (key.name === 'left' || key.name === 'right' || text === ' ')) {
1362
+ const index = resourceClasses.indexOf(draft.resourceClass);
1363
+ draft.resourceClass = resourceClasses[(index + (key.name === 'left' ? 2 : 1)) % 3];
1364
+ draft.error = undefined;
1365
+ }
1366
+ else if (draft.field === 5 && (key.name === 'left' || key.name === 'right' || text === ' ')) {
1367
+ const index = inferenceProviders.indexOf(draft.inference);
1368
+ draft.inference = inferenceProviders[(index + (key.name === 'left' ? 2 : 1)) % 3];
1369
+ draft.error = undefined;
1370
+ }
1371
+ else if (key.name === 'return' && !model.busy && !options.readOnly) {
1372
+ try {
1373
+ const reason = availableActions(model, options).find(action => action.id === 'create')?.reason;
1374
+ if (reason)
1375
+ throw new Error(reason);
1376
+ const fields = creationRequest(draft, options.createOptions, options.backend || 'api');
1377
+ draft.error = undefined;
1378
+ view.creationReview = true;
1379
+ view.scroll = 0;
1380
+ pending = { label: 'Create sandbox with these settings?', run: async () => {
1381
+ if (options.readOnly || snapshotStale(model, options.intervalMs))
1382
+ throw new Error('Refresh successfully before creating a sandbox.');
1383
+ view.screen = 'list';
1384
+ view.creationReview = false;
1385
+ const created = await model.api.create(fields);
1386
+ // Normalize via the next authoritative list; no fabricated running state.
1387
+ model.setFilter('');
1388
+ model.selectedId = sandboxRow(created).id;
1389
+ } };
1390
+ }
1391
+ catch (error) {
1392
+ draft.error = error instanceof Error ? error.message : 'Invalid settings';
1393
+ }
1394
+ }
1395
+ else if (field && key.ctrl && key.name === 'u') {
1396
+ draft[field] = '';
1397
+ draft.replace = false;
1398
+ draft.error = undefined;
1399
+ }
1400
+ else if (field && key.name === 'backspace') {
1401
+ draft[field] = draft[field].slice(0, -1);
1402
+ draft.replace = false;
1403
+ draft.error = undefined;
1404
+ }
1405
+ else if (field && !key.ctrl && !key.meta && text && /^[\x20-\x7e]+$/.test(text)) {
1406
+ draft[field] = ((draft.replace ? '' : draft[field]) + text).slice(0, creationFieldLimit(draft.field));
1407
+ draft.replace = false;
1408
+ draft.error = undefined;
1409
+ }
1410
+ draw();
1411
+ return;
1412
+ }
1413
+ if (view.screen === 'delegate' && view.delegation && !pending) {
1414
+ const draft = view.delegation;
1415
+ const field = delegationFields[draft.field];
1416
+ if (key.name === 'escape') {
1417
+ view.screen = 'tasks';
1418
+ view.tasks ||= { rows: [] };
1419
+ view.scroll = 0;
1420
+ void refreshTasks();
1421
+ }
1422
+ else if (key.name === 'tab' || key.name === 'up' || key.name === 'down') {
1423
+ const delta = key.name === 'up' || key.name === 'tab' && key.shift ? -1 : 1;
1424
+ draft.field = (draft.field + delta + delegationFields.length) % delegationFields.length;
1425
+ draft.replace = true;
1426
+ }
1427
+ else if (key.ctrl && key.name === 'u')
1428
+ editDelegation(draft, '', true);
1429
+ else if (key.name === 'backspace')
1430
+ editDelegation(draft, backspaceText(draft[field.key]), true);
1431
+ else if (key.name === 'return' && !model.busy && !draft.planning) {
1432
+ try {
1433
+ const fingerprint = JSON.stringify([delegationInput(draft), draft.inputBatch, draft.inputSha256]);
1434
+ draft.planning = true;
1435
+ void planDelegation(model.api, draft).then(plan => {
1436
+ if (closed || view.screen !== 'delegate' || view.delegation !== draft || JSON.stringify([delegationInput(draft), draft.inputBatch, draft.inputSha256]) !== fingerprint || pending)
1437
+ return;
1438
+ draft.plan = plan;
1439
+ view.scroll = 0;
1440
+ pending = { label: `Launch task ${plan.record.task_id} in ${draft.sandboxId}?`, run: async () => {
1441
+ if (options.readOnly || snapshotStale(model, options.intervalMs) || !model.rows.some(row => row.id === plan.record.sandbox_id && row.status === 'running')) {
1442
+ draft.error = 'Task sandbox is unavailable or stale. Refresh before launch.';
1443
+ draft.plan = undefined;
1444
+ throw new Error(draft.error);
1445
+ }
1446
+ try {
1447
+ await model.api.tasks.launch(plan, { continueLaunch: () => !closed && view.screen === 'delegate' && view.delegation === draft });
1448
+ }
1449
+ finally {
1450
+ view.tasks ||= { rows: [] };
1451
+ view.tasks.selectedId = plan.record.task_id;
1452
+ view.tasks.detailId = plan.record.task_id;
1453
+ if (!closed) {
1454
+ view.screen = 'task';
1455
+ view.scroll = 0;
1456
+ void refreshTasks();
1457
+ }
1458
+ }
1459
+ } };
1460
+ draw();
1461
+ }).catch(error => { draft.error = error instanceof Error ? error.message : 'Task plan failed'; draw(); }).finally(() => { draft.planning = false; });
1462
+ }
1463
+ catch (error) {
1464
+ draft.error = error instanceof Error ? error.message : 'Invalid task settings';
1465
+ }
1466
+ }
1467
+ else if (!key.ctrl && !key.meta && text)
1468
+ editDelegation(draft, text);
1469
+ draw();
1470
+ return;
1471
+ }
1472
+ if (view.screen === 'command' && view.commandEditing && !pending) {
1473
+ const draft = view.commandMode !== 'exec' ? view.workerLaunch : undefined;
1474
+ const field = draft?.field === 1 ? 'name' : 'timeout';
1475
+ const metadata = Boolean(draft && draft.field > 0);
1476
+ const edit = (value) => {
1477
+ if (metadata && draft) {
1478
+ draft[field] = value;
1479
+ draft.replace = false;
1480
+ }
1481
+ else
1482
+ view.command = value;
1483
+ view.commandMessage = '';
1484
+ };
1485
+ if (key.name === 'escape')
1486
+ view.screen = 'list';
1487
+ else if (view.commandMode === 'python' && !metadata && key.ctrl && key.name === 'j') {
1488
+ if ((view.command || '').length < PYTHON_LIMIT)
1489
+ edit((view.command || '') + '\n');
1490
+ else
1491
+ view.commandMessage = `Input unchanged: maximum ${PYTHON_LIMIT} characters.`;
1492
+ }
1493
+ else if (draft && (key.name === 'tab' || key.name === 'up' || key.name === 'down')) {
1494
+ const delta = key.name === 'up' || key.name === 'tab' && key.shift ? -1 : 1;
1495
+ draft.field = (draft.field + delta + 3) % 3;
1496
+ draft.replace = draft.field > 0;
1497
+ }
1498
+ else if (key.ctrl && key.name === 'u')
1499
+ edit('');
1500
+ else if (key.name === 'backspace')
1501
+ edit(backspaceText(metadata ? draft[field] : view.command || ''));
1502
+ else if (key.name === 'return' && view.command?.trim() && !model.busy) {
1503
+ const id = view.commandId;
1504
+ const command = view.command;
1505
+ const spawning = view.commandMode === 'spawn';
1506
+ const interpreting = view.commandMode === 'python';
1507
+ let task;
1508
+ let workerBody;
1509
+ try {
1510
+ if (spawning)
1511
+ workerBody = workerLaunchRequest(command, draft);
1512
+ if (interpreting)
1513
+ task = pythonTask(command, draft, randomUUID());
1514
+ }
1515
+ catch (error) {
1516
+ view.commandMessage = error instanceof Error ? error.message : 'Invalid worker settings.';
1517
+ draw();
1518
+ return;
1519
+ }
1520
+ if (workerBody && draft) {
1521
+ draft.name = workerBody.name;
1522
+ draft.timeout = String(workerBody.timeout_seconds);
1523
+ }
1524
+ const name = workerBody?.name;
1525
+ view.python = task;
1526
+ view.commandMessage = '';
1527
+ view.commandReview = spawning || interpreting;
1528
+ view.scroll = 0;
1529
+ pending = { label: spawning ? `Launch worker in ${id}?` : interpreting ? `Run Python task in ${id}?` : `Run command in ${id}?`,
1530
+ completed: () => spawning ? `Worker in ${id}: ${view.workers?.selectedId || name}. Inspect workers for status.` : `Command in ${id}: ${view.commandResult?.status || view.commandMessage}`, run: async () => {
1531
+ // Recheck the pinned target after confirmation, including remote removal.
1532
+ if (options.readOnly || snapshotStale(model, options.intervalMs) || !model.rows.some(row => row.id === id && row.status === 'running')) {
1533
+ view.commandMessage = 'Sandbox is unavailable or not running. Refresh before executing.';
1534
+ throw new Error(view.commandMessage);
1535
+ }
1536
+ view.commandEditing = false;
1537
+ view.commandReview = false;
1538
+ view.commandResult = undefined;
1539
+ view.commandMessage = 'Running... Esc returns to the list; submitted commands continue.';
1540
+ view.scroll = 0;
1541
+ draw();
1542
+ try {
1543
+ if (spawning) {
1544
+ if (!model.api.processes)
1545
+ throw new Error('Hosted supervised-process support is unavailable.');
1546
+ const worker = workerRow(await model.api.processes.start(id, workerBody));
1547
+ view.workers = { sandboxId: id, rows: [worker], selectedId: worker.id, updatedAt: new Date() };
1548
+ if (view.screen === 'command') {
1549
+ view.screen = 'workers';
1550
+ view.scroll = 0;
1551
+ void refreshWorkers();
1552
+ }
1553
+ }
1554
+ else if (model.api.executeStream) {
1555
+ if (task) {
1556
+ if (!model.api.mkdir || !model.api.writeFile)
1557
+ throw new Error('Python tasks require workspace file support.');
1558
+ await preparePythonTask({ mkdir: (...args) => model.api.mkdir(...args), writeFile: (...args) => model.api.writeFile(...args) }, id, task);
1559
+ // Quit can occur during source upload, before an execution is accepted.
1560
+ if (closed)
1561
+ return;
1562
+ }
1563
+ view.live?.stopWatching();
1564
+ const live = new LiveExecution(id, { executeStream: (...args) => model.api.executeStream(...args), executions: model.api.executions }, () => {
1565
+ if (!outputTimer && !closed)
1566
+ outputTimer = setTimeout(() => { outputTimer = undefined; draw(); }, 50);
1567
+ });
1568
+ view.live = live;
1569
+ view.commandResult = live.receipt;
1570
+ view.commandMessage = '';
1571
+ await live.run(task ? ['python3', '-u', task.source] : ['sh', '-lc', command], task ? { timeout: task.timeoutMs, workingDir: task.directory } : {});
1572
+ }
1573
+ else
1574
+ view.commandResult = commandReceipt(await model.api.execute(id, ['sh', '-lc', command]));
1575
+ view.commandMessage = '';
1576
+ }
1577
+ catch (error) {
1578
+ view.commandMessage = `Request failed: ${error instanceof Error ? error.message : 'Unknown error'}. Outcome may be unknown; inspect before repeating. Not retried.`;
1579
+ throw error;
1580
+ }
1581
+ } };
1582
+ }
1583
+ else if (!key.ctrl && !key.meta && text && printableInput(text)) {
1584
+ const value = (metadata && draft ? draft.replace ? '' : draft[field] : view.command || '') + text;
1585
+ const limit = metadata && draft ? draft.field === 1 ? 128 : 8 : view.commandMode === 'python' ? PYTHON_LIMIT : COMMAND_LIMIT;
1586
+ if (value.length <= limit)
1587
+ edit(value);
1588
+ else
1589
+ view.commandMessage = `Input unchanged: maximum ${limit} characters.`;
1590
+ }
1591
+ draw();
1592
+ return;
1593
+ }
1594
+ if (key.name === 'q') {
1595
+ cleanup();
1596
+ return;
1597
+ }
1598
+ // Modified shortcuts must not trigger lifecycle actions (e.g. Ctrl+D).
1599
+ // Node marks a standalone Escape as meta after its escape-sequence timeout.
1600
+ if (key.ctrl || (key.meta && key.name !== 'escape'))
1601
+ return;
1602
+ if (pending) {
1603
+ // Other keys cannot retarget a pending destructive action during refresh.
1604
+ if (key.name === 'escape') {
1605
+ pending = undefined;
1606
+ view.creationReview = false;
1607
+ view.commandReview = false;
1608
+ if (view.delegation)
1609
+ view.delegation.plan = undefined;
1610
+ if (view.tasks)
1611
+ view.tasks.collectionPlan = undefined;
1612
+ if (view.upload)
1613
+ view.upload.plan = undefined;
1614
+ if (view.registry)
1615
+ view.registry.review = undefined;
1616
+ if (view.inputBatch)
1617
+ view.inputBatch.review = false;
1618
+ }
1619
+ else if (key.name === 'y') {
1620
+ const action = pending;
1621
+ pending = undefined;
1622
+ if (action.control) {
1623
+ // Cancellation must remain available during foreground work. Local
1624
+ // draft disposal must not dispatch remote refreshes or mutations.
1625
+ void action.run().catch(error => { model.message = error instanceof Error ? error.message : 'Cancellation failed'; }).finally(draw);
1626
+ }
1627
+ else
1628
+ mutate(action.label, action.run, action.completed);
1629
+ }
1630
+ else if (view.screen === 'command' || view.screen === 'create' || view.screen === 'delegate' || view.screen === 'task' || view.screen === 'upload' || view.screen === 'inputBatch')
1631
+ scroll(key.name);
1632
+ draw();
1633
+ return;
1634
+ }
1635
+ if (key.name === 'f2' || text === ':') {
1636
+ const taskTarget = view.tasks?.rows.find(row => row.task.task_id === (view.screen === 'task' ? view.tasks?.detailId : view.tasks?.selectedId))?.task.sandbox_id;
1637
+ view.actionTarget = view.screen === 'details' ? view.detailId : view.screen === 'command' ? view.commandId
1638
+ : view.screen === 'taskResults' ? view.tasks?.rows.find(row => row.task.task_id === view.results?.taskId)?.task.sandbox_id
1639
+ : view.screen === 'agentChat' ? view.tasks?.rows.find(row => row.task.task_id === view.chat?.taskId)?.task.sandbox_id
1640
+ : view.screen === 'task' || view.screen === 'tasks' ? taskTarget || (view.screen === 'tasks' && !hasTaskFilters(view.tasks || {}) ? model.selectedId : undefined)
1641
+ : view.screen === 'files' ? view.files?.sandboxId
1642
+ : view.screen === 'workers' || view.screen === 'workerLogs' || view.screen === 'workerResult' ? view.workers?.sandboxId
1643
+ : view.screen === 'history' || view.screen === 'receipt' ? view.history?.sandboxId : model.selectedId;
1644
+ view.actionReturn = view.screen || 'list';
1645
+ view.screen = 'actions';
1646
+ view.actionQuery = '';
1647
+ view.actionSelected = undefined;
1648
+ view.actionMessage = '';
1649
+ view.scroll = 0;
1650
+ draw();
1651
+ return;
1652
+ }
1653
+ if (view.screen === 'taskRegistry' && view.registry) {
1654
+ const state = view.registry;
1655
+ if (state.logOpen) {
1656
+ if (key.name === 'escape') {
1657
+ state.logOpen = false;
1658
+ state.log = undefined;
1659
+ state.error = undefined;
1660
+ view.scroll = 0;
1661
+ }
1662
+ else if (key.name === 's') {
1663
+ view.scroll = 0;
1664
+ void registryController.logs(state, state.logStream === 'stderr' ? 'stdout' : 'stderr');
1665
+ }
1666
+ else if (key.name === 'r') {
1667
+ view.scroll = 0;
1668
+ void registryController.logs(state, state.logStream || 'stdout');
1669
+ }
1670
+ else if (key.name === 'n' && state.log?.log && !state.loading && !state.error) {
1671
+ const offset = state.log.log.next_offset;
1672
+ view.scroll = 0;
1673
+ void registryController.logs(state, state.logStream || 'stdout', offset);
1674
+ }
1675
+ else
1676
+ scroll(key.name);
1677
+ draw();
1678
+ return;
1679
+ }
1680
+ if (key.name === 'escape') {
1681
+ if (state.detailId && !state.localRecord) {
1682
+ state.detailId = undefined;
1683
+ state.detail = undefined;
1684
+ state.grants = [];
1685
+ state.error = undefined;
1686
+ state.notice = undefined;
1687
+ }
1688
+ else
1689
+ view.screen = state.returnTo;
1690
+ view.scroll = 0;
1691
+ }
1692
+ else if (key.name === 'r') {
1693
+ state.review = undefined;
1694
+ void registryController.refresh(state);
1695
+ }
1696
+ else if (!state.detailId) {
1697
+ if (key.name === 'n' && state.nextCursor && !state.loading && !state.error) {
1698
+ state.history.push(state.cursor);
1699
+ state.cursor = state.nextCursor;
1700
+ view.scroll = 0;
1701
+ void registryController.refresh(state);
1702
+ }
1703
+ else if (key.name === 'b' && state.history.length && !state.loading) {
1704
+ state.cursor = state.history.pop();
1705
+ view.scroll = 0;
1706
+ void registryController.refresh(state);
1707
+ }
1708
+ else if (key.name === 'f' && state.selectedId) {
1709
+ state.rootTaskId = state.rows.find(row => row.task_id === state.selectedId).root_task_id;
1710
+ state.cursor = undefined;
1711
+ state.history = [];
1712
+ view.scroll = 0;
1713
+ void registryController.refresh(state);
1714
+ }
1715
+ else if (key.name === 'a') {
1716
+ state.rootTaskId = undefined;
1717
+ state.cursor = undefined;
1718
+ state.history = [];
1719
+ view.scroll = 0;
1720
+ void registryController.refresh(state);
1721
+ }
1722
+ else if (key.name === 'return' && state.selectedId && !state.loading && !state.error) {
1723
+ state.detailId = state.selectedId;
1724
+ state.form = undefined;
1725
+ state.notice = undefined;
1726
+ view.scroll = 0;
1727
+ void registryController.refresh(state);
1728
+ }
1729
+ else if (['up', 'down', 'j', 'k', 'home', 'end'].includes(key.name || '')) {
1730
+ const index = state.rows.findIndex(row => row.task_id === state.selectedId);
1731
+ const next = key.name === 'home' ? 0 : key.name === 'end' ? state.rows.length - 1 : index + (key.name === 'up' || key.name === 'k' ? -1 : 1);
1732
+ state.selectedId = state.rows[Math.max(0, Math.min(state.rows.length - 1, next))]?.task_id;
1733
+ }
1734
+ else
1735
+ scroll(key.name);
1736
+ }
1737
+ else {
1738
+ try {
1739
+ if (key.name === 'v' && !state.loading)
1740
+ void registryController.observe(state);
1741
+ else if (key.name === 'l' && !state.loading) {
1742
+ view.scroll = 0;
1743
+ void registryController.logs(state, 'stdout');
1744
+ }
1745
+ else if (key.name === 'e' && !state.loading) {
1746
+ view.scroll = 0;
1747
+ void registryController.logs(state, 'stderr');
1748
+ }
1749
+ else if (key.name === 'p')
1750
+ reviewRegistry(state, registryController.registration(state));
1751
+ else if (key.name === 'g')
1752
+ registryController.beginGrant(state);
1753
+ else if (key.name === 'd' && state.selectedGrant)
1754
+ reviewRegistry(state, registryController.access(state, 'revoke', state.selectedGrant));
1755
+ else if (key.name === 'f' && state.detail) {
1756
+ state.rootTaskId = state.detail.root_task_id;
1757
+ state.detailId = undefined;
1758
+ state.localRecord = undefined;
1759
+ state.cursor = undefined;
1760
+ state.history = [];
1761
+ view.scroll = 0;
1762
+ void registryController.refresh(state);
1763
+ }
1764
+ else if (['up', 'down', 'j', 'k'].includes(key.name || '') && state.grants.length) {
1765
+ const index = state.grants.findIndex(grant => grant.principal === state.selectedGrant);
1766
+ state.selectedGrant = state.grants[Math.max(0, Math.min(state.grants.length - 1, index + (key.name === 'up' || key.name === 'k' ? -1 : 1)))]?.principal;
1767
+ }
1768
+ else
1769
+ scroll(key.name);
1770
+ }
1771
+ catch (error) {
1772
+ state.notice = error instanceof Error ? error.message : 'Registry review failed.';
1773
+ }
1774
+ }
1775
+ draw();
1776
+ return;
1777
+ }
1778
+ if (view.screen === 'agentChat' && view.chat) {
1779
+ const state = view.chat, api = model.api.chats;
1780
+ if (state.controls) {
1781
+ const controls = state.controls, requests = chatRequests(state);
1782
+ const index = Math.max(0, requests.findIndex(request => request.request_id === controls.selectedId));
1783
+ const selected = requests[index];
1784
+ if (key.name === 'escape' || key.name === 'c') {
1785
+ state.controls = undefined;
1786
+ state.follow = true;
1787
+ view.scroll = 0;
1788
+ }
1789
+ else if (key.name === 'r')
1790
+ void refreshChat(true);
1791
+ else if (['j', 'k', 'up', 'down'].includes(key.name || '')) {
1792
+ controls.selectedId = requests[Math.max(0, Math.min(requests.length - 1, index + (key.name === 'k' || key.name === 'up' ? -1 : 1)))]?.request_id;
1793
+ controls.receipt = undefined;
1794
+ controls.error = undefined;
1795
+ view.scroll = 0;
1796
+ }
1797
+ else if (key.name === 'return' && api && selected && !controls.loading) {
1798
+ if (!selected.sha256)
1799
+ controls.error = 'This worker did not publish a SHA-256. Use the sending parent’s saved request intent.';
1800
+ else {
1801
+ const request = { request_id: selected.request_id, sha256: selected.sha256 };
1802
+ controls.selectedId = request.request_id;
1803
+ controls.loading = true;
1804
+ controls.error = undefined;
1805
+ controls.receipt = undefined;
1806
+ const scope = observeChat(() => !closed && view.screen === 'agentChat' && view.chat === state
1807
+ && state.controls === controls && controls.selectedId === request.request_id);
1808
+ void model.read(async () => {
1809
+ if (!scope.active())
1810
+ return undefined;
1811
+ markChatReceiptAttempt(state, request);
1812
+ return api.receipt(state.taskId, request.request_id, request.sha256, scope.signal);
1813
+ }).then(receipt => {
1814
+ if (!receipt || !scope.active())
1815
+ return;
1816
+ observeChatReceipt(state, receipt);
1817
+ if (state.controls === controls && controls.selectedId === request.request_id)
1818
+ controls.receipt = receipt;
1819
+ }).catch(error => {
1820
+ if (scope.active())
1821
+ controls.error = error instanceof Error ? error.message : 'Receipt unavailable';
1822
+ }).finally(() => { scope.close(); controls.loading = false; draw(); });
1823
+ }
1824
+ }
1825
+ else if (key.name === 'd' && selected) {
1826
+ if (options.readOnly)
1827
+ controls.error = 'Read-only: draft recovery is disabled.';
1828
+ else if (restoreChatDraft(state, selected.request_id, true)) {
1829
+ state.controls = undefined;
1830
+ state.follow = true;
1831
+ view.scroll = 0;
1832
+ }
1833
+ else
1834
+ controls.error = state.draft ? 'Composer already holds a draft. Review or clear it before recovering another.'
1835
+ : 'No verified rejected draft is held by this parent. Verify its receipt; uncertain messages are never restored.';
1836
+ }
1837
+ else if (key.name === 'delete' && selected) {
1838
+ if (options.readOnly)
1839
+ controls.error = 'Read-only: forgetting local drafts is disabled.';
1840
+ else {
1841
+ const held = state.heldDrafts?.find(draft => draft.request_id === selected.request_id && draft.sha256 === selected.sha256);
1842
+ if (!held || state.sending)
1843
+ controls.error = 'No local draft is available to forget. Receipt history is unchanged.';
1844
+ else {
1845
+ const request = { request_id: held.request_id, sha256: held.sha256 };
1846
+ pending = { label: `Forget local draft ${request.request_id}? Saved receipts remain.`, control: 'forget-chat-draft',
1847
+ run: async () => {
1848
+ if (closed || options.readOnly || view.screen !== 'agentChat' || view.chat !== state || state.controls !== controls)
1849
+ return;
1850
+ if (discardChatDraft(state, request.request_id, request.sha256))
1851
+ controls.error = undefined;
1852
+ else
1853
+ controls.error = 'Draft already resolved or unavailable; nothing was forgotten.';
1854
+ } };
1855
+ }
1856
+ }
1857
+ }
1858
+ else
1859
+ scroll(key.name);
1860
+ draw();
1861
+ return;
1862
+ }
1863
+ if (key.name === 'escape') {
1864
+ view.screen = 'task';
1865
+ view.scroll = 0;
1866
+ }
1867
+ else if (key.name === 'c') {
1868
+ state.controls = { selectedId: state.request?.request_id || chatRequests(state)[0]?.request_id };
1869
+ state.follow = false;
1870
+ view.scroll = 0;
1871
+ }
1872
+ else if (key.name === 'b')
1873
+ openBundles(state.taskId, undefined, 'agentChat');
1874
+ else if (key.name === 'f')
1875
+ openChatFiles(state);
1876
+ else if (key.name === 'r')
1877
+ void refreshChat(true);
1878
+ else if (key.name === 'z' && !options.readOnly && !model.busy && !state.sending && api) {
1879
+ if (!state.snapshot || state.error || state.snapshot.process_status !== 'running')
1880
+ state.notice = 'Refresh a ready agent conversation first.';
1881
+ else if (state.snapshot.state.finish_session !== 'idle-only-v1')
1882
+ state.notice = 'This worker does not advertise graceful session finish.';
1883
+ else if (state.snapshot.state.status !== 'idle' || state.snapshot.state.active_turn_id || state.pendingRequests?.length)
1884
+ state.notice = 'Wait for the current turn and pending controls before finishing this session.';
1885
+ else {
1886
+ state.sending = true;
1887
+ void model.read(() => api.plan(state.taskId, '', 'finish')).then(plan => {
1888
+ if (closed || view.chat !== state || view.screen !== 'agentChat')
1889
+ return;
1890
+ pending = { label: `Finish idle session ${plan.thread_id}? Wait for worker exit before collecting artifacts.`, run: () => deliverChat(state, plan) };
1891
+ }).catch(error => { state.notice = error instanceof Error ? error.message : 'Finish review failed'; })
1892
+ .finally(() => { state.sending = false; draw(); });
1893
+ }
1894
+ }
1895
+ else if ((key.name === 'i' || key.name === 'x') && !options.readOnly && (key.name === 'i' || !model.busy) && !state.sending && api) {
1896
+ if (!state.snapshot || state.error || state.snapshot.process_status !== 'running' || !['idle', 'running'].includes(state.snapshot.state.status))
1897
+ state.notice = 'Refresh a ready agent conversation first.';
1898
+ else if (key.name === 'i') {
1899
+ state.editing = true;
1900
+ state.follow = true;
1901
+ state.notice = undefined;
1902
+ }
1903
+ else if (state.snapshot.state.active_turn_id) {
1904
+ state.sending = true;
1905
+ void model.read(() => api.plan(state.taskId, '', 'interrupt')).then(plan => {
1906
+ if (closed || view.chat !== state || view.screen !== 'agentChat')
1907
+ return;
1908
+ pending = { label: `Interrupt turn ${plan.expected_turn_id} in this conversation?`, run: () => deliverChat(state, plan) };
1909
+ }).catch(error => { state.notice = error instanceof Error ? error.message : 'Interrupt review failed'; })
1910
+ .finally(() => { state.sending = false; draw(); });
1911
+ }
1912
+ else
1913
+ state.notice = 'No active turn to interrupt.';
1914
+ }
1915
+ else if (['i', 'x', 'z'].includes(key.name || '') && options.readOnly)
1916
+ state.notice = key.name === 'z'
1917
+ ? 'Read-only: session finish is disabled.' : 'Read-only: messaging and interruption are disabled.';
1918
+ else {
1919
+ state.follow = key.name === 'end';
1920
+ scroll(key.name);
1921
+ }
1922
+ draw();
1923
+ return;
1924
+ }
1925
+ if (key.name === 'v' && imagePreview()?.image) {
1926
+ const preview = imagePreview();
1927
+ view.imageDetailsKey = view.imageDetailsKey === preview.sha256 ? undefined : preview.sha256;
1928
+ view.scroll = 0;
1929
+ draw();
1930
+ return;
1931
+ }
1932
+ if (view.screen === 'taskResults' && view.results) {
1933
+ const state = view.results;
1934
+ const api = model.api.taskResults;
1935
+ if (key.name === 'escape') {
1936
+ if (state.preview)
1937
+ state.preview = undefined;
1938
+ else if (state.bundle)
1939
+ state.bundle = undefined;
1940
+ else
1941
+ view.screen = state.returnTo || 'task';
1942
+ view.scroll = 0;
1943
+ state.error = undefined;
1944
+ }
1945
+ else if (key.name === 'r' && !resultRead)
1946
+ openBundles(state.taskId, state.bundle?.manifest.collection_id, state.returnTo);
1947
+ else if (!state.preview && ['up', 'down', 'j', 'k', 'home', 'end'].includes(key.name || '')) {
1948
+ const index = state.bundle ? state.artifactIndex : state.rows.findIndex(row => row.collection_id === state.selectedId);
1949
+ const length = state.bundle ? state.bundle.manifest.artifacts.length : state.rows.length;
1950
+ const next = Math.max(0, Math.min(length - 1, key.name === 'home' ? 0 : key.name === 'end' ? length - 1 : index + (key.name === 'up' || key.name === 'k' ? -1 : 1)));
1951
+ if (state.bundle)
1952
+ state.artifactIndex = next;
1953
+ else
1954
+ state.selectedId = state.rows[next]?.collection_id;
1955
+ }
1956
+ else if (key.name === 'return' && api && !resultRead && !state.preview) {
1957
+ const bundle = state.bundle;
1958
+ const selectedId = state.selectedId;
1959
+ const artifact = bundle?.manifest.artifacts[state.artifactIndex];
1960
+ resultRead = (async () => {
1961
+ try {
1962
+ state.error = undefined;
1963
+ if (bundle && artifact) {
1964
+ const file = await readTaskResultArtifact(bundle.directory, artifact.path, bundle.manifest_sha256);
1965
+ if (!closed && view.results === state && state.bundle === bundle)
1966
+ state.preview = filePreview(artifact.path, file.data);
1967
+ }
1968
+ else if (selectedId) {
1969
+ const loaded = await api.get(state.taskId, selectedId);
1970
+ if (!closed && view.results === state) {
1971
+ state.bundle = loaded;
1972
+ state.artifactIndex = 0;
1973
+ }
1974
+ }
1975
+ }
1976
+ catch (error) {
1977
+ state.error = error instanceof Error ? error.message : 'Saved result read failed';
1978
+ }
1979
+ })().finally(() => { if (view.results === state) {
1980
+ resultRead = undefined;
1981
+ view.scroll = 0;
1982
+ } draw(); });
1983
+ }
1984
+ else
1985
+ scroll(key.name);
1986
+ draw();
1987
+ return;
1988
+ }
1989
+ if (view.screen === 'taskArchive' && view.archive) {
1990
+ const state = view.archive;
1991
+ if (key.name === 'escape') {
1992
+ view.screen = 'tasks';
1993
+ view.scroll = 0;
1994
+ }
1995
+ else if (key.name === 'r' && !state.loading && view.tasks) {
1996
+ const tasks = state.members.map(member => view.tasks.rows.find(row => row.task.task_id === member.taskId)?.task)
1997
+ .filter((task) => Boolean(task));
1998
+ if (tasks.length)
1999
+ openArchive(taskArchive(tasks, state.selectedTaskId, state.family, state.query));
2000
+ }
2001
+ else if (['up', 'down', 'j', 'k', 'home', 'end'].includes(key.name || '')) {
2002
+ const index = state.members.findIndex(member => member.taskId === state.selectedTaskId);
2003
+ const next = key.name === 'home' ? 0 : key.name === 'end' ? state.members.length - 1
2004
+ : index + (key.name === 'up' || key.name === 'k' ? -1 : 1);
2005
+ state.selectedTaskId = state.members[Math.max(0, Math.min(state.members.length - 1, next))]?.taskId;
2006
+ }
2007
+ else if (key.name === 'return') {
2008
+ const member = state.members.find(member => member.taskId === state.selectedTaskId);
2009
+ if (member)
2010
+ openBundles(member.taskId, member.bundles?.find(bundle => !bundle.unavailable)?.collection_id, 'taskArchive');
2011
+ }
2012
+ else
2013
+ scroll(key.name);
2014
+ draw();
2015
+ return;
2016
+ }
2017
+ if ((view.screen === 'tasks' || view.screen === 'task') && view.tasks) {
2018
+ const state = view.tasks;
2019
+ const visible = reconcileTaskSelection(state);
2020
+ const row = state.rows.find(row => row.task.task_id === (view.screen === 'task' ? state.detailId : state.selectedId));
2021
+ if (key.name === 'escape') {
2022
+ if (view.screen === 'tasks' && hasTaskFilters(state))
2023
+ clearTaskFilters(state);
2024
+ else
2025
+ view.screen = view.screen === 'task' ? 'tasks' : 'list';
2026
+ view.scroll = 0;
2027
+ }
2028
+ else if (key.name === 'r') {
2029
+ void refreshTasks(true);
2030
+ }
2031
+ else if (key.name === 'u') {
2032
+ openRegistry(registryView(view.screen, view.screen === 'task' ? row?.task : undefined));
2033
+ }
2034
+ else if (key.name === 'g') {
2035
+ const child = view.screen === 'task';
2036
+ if (!row && (child || hasTaskFilters(state)))
2037
+ state.notice = 'No visible task selected. Clear filters before delegating.';
2038
+ else {
2039
+ performAction('delegate', row?.task.sandbox_id || model.selectedId);
2040
+ if (view.delegation && row && child)
2041
+ view.delegation.parent = row.task.task_id;
2042
+ }
2043
+ }
2044
+ else if (key.name === 'n' && view.screen === 'tasks')
2045
+ performAction('create', model.selectedId);
2046
+ else if (view.screen === 'tasks') {
2047
+ const index = visible.findIndex(item => item.task.task_id === state.selectedId);
2048
+ if (key.name === '/' || text === '/') {
2049
+ state.searchBefore = state.query;
2050
+ state.searchSelectedBefore = state.selectedId;
2051
+ state.searching = true;
2052
+ view.scroll = 0;
2053
+ }
2054
+ else if (key.name === 't') {
2055
+ state.mode = taskViewModes[(taskViewModes.indexOf(state.mode || 'all') + 1) % taskViewModes.length];
2056
+ state.notice = undefined;
2057
+ view.scroll = 0;
2058
+ }
2059
+ else if (key.name === 'p') {
2060
+ if (row) {
2061
+ state.family = row.task.parent_task_id || row.task.task_id;
2062
+ state.notice = undefined;
2063
+ view.scroll = 0;
2064
+ }
2065
+ }
2066
+ else if (key.name === 'a') {
2067
+ clearTaskFilters(state);
2068
+ view.scroll = 0;
2069
+ }
2070
+ else if (key.name === 'b') {
2071
+ try {
2072
+ openArchive(taskArchive(visible.map(row => row.task), state.selectedId, state.family, state.query));
2073
+ }
2074
+ catch (error) {
2075
+ state.error = error instanceof Error ? error.message : 'Task archive could not be opened.';
2076
+ }
2077
+ }
2078
+ else if (['up', 'down', 'j', 'k', 'home', 'end', 'pageup', 'pagedown'].includes(key.name || '')) {
2079
+ const delta = key.name === 'pageup' || key.name === 'pagedown' ? Math.max(1, Math.floor(pageSize(output.rows || 24) / 3)) : 1;
2080
+ const next = key.name === 'home' ? 0 : key.name === 'end' ? visible.length - 1 : index + (['up', 'k', 'pageup'].includes(key.name || '') ? -delta : delta);
2081
+ state.selectedId = visible[Math.max(0, Math.min(visible.length - 1, next))]?.task.task_id;
2082
+ }
2083
+ if (key.name === 'return' && row) {
2084
+ state.detailId = row.task.task_id;
2085
+ view.screen = 'task';
2086
+ view.scroll = 0;
2087
+ void refreshTasks(false, true);
2088
+ }
2089
+ }
2090
+ else if (row) {
2091
+ if (key.name === 's') {
2092
+ if (!model.api.chats)
2093
+ state.error = 'Agent conversations require the updated hosted client.';
2094
+ else if (row.task.stdin !== true)
2095
+ state.error = 'This task has no conversational stdin. Use a prepared chat worker with stdin enabled.';
2096
+ else {
2097
+ let chat = chatViews.get(row.task.task_id);
2098
+ if (!chat && chatViews.size >= 30) {
2099
+ const available = [...chatViews].find(([, saved]) => !saved.draft && !saved.heldDrafts?.length && !saved.pendingRequests?.length && !saved.sending);
2100
+ if (available)
2101
+ chatViews.delete(available[0]);
2102
+ else {
2103
+ state.error = '30 conversations hold drafts or pending controls. Resolve their receipts or drafts before opening another.';
2104
+ draw();
2105
+ return;
2106
+ }
2107
+ }
2108
+ if (!chat) {
2109
+ chat = { taskId: row.task.task_id, draft: '', follow: true };
2110
+ chatViews.set(chat.taskId, chat);
2111
+ }
2112
+ view.chat = chat;
2113
+ view.screen = 'agentChat';
2114
+ view.scroll = 0;
2115
+ void refreshChat(true);
2116
+ }
2117
+ }
2118
+ else if (key.name === 'b')
2119
+ openBundles(row.task.task_id);
2120
+ else if (key.name === 'c' && model.api.taskResults && !model.busy && !resultPlanning) {
2121
+ const taskId = row.task.task_id;
2122
+ resultPlanning = true;
2123
+ void model.api.taskResults.plan(taskId).then(plan => {
2124
+ if (closed || view.screen !== 'task' || state.detailId !== taskId || pending)
2125
+ return;
2126
+ state.collectionPlan = plan;
2127
+ state.error = undefined;
2128
+ view.scroll = 0;
2129
+ pending = { label: 'Collect declared artifacts into this new private directory?', run: async () => {
2130
+ state.collectionPlan = undefined;
2131
+ state.collectionMessage = `Collecting declared artifacts into ${plan.directory}`;
2132
+ try {
2133
+ const bundle = await model.api.taskResults.collect(plan);
2134
+ state.collectionMessage = `Collected ${bundle.manifest.artifacts.filter(a => a.state === 'collected').length}/${bundle.manifest.artifacts.length} artifacts: ${bundle.directory}`;
2135
+ if (!closed)
2136
+ openBundles(taskId, bundle.manifest.collection_id);
2137
+ }
2138
+ catch (error) {
2139
+ state.error = error instanceof TaskResultCollectionError ? `${error.message} Directory: ${error.directory}` : error instanceof Error ? error.message : 'Collection failed';
2140
+ state.collectionMessage = `Collection failed: ${state.error}`;
2141
+ throw error;
2142
+ }
2143
+ } };
2144
+ }).catch(error => { if (!closed && view.screen === 'task' && state.detailId === taskId)
2145
+ state.error = error instanceof Error ? error.message : 'Collection planning failed'; })
2146
+ .finally(() => { resultPlanning = false; draw(); });
2147
+ }
2148
+ else if (key.name === 'f' && model.api.listFiles && model.api.readFile) {
2149
+ view.files = { sandboxId: row.task.sandbox_id, directory: row.task.artifact_dir, rows: [], returnTo: 'task' };
2150
+ view.screen = 'files';
2151
+ view.scroll = 0;
2152
+ void refreshFiles();
2153
+ }
2154
+ else if (key.name === 'v' && row.task.process_id) {
2155
+ const id = row.task.process_id;
2156
+ view.workers = { sandboxId: row.task.sandbox_id, rows: [], selectedId: id, resultId: id };
2157
+ view.screen = 'workerResult';
2158
+ view.scroll = 0;
2159
+ void refreshWorkers();
2160
+ }
2161
+ else if (key.name === 'd' && row.task.process_id && !options.readOnly && !model.busy) {
2162
+ const taskId = row.task.task_id, processId = row.task.process_id, sandboxId = row.task.sandbox_id;
2163
+ pending = { label: `Stop task worker ${processId} in ${sandboxId}?`, run: async () => {
2164
+ const current = await model.api.tasks.inspect(taskId);
2165
+ if (current.task.process_id !== processId || current.task.sandbox_id !== sandboxId)
2166
+ throw new Error('Task worker identity changed.');
2167
+ await model.api.processes.kill(sandboxId, processId, 10);
2168
+ void refreshTasks();
2169
+ } };
2170
+ }
2171
+ else
2172
+ scroll(key.name);
2173
+ }
2174
+ draw();
2175
+ return;
2176
+ }
2177
+ if (view.screen === 'files' && view.files) {
2178
+ const state = view.files;
2179
+ const selected = state.rows.find(row => row.path === state.selectedPath);
2180
+ const navigate = (directory) => {
2181
+ state.directory = workspacePath(directory);
2182
+ state.preview = undefined;
2183
+ state.rows = [];
2184
+ state.selectedPath = undefined;
2185
+ state.updatedAt = undefined;
2186
+ state.error = undefined;
2187
+ state.message = '';
2188
+ view.scroll = 0;
2189
+ void refreshFiles();
2190
+ };
2191
+ if (key.name === 'i' && model.api.inputBatches) {
2192
+ view.inputBatch = { sandboxId: state.sandboxId, query: '' };
2193
+ view.screen = 'inputBatch';
2194
+ view.scroll = 0;
2195
+ }
2196
+ else if (key.name === 'u') {
2197
+ const row = model.rows.find(row => row.id === state.sandboxId);
2198
+ if (options.readOnly)
2199
+ state.message = 'Read-only mode disables uploads.';
2200
+ else if (!model.api.inputs)
2201
+ state.message = 'Local input uploads require the hosted API backend.';
2202
+ else if (model.busy || snapshotStale(model, options.intervalMs) || row?.status !== 'running')
2203
+ state.message = 'Refresh a running sandbox before uploading.';
2204
+ else {
2205
+ view.upload = { sandboxId: state.sandboxId, source: '' };
2206
+ view.screen = 'upload';
2207
+ view.scroll = 0;
2208
+ }
2209
+ }
2210
+ else if (key.name === 'escape') {
2211
+ if (state.preview) {
2212
+ state.preview = undefined;
2213
+ view.scroll = 0;
2214
+ }
2215
+ else {
2216
+ view.screen = state.returnTo || 'list';
2217
+ view.scroll = 0;
2218
+ }
2219
+ }
2220
+ else if (key.name === 'backspace') {
2221
+ if (state.preview) {
2222
+ state.preview = undefined;
2223
+ view.scroll = 0;
2224
+ }
2225
+ else if (state.directory !== '/workspace')
2226
+ navigate(posix.dirname(state.directory));
2227
+ }
2228
+ else if (key.name === 'return' && selected && !state.error && state.updatedAt) {
2229
+ if (selected.type === 'directory')
2230
+ navigate(selected.path);
2231
+ else if (selected.size > FILE_LIMIT)
2232
+ state.message = 'File exceeds the 5 MiB TUI limit. Use the file API for larger artifacts.';
2233
+ else if (!filePreviewRead) {
2234
+ const path = selected.path;
2235
+ const loading = `Loading preview: ${path}`;
2236
+ state.message = loading;
2237
+ filePreviewRead = (async () => {
2238
+ try {
2239
+ const data = decodeFile(await model.read(() => fileApi().readFile(state.sandboxId, path)), path);
2240
+ if (!closed && view.files === state && state.selectedPath === path) {
2241
+ state.preview = filePreview(path, data);
2242
+ state.message = '';
2243
+ view.scroll = 0;
2244
+ }
2245
+ }
2246
+ catch (error) {
2247
+ if (view.files === state && state.selectedPath === path)
2248
+ state.message = error instanceof Error ? error.message : 'Preview failed';
2249
+ }
2250
+ })().finally(() => { if (state.message === loading)
2251
+ state.message = ''; filePreviewRead = undefined; draw(); });
2252
+ }
2253
+ }
2254
+ else if (key.name === 'd' && selected?.type === 'file' && !state.error && state.updatedAt && !model.busy) {
2255
+ if (selected.size > FILE_LIMIT)
2256
+ state.message = 'File exceeds the 5 MiB TUI download limit.';
2257
+ else {
2258
+ const path = selected.path;
2259
+ const destination = downloadDestination(path);
2260
+ state.message = `Download ${path} to ${destination}. A new local directory is created; existing files are never replaced.`;
2261
+ pending = { label: `Download ${path} to ${destination}?`, run: async () => {
2262
+ try {
2263
+ const downloaded = await downloadFile(fileApi(), state.sandboxId, path, destination);
2264
+ state.message = `Downloaded: ${destination} | SHA-256: ${downloaded.sha256}`;
2265
+ }
2266
+ catch (error) {
2267
+ state.message = `Download failed: ${error instanceof Error ? error.message : 'Unknown error'}`;
2268
+ throw error;
2269
+ }
2270
+ } };
2271
+ }
2272
+ }
2273
+ else if (key.name === 'r') {
2274
+ state.preview = undefined;
2275
+ void refreshFiles();
2276
+ }
2277
+ else if (!state.preview && ['up', 'down', 'j', 'k', 'home', 'end'].includes(key.name || '')) {
2278
+ const index = state.rows.findIndex(row => row.path === state.selectedPath);
2279
+ const next = key.name === 'home' ? 0 : key.name === 'end' ? state.rows.length - 1 : index + (key.name === 'up' || key.name === 'k' ? -1 : 1);
2280
+ state.selectedPath = state.rows[Math.max(0, Math.min(state.rows.length - 1, next))]?.path;
2281
+ }
2282
+ else
2283
+ scroll(key.name);
2284
+ draw();
2285
+ return;
2286
+ }
2287
+ if ((view.screen === 'history' || view.screen === 'receipt') && view.history) {
2288
+ const state = view.history;
2289
+ if (view.screen === 'receipt') {
2290
+ if (key.name === 'f') {
2291
+ performAction('files', state.sandboxId);
2292
+ draw();
2293
+ return;
2294
+ }
2295
+ if (key.name === 'escape' || key.name === 'return') {
2296
+ view.screen = 'history';
2297
+ view.scroll = 0;
2298
+ }
2299
+ else
2300
+ scroll(key.name);
2301
+ }
2302
+ else {
2303
+ if (key.name === 'escape')
2304
+ view.screen = 'list';
2305
+ const index = state.rows.findIndex(row => row.id === state.selectedId);
2306
+ if (['up', 'down', 'j', 'k'].includes(key.name || '')) {
2307
+ state.selectedId = state.rows[Math.max(0, Math.min(state.rows.length - 1, index + (key.name === 'up' || key.name === 'k' ? -1 : 1)))]?.id;
2308
+ }
2309
+ if (key.name === 'home')
2310
+ state.selectedId = state.rows[0]?.id;
2311
+ if (key.name === 'end')
2312
+ state.selectedId = state.rows.at(-1)?.id;
2313
+ if (key.name === 'return' && state.selectedId) {
2314
+ state.receiptId = state.selectedId;
2315
+ state.receipt = undefined;
2316
+ view.screen = 'receipt';
2317
+ view.scroll = 0;
2318
+ void refreshHistory();
2319
+ }
2320
+ }
2321
+ if (key.name === 'r')
2322
+ void refresh();
2323
+ draw();
2324
+ return;
2325
+ }
2326
+ if ((view.screen === 'workers' || view.screen === 'workerLogs' || view.screen === 'workerResult') && view.workers) {
2327
+ const state = view.workers;
2328
+ const openLogs = (id) => {
2329
+ state.logId = id;
2330
+ state.stdout = '';
2331
+ state.stderr = '';
2332
+ state.rotated = false;
2333
+ state.truncated = false;
2334
+ state.logsUpdatedAt = undefined;
2335
+ view.screen = 'workerLogs';
2336
+ view.scroll = 0;
2337
+ void refreshWorkers();
2338
+ };
2339
+ const openResult = (id) => {
2340
+ state.resultId = id;
2341
+ state.result = undefined;
2342
+ state.resultUpdatedAt = undefined;
2343
+ view.screen = 'workerResult';
2344
+ view.scroll = 0;
2345
+ void refreshWorkers();
2346
+ };
2347
+ if (view.screen === 'workerLogs' || view.screen === 'workerResult') {
2348
+ if (key.name === 'escape' || key.name === 'return') {
2349
+ const inspectedId = view.screen === 'workerResult' ? state.resultId : state.logId;
2350
+ state.selectedId = state.rows.find(row => row.id === inspectedId)?.id || state.rows[0]?.id;
2351
+ view.screen = 'workers';
2352
+ view.scroll = 0;
2353
+ }
2354
+ else if (key.name === 'v' && state.logId && view.screen === 'workerLogs')
2355
+ openResult(state.logId);
2356
+ else if (key.name === 'l' && state.resultId && view.screen === 'workerResult')
2357
+ openLogs(state.resultId);
2358
+ else
2359
+ scroll(key.name);
2360
+ }
2361
+ else {
2362
+ if (key.name === 'escape')
2363
+ view.screen = 'list';
2364
+ const index = state.rows.findIndex(row => row.id === state.selectedId);
2365
+ if (key.name === 'up' || key.name === 'k' || key.name === 'down' || key.name === 'j') {
2366
+ state.selectedId = state.rows[Math.max(0, Math.min(state.rows.length - 1, index + (key.name === 'up' || key.name === 'k' ? -1 : 1)))]?.id;
2367
+ }
2368
+ if (key.name === 'home')
2369
+ state.selectedId = state.rows[0]?.id;
2370
+ if (key.name === 'end')
2371
+ state.selectedId = state.rows.at(-1)?.id;
2372
+ if (key.name === 'return' && state.selectedId)
2373
+ openLogs(state.selectedId);
2374
+ if (key.name === 'v' && state.selectedId)
2375
+ openResult(state.selectedId);
2376
+ if (key.name === 'g')
2377
+ performAction('launch', state.sandboxId);
2378
+ if (key.name === 'd' && state.selectedId) {
2379
+ if (options.readOnly || model.busy || state.error || snapshotStale(model, options.intervalMs)
2380
+ || !state.updatedAt || Date.now() - state.updatedAt.getTime() > Math.max(10_000, options.intervalMs * 2)) {
2381
+ model.message = 'Worker stop unavailable: check read-only mode, in-progress actions and refresh status.';
2382
+ }
2383
+ else {
2384
+ const id = state.sandboxId;
2385
+ const processId = state.selectedId;
2386
+ pending = { label: `Stop worker ${processId}?`, run: async () => {
2387
+ if (snapshotStale(model, options.intervalMs) || state.error || !state.updatedAt
2388
+ || Date.now() - state.updatedAt.getTime() > Math.max(10_000, options.intervalMs * 2))
2389
+ throw new Error('Refresh successfully before stopping the worker.');
2390
+ await model.api.processes.kill(id, processId, 10);
2391
+ void refreshWorkers();
2392
+ } };
2393
+ }
2394
+ }
2395
+ }
2396
+ if (key.name === 'r')
2397
+ void refresh();
2398
+ draw();
2399
+ return;
2400
+ }
2401
+ if (view.screen !== 'list') {
2402
+ if (view.screen === 'command' && key.name === 'f') {
2403
+ performAction('files', view.commandId);
2404
+ draw();
2405
+ return;
2406
+ }
2407
+ if (view.screen === 'command' && !view.commandEditing && view.live) {
2408
+ const live = view.live;
2409
+ if (key.name === 'r') {
2410
+ void live.recover();
2411
+ draw();
2412
+ return;
2413
+ }
2414
+ if (key.name === 'z') {
2415
+ if (options.readOnly || !model.api.executions?.cancel || !live.receipt.executionId || live.receipt.phase === 'finished' || live.receipt.cancellation) {
2416
+ view.commandMessage = 'Cancellation unavailable: inspect the execution ID, receipt and permissions.';
2417
+ }
2418
+ else {
2419
+ view.commandMessage = '';
2420
+ const executionId = live.receipt.executionId;
2421
+ pending = { label: `Cancel execution ${executionId} in ${live.sandboxId}?`, control: 'cancel-execution', run: async () => {
2422
+ if (options.readOnly || live.receipt.executionId !== executionId)
2423
+ throw new Error('Cancellation target is unavailable.');
2424
+ await live.cancel();
2425
+ } };
2426
+ }
2427
+ draw();
2428
+ return;
2429
+ }
2430
+ }
2431
+ if (view.screen === 'command' && key.name === 'h') {
2432
+ performAction('history', view.commandId);
2433
+ draw();
2434
+ return;
2435
+ }
2436
+ if (view.screen === 'command' && key.name === 'x' && canEditCommand(model, options, view.commandId)) {
2437
+ view.live?.stopWatching();
2438
+ view.live = undefined;
2439
+ view.commandEditing = true;
2440
+ view.commandReview = false;
2441
+ view.commandResult = undefined;
2442
+ view.commandMessage = '';
2443
+ view.scroll = 0;
2444
+ draw();
2445
+ return;
2446
+ }
2447
+ if (view.screen === 'subscription' && options.billing && !options.readOnly && !model.busy) {
2448
+ const openSubscription = async () => {
2449
+ try {
2450
+ view.subscriptionUrl = subscriptionUrl(options.billing.dashboardUrl);
2451
+ await options.billing.open(view.subscriptionUrl);
2452
+ view.subscriptionMessage = 'Browser opened. Review your organization, plan and price before subscribing.';
2453
+ }
2454
+ catch (error) {
2455
+ view.subscriptionMessage = error.message;
2456
+ }
2457
+ view.scroll = 0;
2458
+ };
2459
+ if (key.name === 'return')
2460
+ pending = { label: 'Open subscription plans in your browser?', run: openSubscription };
2461
+ if (key.name === 'o' && view.subscriptionUrl)
2462
+ mutate('Open subscription plans', openSubscription);
2463
+ }
2464
+ if (view.screen === 'billing' && options.billing && !options.readOnly && !model.busy) {
2465
+ if (text && /^[0-9.]$/.test(text)) {
2466
+ view.creditAmount = ((view.creditEditing ? view.creditAmount || '' : '') + text).slice(0, 8);
2467
+ view.creditEditing = true;
2468
+ view.creditMessage = '';
2469
+ view.creditUrl = undefined;
2470
+ view.scroll = 0;
2471
+ }
2472
+ if (key.name === 'backspace') {
2473
+ view.creditAmount = (view.creditAmount ?? '25').slice(0, -1);
2474
+ view.creditEditing = true;
2475
+ view.creditMessage = '';
2476
+ view.creditUrl = undefined;
2477
+ view.scroll = 0;
2478
+ }
2479
+ if (key.name === 'return') {
2480
+ try {
2481
+ const cents = creditAmountCents(view.creditAmount ?? '25');
2482
+ const url = creditPurchaseUrl(cents, options.billing.dashboardUrl);
2483
+ pending = { label: `$${(cents / 100).toFixed(2)} USD credits: open browser?`, run: async () => {
2484
+ view.creditUrl = url;
2485
+ view.creditEditing = false;
2486
+ try {
2487
+ await options.billing.open(url);
2488
+ view.creditMessage = 'Browser opened. Review the amount and organization, then pay through Stripe.';
2489
+ }
2490
+ catch (error) {
2491
+ view.creditMessage = error instanceof Error ? error.message : 'Open the billing link manually.';
2492
+ }
2493
+ view.scroll = 0;
2494
+ } };
2495
+ }
2496
+ catch (error) {
2497
+ view.creditMessage = error.message;
2498
+ }
2499
+ }
2500
+ if (key.name === 'o' && view.creditUrl) {
2501
+ mutate('Open billing', async () => {
2502
+ try {
2503
+ await options.billing.open(view.creditUrl);
2504
+ view.creditMessage = 'Browser opened; complete payment through Stripe.';
2505
+ }
2506
+ catch (error) {
2507
+ view.creditMessage = error.message;
2508
+ }
2509
+ });
2510
+ }
2511
+ }
2512
+ if (key.name === 'escape' || (key.name === 'return' && view.screen !== 'billing' && view.screen !== 'subscription') || text === '?' || key.name === 'a' || (key.name === 'o' && view.screen === 'overview') || (key.name === 'v' && view.screen === 'agents'))
2513
+ view.screen = 'list';
2514
+ if (key.name === 's' && view.screen === 'billing') {
2515
+ view.screen = 'subscription';
2516
+ view.scroll = 0;
2517
+ }
2518
+ scroll(key.name);
2519
+ if (key.name === 'r')
2520
+ void refresh();
2521
+ draw();
2522
+ return;
2523
+ }
2524
+ if (text === '/' || key.name === '/') {
2525
+ searchBefore = model.filter;
2526
+ view.searching = true;
2527
+ }
2528
+ if (text === '?') {
2529
+ view.screen = 'help';
2530
+ view.scroll = 0;
2531
+ }
2532
+ if (key.name === 'a') {
2533
+ view.screen = 'activity';
2534
+ view.scroll = 0;
2535
+ }
2536
+ if (key.name === 'o') {
2537
+ view.screen = 'overview';
2538
+ view.scroll = 0;
2539
+ }
2540
+ if (key.name === 'v') {
2541
+ view.screen = 'agents';
2542
+ view.scroll = 0;
2543
+ }
2544
+ if (key.name === 't')
2545
+ model.cycleSort();
2546
+ if (key.name === 'b') {
2547
+ view.screen = 'billing';
2548
+ view.scroll = 0;
2549
+ }
2550
+ if (key.name === 's') {
2551
+ view.screen = 'subscription';
2552
+ view.scroll = 0;
2553
+ }
2554
+ if (key.name === 'return' && model.selected) {
2555
+ view.screen = 'details';
2556
+ view.detailId = model.selectedId;
2557
+ view.scroll = 0;
2558
+ }
2559
+ if (key.name === 'escape')
2560
+ model.setFilter('');
2561
+ if (key.name === 'pagedown')
2562
+ model.move(pageSize(output.rows || 24));
2563
+ if (key.name === 'pageup')
2564
+ model.move(-pageSize(output.rows || 24));
2565
+ if (key.name === 'home')
2566
+ model.move(-model.rows.length);
2567
+ if (key.name === 'end')
2568
+ model.move(model.rows.length);
2569
+ if (key.name === 'down' || key.name === 'j')
2570
+ model.move(1);
2571
+ if (key.name === 'up' || key.name === 'k')
2572
+ model.move(-1);
2573
+ if (key.name === 'r')
2574
+ void refresh();
2575
+ const shortcuts = { n: 'create', x: 'execute', i: 'interpret', f: 'files', h: 'history', g: 'launch', m: 'tasks', l: 'delegate', w: 'workers', d: 'stop', p: 'pause', u: 'resume', e: 'extend', c: 'connection' };
2576
+ if (key.name && shortcuts[key.name])
2577
+ performAction(shortcuts[key.name], model.selectedId);
2578
+ draw();
2579
+ };
2580
+ manager.register('sandbox-dashboard', cleanup);
2581
+ try {
2582
+ input.setRawMode(true);
2583
+ emitKeypressEvents(imageKeys);
2584
+ imageKeys.on('keypress', imageKeypress);
2585
+ input.on('keypress', keypress);
2586
+ input.on('data', imageData);
2587
+ input.resume();
2588
+ output.on('resize', draw);
2589
+ output.write('\x1b[?1049h\x1b[?25l\x1b[?2004h');
2590
+ draw();
2591
+ void refreshTasks();
2592
+ if (registryFocus && view.registry)
2593
+ void registryController.refresh(view.registry);
2594
+ void refresh();
2595
+ timer = setInterval(() => { void refresh(); }, options.intervalMs);
2596
+ // Local redraws keep countdowns moving without increasing backend polling.
2597
+ clockTimer = setInterval(() => {
2598
+ if (view.screen === 'list' || view.screen === 'details' || view.screen === 'overview' || view.screen === 'connection' || view.screen === 'actions')
2599
+ draw();
2600
+ }, 1000);
2601
+ await done;
2602
+ }
2603
+ finally {
2604
+ cleanup();
2605
+ }
2606
+ }
2607
+ //# sourceMappingURL=terminal.js.map