@zhivex-ai/harness 1.7.0 → 1.8.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 (388) hide show
  1. package/CHANGELOG.md +8 -2
  2. package/README.md +17 -5
  3. package/SECURITY.md +1 -1
  4. package/SUPPORT.md +2 -2
  5. package/benchmarks/README.md +26 -0
  6. package/contracts/engine-api.json +1557 -0
  7. package/contracts/public-api.json +114 -0
  8. package/contracts/stable-api-signatures.json +17 -17
  9. package/dist/acp-cli.js +37 -1090
  10. package/dist/application/agenda.d.ts +10 -0
  11. package/dist/application/approval-review.d.ts +61 -0
  12. package/dist/application/assistant/automation/scheduler.d.ts +21 -0
  13. package/dist/application/assistant/automation/summary.d.ts +29 -0
  14. package/dist/application/assistant/automation/time.d.ts +10 -0
  15. package/dist/application/assistant/calendar/calendar.d.ts +238 -0
  16. package/dist/application/assistant/calendar/connection.d.ts +50 -0
  17. package/dist/application/assistant/calendar/create-event.d.ts +75 -0
  18. package/dist/application/assistant/calendar/environment.d.ts +2 -0
  19. package/dist/application/assistant/calendar/http.d.ts +6 -0
  20. package/dist/application/assistant/calendar/oauth.d.ts +68 -0
  21. package/dist/application/assistant/calendar/store.d.ts +11 -0
  22. package/dist/application/assistant/calendar/tools.d.ts +78 -0
  23. package/dist/application/assistant/client.d.ts +10 -0
  24. package/dist/application/assistant/config.d.ts +9 -0
  25. package/dist/application/assistant/contracts.d.ts +77 -0
  26. package/dist/application/assistant/daily/service.d.ts +181 -0
  27. package/dist/application/assistant/doctor.d.ts +22 -0
  28. package/dist/application/assistant/evaluation.d.ts +81 -0
  29. package/dist/application/assistant/host.d.ts +399 -0
  30. package/dist/application/assistant/integrations/google.d.ts +117 -0
  31. package/dist/application/assistant/integrations/public-web.d.ts +16 -0
  32. package/dist/application/assistant/managed/secrets.d.ts +10 -0
  33. package/dist/application/assistant/managed/setup-state.d.ts +346 -0
  34. package/dist/application/assistant/managed/setup.d.ts +492 -0
  35. package/dist/application/assistant/microsoft/connection.d.ts +73 -0
  36. package/dist/application/assistant/microsoft/tools.d.ts +78 -0
  37. package/dist/application/assistant/modules/calendar.d.ts +3 -0
  38. package/dist/application/assistant/modules/catalog.d.ts +38 -0
  39. package/dist/application/assistant/modules/daily.d.ts +5 -0
  40. package/dist/application/assistant/modules/github.d.ts +5 -0
  41. package/dist/application/assistant/modules/google.d.ts +3 -0
  42. package/dist/application/assistant/modules/mcp.d.ts +11 -0
  43. package/dist/application/assistant/modules/microsoft.d.ts +3 -0
  44. package/dist/application/assistant/modules/module.d.ts +224 -0
  45. package/dist/application/assistant/modules/tools.d.ts +11 -0
  46. package/dist/application/assistant/modules/web.d.ts +7 -0
  47. package/dist/application/assistant/private-directory.d.ts +3 -0
  48. package/dist/application/assistant/proactive/service.d.ts +142 -0
  49. package/dist/application/assistant/providers/openai-compatible.d.ts +66 -0
  50. package/dist/application/assistant/providers/provider.d.ts +141 -0
  51. package/dist/application/assistant/providers/web-citations.d.ts +2 -0
  52. package/dist/application/assistant/runtime.d.ts +16 -0
  53. package/dist/application/assistant/task-metrics.d.ts +304 -0
  54. package/dist/application/assistant/telegram/api.d.ts +47 -0
  55. package/dist/application/assistant/telegram/bridge.d.ts +69 -0
  56. package/dist/application/assistant/telegram/store.d.ts +10 -0
  57. package/dist/application/automation.d.ts +5 -0
  58. package/dist/application/calendar-review.d.ts +5 -0
  59. package/dist/application/checkpoint-review.d.ts +30 -0
  60. package/dist/application/client.d.ts +18 -0
  61. package/dist/application/code/context.d.ts +5 -0
  62. package/dist/application/code/delivery.d.ts +6 -0
  63. package/dist/application/code/git-delivery.d.ts +54 -0
  64. package/dist/application/code/github-git-transport.d.ts +15 -0
  65. package/dist/application/code/github-pr-transport.d.ts +6 -0
  66. package/dist/application/code/host.d.ts +25 -0
  67. package/dist/application/code/pr-delivery.d.ts +79 -0
  68. package/dist/application/code/projects.d.ts +90 -0
  69. package/dist/application/code/remote-delivery.d.ts +80 -0
  70. package/dist/application/code/repository.d.ts +9 -0
  71. package/dist/application/code/worktrees.d.ts +123 -0
  72. package/dist/application/contracts.d.ts +288 -0
  73. package/dist/application/coordinator-client.d.ts +33 -0
  74. package/dist/application/coordinator-discovery.d.ts +17 -0
  75. package/dist/application/coordinator-launcher.d.ts +2 -0
  76. package/dist/application/coordinator.d.ts +27 -0
  77. package/dist/application/credential-process.d.ts +13 -0
  78. package/dist/application/host.d.ts +7 -0
  79. package/dist/application/management.d.ts +68 -0
  80. package/dist/application/notes.d.ts +5 -0
  81. package/dist/application/offline-migration.d.ts +16 -0
  82. package/dist/application/personal-state.d.ts +5 -0
  83. package/dist/application/review-channel.d.ts +23 -0
  84. package/dist/application/review-tickets.d.ts +29 -0
  85. package/dist/application/runtime-binding.d.ts +4 -0
  86. package/dist/application-cli-wfh08g41.js +184 -0
  87. package/dist/application-cli-z3f9pvcf.js +209 -0
  88. package/dist/approvals/auto-approve.d.ts +1 -1
  89. package/dist/arguments-75r85mvc.js +27 -0
  90. package/dist/arguments-x24bbqvd.js +22 -0
  91. package/dist/audit/index.js +16 -472
  92. package/dist/audit-pack-1gnych0m.js +93 -0
  93. package/dist/{audit-pack-y02n8zd0.js → audit-pack-h44kjkbj.js} +17 -11
  94. package/dist/calendar-2xw0rr7b.js +49 -0
  95. package/dist/cli/application-cli.d.ts +2 -0
  96. package/dist/cli/arguments.d.ts +14 -1
  97. package/dist/cli/auto-approve-setup.d.ts +13 -0
  98. package/dist/cli/configured-harness.d.ts +1 -2
  99. package/dist/cli/console/console-budget.d.ts +16 -2
  100. package/dist/cli/console/console-checkpoints.d.ts +12 -0
  101. package/dist/cli/console/console-commands.d.ts +3 -3
  102. package/dist/cli/console/console-compaction.d.ts +1 -1
  103. package/dist/cli/console/console-diff.d.ts +2 -0
  104. package/dist/cli/console/console-input.d.ts +29 -1
  105. package/dist/cli/console/console-navigation.d.ts +2 -2
  106. package/dist/cli/console/console-outcome.d.ts +10 -0
  107. package/dist/cli/console/console-presentation.d.ts +17 -2
  108. package/dist/cli/console/console-pricing.d.ts +14 -0
  109. package/dist/cli/console/console-reasoning.d.ts +1 -1
  110. package/dist/cli/console/console-recovery.d.ts +2 -0
  111. package/dist/cli/console/console-review.d.ts +34 -0
  112. package/dist/cli/console/console-run-policy.d.ts +5 -0
  113. package/dist/cli/console/console-run-view.d.ts +28 -0
  114. package/dist/cli/console/console-task.d.ts +30 -0
  115. package/dist/cli/console/console-welcome.d.ts +13 -3
  116. package/dist/cli/console/review-diff.d.ts +20 -0
  117. package/dist/cli/presentation.d.ts +8 -6
  118. package/dist/cli/service-checkpoints.d.ts +234 -0
  119. package/dist/cli/terminal/activity-history.d.ts +4 -2
  120. package/dist/cli/terminal/activity-stream.d.ts +33 -0
  121. package/dist/cli/terminal/file-diff.d.ts +11 -0
  122. package/dist/cli/terminal/terminal-theme.d.ts +9 -0
  123. package/dist/cli/terminal/terminal-ui.d.ts +44 -2
  124. package/dist/cli/terminal/tool-activity.d.ts +6 -2
  125. package/dist/{cli-entry-hdtfef27.js → cli-entry-68kqraj7.js} +95 -43
  126. package/dist/{cli-entry-j6jcb2jb.js → cli-entry-86rcbmwh.js} +294 -14
  127. package/dist/cli-entry-btkpb4h1.js +3627 -0
  128. package/dist/cli-entry-bxjbs6qq.js +200 -0
  129. package/dist/cli-entry-cpm89r9q.js +624 -0
  130. package/dist/{cli-entry-v5db3eb2.js → cli-entry-dksm56sj.js} +39 -297
  131. package/dist/{cli-entry-td04s0fa.js → cli-entry-eka68ttb.js} +3919 -4549
  132. package/dist/cli-entry-h7dcah4p.js +137 -0
  133. package/dist/cli-entry-kwk23ktq.js +33 -0
  134. package/dist/{cli-entry-ynahz9qc.js → cli-entry-vmce694z.js} +1251 -3139
  135. package/dist/cli-entry-wanv05db.js +1113 -0
  136. package/dist/{cli-zw18kdqx.js → cli-z7vhm1rk.js} +1767 -380
  137. package/dist/cli.js +8 -6
  138. package/dist/client/json-contracts.d.ts +153 -0
  139. package/dist/client/local-service.d.ts +7 -12
  140. package/dist/client/local-transport.d.ts +14 -0
  141. package/dist/client/protocol.d.ts +43 -1
  142. package/dist/compat/cli-options.d.ts +7 -1
  143. package/dist/compat/cli.d.ts +2 -0
  144. package/dist/compat/cli.js +4043 -0
  145. package/dist/compat/code-support.d.ts +3 -0
  146. package/dist/compat/code-support.js +50 -28
  147. package/dist/{config-r9fdhce6.js → config-hw78440t.js} +5 -5
  148. package/dist/{config-vyajmksy.js → config-v7s8hp37.js} +1 -1
  149. package/dist/context/adaptive-compaction.d.ts +1 -0
  150. package/dist/context/lossless-lines.d.ts +13 -0
  151. package/dist/context/numbered-read-lines.d.ts +15 -0
  152. package/dist/context/read-attempts.d.ts +21 -0
  153. package/dist/context/request-projection.d.ts +32 -4
  154. package/dist/context/scoped-context.d.ts +14 -0
  155. package/dist/context/working-read-replay.d.ts +12 -0
  156. package/dist/coordinator-client-nzysqxf0.js +10 -0
  157. package/dist/engine/acp.js +27 -21
  158. package/dist/engine/application-client.d.ts +11 -0
  159. package/dist/engine/application-client.js +18 -0
  160. package/dist/engine/application-protocol.d.ts +5 -0
  161. package/dist/engine/application-protocol.js +7 -0
  162. package/dist/engine/application.d.ts +43 -0
  163. package/dist/engine/application.js +206 -0
  164. package/dist/engine/assistant/automation/scheduler.d.ts +2 -0
  165. package/dist/engine/assistant/automation/scheduler.js +11 -0
  166. package/dist/engine/assistant/automation/summary.d.ts +3 -0
  167. package/dist/engine/assistant/automation/summary.js +8 -0
  168. package/dist/engine/assistant/automation/time.d.ts +5 -0
  169. package/dist/engine/assistant/automation/time.js +15 -0
  170. package/dist/engine/assistant/calendar/calendar.d.ts +5 -0
  171. package/dist/engine/assistant/calendar/calendar.js +12 -0
  172. package/dist/engine/assistant/calendar/connection.d.ts +2 -0
  173. package/dist/engine/assistant/calendar/connection.js +11 -0
  174. package/dist/engine/assistant/calendar/environment.d.ts +1 -0
  175. package/dist/engine/assistant/calendar/environment.js +7 -0
  176. package/dist/engine/assistant/calendar/http.d.ts +3 -0
  177. package/dist/engine/assistant/calendar/http.js +9 -0
  178. package/dist/engine/assistant/calendar/oauth.d.ts +5 -0
  179. package/dist/engine/assistant/calendar/oauth.js +12 -0
  180. package/dist/engine/assistant/calendar/store.d.ts +2 -0
  181. package/dist/engine/assistant/calendar/store.js +8 -0
  182. package/dist/engine/assistant/calendar/tools.d.ts +2 -0
  183. package/dist/engine/assistant/calendar/tools.js +46 -0
  184. package/dist/engine/assistant/client.d.ts +2 -0
  185. package/dist/engine/assistant/client.js +33 -0
  186. package/dist/engine/assistant/config.d.ts +1 -0
  187. package/dist/engine/assistant/config.js +102 -0
  188. package/dist/engine/assistant/contracts.d.ts +10 -0
  189. package/dist/engine/assistant/contracts.js +78 -0
  190. package/dist/engine/assistant/daily/service.d.ts +12 -0
  191. package/dist/engine/assistant/daily/service.js +27 -0
  192. package/dist/engine/assistant/doctor.d.ts +1 -0
  193. package/dist/engine/assistant/doctor.js +116 -0
  194. package/dist/engine/assistant/evaluation.d.ts +2 -0
  195. package/dist/engine/assistant/evaluation.js +76 -0
  196. package/dist/engine/assistant/host.d.ts +2 -0
  197. package/dist/engine/assistant/host.js +63 -0
  198. package/dist/engine/assistant/integrations/google.d.ts +9 -0
  199. package/dist/engine/assistant/integrations/google.js +30 -0
  200. package/dist/engine/assistant/integrations/public-web.d.ts +3 -0
  201. package/dist/engine/assistant/integrations/public-web.js +11 -0
  202. package/dist/engine/assistant/managed/secrets.d.ts +1 -0
  203. package/dist/engine/assistant/managed/secrets.js +0 -0
  204. package/dist/engine/assistant/managed/setup-state.d.ts +11 -0
  205. package/dist/engine/assistant/managed/setup-state.js +84 -0
  206. package/dist/engine/assistant/managed/setup.d.ts +3 -0
  207. package/dist/engine/assistant/managed/setup.js +85 -0
  208. package/dist/engine/assistant/microsoft/connection.d.ts +7 -0
  209. package/dist/engine/assistant/microsoft/connection.js +21 -0
  210. package/dist/engine/assistant/microsoft/tools.d.ts +8 -0
  211. package/dist/engine/assistant/microsoft/tools.js +30 -0
  212. package/dist/engine/assistant/modules/calendar.d.ts +1 -0
  213. package/dist/engine/assistant/modules/calendar.js +49 -0
  214. package/dist/engine/assistant/modules/catalog.d.ts +3 -0
  215. package/dist/engine/assistant/modules/catalog.js +67 -0
  216. package/dist/engine/assistant/modules/daily.d.ts +1 -0
  217. package/dist/engine/assistant/modules/daily.js +48 -0
  218. package/dist/engine/assistant/modules/github.d.ts +1 -0
  219. package/dist/engine/assistant/modules/github.js +43 -0
  220. package/dist/engine/assistant/modules/google.d.ts +1 -0
  221. package/dist/engine/assistant/modules/google.js +53 -0
  222. package/dist/engine/assistant/modules/mcp.d.ts +1 -0
  223. package/dist/engine/assistant/modules/mcp.js +42 -0
  224. package/dist/engine/assistant/modules/microsoft.d.ts +1 -0
  225. package/dist/engine/assistant/modules/microsoft.js +53 -0
  226. package/dist/engine/assistant/modules/module.d.ts +5 -0
  227. package/dist/engine/assistant/modules/module.js +42 -0
  228. package/dist/engine/assistant/modules/tools.d.ts +2 -0
  229. package/dist/engine/assistant/modules/tools.js +42 -0
  230. package/dist/engine/assistant/modules/web.d.ts +1 -0
  231. package/dist/engine/assistant/modules/web.js +45 -0
  232. package/dist/engine/assistant/private-directory.d.ts +1 -0
  233. package/dist/engine/assistant/private-directory.js +7 -0
  234. package/dist/engine/assistant/proactive/service.d.ts +6 -0
  235. package/dist/engine/assistant/proactive/service.js +16 -0
  236. package/dist/engine/assistant/providers/openai-compatible.d.ts +4 -0
  237. package/dist/engine/assistant/providers/openai-compatible.js +12 -0
  238. package/dist/engine/assistant/providers/provider.d.ts +7 -0
  239. package/dist/engine/assistant/providers/provider.js +54 -0
  240. package/dist/engine/assistant/providers/web-citations.d.ts +1 -0
  241. package/dist/engine/assistant/providers/web-citations.js +7 -0
  242. package/dist/engine/assistant/runtime.d.ts +2 -0
  243. package/dist/engine/assistant/runtime.js +73 -0
  244. package/dist/engine/assistant/task-metrics.d.ts +8 -0
  245. package/dist/engine/assistant/task-metrics.js +17 -0
  246. package/dist/engine/assistant/telegram/api.d.ts +5 -0
  247. package/dist/engine/assistant/telegram/api.js +11 -0
  248. package/dist/engine/assistant/telegram/bridge.d.ts +2 -0
  249. package/dist/engine/assistant/telegram/bridge.js +40 -0
  250. package/dist/engine/assistant/telegram/store.d.ts +2 -0
  251. package/dist/engine/assistant/telegram/store.js +8 -0
  252. package/dist/engine/client.js +26 -18
  253. package/dist/engine/desktop-providers-v1.js +4 -4
  254. package/dist/engine/desktop-state-v1.js +16 -13
  255. package/dist/engine/index.js +111 -159
  256. package/dist/engine/mcp-stdio-v1.js +13 -12
  257. package/dist/engine/models.js +65 -23
  258. package/dist/engine/protocol.js +10 -6
  259. package/dist/engine/service.js +32 -21
  260. package/dist/hostile-repository-demo.js +1822 -696
  261. package/dist/index-09rsdr2d.js +1744 -0
  262. package/dist/index-0csc5sc7.js +139 -0
  263. package/dist/{index-v86bh0eg.js → index-0dkty795.js} +8 -6
  264. package/dist/index-0kkgqvg7.js +0 -0
  265. package/dist/index-0mzz9axm.js +58 -0
  266. package/dist/index-1e69ar8r.js +38 -0
  267. package/dist/index-1z0xhkh9.js +18 -0
  268. package/dist/index-2cef1k92.js +356 -0
  269. package/dist/{index-k1a1xesg.js → index-2j0v1xwr.js} +17 -13
  270. package/dist/index-2jw9jd7h.js +116 -0
  271. package/dist/index-2n9qx4km.js +0 -0
  272. package/dist/index-3rvk23e8.js +877 -0
  273. package/dist/index-3wa4j0yk.js +71 -0
  274. package/dist/index-41q1k17x.js +210 -0
  275. package/dist/index-4vz4bqqw.js +33 -0
  276. package/dist/index-5jxm2wy5.js +123 -0
  277. package/dist/index-5rk6ss42.js +216 -0
  278. package/dist/index-5v1skxf7.js +1852 -0
  279. package/dist/{index-qz4fs9f9.js → index-6ehtssyz.js} +355 -332
  280. package/dist/index-76kpdbpw.js +80 -0
  281. package/dist/{index-r0q0r88h.js → index-7nbmhmw5.js} +10 -10
  282. package/dist/index-8mx0yrkz.js +31 -0
  283. package/dist/index-8tjev5ds.js +11 -0
  284. package/dist/index-91n5wr6s.js +163 -0
  285. package/dist/index-91trs3ew.js +151 -0
  286. package/dist/index-9y8p5vy5.js +222 -0
  287. package/dist/index-abxahprd.js +55 -0
  288. package/dist/index-aptyr511.js +84 -0
  289. package/dist/{index-8sm2a1wa.js → index-ay26xfxt.js} +28 -20
  290. package/dist/index-b4yed1s3.js +657 -0
  291. package/dist/index-bb7phvtg.js +23 -0
  292. package/dist/index-bk5tn9b8.js +236 -0
  293. package/dist/index-bw34861c.js +292 -0
  294. package/dist/index-c6fnjhgv.js +55 -0
  295. package/dist/{index-qfsrrnz6.js → index-cjevq9s8.js} +2 -2
  296. package/dist/{index-c39197wq.js → index-ctcwrkrc.js} +4 -4
  297. package/dist/{index-yx52bt4a.js → index-cztmcesv.js} +2 -2
  298. package/dist/index-dpbmxnrf.js +564 -0
  299. package/dist/index-ekxdcy36.js +134 -0
  300. package/dist/index-f8zpcsx3.js +289 -0
  301. package/dist/{index-6dxrbnxm.js → index-f970qtb4.js} +7 -143
  302. package/dist/index-fatcn6fp.js +2791 -0
  303. package/dist/index-fbzykqxy.js +105 -0
  304. package/dist/{index-1265j7t2.js → index-fwf274vc.js} +24 -14
  305. package/dist/index-fy4w0a7v.js +0 -0
  306. package/dist/index-gvva3e5x.js +76 -0
  307. package/dist/index-h7dcah4p.js +137 -0
  308. package/dist/index-hm9r120s.js +42 -0
  309. package/dist/index-j3d2tw97.js +328 -0
  310. package/dist/index-jfqj20x8.js +41 -0
  311. package/dist/{index-yp0jtaxp.js → index-k529a278.js} +6 -6
  312. package/dist/{index-bt2p8x7r.js → index-kbrf5bx7.js} +110 -106
  313. package/dist/index-kwk23ktq.js +33 -0
  314. package/dist/index-kz857p1j.js +557 -0
  315. package/dist/{index-tc2r2n8b.js → index-mkt5yrax.js} +31 -105
  316. package/dist/{index-tgt8gtq7.js → index-ndgnvjez.js} +18 -18
  317. package/dist/index-nemn4epv.js +43 -0
  318. package/dist/index-nkwy5bjr.js +1225 -0
  319. package/dist/index-nvvzr4ny.js +136 -0
  320. package/dist/index-pkspzsfs.js +78 -0
  321. package/dist/{index-fm84men1.js → index-px1tnqgt.js} +2 -2
  322. package/dist/index-q7qdw883.js +79 -0
  323. package/dist/{index-mzydbzp8.js → index-qvbg6tx1.js} +65 -23
  324. package/dist/index-r3mwr5fb.js +0 -0
  325. package/dist/index-rdr78m0k.js +91 -0
  326. package/dist/index-rtamqsfs.js +59 -0
  327. package/dist/index-s125ss45.js +38 -0
  328. package/dist/{index-h8r80xhk.js → index-sx1t6dnd.js} +4005 -2781
  329. package/dist/index-tar0ngkm.js +359 -0
  330. package/dist/index-tn58cr6w.js +471 -0
  331. package/dist/{index-v17e1xs8.js → index-v79s9bf9.js} +96 -23
  332. package/dist/index-vk3rq21m.js +17 -0
  333. package/dist/index-vmvnr28y.js +72 -0
  334. package/dist/index-vz629cg8.js +49 -0
  335. package/dist/{index-eps3c3g6.js → index-w292hdpz.js} +197 -960
  336. package/dist/{index-t6sjhxh8.js → index-w9eqg6p9.js} +24 -302
  337. package/dist/index-wj96kdw2.js +57 -0
  338. package/dist/index-wyck5yhd.js +141 -0
  339. package/dist/index-xvtk8pxs.js +674 -0
  340. package/dist/{index-bpc596v3.js → index-xwb691v9.js} +2 -2
  341. package/dist/index-ym69x168.js +518 -0
  342. package/dist/index-yprdjk9v.js +65 -0
  343. package/dist/index-z2a81ccr.js +35 -0
  344. package/dist/{index-3ah1f369.js → index-z69cqk74.js} +3 -3
  345. package/dist/index-zaakvmzq.js +62 -0
  346. package/dist/index-zk3m4mzg.js +232 -0
  347. package/dist/index-zx3wgvx4.js +218 -0
  348. package/dist/index.js +102 -83
  349. package/dist/persistence/migration-guard.d.ts +3 -0
  350. package/dist/runtime/harness.d.ts +2 -0
  351. package/dist/service-cli.js +130 -40
  352. package/dist/service-client-cli-2rzxy5mj.js +1166 -0
  353. package/dist/service-client-cli-5ne8q5ej.js +543 -0
  354. package/dist/tools/ooxml-zip.d.ts +21 -0
  355. package/dist/tools/presentations.d.ts +47 -0
  356. package/dist/tools/tabular-data.d.ts +114 -0
  357. package/dist/tools/workspace.d.ts +76 -0
  358. package/dist/verify-historical-migrations.js +1923 -797
  359. package/dist/workspace/workspace.d.ts +13 -1
  360. package/dist/zhx.js +8 -6
  361. package/docs/APPLICATION_MIGRATION.md +32 -0
  362. package/docs/CLI.md +166 -2
  363. package/docs/CODE_RELEASE.md +5 -3
  364. package/docs/CODE_WEB_TASKS.md +3 -114
  365. package/docs/CONTEXT_ENGINEERING.md +27 -0
  366. package/docs/ENGINE_API.md +1 -1
  367. package/docs/EXTENSIBILITY.md +1 -1
  368. package/docs/FIRST_USE.md +6 -6
  369. package/docs/INTERNAL_ARCHIVE.md +43 -0
  370. package/docs/LOCAL_SERVICE.md +1 -1
  371. package/docs/MODEL_CATALOG.md +14 -0
  372. package/docs/README.md +13 -2
  373. package/evaluations/representative-assembly-matrix.json +10 -1
  374. package/examples/README.md +3 -3
  375. package/examples/assistant/compatible-calendar.json +17 -0
  376. package/examples/assistant/composed-modules.json +23 -0
  377. package/examples/assistant/connected-tools.json +9 -0
  378. package/examples/assistant/daily-tools.json +6 -0
  379. package/examples/assistant/offline.mjs +24 -0
  380. package/fixtures/cli-compatibility/README.md +10 -0
  381. package/fixtures/cli-compatibility/inventory.json +7858 -0
  382. package/package.json +230 -28
  383. package/dist/cli/console/console-model-catalog.d.ts +0 -8
  384. package/dist/index-4gt045j0.js +0 -288
  385. package/dist/index-4jw3tvy8.js +0 -301
  386. package/dist/index-ebb5d4s3.js +0 -640
  387. package/dist/index-x9hv1a34.js +0 -274
  388. package/dist/service-client-cli-gtk26axb.js +0 -1251
@@ -0,0 +1,3627 @@
1
+ import {
2
+ checkEvidence,
3
+ createHarness,
4
+ decideBatch,
5
+ formatApproval,
6
+ formatTerminalEvent,
7
+ formatVerificationSummary,
8
+ isTableSeparator,
9
+ issueAutomaticApprovalResponses,
10
+ issueExplicitReviewResponses,
11
+ issueObservedApprovalResponses,
12
+ loadModelCatalog,
13
+ paintTerminal,
14
+ renderTerminalTable,
15
+ requiresExplicitHostReview,
16
+ resolveTerminalApprovals,
17
+ revealInvisibleText,
18
+ sanitizeTerminalText,
19
+ tableCells,
20
+ terminalCellWidth,
21
+ terminalRunFailure,
22
+ terminalSupportsColor,
23
+ terminalToneCode
24
+ } from "./cli-entry-eka68ttb.js";
25
+ import {
26
+ CLI_JSON_SCHEMA_VERSION,
27
+ serializeStreamEvent,
28
+ serializeStreamResult
29
+ } from "./cli-entry-cpm89r9q.js";
30
+ import {
31
+ CliUsageError,
32
+ resolveHarnessModelRoutes,
33
+ serializeHarnessModelRoutes
34
+ } from "./cli-entry-wanv05db.js";
35
+ import {
36
+ USAGE_LEDGER_KEY,
37
+ createPolicyDecisionEvidence,
38
+ formatUsageLedger,
39
+ inspectHarnessPolicy,
40
+ inspectUsageLedger,
41
+ observeHarnessPolicyDecisions,
42
+ usagePricingSchema
43
+ } from "./cli-entry-vmce694z.js";
44
+ import {
45
+ readRegularFileNoFollow
46
+ } from "./cli-entry-h7dcah4p.js";
47
+ import {
48
+ PROVIDERS,
49
+ azureOpenAIApiVersion,
50
+ azureOpenAIDeployments,
51
+ azureOpenAIEndpoint,
52
+ bedrockConfigured,
53
+ bedrockOpenAIBaseURL,
54
+ bedrockRegion,
55
+ bedrockRuntime,
56
+ bundledModelCatalog,
57
+ catalogModels,
58
+ createProviderModel,
59
+ modelDescription,
60
+ modelReasoningEfforts,
61
+ normalizeHarnessError,
62
+ providerDescriptor,
63
+ resolveHarnessConfig,
64
+ vertexConfigured,
65
+ vertexRoute
66
+ } from "./cli-entry-68kqraj7.js";
67
+ import {
68
+ __require
69
+ } from "./cli-entry-1bx83sw4.js";
70
+
71
+ // packages/core/src/cli/policy-decisions.ts
72
+ var formatPolicyDecision = (event) => sanitizeTerminalText(`Policy · ${event.toolName} · ${event.phase} · ${event.decision}${event.explicitReviewRequired ? " · explicit review required" : ""} · ${event.ruleIds.join(", ") || "baseline"}: ${event.reason}${event.reasonTruncated ? " [reason truncated]" : ""}`);
73
+ async function observeCliPolicy(options, tracker, work) {
74
+ const evidence = createPolicyDecisionEvidence();
75
+ try {
76
+ return await observeHarnessPolicyDecisions((event) => {
77
+ evidence.append(event);
78
+ if (options.jsonl)
79
+ process.stdout.write(JSON.stringify({ ...event, kind: "run-event", sequence: tracker.sequence = (tracker.sequence ?? 0) + 1 }) + `
80
+ `);
81
+ else if (!options.json)
82
+ process.stderr.write(formatPolicyDecision(event) + `
83
+ `);
84
+ }, work);
85
+ } finally {
86
+ tracker.policyEvidence = evidence.snapshot();
87
+ }
88
+ }
89
+
90
+ // packages/core/src/cli/terminal/tool-activity.ts
91
+ import { createRedactionPolicy } from "@zhivex-ai/agents";
92
+ var failureRedaction = createRedactionPolicy({ includeEmails: true });
93
+ var labels = {
94
+ read_file: "Reading a file",
95
+ read_files: "Reading files",
96
+ read_dependency: "Inspecting a dependency",
97
+ search_files: "Searching files",
98
+ search_many: "Searching the project",
99
+ list_files: "Listing files",
100
+ run_check: "Running checks",
101
+ run_environment_command: "Running a command",
102
+ apply_patch: "Preparing edits",
103
+ apply_reviewed_edits: "Preparing reviewed edits",
104
+ apply_reviewed_replacement: "Preparing a reviewed replacement",
105
+ git_diff: "Reviewing changes"
106
+ };
107
+ var summaries = {
108
+ read_file: "reads",
109
+ read_files: "reads",
110
+ read_dependency: "dependency inspections",
111
+ search_files: "searches",
112
+ search_many: "searches",
113
+ list_files: "listings",
114
+ git_diff: "diffs"
115
+ };
116
+
117
+ class ToolActivity {
118
+ write;
119
+ tty;
120
+ columns;
121
+ inputStatus;
122
+ active = 0;
123
+ visible = false;
124
+ label = "Working";
125
+ completed = new Map;
126
+ started = Date.now();
127
+ runStarted = Date.now();
128
+ timer;
129
+ constructor(write, tty, columns = () => 80, inputStatus = () => "") {
130
+ this.write = write;
131
+ this.tty = tty;
132
+ this.columns = columns;
133
+ this.inputStatus = inputStatus;
134
+ }
135
+ phase(label, _step) {
136
+ this.clear();
137
+ this.label = label;
138
+ this.begin();
139
+ }
140
+ start(name) {
141
+ this.active++;
142
+ this.label = labels[name ?? ""] ?? "Running a tool";
143
+ this.begin();
144
+ }
145
+ finish(name, success = true) {
146
+ this.active = Math.max(0, this.active - 1);
147
+ if (success && !["run_check", "run_environment_command"].includes(name) && !name.startsWith("verify_and_apply_") && !editLabels[name]) {
148
+ const label = summaries[name] ?? "other operations";
149
+ this.completed.set(label, (this.completed.get(label) ?? 0) + 1);
150
+ }
151
+ this.label = this.active ? this.label : "Waiting for model response";
152
+ this.begin();
153
+ }
154
+ begin() {
155
+ this.started = Date.now();
156
+ this.render();
157
+ if (this.tty && !this.timer) {
158
+ this.timer = setInterval(() => this.render(), 250);
159
+ this.timer.unref();
160
+ }
161
+ }
162
+ render() {
163
+ if (!this.tty)
164
+ return;
165
+ const elapsed = Math.floor((Date.now() - this.started) / 1000);
166
+ const done = [...this.completed.values()].reduce((sum, count) => sum + count, 0);
167
+ const total = Math.floor((Date.now() - this.runStarted) / 1000);
168
+ const input = this.inputStatus();
169
+ const timing = `${elapsed}s phase · ${total}s total`;
170
+ const text = input.includes("draft:") || !input.startsWith("0 queued") && input ? `… ${input} · ${timing}` : `… ${this.label} · ${timing}${done ? ` · ${done} tools done` : ""}`;
171
+ this.write(`\r\x1B[2K${Array.from(text).slice(0, Math.max(1, this.columns() - 1)).join("")}`);
172
+ this.visible = true;
173
+ }
174
+ pause() {
175
+ this.clear();
176
+ }
177
+ clear() {
178
+ clearInterval(this.timer);
179
+ this.timer = undefined;
180
+ if (this.visible)
181
+ this.write("\r\x1B[2K");
182
+ this.visible = false;
183
+ }
184
+ flush(options) {
185
+ this.clear();
186
+ if ((options?.summary ?? true) && this.completed.size) {
187
+ const details = [...this.completed].map(([label, count]) => `${label}: ${count}`).join(" · ");
188
+ this.write(`✓ Activity · ${details}
189
+ `);
190
+ }
191
+ this.completed.clear();
192
+ }
193
+ }
194
+ var editLabels = {
195
+ apply_patch: "Edits applied",
196
+ apply_reviewed_edits: "Reviewed edits applied",
197
+ apply_reviewed_replacement: "Reviewed replacement applied",
198
+ apply_environment_patch: "Environment changes imported"
199
+ };
200
+ var SAFE_CAUSE = /^(?:file is binary after edit:|Refusing to write a control byte|Stale patch|Replacement requires|Preview requires|The patch |oldText |Content exceeds|proposalId does not match)/;
201
+ var clipCause = (message) => failureRedaction.redactText(sanitizeTerminalText(message)).replace(/\s+/g, " ").trim().slice(0, 240);
202
+ var compactToolResult = (result, options) => {
203
+ if (!result.isError)
204
+ return options?.includeSuccessEdits && editLabels[result.toolName] ? `✓ ${editLabels[result.toolName]}` : undefined;
205
+ const error = result.error && typeof result.error === "object" ? result.error : {};
206
+ const message = typeof error.message === "string" ? error.message : "";
207
+ const binaryRead = /^The file appears to be binary and cannot be read as text(?:: ([^.]+))?/.exec(message);
208
+ let reason = "operation failed. Inspect /activity and retry that file.";
209
+ if (message === "Denied by the operator." || message === "Computer action was denied by the approval policy." || /^Tool ".+" was denied by the approval policy\.$/.test(message))
210
+ reason = "rejected by you";
211
+ else if (binaryRead)
212
+ reason = `file is binary${binaryRead[1] ? `: ${binaryRead[1]}` : ""}. Restore the text version, then read it again.`;
213
+ else if (error.code === "TOOL_INPUT_VALIDATION_ERROR")
214
+ reason = "invalid arguments; the assistant can correct and retry";
215
+ else if (error.code === "ENOENT" || /^ENOENT: /.test(message))
216
+ reason = "file not found; list files to locate the correct path";
217
+ else if (message.startsWith("Dependency package or path was not found in ") || message.startsWith("Dependency path was not found in "))
218
+ reason = "dependency path not found; list the package files before retrying";
219
+ else if (message.startsWith("Dependency ") && message.includes(" is not installed in this workspace's node_modules."))
220
+ reason = "dependency not installed; check the project installation";
221
+ else if (message.startsWith("Dependency paths must be package-relative;"))
222
+ reason = "dependency path is outside the permitted boundary; use a package-relative path";
223
+ else if (/^The path is protected by the harness policy: node_modules(?:\/|$)/.test(message))
224
+ reason = "dependency access requires the dependency tools";
225
+ else if (/^The path is protected by the harness policy: /.test(message))
226
+ reason = "path protected by workspace policy";
227
+ else if (message === "Dependency access only permits package.json and TypeScript declaration files.")
228
+ reason = "dependency file type is not permitted";
229
+ else if (message === "Dependency directory links are not allowed.")
230
+ reason = "dependency link is outside the permitted boundary";
231
+ else if (message.startsWith("Dependency directory changed during inspection."))
232
+ reason = "dependency changed during inspection; retry the read";
233
+ else if (SAFE_CAUSE.test(message)) {
234
+ reason = clipCause(message);
235
+ if (!/not changed|reverted|retry|Read the file/i.test(reason))
236
+ reason += " Read the file again before retrying.";
237
+ }
238
+ const operation = labels[result.toolName] ?? "Tool operation";
239
+ return `✗ ${operation} · ${reason}${editLabels[result.toolName] && error.code === "TOOL_INPUT_VALIDATION_ERROR" ? " · edits not applied" : ""}`;
240
+ };
241
+
242
+ // packages/core/src/client/run-document.ts
243
+ import { getAgentBudgetStatus } from "@zhivex-ai/agents";
244
+ import { estimateAgentRunCost } from "@zhivex-ai/agents/ops";
245
+ var costPricing = (harness) => harness.config.costBudget ? {
246
+ inputCostPer1kTokens: harness.config.costBudget.inputCostPer1kTokens,
247
+ outputCostPer1kTokens: harness.config.costBudget.outputCostPer1kTokens,
248
+ currency: "USD"
249
+ } : undefined;
250
+ var runResultDocument = (result, harness) => ({
251
+ schemaVersion: CLI_JSON_SCHEMA_VERSION,
252
+ kind: "run-result",
253
+ runId: result.state.runId,
254
+ status: result.status,
255
+ provider: result.state.provider,
256
+ model: result.state.modelId,
257
+ output: result.outputText,
258
+ steps: result.steps.length,
259
+ toolCalls: result.toolResults.length,
260
+ verification: checkEvidence(result.toolResults),
261
+ mutations: harness.workspace.mutationAudit(),
262
+ pendingApprovals: result.state.pendingApprovals.map((approval) => ({
263
+ id: approval.id,
264
+ kind: approval.kind ?? "provider",
265
+ name: approval.name,
266
+ arguments: approval.arguments,
267
+ ...approval.childRunId ? { childRunId: approval.childRunId } : {},
268
+ ...approval.childAgentId ? { childAgentId: approval.childAgentId } : {}
269
+ })),
270
+ children: (result.state.childRuns ?? []).map((child) => ({
271
+ runId: child.runId,
272
+ agentId: child.agentId,
273
+ toolName: child.toolName,
274
+ status: child.status,
275
+ steps: child.steps,
276
+ toolCalls: child.toolCalls,
277
+ toolErrors: child.toolErrors,
278
+ usage: child.usage
279
+ })),
280
+ usage: result.usage,
281
+ ...result.state.metadata?.[USAGE_LEDGER_KEY] ? { usageLedger: inspectUsageLedger(result.state.metadata[USAGE_LEDGER_KEY]) } : {},
282
+ budget: getAgentBudgetStatus(result.state, harness.config.budget, result),
283
+ ...harness.config.costBudget ? {
284
+ costBudget: {
285
+ limitUsd: harness.config.costBudget.maxCostUsd,
286
+ estimate: estimateAgentRunCost(result.state, costPricing(harness))
287
+ }
288
+ } : {},
289
+ scope: result.state.scope,
290
+ capabilities: harness.capabilities,
291
+ orchestration: {
292
+ profiles: harness.config.orchestration.profiles,
293
+ childBudget: harness.config.orchestration.childBudget,
294
+ mcpServers: harness.mcpConfiguration.servers.map((server) => server.name)
295
+ },
296
+ execution: harness.executionEnvironment ? {
297
+ backend: "oci",
298
+ binding: result.state.executionEnvironment,
299
+ image: harness.executionEnvironment.image
300
+ } : { backend: "none" },
301
+ store: {
302
+ backend: harness.config.storeBackend,
303
+ stateDirectory: harness.config.stateDirectory,
304
+ migration: harness.persistence?.migration
305
+ },
306
+ stateDirectory: harness.config.stateDirectory
307
+ });
308
+ // packages/core/src/cli/resume-metadata.ts
309
+ var HARNESS_RESUME_METADATA_KEY = "zhivexHarnessResume";
310
+ var HARNESS_RESUME_METADATA_SCHEMA_VERSION = 1;
311
+ var harnessConfigInput = (config) => ({
312
+ schemaVersion: config.schemaVersion,
313
+ provider: config.provider,
314
+ model: config.model,
315
+ ...config.reasoningEffort ? { reasoningEffort: config.reasoningEffort } : {},
316
+ workspace: config.workspace,
317
+ stateDirectory: config.stateDirectory,
318
+ storeBackend: config.storeBackend,
319
+ tenantId: config.scope.tenantId,
320
+ ...config.scope.userId ? { userId: config.scope.userId } : {},
321
+ ...config.scope.namespace ? { namespace: config.scope.namespace } : {},
322
+ requireVerifiedDelivery: config.requireVerifiedDelivery,
323
+ maxSteps: config.maxSteps,
324
+ timeoutMs: config.timeoutMs,
325
+ ...config.unlimitedDuration === undefined ? {} : { unlimitedDuration: config.unlimitedDuration },
326
+ maxToolCalls: config.budget.maxToolCalls,
327
+ maxToolErrors: config.budget.maxToolErrors,
328
+ ...config.budget.unlimitedSteps === undefined ? {} : { unlimitedSteps: config.budget.unlimitedSteps },
329
+ ...config.budget.unlimitedToolCalls === undefined ? {} : { unlimitedToolCalls: config.budget.unlimitedToolCalls },
330
+ ...config.budget.unlimitedTokens !== undefined ? { unlimitedTokens: config.budget.unlimitedTokens } : {},
331
+ maxInputTokens: config.budget.maxInputTokens,
332
+ maxOutputTokens: config.budget.maxOutputTokens,
333
+ maxTotalTokens: config.budget.maxTotalTokens,
334
+ ...config.costBudget ? {
335
+ maxCostUsd: config.costBudget.maxCostUsd,
336
+ inputCostPerMillion: config.costBudget.inputCostPer1kTokens * 1000,
337
+ outputCostPerMillion: config.costBudget.outputCostPer1kTokens * 1000
338
+ } : {},
339
+ compactionMaxMessages: config.compaction.maxMessages,
340
+ compactionMaxEstimatedInputTokens: config.compaction.maxEstimatedInputTokens,
341
+ compactionKeepRecentMessages: config.compaction.keepRecentMessages,
342
+ ...config.compaction.model ? { compactionModel: config.compaction.model.model, compactionProvider: config.compaction.model.provider } : {},
343
+ allowedChecks: [...config.allowedChecks],
344
+ requiredCapabilities: [...config.requiredCapabilities],
345
+ subagentProfiles: [...config.orchestration.profiles],
346
+ subagentMaxSteps: config.orchestration.childBudget.maxSteps,
347
+ subagentMaxToolCalls: config.orchestration.childBudget.maxToolCalls,
348
+ subagentMaxToolErrors: config.orchestration.childBudget.maxToolErrors,
349
+ subagentMaxInputTokens: config.orchestration.childBudget.maxInputTokens,
350
+ subagentMaxOutputTokens: config.orchestration.childBudget.maxOutputTokens,
351
+ subagentMaxTotalTokens: config.orchestration.childBudget.maxTotalTokens,
352
+ subagentTimeoutMs: config.orchestration.childTimeoutMs,
353
+ maxParallelReviews: config.orchestration.maxParallelReviews,
354
+ projectContext: config.context.enabled,
355
+ contextConfigPath: config.context.configPath,
356
+ executionBackend: config.execution.backend,
357
+ ...config.execution.backend === "oci" ? {
358
+ ociRuntime: config.execution.runtime,
359
+ ociImage: config.execution.image,
360
+ ociAllowedCommands: [...config.execution.allowedCommands],
361
+ ociShellMode: config.execution.shellMode,
362
+ ociMaxProcessRuntimeMs: config.execution.maxProcessRuntimeMs,
363
+ ociMaxProcessOutputBytes: config.execution.maxProcessOutputBytes,
364
+ ociMaxMemoryMb: config.execution.maxMemoryMb,
365
+ ociMaxPids: config.execution.maxPids,
366
+ ociMaxCpus: config.execution.maxCpus,
367
+ ociMaxWorkspaceBytes: config.execution.maxWorkspaceBytes,
368
+ ociMaxFileWriteBytes: config.execution.maxFileWriteBytes,
369
+ ociTmpfsMb: config.execution.tmpfsMb
370
+ } : {},
371
+ ...config.mcpConfigPath ? { mcpConfigPath: config.mcpConfigPath } : {}
372
+ });
373
+ var persistedCliOptions = (input) => input ? {
374
+ ...input,
375
+ ...input.allowedChecks ? { allowedChecks: [...input.allowedChecks] } : {},
376
+ ...input.requiredCapabilities ? { requiredCapabilities: [...input.requiredCapabilities] } : {},
377
+ ...input.subagentProfiles ? { subagentProfiles: [...input.subagentProfiles] } : {},
378
+ ...input.ociAllowedCommands ? { ociAllowedCommands: [...input.ociAllowedCommands] } : {}
379
+ } : {};
380
+ var createHarnessResumeMetadata = (config, routes) => ({
381
+ [HARNESS_RESUME_METADATA_KEY]: JSON.parse(JSON.stringify({
382
+ schemaVersion: HARNESS_RESUME_METADATA_SCHEMA_VERSION,
383
+ config,
384
+ ...routes && routes.size > 0 ? { routes: serializeHarnessModelRoutes(routes) } : {}
385
+ }))
386
+ });
387
+ var readHarnessResumeDocument = (state) => {
388
+ const value = state.metadata?.[HARNESS_RESUME_METADATA_KEY];
389
+ if (value === undefined)
390
+ return;
391
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
392
+ throw new Error("Persisted harness resume metadata is invalid.");
393
+ }
394
+ const document = value;
395
+ if (document.schemaVersion !== HARNESS_RESUME_METADATA_SCHEMA_VERSION || !document.config || typeof document.config !== "object" || Array.isArray(document.config)) {
396
+ throw new Error("Persisted harness resume metadata is invalid.");
397
+ }
398
+ return document;
399
+ };
400
+ var readHarnessResumeConfig = (state) => {
401
+ const document = readHarnessResumeDocument(state);
402
+ if (!document)
403
+ return;
404
+ try {
405
+ return harnessConfigInput(document.config);
406
+ } catch {
407
+ throw new Error("Persisted harness resume metadata is invalid.");
408
+ }
409
+ };
410
+ var readHarnessResumeRoutes = (state) => {
411
+ const document = readHarnessResumeDocument(state);
412
+ if (!document?.routes)
413
+ return resolveHarnessModelRoutes();
414
+ if (typeof document.routes !== "object" || Array.isArray(document.routes)) {
415
+ throw new Error("Persisted harness routing metadata is invalid.");
416
+ }
417
+ try {
418
+ const values = Object.entries(document.routes).map(([profile, target]) => {
419
+ if (!target || typeof target !== "object" || Array.isArray(target))
420
+ throw new Error("invalid");
421
+ const route = target;
422
+ if (typeof route.provider !== "string" || typeof route.model !== "string")
423
+ throw new Error("invalid");
424
+ return `${profile}=${route.provider}:${route.model}`;
425
+ });
426
+ return resolveHarnessModelRoutes(values);
427
+ } catch {
428
+ throw new Error("Persisted harness routing metadata is invalid.");
429
+ }
430
+ };
431
+ var shellArgument = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
432
+ var resumeCommand = (runId, config, approve = true) => [
433
+ "zhivex-harness",
434
+ "resume",
435
+ shellArgument(runId),
436
+ approve ? "--approve" : "--deny",
437
+ "--workspace",
438
+ shellArgument(config.workspace),
439
+ "--state-dir",
440
+ shellArgument(config.stateDirectory),
441
+ "--store",
442
+ config.storeBackend,
443
+ "--tenant",
444
+ shellArgument(config.scope.tenantId),
445
+ ...config.scope.userId ? ["--user", shellArgument(config.scope.userId)] : [],
446
+ ...config.scope.namespace ? ["--namespace", shellArgument(config.scope.namespace)] : []
447
+ ].join(" ");
448
+
449
+ // packages/core/src/cli/terminal/activity-stream.ts
450
+ import { createRedactionPolicy as createRedactionPolicy2 } from "@zhivex-ai/agents";
451
+ var redaction = createRedactionPolicy2({ includeEmails: true });
452
+ var SECRETISH = /password|secret|api[_-]?key|token|authorization|bearer/i;
453
+ var EDIT_TOOLS = new Set(["apply_patch", "apply_reviewed_edits", "apply_reviewed_replacement"]);
454
+ var EXPLORE_TOOLS = new Set(["read_file", "read_files", "search_files", "search_many", "list_files", "git_diff", "read_dependency"]);
455
+ var CHECK_TOOLS = new Set(["run_check", "run_environment_command", "run_environment_shell", "run_environment_batch"]);
456
+ var KNOWN_TOOLS = new Set([...EDIT_TOOLS, ...EXPLORE_TOOLS, ...CHECK_TOOLS, "propose_edits", "move_file", "quarantine_file", "restore_file", "apply_environment_patch"]);
457
+ var isCheck = (name) => CHECK_TOOLS.has(name) || name.startsWith("verify_and_apply_");
458
+ var asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
459
+ var safe = (value, limit = 160) => redaction.redactText(sanitizeTerminalText(value)).replace(/[\r\n\t]/g, " ").trim().slice(0, limit);
460
+ var clipLive = (line) => {
461
+ const clean = line.replace(/[\r\n]/g, " ");
462
+ return clean.length > 240 ? `${clean.slice(0, 239)}…` : clean;
463
+ };
464
+ var emission = (line, children = []) => ({
465
+ live: clipLive(line),
466
+ history: [clipLive(line), ...children.map((child) => child.slice(0, 500))]
467
+ });
468
+ var lineCount = (text) => {
469
+ if (text.length === 0)
470
+ return 0;
471
+ const parts = text.split(`
472
+ `);
473
+ if (text.endsWith(`
474
+ `))
475
+ parts.pop();
476
+ return parts.length;
477
+ };
478
+ var lineRange = (start, end) => {
479
+ const from = typeof start === "number" && Number.isSafeInteger(start) ? start : undefined;
480
+ const to = typeof end === "number" && Number.isSafeInteger(end) ? end : undefined;
481
+ if (from !== undefined && to !== undefined)
482
+ return ` L${from}-${to}`;
483
+ if (from !== undefined && from !== 1)
484
+ return ` L${from}`;
485
+ return "";
486
+ };
487
+ var baseName = (path) => path.split(/[/\\]/).pop() || path;
488
+ var editPath = (name, input) => {
489
+ const record = asRecord(input);
490
+ if (!record)
491
+ return "";
492
+ if (name === "apply_reviewed_replacement" && typeof record.path === "string")
493
+ return record.path;
494
+ if (!Array.isArray(record.changes))
495
+ return typeof record.path === "string" ? record.path : "";
496
+ const paths = record.changes.map((change) => asRecord(change)?.path).filter((path) => typeof path === "string");
497
+ if (paths.length === 1)
498
+ return paths[0] ?? "";
499
+ if (paths.length > 1)
500
+ return paths.join(`
501
+ `);
502
+ return "";
503
+ };
504
+ var editLabel = (path) => path.includes(`
505
+ `) ? `${path.split(`
506
+ `).length} files` : safe(baseName(path), 80);
507
+ var statedIntent = (input) => {
508
+ const record = asRecord(input);
509
+ if (!record)
510
+ return;
511
+ for (const key of ["intent", "reason", "summary", "description"]) {
512
+ const value = record[key];
513
+ if (typeof value === "string" && value.trim() && !SECRETISH.test(value))
514
+ return safe(value.trim().split(`
515
+ `)[0] ?? "", 60);
516
+ }
517
+ return;
518
+ };
519
+ var inferredIntent = (oldText, newText) => {
520
+ const previous = new Set(oldText.split(`
521
+ `).map((line) => line.trim()));
522
+ for (const line of newText.split(`
523
+ `)) {
524
+ const trimmed = line.trim().replace(/\s+/g, " ");
525
+ if (trimmed.length < 8 || trimmed.length > 80 || previous.has(trimmed) || SECRETISH.test(trimmed))
526
+ continue;
527
+ return safe(trimmed, 60);
528
+ }
529
+ return;
530
+ };
531
+ var replacementStats = (input) => {
532
+ const record = asRecord(input);
533
+ if (!record || typeof record.oldText !== "string" || typeof record.newText !== "string")
534
+ return;
535
+ return {
536
+ added: lineCount(record.newText),
537
+ removed: lineCount(record.oldText),
538
+ intent: statedIntent(record) ?? inferredIntent(record.oldText, record.newText)
539
+ };
540
+ };
541
+ var matchedFiles = (output) => {
542
+ const record = asRecord(output);
543
+ if (!record)
544
+ return;
545
+ const paths = new Set;
546
+ const take = (matches) => {
547
+ if (!Array.isArray(matches))
548
+ return false;
549
+ for (const match of matches) {
550
+ const path = asRecord(match)?.path;
551
+ if (typeof path === "string")
552
+ paths.add(path);
553
+ }
554
+ return true;
555
+ };
556
+ const direct = take(record.matches);
557
+ let nested = false;
558
+ let truncated = record.truncated === true;
559
+ if (Array.isArray(record.results)) {
560
+ for (const result of record.results) {
561
+ const item = asRecord(result);
562
+ if (take(item?.matches))
563
+ nested = true;
564
+ if (item?.truncated === true)
565
+ truncated = true;
566
+ }
567
+ }
568
+ if (!direct && !nested)
569
+ return;
570
+ return { files: paths.size, truncated };
571
+ };
572
+ var readLine = (input) => {
573
+ const record = asRecord(input);
574
+ const path = typeof record?.path === "string" ? safe(record.path) : "a file";
575
+ return `Read ${path}${lineRange(record?.startLine, record?.endLine)}`;
576
+ };
577
+ var readFilesLine = (input) => {
578
+ const files = asRecord(input)?.files;
579
+ if (!Array.isArray(files) || files.length === 0)
580
+ return "Read files";
581
+ const parts = files.slice(0, 3).map((file) => {
582
+ const record = asRecord(file);
583
+ const path = typeof record?.path === "string" ? safe(record.path, 80) : "a file";
584
+ return `${path}${lineRange(record?.startLine, record?.endLine)}`;
585
+ });
586
+ const more = files.length > 3 ? ` · +${files.length - 3} more` : "";
587
+ return `Read ${parts.join(", ")}${more}`;
588
+ };
589
+ var searchLine = (name, input, output) => {
590
+ const record = asRecord(input);
591
+ const queries = Array.isArray(record?.queries) ? record.queries : undefined;
592
+ const firstQuery = queries ? asRecord(queries[0])?.query : record?.query;
593
+ const query = typeof firstQuery === "string" ? JSON.stringify(safe(firstQuery, 80)) : undefined;
594
+ const matches = matchedFiles(output);
595
+ const where = matches === undefined ? "" : matches.files === 0 ? " · no matches" : ` in ${matches.files} file${matches.files === 1 ? "" : "s"}${matches.truncated ? " · more remain" : ""}`;
596
+ if (name === "search_many" && queries && queries.length > 1) {
597
+ return `Searched ${queries.length} queries${query ? ` · ${query}` : ""}${where}`;
598
+ }
599
+ return `Searched ${query ?? "files"}${where}`;
600
+ };
601
+ var exploreItem = (name, input, output) => {
602
+ if (name === "read_file")
603
+ return { kind: "read", files: 1, line: readLine(input) };
604
+ if (name === "read_files") {
605
+ const files = asRecord(input)?.files;
606
+ return { kind: "read", files: Array.isArray(files) ? files.length : 1, line: readFilesLine(input) };
607
+ }
608
+ if (name === "search_files" || name === "search_many")
609
+ return { kind: "search", files: 0, line: searchLine(name, input, output) };
610
+ if (name === "list_files") {
611
+ const path = asRecord(input)?.path;
612
+ return { kind: "list", files: 0, line: `Listed ${typeof path === "string" ? safe(path) : "."}` };
613
+ }
614
+ if (name === "read_dependency") {
615
+ const record = asRecord(input);
616
+ const pkg = record?.package ?? record?.name;
617
+ return { kind: "read", files: 1, line: `Inspected ${typeof pkg === "string" ? safe(pkg, 80) : "a dependency"}` };
618
+ }
619
+ return { kind: "diff", files: 0, line: "Reviewed the git diff" };
620
+ };
621
+ var exploreSummary = (items) => {
622
+ const reads = items.filter((item) => item.kind === "read").reduce((sum, item) => sum + item.files, 0);
623
+ const searches = items.filter((item) => item.kind === "search").length;
624
+ const listings = items.filter((item) => item.kind === "list").length;
625
+ const diffs = items.filter((item) => item.kind === "diff").length;
626
+ const parts = [];
627
+ if (reads)
628
+ parts.push(`${reads} file${reads === 1 ? "" : "s"}`);
629
+ if (searches)
630
+ parts.push(`${searches} search${searches === 1 ? "" : "es"}`);
631
+ if (listings)
632
+ parts.push(`${listings} listing${listings === 1 ? "" : "s"}`);
633
+ if (diffs)
634
+ parts.push(`${diffs} diff${diffs === 1 ? "" : "s"}`);
635
+ const sample = items[0]?.line ?? "activity";
636
+ return `Explored ${parts.join(" · ") || `${items.length} steps`} · ${sample} · /activity`;
637
+ };
638
+ var otherLine = (name, input) => {
639
+ const record = asRecord(input);
640
+ if (name === "move_file" && typeof record?.source === "string" && typeof record.destination === "string") {
641
+ return `Moved ${safe(record.source)} → ${safe(record.destination)}`;
642
+ }
643
+ if (name === "quarantine_file" && typeof record?.path === "string")
644
+ return `Quarantined ${safe(record.path)}`;
645
+ if (name === "restore_file" && typeof record?.destination === "string")
646
+ return `Restored ${safe(record.destination)}`;
647
+ if (name === "apply_environment_patch")
648
+ return "Imported environment changes";
649
+ if (name === "propose_edits") {
650
+ const changes = Array.isArray(record?.changes) ? record.changes : [];
651
+ const first = asRecord(changes[0])?.path;
652
+ if (changes.length === 1 && typeof first === "string")
653
+ return `Proposed edits for ${safe(first)}`;
654
+ if (changes.length > 1)
655
+ return `Proposed edits for ${changes.length} files`;
656
+ return "Proposed edits";
657
+ }
658
+ if (!KNOWN_TOOLS.has(name) && !name.startsWith("verify_and_apply_"))
659
+ return "Ran tool";
660
+ return `Ran ${safe(name.replaceAll("_", " "), 40)}`;
661
+ };
662
+
663
+ class ActivityStream {
664
+ diff;
665
+ calls = new Map;
666
+ explore = [];
667
+ edit = null;
668
+ constructor(diff) {
669
+ this.diff = diff;
670
+ }
671
+ noteCall(call) {
672
+ this.calls.set(call.id, { name: call.name, input: call.input });
673
+ if (this.calls.size > 40) {
674
+ const oldest = this.calls.keys().next().value;
675
+ if (oldest)
676
+ this.calls.delete(oldest);
677
+ }
678
+ if (isCheck(call.name))
679
+ return this.flushPending();
680
+ if (EDIT_TOOLS.has(call.name)) {
681
+ const path = editPath(call.name, call.input) || call.name;
682
+ const flushed = this.edit && this.edit.path !== path ? this.flushEdit() : [];
683
+ return [...this.flushExplore(), ...flushed];
684
+ }
685
+ if (EXPLORE_TOOLS.has(call.name))
686
+ return this.flushEdit();
687
+ return this.flushPending();
688
+ }
689
+ noteResult(result) {
690
+ const call = this.calls.get(result.toolCallId);
691
+ this.calls.delete(result.toolCallId);
692
+ const name = result.toolName || call?.name || "tool";
693
+ const input = call?.input;
694
+ if (result.isError) {
695
+ const line = compactToolResult({ toolName: name, isError: true, error: result.error }) ?? "✗ Tool operation · operation failed. Inspect /activity and retry that file.";
696
+ return [...this.flushPending(), emission(line)];
697
+ }
698
+ if (name.startsWith("verify_and_apply_")) {
699
+ this.appendEdit(name, input);
700
+ return this.flushPending();
701
+ }
702
+ if (isCheck(name))
703
+ return this.flushPending();
704
+ if (EDIT_TOOLS.has(name)) {
705
+ const path = editPath(name, input) || name;
706
+ const flushed = this.edit && this.edit.path !== path ? this.flushEdit() : [];
707
+ this.appendEdit(name, input);
708
+ return [...this.flushExplore(), ...flushed];
709
+ }
710
+ if (EXPLORE_TOOLS.has(name)) {
711
+ const flushed = this.flushEdit();
712
+ this.explore.push(exploreItem(name, input, result.output));
713
+ return flushed;
714
+ }
715
+ return [...this.flushPending(), emission(otherLine(name, input))];
716
+ }
717
+ flush() {
718
+ return this.flushPending();
719
+ }
720
+ flushPending() {
721
+ return [...this.flushExplore(), ...this.flushEdit()];
722
+ }
723
+ flushExplore() {
724
+ if (!this.explore.length)
725
+ return [];
726
+ const items = this.explore;
727
+ this.explore = [];
728
+ if (items.length === 1)
729
+ return [emission(items[0]?.line ?? "Read a file")];
730
+ return [emission(exploreSummary(items), items.map((item) => ` ${item.line}`))];
731
+ }
732
+ flushEdit() {
733
+ if (!this.edit)
734
+ return [];
735
+ const group = this.edit;
736
+ this.edit = null;
737
+ const stats = group.stats ? ` +${group.added} −${group.removed}` : "";
738
+ const intent = group.intent ? `: ${group.intent}` : "";
739
+ const attempts = group.attempts > 1 ? ` · ${group.attempts} attempts` : "";
740
+ return [emission(`Edited ${editLabel(group.path)}${stats}${intent}${attempts}`, group.attempts > 1 ? group.details : [])];
741
+ }
742
+ appendEdit(name, input) {
743
+ const path = editPath(name, input) || name;
744
+ if (!this.edit || this.edit.path !== path) {
745
+ this.edit = { path, added: 0, removed: 0, attempts: 0, stats: true, details: [] };
746
+ }
747
+ const group = this.edit;
748
+ const stats = name === "apply_reviewed_replacement" ? replacementStats(input) : undefined;
749
+ const intent = stats?.intent ?? statedIntent(input);
750
+ group.attempts += 1;
751
+ if (!group.intent && intent)
752
+ group.intent = intent;
753
+ if (stats) {
754
+ group.added += stats.added;
755
+ group.removed += stats.removed;
756
+ this.diff.added += stats.added;
757
+ this.diff.removed += stats.removed;
758
+ group.details.push(` attempt ${group.attempts} +${stats.added} −${stats.removed}${intent ? `: ${intent}` : ""}`);
759
+ } else {
760
+ group.stats = false;
761
+ group.details.push(` attempt ${group.attempts}`);
762
+ }
763
+ }
764
+ }
765
+
766
+ // packages/core/src/cli/terminal/terminal-markdown.ts
767
+ class TerminalMarkdown {
768
+ output;
769
+ color;
770
+ columns;
771
+ pending = "";
772
+ code = false;
773
+ heading = false;
774
+ lineStart = true;
775
+ timer;
776
+ tableLines = [];
777
+ constructor(output, color, columns = () => 80) {
778
+ this.output = output;
779
+ this.color = color;
780
+ this.columns = columns;
781
+ }
782
+ drain(final = false) {
783
+ let rendered = "", activeStyle = 0;
784
+ const emit = (text, style = this.code ? 36 : this.heading ? 1 : 0) => {
785
+ if (this.color && style !== activeStyle) {
786
+ if (activeStyle)
787
+ rendered += "\x1B[0m";
788
+ if (style)
789
+ rendered += `\x1B[${style}m`;
790
+ activeStyle = style;
791
+ }
792
+ rendered += text;
793
+ };
794
+ const finishTable = () => {
795
+ if (!this.tableLines.length)
796
+ return;
797
+ emit(this.tableLines.length > 1 ? renderTerminalTable(this.tableLines, this.columns(), this.color) : this.tableLines[0], 0);
798
+ this.tableLines = [];
799
+ };
800
+ while (this.pending) {
801
+ if (!final && this.pending.length === 1 && /[\uD800-\uDBFF]/.test(this.pending))
802
+ break;
803
+ if (this.lineStart) {
804
+ if (!this.code && (this.pending.startsWith("|") || this.tableLines.length)) {
805
+ const end = this.pending.indexOf(`
806
+ `);
807
+ if (this.pending.startsWith("|") && end < 0 && !final && this.pending.length < 8192)
808
+ break;
809
+ const line = this.pending.slice(0, end < 0 ? this.pending.length : end + 1);
810
+ const count = this.tableLines.length ? tableCells(this.tableLines[0]).length : 0;
811
+ const accepted = (end >= 0 || final) && this.pending.startsWith("|") && line.length <= 8192 && (this.tableLines.length === 0 ? tableCells(line).length > 0 : this.tableLines.length === 1 ? isTableSeparator(line, count) : tableCells(line).length === count);
812
+ if (accepted && this.tableLines.length < 128) {
813
+ this.tableLines.push(line);
814
+ this.pending = this.pending.slice(line.length);
815
+ continue;
816
+ }
817
+ finishTable();
818
+ }
819
+ if (!final && (/^`{1,2}$/.test(this.pending) || /^#{1,6}$/.test(this.pending)))
820
+ break;
821
+ if (this.pending.startsWith("```")) {
822
+ const end = this.pending.indexOf(`
823
+ `);
824
+ if (end < 0 && !final && this.pending.length < 128)
825
+ break;
826
+ const length = end < 0 ? this.pending.length : end;
827
+ emit(this.pending.slice(0, length), 90);
828
+ this.pending = this.pending.slice(length);
829
+ this.code = !this.code;
830
+ this.lineStart = false;
831
+ continue;
832
+ }
833
+ if (!this.code) {
834
+ const heading = /^#{1,6} /.exec(this.pending);
835
+ if (heading) {
836
+ this.heading = true;
837
+ this.pending = this.pending.slice(heading[0].length);
838
+ this.lineStart = false;
839
+ continue;
840
+ }
841
+ }
842
+ this.lineStart = false;
843
+ }
844
+ if (this.pending[0] === `
845
+ `) {
846
+ emit(`
847
+ `, 0);
848
+ this.pending = this.pending.slice(1);
849
+ this.lineStart = true;
850
+ this.heading = false;
851
+ continue;
852
+ }
853
+ if (this.color && !this.code) {
854
+ if (this.pending === "*" && !final)
855
+ break;
856
+ const marker = this.pending.startsWith("**") ? "**" : this.pending[0] === "`" ? "`" : undefined;
857
+ if (marker) {
858
+ const end = this.pending.indexOf(marker, marker.length);
859
+ const newline = this.pending.indexOf(`
860
+ `);
861
+ if (end > marker.length && (newline < 0 || end < newline)) {
862
+ emit(this.pending.slice(marker.length, end), marker === "`" ? 36 : 1);
863
+ this.pending = this.pending.slice(end + marker.length);
864
+ continue;
865
+ }
866
+ if (!final && newline < 0 && this.pending.length < 2048)
867
+ break;
868
+ emit(marker);
869
+ this.pending = this.pending.slice(marker.length);
870
+ continue;
871
+ }
872
+ }
873
+ const point = String.fromCodePoint(this.pending.codePointAt(0));
874
+ emit(point);
875
+ this.pending = this.pending.slice(point.length);
876
+ }
877
+ if (final)
878
+ finishTable();
879
+ if (activeStyle)
880
+ rendered += "\x1B[0m";
881
+ if (rendered)
882
+ this.output(rendered);
883
+ }
884
+ write(delta) {
885
+ this.pending += sanitizeTerminalText(delta);
886
+ if (this.pending.includes(`
887
+ `) || this.pending.length >= 2048)
888
+ this.drain();
889
+ if (this.pending && !this.timer) {
890
+ this.timer = setTimeout(() => {
891
+ this.timer = undefined;
892
+ this.drain();
893
+ }, 24);
894
+ this.timer.unref();
895
+ }
896
+ }
897
+ flush() {
898
+ clearTimeout(this.timer);
899
+ this.timer = undefined;
900
+ this.drain(true);
901
+ }
902
+ }
903
+
904
+ // packages/core/src/cli/presentation.ts
905
+ import { createInterface } from "node:readline/promises";
906
+ import {
907
+ createRedactionPolicy as createRedactionPolicy3
908
+ } from "@zhivex-ai/agents";
909
+ var CLI_STREAM_ERROR_SEQUENCE = Symbol("cliStreamErrorSequence");
910
+ var terminalErrorRedaction = createRedactionPolicy3({ includeEmails: true });
911
+ var annotateCliStreamError = (error, lastSequence) => {
912
+ const normalized = error instanceof Error ? error : normalizeHarnessError(error);
913
+ Object.defineProperty(normalized, CLI_STREAM_ERROR_SEQUENCE, {
914
+ configurable: true,
915
+ enumerable: false,
916
+ value: (lastSequence ?? 0) + 1
917
+ });
918
+ return normalized;
919
+ };
920
+ var cliStreamErrorSequence = (error) => error && typeof error === "object" && Number.isSafeInteger(error[CLI_STREAM_ERROR_SEQUENCE]) ? error[CLI_STREAM_ERROR_SEQUENCE] : 1;
921
+ var terminalErrorMessage = (error) => terminalErrorRedaction.redactText(error instanceof Error ? error.message : String(error));
922
+ var summarizeApproval = (approval) => {
923
+ return formatApproval(approval);
924
+ };
925
+ var approvalResponses = (approvals, approve, reason) => approvals.map((approval) => ({
926
+ provider: approval.provider,
927
+ approvalRequestId: approval.id,
928
+ approve,
929
+ reason
930
+ }));
931
+ var interactiveApprovalResolver = (automaticallyApprove, ask, ui) => {
932
+ return async (approvals) => {
933
+ if (automaticallyApprove === "restricted")
934
+ return approvalResponses(approvals, false, "Denied by restricted approval mode.");
935
+ if (automaticallyApprove === true || automaticallyApprove === "auto") {
936
+ return approvalResponses(approvals, true, "Approved by automatic mode.");
937
+ }
938
+ const policy = ui?.requireCompleteReview ? undefined : ui?.autoApprove?.();
939
+ if (policy && policy.mode !== "manual") {
940
+ const batch = decideBatch(approvals.map((approval) => ({ name: approval.name, arguments: approval.arguments })), policy);
941
+ if (batch.auto && ui) {
942
+ const { review: _review, select: _select, ...rest } = ui;
943
+ return resolveTerminalApprovals(approvals, {
944
+ ask: async () => "",
945
+ write: () => {
946
+ return;
947
+ },
948
+ ...rest
949
+ });
950
+ }
951
+ }
952
+ if (!ask && (!process.stdin.isTTY || !process.stdout.isTTY))
953
+ return;
954
+ const readline = ask ? undefined : createInterface({ input: process.stdin, output: process.stdout });
955
+ try {
956
+ return await resolveTerminalApprovals(approvals, {
957
+ ask: ask ?? ((text) => readline.question(text)),
958
+ write: (text) => process.stderr.write(text),
959
+ ...ui
960
+ });
961
+ } finally {
962
+ readline?.close();
963
+ }
964
+ };
965
+ };
966
+ var terminalApprovalResolver = (automaticallyApprove, ask, ui, reviewHost) => {
967
+ return async (approvals, state) => {
968
+ const automatic = (approve, reason) => {
969
+ const responses2 = approvalResponses(approvals, approve, reason);
970
+ return reviewHost ? issueAutomaticApprovalResponses(reviewHost, state, responses2, "cli-automatic") : responses2;
971
+ };
972
+ if (automaticallyApprove === "restricted")
973
+ return automatic(false, "Denied by restricted approval mode.");
974
+ if (automaticallyApprove === true || automaticallyApprove === "auto") {
975
+ return automatic(true, "Approved by automatic mode.");
976
+ }
977
+ if (!reviewHost) {
978
+ return interactiveApprovalResolver(automaticallyApprove, ask, ui)(approvals, state);
979
+ }
980
+ const explicit = requiresExplicitHostReview(reviewHost);
981
+ const startedAt = Date.now();
982
+ const snapshot = structuredClone(state);
983
+ const origins = [];
984
+ const effectiveUi = explicit ? {
985
+ ...ui?.select && ui.workspace ? { select: ui.select, workspace: ui.workspace } : {},
986
+ requireCompleteReview: true,
987
+ onDecisionOrigin: (origin) => origins.push(origin)
988
+ } : {
989
+ ...ui,
990
+ onDecisionOrigin: (origin) => origins.push(origin)
991
+ };
992
+ const responses = await interactiveApprovalResolver(automaticallyApprove, ask, effectiveUi)(explicit ? snapshot.pendingApprovals : approvals, state);
993
+ if (!responses)
994
+ return;
995
+ return explicit ? issueExplicitReviewResponses(reviewHost, snapshot, responses, "cli-terminal", startedAt) : issueObservedApprovalResponses(reviewHost, snapshot, responses, "cli-terminal", origins, startedAt);
996
+ };
997
+ };
998
+ var printTerminalResult = (result, harness, output, tracker) => {
999
+ tracker.markdown?.flush();
1000
+ const document = {
1001
+ ...runResultDocument(result, harness),
1002
+ ...tracker.policyEvidence ? { policyEvidence: tracker.policyEvidence } : {}
1003
+ };
1004
+ if (output.jsonl) {
1005
+ tracker.sequence = (tracker.sequence ?? 0) + 1;
1006
+ process.stdout.write(`${serializeStreamResult(document, tracker.sequence)}
1007
+ `);
1008
+ return;
1009
+ }
1010
+ if (output.json) {
1011
+ process.stdout.write(`${JSON.stringify(document, null, 2)}
1012
+ `);
1013
+ return;
1014
+ }
1015
+ if (!tracker.streamedText && result.outputText) {
1016
+ process.stdout.write(sanitizeTerminalText(result.outputText));
1017
+ }
1018
+ if (result.outputText || tracker.streamedText) {
1019
+ process.stdout.write(`
1020
+ `);
1021
+ }
1022
+ process.stderr.write(`
1023
+ run ${result.state.runId} · ${result.state.provider}/${result.state.modelId} · ${result.status} · ${result.steps.length} steps · ${harness.workspace.mutationAudit().length} mutations
1024
+ `);
1025
+ if (result.state.metadata?.[USAGE_LEDGER_KEY])
1026
+ process.stderr.write(formatUsageLedger(result.state.metadata[USAGE_LEDGER_KEY]) + `
1027
+ `);
1028
+ process.stderr.write(formatVerificationSummary(result.toolResults) + `
1029
+ `);
1030
+ if (result.status === "waiting_approval") {
1031
+ for (const approval of result.state.pendingApprovals) {
1032
+ process.stderr.write(`
1033
+ Pending approval:
1034
+ ${summarizeApproval(approval)}
1035
+ `);
1036
+ }
1037
+ process.stderr.write(`The state was persisted. Resume with: ${resumeCommand(result.state.runId, harness.config)}
1038
+ `);
1039
+ }
1040
+ };
1041
+ var proseLineOpen = new WeakSet;
1042
+ var conversationStarted = new WeakSet;
1043
+ var toolActivities = new WeakMap;
1044
+ var activityStreams = new WeakMap;
1045
+ var lastTerminalFailures = new WeakMap;
1046
+ var activityStreamFor = (tracker) => {
1047
+ let stream2 = activityStreams.get(tracker);
1048
+ if (!stream2) {
1049
+ tracker.turnDiff ??= { added: 0, removed: 0 };
1050
+ stream2 = new ActivityStream(tracker.turnDiff);
1051
+ activityStreams.set(tracker, stream2);
1052
+ }
1053
+ return stream2;
1054
+ };
1055
+ var emitActivity = (tracker, batch, print) => {
1056
+ for (const item of batch) {
1057
+ if (print && item.live)
1058
+ process.stderr.write(`${item.live}
1059
+ `);
1060
+ for (const line of item.history)
1061
+ tracker.activityHistory?.add(line);
1062
+ }
1063
+ };
1064
+ var recordActivity = (tracker, event, print) => {
1065
+ const stream2 = activityStreamFor(tracker);
1066
+ const batch = event.type === "tool-call" ? stream2.noteCall(event.toolCall) : event.type === "tool-result" ? stream2.noteResult(event.toolResult) : event.type === "text-delta" || event.type === "agent-run-finish" || event.type === "error" || event.type === "tool-approval-request" || event.type === "agent-approval-request" ? stream2.flush() : undefined;
1067
+ if (!batch?.length)
1068
+ return;
1069
+ if (print && batch.some((item) => item.live))
1070
+ toolActivities.get(tracker)?.pause();
1071
+ emitActivity(tracker, batch, print);
1072
+ };
1073
+ var flushToolActivity = (tracker) => {
1074
+ const host = tracker;
1075
+ const stream2 = activityStreams.get(tracker);
1076
+ if (stream2)
1077
+ emitActivity(host, stream2.flush(), true);
1078
+ toolActivities.get(tracker)?.flush({ summary: !host.consoleView });
1079
+ };
1080
+ var streamSink = (output, tracker, compact = false) => async (event) => {
1081
+ if (!output.json && !output.jsonl) {
1082
+ if (tracker.consoleView) {
1083
+ recordActivity(tracker, event, compact);
1084
+ tracker.activityHistory?.observe(event, { includeTools: false });
1085
+ } else {
1086
+ tracker.activityHistory?.observe(event);
1087
+ }
1088
+ }
1089
+ if (output.jsonl) {
1090
+ const sequence = (tracker.sequence ?? 0) + 1;
1091
+ const serialized = serializeStreamEvent(event, sequence);
1092
+ if (serialized === undefined)
1093
+ return;
1094
+ tracker.sequence = sequence;
1095
+ process.stdout.write(`${serialized}
1096
+ `);
1097
+ return;
1098
+ }
1099
+ if (!output.json && compact && event.type === "agent-run-update")
1100
+ return;
1101
+ if (!output.json && compact) {
1102
+ let activity = toolActivities.get(tracker);
1103
+ if (!activity) {
1104
+ activity = new ToolActivity((text) => {
1105
+ process.stderr.write(text);
1106
+ }, Boolean(process.stderr.isTTY && process.stdout.isTTY && !tracker.consoleView), () => process.stderr.columns || 80, tracker.inputStatus);
1107
+ toolActivities.set(tracker, activity);
1108
+ }
1109
+ if (event.type === "agent-compaction") {
1110
+ tracker.markdown?.flush();
1111
+ if (proseLineOpen.has(tracker)) {
1112
+ process.stdout.write(`
1113
+ `);
1114
+ proseLineOpen.delete(tracker);
1115
+ }
1116
+ activity.phase("Updating context");
1117
+ return;
1118
+ }
1119
+ if (event.type === "agent-step-start") {
1120
+ tracker.markdown?.flush();
1121
+ if (proseLineOpen.has(tracker)) {
1122
+ process.stdout.write(`
1123
+ `);
1124
+ proseLineOpen.delete(tracker);
1125
+ }
1126
+ activity.phase("Waiting for model response", event.stepIndex);
1127
+ return;
1128
+ }
1129
+ if (event.type === "agent-run-start") {
1130
+ lastTerminalFailures.delete(tracker);
1131
+ activity.phase("Waiting for model response", event.currentStep);
1132
+ return;
1133
+ }
1134
+ if (event.type === "tool-call") {
1135
+ tracker.markdown?.flush();
1136
+ if (proseLineOpen.has(tracker)) {
1137
+ process.stdout.write(`
1138
+ `);
1139
+ proseLineOpen.delete(tracker);
1140
+ }
1141
+ activity.start(event.toolCall.name);
1142
+ return;
1143
+ }
1144
+ if (event.type === "tool-result") {
1145
+ activity.finish(event.toolResult.toolName, !event.toolResult.isError);
1146
+ const check = ["run_check", "run_environment_command"].includes(event.toolResult.toolName) || event.toolResult.toolName.startsWith("verify_and_apply_");
1147
+ if (!tracker.consoleView) {
1148
+ const detail = compactToolResult(event.toolResult, { includeSuccessEdits: true });
1149
+ if (detail && !check) {
1150
+ activity.pause();
1151
+ tracker.markdown?.flush();
1152
+ if (proseLineOpen.has(tracker)) {
1153
+ process.stdout.write(`
1154
+ `);
1155
+ proseLineOpen.delete(tracker);
1156
+ }
1157
+ process.stderr.write(`${detail}
1158
+ `);
1159
+ return;
1160
+ }
1161
+ }
1162
+ if (!check) {
1163
+ activity.pause();
1164
+ return;
1165
+ }
1166
+ activity.pause();
1167
+ } else if (["agent-run-finish", "error", "tool-approval-request", "agent-approval-request"].includes(event.type)) {
1168
+ tracker.markdown?.flush();
1169
+ if (proseLineOpen.has(tracker)) {
1170
+ process.stdout.write(`
1171
+ `);
1172
+ proseLineOpen.delete(tracker);
1173
+ }
1174
+ activity.flush({ summary: !tracker.consoleView });
1175
+ } else if (!["provider-data", "finish", "agent-step-start", "agent-step-finish"].includes(event.type)) {
1176
+ activity.pause();
1177
+ }
1178
+ }
1179
+ if (!output.json && event.type === "text-delta") {
1180
+ if (compact && !conversationStarted.has(tracker)) {
1181
+ process.stdout.write(terminalSupportsColor(Boolean(process.stdout.isTTY)) ? `
1182
+ \x1B[1mZhivex\x1B[0m
1183
+ ` : `
1184
+ Zhivex
1185
+ `);
1186
+ conversationStarted.add(tracker);
1187
+ }
1188
+ if (event.textDelta.endsWith(`
1189
+ `))
1190
+ proseLineOpen.delete(tracker);
1191
+ else if (event.textDelta)
1192
+ proseLineOpen.add(tracker);
1193
+ tracker.streamedText = true;
1194
+ if (process.stdout.isTTY) {
1195
+ tracker.markdown ??= new TerminalMarkdown((text) => {
1196
+ process.stdout.write(text);
1197
+ }, terminalSupportsColor(true), () => process.stdout.columns || 80);
1198
+ tracker.markdown.write(event.textDelta);
1199
+ } else
1200
+ process.stdout.write(sanitizeTerminalText(event.textDelta));
1201
+ return;
1202
+ }
1203
+ if (!output.json) {
1204
+ if (tracker.consoleView && event.type === "agent-run-finish" && event.status === "completed")
1205
+ return;
1206
+ if (compact && ["provider-data", "finish", "agent-run-start", "agent-step-start", "agent-step-finish", "tool-approval-request", "agent-approval-request", "agent-approval-resolved"].includes(event.type))
1207
+ return;
1208
+ if (compact && event.type === "agent-run-finish" && event.status === "waiting_approval")
1209
+ return;
1210
+ tracker.markdown?.flush();
1211
+ proseLineOpen.delete(tracker);
1212
+ let line = formatTerminalEvent(event, {
1213
+ color: terminalSupportsColor(Boolean(process.stderr.isTTY))
1214
+ });
1215
+ if (compact && event.type === "tool-result" && event.toolResult.isError && line?.endsWith(" · error")) {
1216
+ line = compactToolResult(event.toolResult);
1217
+ }
1218
+ if ((event.type === "error" || event.type === "agent-run-finish" && event.status === "failed") && line) {
1219
+ const cause = terminalRunFailure(event.type === "error" ? event.error : event.state.error);
1220
+ if (lastTerminalFailures.get(tracker) === cause)
1221
+ return;
1222
+ lastTerminalFailures.set(tracker, cause);
1223
+ } else if (event.type === "agent-run-start")
1224
+ lastTerminalFailures.delete(tracker);
1225
+ if (line)
1226
+ process.stderr.write(`
1227
+ ${line}
1228
+ `);
1229
+ }
1230
+ };
1231
+ var orchestrationObserver = (json) => async (event) => {
1232
+ if (json)
1233
+ return;
1234
+ if (event.type === "subagent-start") {
1235
+ process.stderr.write(`
1236
+ subagent start · ${event.childAgentId ?? event.toolName}
1237
+ `);
1238
+ } else if (event.type === "subagent-finish") {
1239
+ process.stderr.write(`
1240
+ subagent finish · ${event.childRun.agentId ?? event.childRun.toolName} · ${event.childRun.status}
1241
+ `);
1242
+ }
1243
+ };
1244
+
1245
+ // packages/core/src/cli/console/console-commands.ts
1246
+ var CONSOLE_COMMAND_CATALOG = [
1247
+ ["/menu", "Open navigation menu", true],
1248
+ ["/theme", "Choose light, dark or system terminal colors", true],
1249
+ ["/help", "Show commands; /help all shows everything", true],
1250
+ ["/connection", "Inspect credentials and optionally test selected model access", false],
1251
+ ["/credentials", "Manage provider keys in the system keychain or this session", false],
1252
+ ["/provider", "Select a provider", false],
1253
+ ["/model", "Select a model and reasoning effort", false],
1254
+ ["/reasoning", "Choose reasoning effort for the current model", false],
1255
+ ["/route", "Configure specialist model routes", false],
1256
+ ["/status", "Inspect the current session and run", true],
1257
+ ["/diff", "Review workspace changes", false],
1258
+ ["/task", "Define, review, keep or revise a bounded task", false],
1259
+ ["/checkpoint", "Capture, review and restore selected text files", false],
1260
+ ["/budget", "Set estimated USD policy for each next run", false],
1261
+ ["/pricing", "Inspect advisory model prices and their source", false],
1262
+ ["/review", "Review a task", false],
1263
+ ["/resume", "Reopen a conversation by session ID", true],
1264
+ ["/pending", "Inspect pending approvals", true],
1265
+ ["/approve", "Approve the pending actions", true],
1266
+ ["/deny", "Deny the pending actions", true],
1267
+ ["/approvals", "Change approval mode for this CLI session", false],
1268
+ ["/auto-approve", "Set Manual, Auto-edits, or Auto with limits for this session", false],
1269
+ ["/manual", "Drop auto-approve back to Manual for this session", true],
1270
+ ["/undo", "Revert the latest auto-approved file change", false],
1271
+ ["/continue", "Continue an interrupted task with retained results in a new run", false],
1272
+ ["/compact", "Compact conversation context", false],
1273
+ ["/compaction", "Choose a compaction model or inspect recommendations", false],
1274
+ ["/new", "Start a new conversation", true],
1275
+ ["/rename", "Rename the current conversation", true],
1276
+ ["/clear", "Clear conversation context", false],
1277
+ ["/exit", "Exit the console", true],
1278
+ ["/paste", "Compose a literal multiline draft", true],
1279
+ ["/activity", "Show recent activity; /activity clear resets it", true],
1280
+ ["/queue", "Inspect queued tasks; /queue clear discards them", true],
1281
+ ["/verbose", "Toggle full or compact activity details", false],
1282
+ ["/context", "Inspect project rules and selected context", false],
1283
+ ["/attach", "Attach a workspace file to the next request", false],
1284
+ ["/attachments", "List selected attachments", false],
1285
+ ["/detach", "Remove selected attachments", false],
1286
+ ["/sessions", "Find saved conversations", true],
1287
+ ["/limits", "Inspect or change the step limit for next turns", false],
1288
+ ["/usage", "Inspect transport usage", false],
1289
+ ["/cancel", "Cancel the active run", true]
1290
+ ];
1291
+ var consoleCommands = (mode = "direct") => CONSOLE_COMMAND_CATALOG.filter(([name, , service]) => mode === "service" ? service : name !== "/cancel");
1292
+ var everyday = new Set(["/theme", "/menu", "/help", "/model", "/new", "/sessions", "/attach", "/task", "/diff", "/exit"]);
1293
+ var approvals = new Set(["/approvals", "/pending", "/approve", "/deny", "/auto-approve", "/manual", "/undo"]);
1294
+ var searchConsoleCommands = (query, mode = "direct") => {
1295
+ const search = query.replace(/^\//, "").toLowerCase();
1296
+ return consoleCommands(mode).filter(([name, description]) => search ? name.slice(1).startsWith(search) || description.toLowerCase().includes(search) : everyday.has(name)).sort(([a], [b]) => Number(b.slice(1).startsWith(search)) - Number(a.slice(1).startsWith(search)));
1297
+ };
1298
+ var argumentsFor = {
1299
+ "/theme": "[light|dark|system]",
1300
+ "/task": "[start JSON|review|keep|revise text]",
1301
+ "/limits": "[positive integer]",
1302
+ "/budget": "[USD|off]",
1303
+ "/checkpoint": "[capture|list|review|restore|retry]",
1304
+ "/compaction": "[provider:model|off|recommend]",
1305
+ "/approvals": "[ask|auto|restricted]",
1306
+ "/auto-approve": "[manual|auto-edits|auto-limits|workspace <mode>]",
1307
+ "/undo": "[audit id]",
1308
+ "/provider": "[id]",
1309
+ "/model": "[id]",
1310
+ "/route": "[role=provider[:model] | clear [role]]",
1311
+ "/review": "<task>",
1312
+ "/resume": "[last|sessionId]",
1313
+ "/new": "[title]",
1314
+ "/rename": "<title>",
1315
+ "/attach": "<path>",
1316
+ "/detach": "[path]",
1317
+ "/sessions": "[search]"
1318
+ };
1319
+ var formatConsoleHelp = (mode = "direct", all = false) => {
1320
+ const commands = consoleCommands(mode);
1321
+ const format = (names) => commands.filter(([name]) => names.has(name)).map(([name, description]) => {
1322
+ const args = mode === "service" && name === "/new" ? "" : mode === "service" && name === "/resume" ? "[sessionId]" : name === "/help" ? "[all]" : argumentsFor[name] ?? "";
1323
+ return `${`${name} ${args}`.trim().padEnd(28)} ${description}`;
1324
+ }).join(`
1325
+ `);
1326
+ return `Everyday commands:
1327
+ ` + format(everyday) + `
1328
+
1329
+ Pending approvals (review the actions before deciding):
1330
+ ` + format(approvals) + (all ? `
1331
+
1332
+ Advanced commands:
1333
+ ` + format(new Set(commands.map(([name]) => name).filter((name) => !everyday.has(name) && !approvals.has(name)))) : `
1334
+
1335
+ Use /help all for advanced commands, or type / followed by a search term.`) + `
1336
+ Up/Down selects, Tab inserts, Enter submits. Ctrl+R searches prompt history.
1337
+ ` + `? shows shortcuts; Alt+Enter inserts a newline. Bracketed paste stays literal.
1338
+ ` + `Ctrl+C discards input or stops the active operation.
1339
+ ` + (mode === "service" ? `Provider, model and tool policy are managed by the service host.
1340
+ ` : "");
1341
+ };
1342
+
1343
+ // packages/core/src/cli/console/console-input.ts
1344
+ import { createInterface as createInterface2 } from "node:readline";
1345
+ import { PassThrough, Writable } from "node:stream";
1346
+ import { StringDecoder } from "node:string_decoder";
1347
+
1348
+ // packages/core/src/cli/console/console-presentation.ts
1349
+ var segments = new Intl.Segmenter(undefined, { granularity: "grapheme" });
1350
+ var consoleLines = (text, width) => {
1351
+ const result = [];
1352
+ for (const source of sanitizeTerminalText(text).replace(/\t/g, " ").split(`
1353
+ `)) {
1354
+ let line = "", cells = 0;
1355
+ for (const { segment } of segments.segment(source)) {
1356
+ const size = terminalCellWidth(segment);
1357
+ if (line && cells + size > Math.max(1, width)) {
1358
+ result.push(line);
1359
+ line = "";
1360
+ cells = 0;
1361
+ }
1362
+ line += segment;
1363
+ cells += size;
1364
+ }
1365
+ result.push(line);
1366
+ }
1367
+ return result;
1368
+ };
1369
+ var consoleLabel = (text, width) => {
1370
+ if (width <= 0)
1371
+ return "";
1372
+ const safe2 = sanitizeTerminalText(text).replace(/[\r\n\t]/g, " ");
1373
+ if (terminalCellWidth(safe2) <= width)
1374
+ return safe2;
1375
+ let value = "";
1376
+ for (const { segment } of segments.segment(safe2)) {
1377
+ if (terminalCellWidth(value + segment) > width - 1)
1378
+ break;
1379
+ value += segment;
1380
+ }
1381
+ return value + "…";
1382
+ };
1383
+ var consoleWidth = (columns = 80) => Math.max(1, Math.min((columns || 80) - 1, 100));
1384
+ var muted = (text, color) => paintTerminal(text, "muted", color);
1385
+ var usd = (value) => typeof value === "number" ? `$${value.toFixed(6)}` : "unknown";
1386
+ var money = (value) => `$${value.toFixed(6)}`;
1387
+ var pendingDecision = (status) => status.startsWith("Waiting for your decision") || status.startsWith("approval pending");
1388
+ var approvalPhrase = (input) => input.autoApproveMode === "auto-edits" ? "auto-edits · m for manual" : input.autoApproveMode === "auto-limits" ? "auto-limits · m for manual" : input.autoApproveMode === "manual" ? "manual approvals" : input.approvalMode === "restricted" ? "restricted approvals" : input.approvalMode === "auto" || input.automaticApprovals ? "auto approvals" : "ask before changes";
1389
+ var consoleStatusParts = (input) => {
1390
+ const runCap = input.runUsage?.limitUsd;
1391
+ const nextCap = input.nextLimitUsd;
1392
+ const hasRunCap = typeof runCap === "number";
1393
+ const hasNextCap = typeof nextCap === "number";
1394
+ const incomplete = Boolean(input.runUsage && !input.runUsage.usageComplete && (hasRunCap || hasNextCap));
1395
+ const showRun = Boolean(input.runUsage && (hasRunCap || incomplete || hasNextCap && typeof input.runUsage.estimatedUsd === "number"));
1396
+ const attachments = (input.attachments ?? 0) > 0 ? `${input.attachments} attached` : "";
1397
+ return [
1398
+ input.model,
1399
+ approvalPhrase(input),
1400
+ input.status,
1401
+ ...attachments ? [attachments] : [],
1402
+ ...showRun && input.runUsage ? [`Run est. ${usd(input.runUsage.estimatedUsd)}${input.runUsage.usageComplete ? "" : " INCOMPLETE"}${hasRunCap ? ` / ${money(runCap)} cap` : ""}`] : [],
1403
+ ...hasNextCap ? [`Next run cap ${money(nextCap)}`] : []
1404
+ ];
1405
+ };
1406
+ var consoleStatusText = (input) => consoleStatusParts(input).join(" · ");
1407
+ var wrapClause = (text, width) => {
1408
+ if (terminalCellWidth(text) <= width)
1409
+ return [text];
1410
+ const lines = [];
1411
+ let current = "";
1412
+ for (const word of text.split(" ")) {
1413
+ if (terminalCellWidth(word) > width) {
1414
+ if (current)
1415
+ lines.push(current);
1416
+ current = "";
1417
+ lines.push(...consoleLines(word, width));
1418
+ continue;
1419
+ }
1420
+ const next = current ? `${current} ${word}` : word;
1421
+ if (current && terminalCellWidth(next) > width) {
1422
+ lines.push(current);
1423
+ current = word;
1424
+ } else
1425
+ current = next;
1426
+ }
1427
+ if (current)
1428
+ lines.push(current);
1429
+ return lines.length ? lines : [""];
1430
+ };
1431
+ var packClauses = (parts, width) => {
1432
+ const lines = [];
1433
+ let current = "";
1434
+ for (const part of parts) {
1435
+ const next = current ? `${current} · ${part}` : part;
1436
+ if (current && terminalCellWidth(next) > width) {
1437
+ lines.push(...wrapClause(current, width));
1438
+ current = part;
1439
+ } else
1440
+ current = next;
1441
+ }
1442
+ if (current)
1443
+ lines.push(...wrapClause(current, width));
1444
+ return lines;
1445
+ };
1446
+ var consoleStateLines = (input, columns = 80) => packClauses(consoleStatusParts(input), consoleWidth(columns));
1447
+ var legacyStateLines = (input, columns = 80) => {
1448
+ const width = consoleWidth(columns);
1449
+ const policy = input.autoApproveMode ? approvalPhrase(input) : input.approvalMode === "restricted" ? "restricted approvals" : input.approvalMode === "auto" || input.automaticApprovals ? "auto approvals" : "review approvals";
1450
+ const cap = (value) => typeof value === "number" ? money(value) : "none";
1451
+ return [
1452
+ ...consoleLines(consoleLabel(`Model ${input.model}${input.reasoning ? ` · ${input.reasoning}` : ""}`, width * 2), width),
1453
+ ...input.runUsage ? consoleLines(`Run est. ${usd(input.runUsage.estimatedUsd)}${input.runUsage.usageComplete ? "" : " INCOMPLETE"} / ${cap(input.runUsage.limitUsd)} cap`, width) : ["Run: no usage recorded"],
1454
+ ...consoleLines(`Next run cap ${cap(input.nextLimitUsd)} · ${policy}`, width),
1455
+ ...consoleLines(`Context ~${input.contextTokens ?? 0} retained tokens* · ${input.attachments ?? 0} attached`, width)
1456
+ ];
1457
+ };
1458
+ var formatComposer = (input, columns = 80, color = terminalSupportsColor(Boolean(process.stdout.isTTY)), layout = "legacy") => {
1459
+ const width = consoleWidth(columns);
1460
+ const title = input.title ? muted(consoleLabel(input.title, width), color) + `
1461
+ ` : "";
1462
+ if (layout === "focus")
1463
+ return `
1464
+ ${title}${muted("─".repeat(width), color)}
1465
+ `;
1466
+ if (input.runUsage !== undefined || input.nextLimitUsd !== undefined || input.contextTokens !== undefined || input.autoApproveMode !== undefined) {
1467
+ const status2 = consoleLabel(input.status, width);
1468
+ const painted = color && pendingDecision(input.status) ? paintTerminal(status2, "pending", color) : status2;
1469
+ return `
1470
+ ${title}${legacyStateLines(input, columns).map((line) => muted(line, color)).join(`
1471
+ `)}
1472
+ ${painted}
1473
+ ${muted("─".repeat(width), color)}
1474
+ `;
1475
+ }
1476
+ const model = consoleLabel([input.model, input.reasoning ? `reasoning ${input.reasoning}` : undefined].filter(Boolean).join(" · "), width);
1477
+ const policy = input.approvalMode === "restricted" ? "restricted approvals" : input.approvalMode === "auto" || input.automaticApprovals ? "auto approvals" : "review approvals";
1478
+ const status = consoleLabel([input.status, policy, input.attachments ? `${input.attachments} attached` : undefined].filter(Boolean).join(" · "), width);
1479
+ return `
1480
+ ${title}${muted(model, color)}
1481
+ ${color && pendingDecision(input.status) ? paintTerminal(status, "pending", color) : muted(status, color)}
1482
+ ${muted("─".repeat(width), color)}
1483
+ `;
1484
+ };
1485
+ var formatComposerFooter = (columns = 80, color = false, focus) => {
1486
+ const width = consoleWidth(columns);
1487
+ const rule = muted("─".repeat(width), color);
1488
+ if (!focus) {
1489
+ const hints2 = width >= 65 ? "/ commands · Ctrl+R history · Alt+Enter newline · ? shortcuts" : width >= 40 ? "/ commands · Ctrl+R history · ? shortcuts" : "/ commands · ? help";
1490
+ return [rule, muted(consoleLabel(hints2, width), color)];
1491
+ }
1492
+ const hints = width >= 32 ? "/ commands · ? shortcuts" : "?";
1493
+ const text = consoleStatusText(focus);
1494
+ const paint = (line) => color && pendingDecision(focus.status) ? paintTerminal(line, "pending", color) : muted(line, color);
1495
+ const hintWidth = terminalCellWidth(hints);
1496
+ if (terminalCellWidth(text) + 2 + hintWidth <= width) {
1497
+ return [rule, `${paint(text)}${" ".repeat(width - terminalCellWidth(text) - hintWidth)}${muted(hints, color)}`];
1498
+ }
1499
+ return [rule, ...consoleStateLines(focus, columns).map(paint), muted(consoleLabel(hints, width), color)];
1500
+ };
1501
+ var formatComposerPlaceholder = (columns = 80, color = false) => muted(consoleLabel("Ask a question or describe a task", Math.max(0, consoleWidth(columns) - 2)), color);
1502
+ var CONSOLE_SHORTCUTS = [
1503
+ "Keyboard shortcuts",
1504
+ "Enter Send task (history search only restores a draft)",
1505
+ "Alt+Enter Insert a newline",
1506
+ "Up / Down Move within multiline input; recall history at its edges",
1507
+ "Ctrl+R Search this session's in-memory prompt history",
1508
+ "Tab Insert selected command or history match",
1509
+ "Esc Close command menu or cancel history search",
1510
+ "Ctrl+C Discard draft or cancel the active operation",
1511
+ "Ctrl+D Exit when the draft is empty",
1512
+ "/menu Browse providers, models and conversations",
1513
+ "/resume Choose a saved conversation",
1514
+ "Credential source, retained-token estimates and run caps are on /status.",
1515
+ "Context estimates cover retained messages only. They exclude request instructions and tools. Costs are estimates, not invoices.",
1516
+ "While working: type a draft, Enter queues the next task, Up recalls the last queued task. Ctrl+C stops and clears the queue."
1517
+ ].join(`
1518
+ `);
1519
+ var chooseConsoleItem = async (title, items, io) => {
1520
+ if (!items.length) {
1521
+ io.write(`No matches.
1522
+ `);
1523
+ return;
1524
+ }
1525
+ let query = "";
1526
+ for (;; ) {
1527
+ const matches = items.filter((item) => `${item.label} ${item.detail ?? ""}`.toLowerCase().includes(query.toLowerCase()));
1528
+ const visible = matches.slice(0, 12);
1529
+ io.write(`
1530
+ ${sanitizeTerminalText(title)}
1531
+ ` + visible.map((item, i) => ` ${i + 1}. ${consoleLabel(item.label, 60)}${item.detail ? ` · ${consoleLabel(item.detail, 60)}` : ""}`).join(`
1532
+ `) + `
1533
+ ${matches.length > 12 ? `${matches.length} matches; type a filter to narrow the list.
1534
+ ` : ""}`);
1535
+ const answer = (await io.ask("Choose number, type a filter, or Enter to cancel: ")).trim();
1536
+ if (!answer)
1537
+ return;
1538
+ if (/^[a-z]$/.test(answer)) {
1539
+ const keyed = items.find((item) => item.key === answer);
1540
+ if (keyed)
1541
+ return keyed.value;
1542
+ }
1543
+ if (/^\d+$/.test(answer)) {
1544
+ const selected = visible[Number(answer) - 1];
1545
+ if (selected)
1546
+ return selected.value;
1547
+ io.write(`Choose a number from the visible list.
1548
+ `);
1549
+ } else
1550
+ query = answer;
1551
+ }
1552
+ };
1553
+
1554
+ // packages/core/src/cli/console/console-review.ts
1555
+ var fits = (text, width) => terminalCellWidth(text) <= width;
1556
+ var hintFor = (width, selected) => {
1557
+ const options = selected < 0 ? [
1558
+ "No action highlighted · ↑↓ then a or r · n/p hunks · PgUp/PgDn",
1559
+ "No action highlighted · a or r · PgUp/PgDn",
1560
+ "a approve · r reject · PgUp/PgDn",
1561
+ "PgUp/PgDn"
1562
+ ] : [
1563
+ "↑↓ move · Enter confirms the highlight · n/p hunks · PgUp/PgDn",
1564
+ "Enter confirms the highlight · PgUp/PgDn",
1565
+ "n/p hunks · PgUp/PgDn",
1566
+ "PgUp/PgDn"
1567
+ ];
1568
+ return options.find((option) => fits(option, width)) ?? "PgUp/PgDn";
1569
+ };
1570
+ var headerLine = (right, width) => {
1571
+ const left = "( Z ) Review changes";
1572
+ const place = (value) => {
1573
+ const gap = width - terminalCellWidth(left) - terminalCellWidth(value);
1574
+ return gap >= 2 ? left + " ".repeat(gap) + value : undefined;
1575
+ };
1576
+ if (right) {
1577
+ const full = place(right);
1578
+ if (full)
1579
+ return full;
1580
+ const project = right.split(" · ")[0] ?? "";
1581
+ const short = project && project !== right ? place(project) : undefined;
1582
+ if (short)
1583
+ return short;
1584
+ }
1585
+ return consoleLabel(left, width);
1586
+ };
1587
+ var wrapWords = (text, width) => {
1588
+ const lines = [];
1589
+ let line = "";
1590
+ for (const word of text.split(" ")) {
1591
+ const next = line ? `${line} ${word}` : word;
1592
+ if (fits(next, width)) {
1593
+ line = next;
1594
+ continue;
1595
+ }
1596
+ if (line)
1597
+ lines.push(line);
1598
+ if (fits(word, width))
1599
+ line = word;
1600
+ else {
1601
+ const broken = consoleLines(word, width);
1602
+ lines.push(...broken.slice(0, -1));
1603
+ line = broken.at(-1) ?? "";
1604
+ }
1605
+ }
1606
+ if (line)
1607
+ lines.push(line);
1608
+ return lines.length ? lines : [""];
1609
+ };
1610
+ var itemLines = (items, selected, width, details) => {
1611
+ const lines = [];
1612
+ for (const [index, item] of items.entries()) {
1613
+ const mark = index === selected ? "> " : " ";
1614
+ const key = item.key ? `${item.key} ` : "";
1615
+ lines.push(...wrapWords(`${mark}${key}${item.label}`, width));
1616
+ if (details && item.detail)
1617
+ lines.push(...wrapWords(` ${item.detail}`, width));
1618
+ }
1619
+ return lines;
1620
+ };
1621
+ var reviewFrame = (review, items, selected, _query, offset, columns = 80, rows = 24, wrappedBody) => {
1622
+ const width = consoleWidth(columns);
1623
+ const banner = review.banner ? wrapWords(review.banner, width).slice(0, 2) : [];
1624
+ const summary = review.summary ? wrapWords(review.summary, width).slice(0, 2) : [];
1625
+ const files = review.fileList ? review.fileList.split(`
1626
+ `).filter(Boolean).flatMap((line) => wrapWords(line, width)) : [];
1627
+ const preface = [...banner, ...summary, ...files];
1628
+ const body = wrappedBody ?? consoleLines(review.body, width);
1629
+ const hint = hintFor(width, selected);
1630
+ const title = consoleLabel(review.title, width);
1631
+ const notice = review.notice ? consoleLabel(review.notice, width) : undefined;
1632
+ let details = true;
1633
+ let showNotice = Boolean(notice);
1634
+ const footerOf = () => {
1635
+ const decisions = itemLines(items, selected, width, details);
1636
+ return [title, ...decisions.length ? decisions : [" No decisions"], hint, ...showNotice && notice ? [notice] : []];
1637
+ };
1638
+ let footer = footerOf();
1639
+ while (footer.length > rows - 3 && (details || showNotice)) {
1640
+ if (details)
1641
+ details = false;
1642
+ else
1643
+ showNotice = false;
1644
+ footer = footerOf();
1645
+ }
1646
+ const chrome = preface.length + footer.length + 2;
1647
+ const capacity = Math.max(1, rows - chrome);
1648
+ const start = Math.max(0, Math.min(offset, Math.max(0, body.length - capacity)));
1649
+ const visible = body.slice(start, start + Math.min(capacity, body.length));
1650
+ const remaining = Math.max(0, body.length - (start + visible.length));
1651
+ const count = review.files ?? 0;
1652
+ const fileLabel = count === 1 ? "1 file" : `${count} files`;
1653
+ const marker = remaining > 0 ? `↓ ${remaining} more lines · n/p hunks · PgUp/PgDn` : count > 0 ? `End of changes · ${fileLabel}` : "End of changes";
1654
+ const lines = [
1655
+ headerLine(review.headerRight ?? "", width),
1656
+ ...preface,
1657
+ ...visible,
1658
+ consoleLabel(marker, width),
1659
+ ...footer
1660
+ ];
1661
+ const selectedRow = lines.findIndex((line) => line.startsWith("> "));
1662
+ const decisionRow = lines.findIndex((line) => line.includes("Reject") || line.includes("Approve"));
1663
+ return { lines, offset: start, capacity, filterRow: (selectedRow >= 0 ? selectedRow : Math.max(0, decisionRow)) + 1 };
1664
+ };
1665
+
1666
+ // packages/core/src/cli/console/console-input.ts
1667
+ var CONSOLE_COMMANDS = consoleCommands().map(([name]) => name);
1668
+ var MAX_CONSOLE_INPUT_BYTES = 64 * 1024;
1669
+ var interrupted = () => Object.assign(new Error("Input interrupted."), { name: "AbortError" });
1670
+ var incompleteTerminalSequence = (sequence) => {
1671
+ if (sequence.length > 32)
1672
+ return false;
1673
+ if (sequence === "\x1B" || sequence === "\x1BO")
1674
+ return true;
1675
+ if (!sequence.startsWith("\x1B["))
1676
+ return false;
1677
+ const body = sequence.slice(2);
1678
+ if (!body)
1679
+ return true;
1680
+ for (let index = 0;index < body.length - 1; index += 1) {
1681
+ const code = body.charCodeAt(index);
1682
+ if (code < 32 || code > 63)
1683
+ return false;
1684
+ }
1685
+ const last = body.charCodeAt(body.length - 1);
1686
+ return last < 64 || last > 126;
1687
+ };
1688
+
1689
+ class ConsoleInput {
1690
+ input;
1691
+ output;
1692
+ terminal;
1693
+ mode;
1694
+ background = false;
1695
+ backgroundDraft = "";
1696
+ queued = [];
1697
+ queueNotice = "";
1698
+ queueEnabled = true;
1699
+ hidden;
1700
+ reader;
1701
+ keyboard = new PassThrough;
1702
+ display;
1703
+ decoder = new StringDecoder("utf8");
1704
+ escape = "";
1705
+ clipboard;
1706
+ clipboardBytes = 0;
1707
+ clipboardAllowed = false;
1708
+ draftWasPaste = false;
1709
+ lastSubmissionWasPaste = false;
1710
+ closed = false;
1711
+ completeCommands = false;
1712
+ history = [];
1713
+ historyPosition = -1;
1714
+ historyDraft = "";
1715
+ historyDraftWasPaste = false;
1716
+ pending;
1717
+ focusState;
1718
+ paste;
1719
+ onInterrupt;
1720
+ constructor(input, output, terminal = true, mode = "direct") {
1721
+ this.input = input;
1722
+ this.output = output;
1723
+ this.terminal = terminal;
1724
+ this.mode = mode;
1725
+ const source = terminal ? this.keyboard : input;
1726
+ this.display = new Writable({ write: (chunk, encoding, callback) => {
1727
+ if (!this.reviewing && !(this.background && !this.pending))
1728
+ output.write(chunk, encoding);
1729
+ callback();
1730
+ } });
1731
+ Object.defineProperty(this.display, "columns", {
1732
+ get: () => output.columns
1733
+ });
1734
+ Object.assign(this.keyboard, { isTTY: terminal, setRawMode: (enabled) => {
1735
+ input.setRawMode?.(enabled);
1736
+ } });
1737
+ this.reader = createInterface2({
1738
+ input: source,
1739
+ output: terminal ? this.display : output,
1740
+ terminal,
1741
+ historySize: 0,
1742
+ completer: (line) => this.pending && this.completeCommands ? [consoleCommands(this.mode).map(([name]) => name).filter((name) => name.startsWith(line)), line] : [[], line]
1743
+ });
1744
+ this.reader.setPrompt("");
1745
+ source.prependListener("keypress", this.onKeypress);
1746
+ this.reader.on("line", (line) => {
1747
+ if (this.background && !this.pending) {
1748
+ if (line.trim() && Buffer.byteLength(line) <= MAX_CONSOLE_INPUT_BYTES) {
1749
+ if (this.queued.length < 8 && this.queued.reduce((n, item) => n + Buffer.byteLength(item), 0) + Buffer.byteLength(line) <= 256 * 1024) {
1750
+ this.queued.push(line);
1751
+ this.backgroundDraft = "";
1752
+ this.queueNotice = "";
1753
+ } else {
1754
+ this.backgroundDraft = line;
1755
+ this.queueNotice = "Queue full; draft retained";
1756
+ }
1757
+ }
1758
+ this.draftWasPaste = false;
1759
+ queueMicrotask(() => {
1760
+ if (this.background && this.backgroundDraft)
1761
+ Object.assign(this.reader, { line: this.backgroundDraft, cursor: this.backgroundDraft.length });
1762
+ });
1763
+ return;
1764
+ }
1765
+ if (this.paste) {
1766
+ const paste = this.paste;
1767
+ if (line === ".end") {
1768
+ this.paste = undefined;
1769
+ paste.resolve(paste.lines.join(`
1770
+ `));
1771
+ } else {
1772
+ paste.bytes += Buffer.byteLength(line) + 1;
1773
+ if (paste.bytes > MAX_CONSOLE_INPUT_BYTES) {
1774
+ this.paste = undefined;
1775
+ paste.reject(new Error("Multiline input exceeds 64 KiB; draft discarded."));
1776
+ } else
1777
+ paste.lines.push(line);
1778
+ }
1779
+ return;
1780
+ }
1781
+ const pending = this.pending;
1782
+ this.pending = undefined;
1783
+ this.lastSubmissionWasPaste = this.draftWasPaste;
1784
+ this.draftWasPaste = false;
1785
+ this.reader.setPrompt("");
1786
+ if (Buffer.byteLength(line) > MAX_CONSOLE_INPUT_BYTES) {
1787
+ pending?.reject(new Error("Input exceeds 64 KiB."));
1788
+ } else
1789
+ pending?.resolve(line);
1790
+ });
1791
+ this.reader.on("SIGINT", () => this.interrupt());
1792
+ this.reader.on("close", () => {
1793
+ this.finishSecret(false);
1794
+ this.closed = true;
1795
+ if (terminal) {
1796
+ output.write("\x1B[?2004l");
1797
+ input.off("data", this.onData);
1798
+ input.off("end", this.onEnd);
1799
+ output.off("resize", this.onResize);
1800
+ input.pause();
1801
+ }
1802
+ this.interrupt();
1803
+ });
1804
+ if (terminal) {
1805
+ output.write("\x1B[?2004h");
1806
+ input.on("data", this.onData);
1807
+ input.on("end", this.onEnd);
1808
+ output.on("resize", this.onResize);
1809
+ input.resume();
1810
+ }
1811
+ }
1812
+ selection;
1813
+ reviewing;
1814
+ reviewOffset = 0;
1815
+ reviewPage = 1;
1816
+ reviewNotice;
1817
+ reviewHunks = [];
1818
+ manualRequest;
1819
+ reviewWrapped;
1820
+ reviewLinesDrawn = 0;
1821
+ selectionMatches() {
1822
+ const indexed = this.selection?.items.map((item, index) => ({ ...item, index })) ?? [];
1823
+ if (this.reviewing)
1824
+ return indexed;
1825
+ const query = this.reader.line.toLowerCase();
1826
+ return indexed.filter((item) => `${item.label} ${item.detail ?? ""}`.toLowerCase().includes(query));
1827
+ }
1828
+ finishSelection(accept) {
1829
+ const selected = accept ? this.selectionMatches()[this.menuSelection] : undefined;
1830
+ this.hideMenu();
1831
+ const pending = this.pending;
1832
+ this.pending = undefined;
1833
+ this.draftWasPaste = false;
1834
+ this.reader.setPrompt("");
1835
+ this.output.write(`
1836
+ `);
1837
+ pending?.resolve(selected ? String(selected.index) : "");
1838
+ }
1839
+ async select(title, items) {
1840
+ if (!items.length) {
1841
+ this.output.write(`No matches.
1842
+ `);
1843
+ return;
1844
+ }
1845
+ if (!this.terminal || process.env.TERM === "dumb")
1846
+ return chooseConsoleItem(title, items, {
1847
+ write: (text) => {
1848
+ this.output.write(text);
1849
+ },
1850
+ ask: (prompt) => this.question(prompt)
1851
+ });
1852
+ this.selection = { title, items };
1853
+ if (!this.reviewing)
1854
+ this.menuSelection = 0;
1855
+ try {
1856
+ if (!this.reviewing)
1857
+ this.output.write(`
1858
+ ${sanitizeTerminalText(title)}
1859
+ `);
1860
+ const answer = this.question(this.reviewing ? "" : "Filter > ", true);
1861
+ this.renderMenu();
1862
+ const value = await answer;
1863
+ return value === "" ? undefined : items[Number(value)]?.value;
1864
+ } finally {
1865
+ this.hideMenu();
1866
+ this.selection = undefined;
1867
+ }
1868
+ }
1869
+ onManual(handler) {
1870
+ this.manualRequest = handler;
1871
+ }
1872
+ async review(review, items) {
1873
+ if (!this.terminal || process.env.TERM === "dumb" || (this.output.rows ?? 24) < 24 || (this.output.columns ?? 80) < 32) {
1874
+ this.output.write(revealInvisibleText(review.body) + `
1875
+ `);
1876
+ return this.select(review.title, items);
1877
+ }
1878
+ this.hideMenu();
1879
+ this.clearQueue();
1880
+ Object.assign(this.reader, { line: "", cursor: 0 });
1881
+ this.reviewing = review;
1882
+ this.reviewOffset = 0;
1883
+ this.reviewHunks = [];
1884
+ this.menuSelection = -1;
1885
+ this.reviewNotice = undefined;
1886
+ this.reviewWrapped = undefined;
1887
+ this.reviewLinesDrawn = 0;
1888
+ try {
1889
+ return await this.select(review.title, items);
1890
+ } finally {
1891
+ this.eraseReview();
1892
+ this.reviewing = undefined;
1893
+ this.reviewWrapped = undefined;
1894
+ }
1895
+ }
1896
+ eraseReview() {
1897
+ if (!this.reviewLinesDrawn)
1898
+ return;
1899
+ const up = this.reviewLinesDrawn - 1;
1900
+ this.output.write((up > 0 ? `\x1B[${up}A` : "") + "\r\x1B[J");
1901
+ this.reviewLinesDrawn = 0;
1902
+ }
1903
+ styleReviewLine(line) {
1904
+ const gutter = line.length > 14 && line[13] === " " && (line[14] === "+" || line[14] === "-") ? line[14] : "";
1905
+ const mark = line.startsWith("+") || line.startsWith("-") || line.startsWith("@@") ? line[0] : gutter;
1906
+ const code = line.startsWith("( Z )") ? `1;${terminalToneCode("accent")}` : mark === "+" ? terminalToneCode("added") : mark === "-" ? terminalToneCode("removed") : mark === "@" || line.startsWith("@@") ? terminalToneCode("info") : line.startsWith("> ") || line.startsWith("Waiting for your decision") ? `1;${terminalToneCode("pending")}` : "";
1907
+ const color = terminalSupportsColor(this.terminal);
1908
+ return color && code ? `\x1B[${code}m${line}\x1B[0m` : line;
1909
+ }
1910
+ paintReview(lines) {
1911
+ const screen = this.output.rows ?? 24;
1912
+ const painted = lines.map((line) => this.styleReviewLine(line) + "\x1B[K");
1913
+ const fills = lines.length >= screen;
1914
+ if (this.reviewLinesDrawn === 0 && fills)
1915
+ this.output.write("\x1B[H" + painted.join(`\r
1916
+ `) + "\x1B[J");
1917
+ else if (this.reviewLinesDrawn === 0)
1918
+ this.output.write(painted.join(`\r
1919
+ `));
1920
+ else {
1921
+ const up = this.reviewLinesDrawn - 1;
1922
+ this.output.write((up > 0 ? `\x1B[${up}A` : "") + "\r" + painted.join(`\r
1923
+ `) + "\x1B[J");
1924
+ }
1925
+ this.reviewLinesDrawn = lines.length;
1926
+ }
1927
+ taskPrompt = "";
1928
+ shortcutsShown = false;
1929
+ historySearch;
1930
+ historyMatches() {
1931
+ const query = this.reader.line.toLowerCase();
1932
+ return this.history.filter((entry) => entry.text.toLowerCase().includes(query));
1933
+ }
1934
+ finishHistorySearch(accept) {
1935
+ const saved = this.historySearch;
1936
+ if (!saved)
1937
+ return;
1938
+ const selected = accept ? this.historyMatches()[this.menuSelection] : undefined;
1939
+ this.hideMenu();
1940
+ this.historySearch = undefined;
1941
+ const line = selected?.text ?? saved.draft;
1942
+ this.draftWasPaste = selected?.literal ?? saved.literal;
1943
+ Object.assign(this.reader, { line, cursor: selected ? line.length : saved.cursor });
1944
+ this.reader.setPrompt(this.taskPrompt);
1945
+ this.reader.prompt(true);
1946
+ this.menuDismissed = true;
1947
+ }
1948
+ menuVisible = false;
1949
+ placeholderVisible = false;
1950
+ focusComposer = false;
1951
+ menuSelection = 0;
1952
+ menuQuery = "";
1953
+ menuDismissed = false;
1954
+ escapeMenuTimer;
1955
+ standaloneMenuEscape = false;
1956
+ hideMenu() {
1957
+ if (this.reviewing)
1958
+ return;
1959
+ if (this.placeholderVisible)
1960
+ this.output.write("\x1B[K");
1961
+ if (this.menuVisible) {
1962
+ const { rows } = this.draftPosition();
1963
+ this.output.write(`\x1B7${rows ? `\x1B[${rows}B` : ""}\r
1964
+ \x1B[J\x1B8`);
1965
+ }
1966
+ this.menuVisible = false;
1967
+ this.placeholderVisible = false;
1968
+ }
1969
+ draftPosition() {
1970
+ const position = this.reader.getCursorPos();
1971
+ const cursor = this.reader.cursor;
1972
+ Object.assign(this.reader, { cursor: this.reader.line.length });
1973
+ const end = this.reader.getCursorPos();
1974
+ Object.assign(this.reader, { cursor });
1975
+ return { column: position.cols, rows: Math.max(0, end.rows - position.rows) };
1976
+ }
1977
+ showOverlay(lines, placeholder) {
1978
+ const { column, rows } = this.draftPosition();
1979
+ const reserve = rows + lines.length;
1980
+ const height = this.output.rows ?? 24;
1981
+ if (reserve >= height)
1982
+ return;
1983
+ this.output.write(`
1984
+ `.repeat(reserve) + `\x1B[${reserve}A\x1B[${column + 1}G`);
1985
+ this.output.write("\x1B7" + (placeholder ?? "") + (rows ? `\x1B[${rows}B` : "") + lines.map((line) => `\r
1986
+ ` + line).join("") + "\x1B8");
1987
+ this.menuVisible = true;
1988
+ this.placeholderVisible = Boolean(placeholder);
1989
+ }
1990
+ renderFocus() {
1991
+ if (!this.focusComposer || this.selection || this.historySearch)
1992
+ return;
1993
+ const rows = this.output.rows ?? 24;
1994
+ if (rows < 6)
1995
+ return;
1996
+ const columns = this.output.columns ?? 80;
1997
+ const color = terminalSupportsColor(this.terminal);
1998
+ this.showOverlay(formatComposerFooter(columns, color, this.mode === "direct" ? this.focusState : undefined), !this.reader.line && columns >= 40 ? formatComposerPlaceholder(columns, color) : undefined);
1999
+ }
2000
+ renderMenu() {
2001
+ if (this.reviewing && this.selection && this.pending) {
2002
+ if (!this.reviewing && this.menuQuery !== this.reader.line) {
2003
+ this.menuSelection = 0;
2004
+ this.menuQuery = this.reader.line;
2005
+ }
2006
+ const matches2 = this.selectionMatches();
2007
+ if (this.menuSelection >= matches2.length)
2008
+ this.menuSelection = matches2.length ? matches2.length - 1 : -1;
2009
+ const columns2 = this.output.columns ?? 80;
2010
+ const width = consoleWidth(columns2);
2011
+ let wrappedLines;
2012
+ if (this.reviewing.layout) {
2013
+ const laid = this.reviewing.layout(width);
2014
+ this.reviewHunks = laid.hunks;
2015
+ wrappedLines = laid.lines;
2016
+ } else {
2017
+ this.reviewHunks = [];
2018
+ if (!this.reviewWrapped || this.reviewWrapped.columns !== columns2)
2019
+ this.reviewWrapped = {
2020
+ columns: columns2,
2021
+ lines: consoleLines(this.reviewing.body, width)
2022
+ };
2023
+ wrappedLines = this.reviewWrapped.lines;
2024
+ }
2025
+ const frame = reviewFrame({ ...this.reviewing, ...this.reviewNotice ? { notice: this.reviewNotice } : {} }, matches2, this.menuSelection, this.reader.line, this.reviewOffset, columns2, this.output.rows ?? 24, wrappedLines);
2026
+ this.reviewOffset = frame.offset;
2027
+ this.reviewPage = frame.capacity;
2028
+ this.paintReview(frame.lines);
2029
+ return;
2030
+ }
2031
+ this.hideMenu();
2032
+ const query = this.reader.line;
2033
+ if (query !== this.menuQuery) {
2034
+ this.menuQuery = query;
2035
+ this.menuSelection = 0;
2036
+ this.menuDismissed = false;
2037
+ }
2038
+ if (!this.terminal || process.env.TERM === "dumb" || !this.pending || !this.completeCommands)
2039
+ return;
2040
+ if (!this.selection && !this.historySearch && (this.draftWasPaste || this.menuDismissed || !/^\/[^\s]*$/.test(query))) {
2041
+ this.renderFocus();
2042
+ return;
2043
+ }
2044
+ const matches = this.selection ? this.selectionMatches().map((item) => [item.label, item.detail ?? ""]) : this.historySearch ? this.historyMatches().map((entry) => [consoleLabel(entry.text, 64), ""]) : searchConsoleCommands(query, this.mode).map(([name, description]) => [name, description]);
2045
+ if (!matches.length && !this.historySearch && !this.selection) {
2046
+ this.renderFocus();
2047
+ return;
2048
+ }
2049
+ this.menuSelection = Math.max(0, Math.min(this.menuSelection, matches.length - 1));
2050
+ const rows = this.output.rows ?? 24;
2051
+ if (rows < 6)
2052
+ return;
2053
+ const pageSize = Math.min(5, rows - 4);
2054
+ const start = Math.floor(this.menuSelection / pageSize) * pageSize;
2055
+ const columns = Math.max(10, this.output.columns ?? 80);
2056
+ const lines = matches.slice(start, start + pageSize).map(([name, description], i) => `${i + start === this.menuSelection ? ">" : " "} ${name.padEnd(14)} ${description}`.slice(0, columns - 1));
2057
+ if (!matches.length)
2058
+ lines.push(" No matches; edit the filter".slice(0, columns - 1));
2059
+ lines.push((this.selection ? " ↑↓ navigate · Enter choose · Esc back" : this.historySearch ? " ↑↓ select · Enter restore · Esc cancel" : ` ${this.menuSelection + 1}/${matches.length} · ↑↓ select · Tab insert · Esc close`).slice(0, columns - 1));
2060
+ this.showOverlay(lines);
2061
+ }
2062
+ onEnd = () => {
2063
+ this.finishSecret(false);
2064
+ this.keyboard.end();
2065
+ };
2066
+ onResize = () => {
2067
+ if (this.pending || this.paste) {
2068
+ this.hideMenu();
2069
+ this.display.emit("resize");
2070
+ this.renderMenu();
2071
+ }
2072
+ };
2073
+ finishSecret(accept) {
2074
+ const hidden = this.hidden;
2075
+ if (!hidden)
2076
+ return;
2077
+ this.hidden = undefined;
2078
+ this.output.write(`
2079
+ `);
2080
+ const value = hidden.value;
2081
+ hidden.value = "";
2082
+ if (accept)
2083
+ hidden.resolve(value);
2084
+ else
2085
+ hidden.reject(interrupted());
2086
+ }
2087
+ secret(prompt) {
2088
+ if (!this.terminal || this.closed || this.pending || this.paste || this.hidden) {
2089
+ return Promise.reject(new Error("API key entry requires an idle interactive terminal."));
2090
+ }
2091
+ this.hideMenu();
2092
+ Object.assign(this.reader, { line: "", cursor: 0 });
2093
+ this.escape = "";
2094
+ this.output.write(prompt);
2095
+ return new Promise((resolve, reject) => {
2096
+ this.hidden = { value: "", escape: "", pasted: false, resolve, reject };
2097
+ });
2098
+ }
2099
+ onData = (chunk) => {
2100
+ if (this.hidden) {
2101
+ const text2 = typeof chunk === "string" ? chunk : this.decoder.write(chunk);
2102
+ for (const character of text2) {
2103
+ const hidden = this.hidden;
2104
+ if (!hidden)
2105
+ break;
2106
+ if (character === "\x03" || character === "\x04") {
2107
+ this.finishSecret(false);
2108
+ break;
2109
+ }
2110
+ if (character === "\x1B" || hidden.escape) {
2111
+ hidden.escape += character;
2112
+ const marker = hidden.pasted ? "\x1B[201~" : "\x1B[200~";
2113
+ if (!marker.startsWith(hidden.escape)) {
2114
+ this.finishSecret(false);
2115
+ break;
2116
+ }
2117
+ if (hidden.escape === marker) {
2118
+ hidden.pasted = !hidden.pasted;
2119
+ hidden.escape = "";
2120
+ }
2121
+ continue;
2122
+ }
2123
+ if (!hidden.pasted && (character === "\r" || character === `
2124
+ `)) {
2125
+ this.finishSecret(true);
2126
+ break;
2127
+ }
2128
+ if (!hidden.pasted && (character === "" || character === "\b")) {
2129
+ hidden.value = hidden.value.slice(0, -1);
2130
+ continue;
2131
+ }
2132
+ if (!/^[\x21-\x7e]$/.test(character) || hidden.value.length >= 8192) {
2133
+ this.finishSecret(false);
2134
+ break;
2135
+ }
2136
+ hidden.value += character;
2137
+ }
2138
+ return;
2139
+ }
2140
+ clearTimeout(this.escapeMenuTimer);
2141
+ const text = typeof chunk === "string" ? chunk : this.decoder.write(chunk);
2142
+ for (const character of text) {
2143
+ if (this.standaloneMenuEscape) {
2144
+ if (character !== "[")
2145
+ this.escape = "";
2146
+ this.standaloneMenuEscape = false;
2147
+ }
2148
+ if (character === "\x03") {
2149
+ if (this.selection) {
2150
+ this.escape = "";
2151
+ this.finishSelection(false);
2152
+ continue;
2153
+ }
2154
+ this.escape = "";
2155
+ this.clipboard = undefined;
2156
+ this.interrupt();
2157
+ continue;
2158
+ }
2159
+ this.escape += character;
2160
+ const marker = this.clipboard === undefined ? "\x1B[200~" : "\x1B[201~";
2161
+ if (marker.startsWith(this.escape)) {
2162
+ if (this.escape !== marker) {
2163
+ if (this.escape === "\x1B" && (this.menuVisible || this.historySearch || this.selection)) {
2164
+ this.escapeMenuTimer = setTimeout(() => {
2165
+ if (this.escape !== "\x1B")
2166
+ return;
2167
+ if (this.selection)
2168
+ this.finishSelection(false);
2169
+ else if (this.historySearch)
2170
+ this.finishHistorySearch(false);
2171
+ this.hideMenu();
2172
+ this.menuDismissed = true;
2173
+ this.standaloneMenuEscape = true;
2174
+ }, 100);
2175
+ }
2176
+ continue;
2177
+ }
2178
+ this.escape = "";
2179
+ if (this.clipboard === undefined) {
2180
+ this.hideMenu();
2181
+ this.clipboard = "";
2182
+ this.clipboardBytes = 0;
2183
+ this.clipboardAllowed = Boolean(this.pending && this.completeCommands && !this.selection) || Boolean(this.paste) || this.background;
2184
+ } else {
2185
+ const clipboard = this.clipboard;
2186
+ this.clipboard = undefined;
2187
+ if (this.clipboardAllowed && this.clipboardBytes <= MAX_CONSOLE_INPUT_BYTES) {
2188
+ const safe2 = sanitizeTerminalText(clipboard.replace(/\r\n?/g, `
2189
+ `));
2190
+ if (this.paste) {
2191
+ if (this.paste.bytes + Buffer.byteLength(safe2) + 1 <= MAX_CONSOLE_INPUT_BYTES) {
2192
+ this.paste.lines.push(safe2);
2193
+ this.paste.bytes += Buffer.byteLength(safe2) + 1;
2194
+ this.output.write(safe2 + `
2195
+ `);
2196
+ } else
2197
+ this.output.write(`
2198
+ Paste exceeds 64 KiB; clipboard discarded.
2199
+ `);
2200
+ } else if (this.pending && this.completeCommands || this.background) {
2201
+ this.insert(safe2);
2202
+ this.draftWasPaste = true;
2203
+ }
2204
+ } else if (this.clipboardAllowed)
2205
+ this.output.write(`
2206
+ Paste exceeds 64 KiB; clipboard discarded.
2207
+ `);
2208
+ else if (this.reviewing)
2209
+ this.reviewNotice = "Paste ignored · fresh keys required";
2210
+ this.renderMenu();
2211
+ return;
2212
+ }
2213
+ continue;
2214
+ }
2215
+ if (incompleteTerminalSequence(this.escape))
2216
+ continue;
2217
+ const plain = this.escape;
2218
+ this.escape = "";
2219
+ if (this.clipboard !== undefined) {
2220
+ this.clipboardBytes += Buffer.byteLength(plain);
2221
+ if (this.clipboardAllowed && this.clipboardBytes <= MAX_CONSOLE_INPUT_BYTES)
2222
+ this.clipboard += plain;
2223
+ } else if (this.pending || this.paste || this.background) {
2224
+ this.reviewNotice = undefined;
2225
+ this.hideMenu();
2226
+ if (this.reviewing && plain.length === 1 && plain !== `
2227
+ ` && plain !== "\r") {
2228
+ if ((plain === "n" || plain === "p") && this.reviewHunks.length) {
2229
+ const current = this.reviewOffset;
2230
+ const target = plain === "n" ? this.reviewHunks.find((hunk) => hunk > current) ?? this.reviewHunks[0] : [...this.reviewHunks].reverse().find((hunk) => hunk < current) ?? this.reviewHunks.at(-1);
2231
+ this.reviewOffset = target ?? 0;
2232
+ this.renderMenu();
2233
+ continue;
2234
+ }
2235
+ if (plain === "m" && this.manualRequest) {
2236
+ this.manualRequest();
2237
+ this.reviewNotice = "Approvals are manual. This change still needs a decision.";
2238
+ this.renderMenu();
2239
+ continue;
2240
+ }
2241
+ if (/^[a-z]$/.test(plain)) {
2242
+ const index = this.selection?.items.findIndex((item) => item.key === plain) ?? -1;
2243
+ if (index >= 0) {
2244
+ this.menuSelection = index;
2245
+ this.finishSelection(true);
2246
+ }
2247
+ }
2248
+ this.renderMenu();
2249
+ continue;
2250
+ }
2251
+ if (this.selection && !/[\u0000-\u001f\u007f]/.test(plain) && Buffer.byteLength(this.reader.line) + Buffer.byteLength(plain) > MAX_CONSOLE_INPUT_BYTES)
2252
+ continue;
2253
+ if (this.selection && (plain === `
2254
+ ` || plain === "\r")) {
2255
+ if (this.reviewing && this.menuSelection < 0)
2256
+ this.reviewNotice = "Highlight an action with the arrow keys. Enter does not approve or reject yet.";
2257
+ else if (this.selectionMatches().length)
2258
+ this.finishSelection(true);
2259
+ } else if (plain === "?" && !this.selection && this.pending && this.completeCommands && !this.historySearch && !this.reader.line && !this.shortcutsShown) {
2260
+ this.shortcutsShown = true;
2261
+ this.output.write(`
2262
+ ` + CONSOLE_SHORTCUTS + `
2263
+ `);
2264
+ this.reader.prompt(true);
2265
+ } else {
2266
+ const matches = this.pending && this.completeCommands && !this.historySearch && !this.draftWasPaste && !this.menuDismissed && /^\/[^\s]*$/.test(this.reader.line) ? searchConsoleCommands(this.reader.line, this.mode) : [];
2267
+ const selected = matches[this.menuSelection % Math.max(1, matches.length)]?.[0];
2268
+ if ((plain === `
2269
+ ` || plain === "\r") && selected && selected !== this.reader.line) {
2270
+ Object.assign(this.reader, { line: selected + " ", cursor: selected.length + 1 });
2271
+ this.reader.prompt(true);
2272
+ } else
2273
+ this.keyboard.write(plain);
2274
+ }
2275
+ this.renderMenu();
2276
+ }
2277
+ }
2278
+ };
2279
+ insert(text) {
2280
+ const line = this.reader.line;
2281
+ if (Buffer.byteLength(line) + Buffer.byteLength(text) > MAX_CONSOLE_INPUT_BYTES) {
2282
+ this.output.write(`
2283
+ Input exceeds 64 KiB; insertion discarded.
2284
+ `);
2285
+ } else {
2286
+ const cursor = this.reader.cursor;
2287
+ Object.assign(this.reader, { line: line.slice(0, cursor) + text + line.slice(cursor), cursor: cursor + text.length });
2288
+ }
2289
+ this.reader.prompt(true);
2290
+ }
2291
+ onKeypress = (_text, key) => {
2292
+ if (this.background && !this.pending) {
2293
+ if (key.name === "up" && !this.reader.line && this.queued.length) {
2294
+ key.name = "console-queue";
2295
+ key.meta = true;
2296
+ const draft = this.queued.pop();
2297
+ Object.assign(this.reader, { line: draft, cursor: draft.length });
2298
+ } else if (key.meta && ["return", "enter"].includes(key.name ?? "")) {
2299
+ key.name = "console-newline";
2300
+ this.insert(`
2301
+ `);
2302
+ } else if (_text && !key.ctrl && !key.meta && Buffer.byteLength(this.reader.line) + Buffer.byteLength(_text) > MAX_CONSOLE_INPUT_BYTES) {
2303
+ key.name = "console-input-limit";
2304
+ key.meta = true;
2305
+ }
2306
+ return;
2307
+ }
2308
+ if (!this.pending || !this.completeCommands)
2309
+ return;
2310
+ if (this.selection) {
2311
+ if (this.reviewing && ["pageup", "pagedown"].includes(key.name ?? "")) {
2312
+ this.reviewOffset += key.name === "pageup" ? -this.reviewPage : this.reviewPage;
2313
+ key.name = "console-review";
2314
+ key.meta = true;
2315
+ } else if (["up", "down", "tab"].includes(key.name ?? "")) {
2316
+ const previous = key.name === "up";
2317
+ key.name = "console-select";
2318
+ key.meta = true;
2319
+ const count = Math.max(1, this.selectionMatches().length);
2320
+ if (this.reviewing && this.menuSelection < 0)
2321
+ this.menuSelection = previous ? count - 1 : 0;
2322
+ else
2323
+ this.menuSelection = (this.menuSelection + (previous ? -1 : 1) + count) % count;
2324
+ } else if (key.ctrl && key.name === "r") {
2325
+ key.name = "console-select";
2326
+ key.ctrl = false;
2327
+ key.meta = true;
2328
+ }
2329
+ return;
2330
+ }
2331
+ if (key.ctrl && key.name === "r") {
2332
+ key.name = "console-search";
2333
+ key.ctrl = false;
2334
+ key.meta = true;
2335
+ if (!this.historySearch) {
2336
+ this.historySearch = { draft: this.reader.line, cursor: this.reader.cursor, literal: this.draftWasPaste };
2337
+ this.draftWasPaste = false;
2338
+ this.menuSelection = 0;
2339
+ Object.assign(this.reader, { line: "", cursor: 0 });
2340
+ this.reader.setPrompt("history > ");
2341
+ this.reader.prompt(true);
2342
+ } else
2343
+ this.menuSelection = (this.menuSelection + 1) % Math.max(1, this.historyMatches().length);
2344
+ return;
2345
+ }
2346
+ if (this.historySearch && ["return", "enter", "tab", "up", "down"].includes(key.name ?? "")) {
2347
+ const name = key.name;
2348
+ key.name = "console-search";
2349
+ key.meta = true;
2350
+ if (["return", "enter", "tab"].includes(name))
2351
+ this.finishHistorySearch(true);
2352
+ else {
2353
+ const count = Math.max(1, this.historyMatches().length);
2354
+ this.menuSelection = (this.menuSelection + (name === "up" ? -1 : 1) + count) % count;
2355
+ }
2356
+ return;
2357
+ }
2358
+ const menu = !this.historySearch && !this.draftWasPaste && !this.menuDismissed && /^\/[^\s]*$/.test(this.reader.line) ? searchConsoleCommands(this.reader.line, this.mode) : [];
2359
+ if (menu.length && ["up", "down", "tab", "escape"].includes(key.name ?? "")) {
2360
+ const name = key.name;
2361
+ key.name = "console-menu";
2362
+ key.meta = true;
2363
+ if (name === "escape")
2364
+ this.menuDismissed = true;
2365
+ else if (name === "tab") {
2366
+ const selected = menu[this.menuSelection % menu.length][0];
2367
+ Object.assign(this.reader, { line: selected + " ", cursor: selected.length + 1 });
2368
+ this.reader.prompt(true);
2369
+ } else
2370
+ this.menuSelection = (this.menuSelection + (name === "up" ? -1 : 1) + menu.length) % menu.length;
2371
+ return;
2372
+ }
2373
+ if (_text && !key.ctrl && !key.meta && !/[\u0000-\u001f\u007f]/.test(_text) && Buffer.byteLength(this.reader.line) + Buffer.byteLength(_text) > MAX_CONSOLE_INPUT_BYTES) {
2374
+ key.name = "console-input-limit";
2375
+ key.meta = true;
2376
+ return;
2377
+ }
2378
+ if (key.name === "up" || key.name === "down") {
2379
+ const previous = key.name === "up";
2380
+ const line = this.reader.line;
2381
+ const cursor = this.reader.cursor;
2382
+ const lineStart = line.lastIndexOf(`
2383
+ `, cursor - 1) + 1;
2384
+ const lineEnd = line.indexOf(`
2385
+ `, cursor);
2386
+ if (previous && lineStart > 0 || !previous && lineEnd >= 0) {
2387
+ key.name = "console-cursor";
2388
+ key.meta = true;
2389
+ const column = cursor - lineStart;
2390
+ const targetStart = previous ? line.lastIndexOf(`
2391
+ `, lineStart - 2) + 1 : lineEnd + 1;
2392
+ const targetEnd = line.indexOf(`
2393
+ `, targetStart);
2394
+ const target = Math.min(targetStart + column, targetEnd < 0 ? line.length : targetEnd);
2395
+ Object.assign(this.reader, { line, cursor: target });
2396
+ this.reader.prompt(true);
2397
+ return;
2398
+ }
2399
+ key.name = "console-history";
2400
+ key.meta = true;
2401
+ if (this.historyPosition === -1) {
2402
+ this.historyDraft = this.reader.line;
2403
+ this.historyDraftWasPaste = this.draftWasPaste;
2404
+ }
2405
+ this.historyPosition = previous ? Math.min(this.history.length - 1, this.historyPosition + 1) : Math.max(-1, this.historyPosition - 1);
2406
+ const entry = this.history[this.historyPosition];
2407
+ const historyLine = entry?.text ?? this.historyDraft;
2408
+ this.draftWasPaste = entry?.literal ?? this.historyDraftWasPaste;
2409
+ Object.assign(this.reader, { line: historyLine, cursor: historyLine.length });
2410
+ this.reader.prompt(true);
2411
+ return;
2412
+ }
2413
+ if (!key.meta || key.name !== "return" && key.name !== "enter")
2414
+ return;
2415
+ key.name = "console-newline";
2416
+ this.insert(`
2417
+ `);
2418
+ };
2419
+ rememberPrompt(prompt, literal = false) {
2420
+ if (!prompt.trim() || !literal && prompt.startsWith("/") || Buffer.byteLength(prompt) > MAX_CONSOLE_INPUT_BYTES)
2421
+ return;
2422
+ this.history = [{ text: prompt, literal }, ...this.history.filter((entry) => entry.text !== prompt)].slice(0, 100);
2423
+ while (this.history.reduce((bytes, entry) => bytes + Buffer.byteLength(entry.text), 0) > 256 * 1024)
2424
+ this.history.pop();
2425
+ }
2426
+ startBackground() {
2427
+ if (!this.terminal || this.closed || this.pending || this.hidden || this.paste)
2428
+ return;
2429
+ this.background = true;
2430
+ this.completeCommands = false;
2431
+ this.reader.setPrompt("");
2432
+ Object.assign(this.reader, { line: this.backgroundDraft, cursor: this.backgroundDraft.length });
2433
+ }
2434
+ stopBackground() {
2435
+ if (!this.background)
2436
+ return;
2437
+ this.backgroundDraft = this.reader.line;
2438
+ this.background = false;
2439
+ Object.assign(this.reader, { line: "", cursor: 0 });
2440
+ this.clipboardAllowed = false;
2441
+ }
2442
+ get backgroundStatus() {
2443
+ const draft = this.background ? this.reader.line : this.backgroundDraft;
2444
+ return this.queueNotice || `${this.queued.length} queued${draft ? ` · draft: ${consoleLabel(draft, 80)}` : " · type to draft, Enter queues"}`;
2445
+ }
2446
+ queueSummary() {
2447
+ const lines = this.queued.map((text, index) => `${index + 1}. ${consoleLabel(text, 240)}`);
2448
+ if (this.backgroundDraft)
2449
+ lines.push(`Draft: ${consoleLabel(this.backgroundDraft, 240)}`);
2450
+ return lines.length ? lines.join(`
2451
+ `) + `
2452
+ ` : `No queued tasks or draft.
2453
+ `;
2454
+ }
2455
+ setQueueEnabled(enabled) {
2456
+ this.queueEnabled = enabled;
2457
+ }
2458
+ clearQueue() {
2459
+ this.queued = [];
2460
+ this.backgroundDraft = "";
2461
+ this.queueNotice = "";
2462
+ }
2463
+ clearHistory() {
2464
+ this.clearQueue();
2465
+ this.history = [];
2466
+ this.historyPosition = -1;
2467
+ this.historyDraft = "";
2468
+ }
2469
+ interrupt() {
2470
+ this.finishSecret(false);
2471
+ clearTimeout(this.escapeMenuTimer);
2472
+ this.standaloneMenuEscape = false;
2473
+ this.historySearch = undefined;
2474
+ this.hideMenu();
2475
+ this.pending?.reject(interrupted());
2476
+ this.paste?.reject(interrupted());
2477
+ this.pending = undefined;
2478
+ this.paste = undefined;
2479
+ this.draftWasPaste = false;
2480
+ this.reader.setPrompt("");
2481
+ if (this.terminal)
2482
+ Object.assign(this.reader, { line: "", cursor: 0 });
2483
+ if (this.background) {
2484
+ this.backgroundDraft = "";
2485
+ this.queued = [];
2486
+ this.queueNotice = "Queued messages cleared after interruption";
2487
+ }
2488
+ this.onInterrupt?.();
2489
+ }
2490
+ get isClosed() {
2491
+ return this.closed;
2492
+ }
2493
+ compose(input) {
2494
+ this.stopBackground();
2495
+ if (this.queueEnabled && this.queued.length && !this.closed && !this.pending && !this.hidden && !this.paste) {
2496
+ const queued = this.queued.shift();
2497
+ this.lastSubmissionWasPaste = true;
2498
+ this.output.write(`
2499
+ Queued task > ${sanitizeTerminalText(queued)}
2500
+ `);
2501
+ return Promise.resolve(queued);
2502
+ }
2503
+ if (this.closed)
2504
+ return Promise.reject(interrupted());
2505
+ if (this.pending || this.paste || this.hidden)
2506
+ return Promise.reject(new Error("A console question is already active."));
2507
+ const columns = this.output.columns ?? 80;
2508
+ const color = terminalSupportsColor(this.terminal);
2509
+ const focus = this.mode === "direct";
2510
+ this.focusState = focus ? input : undefined;
2511
+ this.output.write(formatComposer(input, columns, color, focus ? "focus" : "legacy"));
2512
+ if (!this.terminal || process.env.TERM === "dumb") {
2513
+ const footer = formatComposerFooter(columns, color, focus ? input : undefined);
2514
+ this.output.write(footer.slice(1).join(`
2515
+ `) + `
2516
+ `);
2517
+ }
2518
+ const answer = this.question(focus ? "> " : `
2519
+ > `, true, true);
2520
+ if (this.backgroundDraft) {
2521
+ const draft = this.backgroundDraft;
2522
+ this.backgroundDraft = "";
2523
+ this.draftWasPaste = true;
2524
+ this.insert(draft);
2525
+ this.renderMenu();
2526
+ }
2527
+ return answer;
2528
+ }
2529
+ question(prompt, completeCommands = false, focus = false) {
2530
+ this.stopBackground();
2531
+ if (this.closed)
2532
+ return Promise.reject(interrupted());
2533
+ if (this.pending || this.paste || this.hidden)
2534
+ return Promise.reject(new Error("A console question is already active."));
2535
+ clearTimeout(this.escapeMenuTimer);
2536
+ this.escape = "";
2537
+ this.standaloneMenuEscape = false;
2538
+ this.hideMenu();
2539
+ this.focusComposer = focus;
2540
+ this.menuDismissed = false;
2541
+ this.menuQuery = "";
2542
+ this.completeCommands = completeCommands;
2543
+ this.taskPrompt = prompt;
2544
+ this.historySearch = undefined;
2545
+ this.shortcutsShown = false;
2546
+ this.historyPosition = -1;
2547
+ this.historyDraft = "";
2548
+ if (this.terminal) {
2549
+ Object.assign(this.reader, { line: "", cursor: 0 });
2550
+ }
2551
+ return new Promise((resolve, reject) => {
2552
+ this.pending = { resolve, reject };
2553
+ if (this.terminal) {
2554
+ this.reader.setPrompt(prompt);
2555
+ this.reader.prompt();
2556
+ if (focus)
2557
+ this.renderMenu();
2558
+ } else
2559
+ this.output.write(prompt);
2560
+ });
2561
+ }
2562
+ multiline() {
2563
+ if (this.closed)
2564
+ return Promise.reject(interrupted());
2565
+ if (this.pending || this.paste || this.hidden)
2566
+ return Promise.reject(new Error("A console question is already active."));
2567
+ return new Promise((resolve, reject) => {
2568
+ this.paste = { lines: [], bytes: 0, resolve, reject };
2569
+ this.reader.setPrompt("");
2570
+ this.output.write(`Paste text; finish with .end on its own line. Ctrl+C discards the draft.
2571
+ `);
2572
+ });
2573
+ }
2574
+ close() {
2575
+ this.finishSecret(false);
2576
+ clearTimeout(this.escapeMenuTimer);
2577
+ this.hideMenu();
2578
+ (this.terminal ? this.keyboard : this.input).off("keypress", this.onKeypress);
2579
+ this.clearHistory();
2580
+ this.reader.close();
2581
+ }
2582
+ }
2583
+
2584
+ // packages/core/src/cli/console/console-reasoning.ts
2585
+ var descriptions = {
2586
+ default: "Provider default; send no effort override",
2587
+ none: "Disable reasoning where supported",
2588
+ minimal: "Smallest reasoning effort",
2589
+ low: "Lighter reasoning for focused changes",
2590
+ medium: "Balance reasoning depth and latency",
2591
+ high: "Deeper reasoning for complex tasks",
2592
+ xhigh: "Extra reasoning; higher latency and token use",
2593
+ max: "Maximum supported reasoning effort"
2594
+ };
2595
+ var chooseReasoning = async (input, provider, model, current) => {
2596
+ const efforts = modelReasoningEfforts(provider, model);
2597
+ if (current && efforts.includes(current))
2598
+ efforts.sort((a, b) => Number(b === current) - Number(a === current));
2599
+ return input.select(`Zhivex / ${model} / Reasoning
2600
+ ${efforts.length === 1 ? "No configurable levels declared by this adapter; provider default only" : "Higher effort can take longer and use more tokens"}`, efforts.map((value) => ({
2601
+ value,
2602
+ label: `${value}${value === (current ?? "default") ? " (current)" : ""}`,
2603
+ detail: descriptions[value]
2604
+ })));
2605
+ };
2606
+
2607
+ // packages/core/src/cli/console/console-pricing.ts
2608
+ import path from "node:path";
2609
+ var catalogPrice = (model) => {
2610
+ const price = model?.pricing;
2611
+ return price ? `Estimated USD / 1M tokens: input $${price.inputPerMillionTokens}; output $${price.outputPerMillionTokens} · checked ${price.evidence.checkedAt}${price.maxInputTokens ? ` · input tier ≤${price.maxInputTokens}` : ""}` : "Price: unknown";
2612
+ };
2613
+ var handleConsoleBudget = async (command, context) => {
2614
+ if (command !== "/budget" && !command.startsWith("/budget ") && command !== "/pricing")
2615
+ return false;
2616
+ const write = context.write ?? ((text) => {
2617
+ process.stdout.write(text);
2618
+ });
2619
+ write(context.guidedTask ? `The current guided task retains one monetary policy across new turns, corrections, /continue and restarts. Changes here apply to future tasks. Estimates are not invoices or guaranteed financial caps.
2620
+ ` : `Monetary policies are per RUN; every new turn, /continue and review group starts a new budget. Resuming a pending run retains its original policy. Estimates are not invoices or guaranteed financial caps.
2621
+ `);
2622
+ if (command === "/pricing") {
2623
+ const snapshot = await loadModelCatalog();
2624
+ const model = snapshot.catalog.providers.find((item) => item.id === context.provider)?.models.find((item) => item.id === context.model);
2625
+ write(`${sanitizeTerminalText(context.provider + "/" + context.model)} · ${catalogPrice(model)}
2626
+ `);
2627
+ if (model?.pricing)
2628
+ write(sanitizeTerminalText(`Scope: ${model.pricing.scope}
2629
+ Source: ${model.pricing.evidence.sourceUrl}
2630
+ `));
2631
+ write(`Catalog prices are advisory. Monetary execution limits use an explicit operator pricing file with validity dates for every active route.
2632
+ `);
2633
+ return true;
2634
+ }
2635
+ const policyScope = context.guidedTask ? "future task" : "new run";
2636
+ write(`${context.guidedTask ? "Future task" : "Next run"} estimated USD limit: ${context.options.usageLimitUsd ?? "off"}; pricing file: ${sanitizeTerminalText(context.options.pricingFile ?? "none")}
2637
+ `);
2638
+ if (await context.hasActiveTurn()) {
2639
+ write(`Finish or deny pending work before changing the next-run policy.
2640
+ `);
2641
+ return true;
2642
+ }
2643
+ if (context.options.maxCostUsd !== undefined || process.env.ZHIVEX_HARNESS_MAX_COST_USD !== undefined) {
2644
+ write(`A legacy measured-cost policy is configured. Start a console without it before selecting the transport-ledger policy.
2645
+ `);
2646
+ return true;
2647
+ }
2648
+ const argument = command.slice("/budget".length).trim();
2649
+ const selected = argument || await context.input.select(context.guidedTask ? "Budget for future tasks" : "Budget for each next run", [
2650
+ { value: "", label: "Keep current policy" },
2651
+ { value: "set", label: "Set estimated USD limit and pricing file" },
2652
+ { value: "off", label: "Disable monetary limit", detail: "Other step, tool, time and token limits still apply" }
2653
+ ]);
2654
+ if (!selected)
2655
+ return true;
2656
+ if (selected === "off") {
2657
+ const next = { ...context.options };
2658
+ delete next.usageLimitUsd;
2659
+ await context.replaceOptions(next);
2660
+ write(context.guidedTask ? `Monetary limit disabled for future tasks; current task policy retained.
2661
+ ` : `Monetary limit disabled for next runs.
2662
+ `);
2663
+ return true;
2664
+ }
2665
+ const amount = selected === "set" ? (await context.input.question(`Estimated USD limit per ${policyScope}: `)).trim() : selected;
2666
+ if (!/^\d+(?:\.\d+)?$/.test(amount) || !Number.isFinite(Number(amount)) || Number(amount) <= 0) {
2667
+ write(`Use a positive finite USD amount, or /budget off.
2668
+ `);
2669
+ return true;
2670
+ }
2671
+ const file = (await context.input.question(`Pricing JSON file${context.options.pricingFile ? ` (Enter keeps ${sanitizeTerminalText(context.options.pricingFile)})` : ""}: `)).trim() || context.options.pricingFile;
2672
+ if (!file) {
2673
+ write(`Pricing file required; policy unchanged.
2674
+ `);
2675
+ return true;
2676
+ }
2677
+ const pricing = usagePricingSchema.parse(JSON.parse((await readRegularFileNoFollow(path.resolve(file), { maxBytes: 128 * 1024, label: "Usage pricing" })).contents.toString("utf8")));
2678
+ const price = pricing.prices.find((item) => item.provider === context.provider && item.model === context.model);
2679
+ if (!price || Date.parse(price.asOf) > Date.now() || Date.parse(price.expiresAt) <= Date.now()) {
2680
+ write(`Current model price is missing or stale; policy unchanged.
2681
+ `);
2682
+ return true;
2683
+ }
2684
+ write(sanitizeTerminalText(`Operator estimate: input $${price.inputUsdPerMillion}, output $${price.outputUsdPerMillion} / 1M tokens.
2685
+ Source: ${price.source}; valid ${price.asOf} through ${price.expiresAt}.
2686
+ `));
2687
+ write(`The engine reserves estimated requests using their explicit output cap, with a 2048-token fallback when none is supplied, and blocks missing/stale prices, uncertain usage or insufficient estimated budget. Other routes also require valid prices.
2688
+ `);
2689
+ if ((await context.input.question(`Type budget to apply $${amount} per ${policyScope}: `)).trim() !== "budget")
2690
+ return true;
2691
+ await context.replaceOptions({ ...context.options, pricingFile: path.resolve(file), usageLimitUsd: Number(amount) });
2692
+ write(`Estimated USD limit set: $${amount} per ${policyScope}.
2693
+ `);
2694
+ return true;
2695
+ };
2696
+
2697
+ // packages/core/src/cli/console/console-navigation.ts
2698
+ var consoleModelChoices = (provider, defaultModel, current, catalog = bundledModelCatalog) => {
2699
+ const models = catalogModels(catalog, provider, current).sort((a, b) => Number(b.group === "primary") - Number(a.group === "primary"));
2700
+ return [...new Set([...models.map((m) => m.id), defaultModel])].map((model) => {
2701
+ const entry = models.find((m) => m.id === model);
2702
+ return {
2703
+ value: model,
2704
+ label: entry?.name ?? model,
2705
+ group: entry?.group ?? "other",
2706
+ detail: [
2707
+ entry?.name !== model ? model : "",
2708
+ model === current ? "Current" : "",
2709
+ model === defaultModel ? "Recommended default" : "",
2710
+ entry ? modelDescription(entry) : "Unverified",
2711
+ catalogPrice(entry)
2712
+ ].filter(Boolean).join(" · ")
2713
+ };
2714
+ });
2715
+ };
2716
+ var navigateConsole = async (input, options) => {
2717
+ const snapshot = options.service ? undefined : await loadModelCatalog();
2718
+ let page = options.entry;
2719
+ let provider = options.current.provider;
2720
+ let modelParent = options.entry === "model" ? undefined : "provider";
2721
+ for (;; ) {
2722
+ if (page === "menu") {
2723
+ const action = await input.select("Zhivex / Menu", [
2724
+ ...!options.service ? [
2725
+ { value: "provider", label: "Providers", detail: "Browse providers and their models" },
2726
+ { value: "model", label: "Models", detail: `Browse ${options.current.provider} models` },
2727
+ { value: "/limits", label: "Execution limits", detail: "Steps available per turn" },
2728
+ { value: "/budget", label: "Run budget", detail: "Estimated USD limit and operator pricing" },
2729
+ { value: "/pricing", label: "Model pricing", detail: "Source and scope of advisory prices" },
2730
+ { value: "/checkpoint", label: "Checkpoints", detail: "Capture, review and explicitly restore selected text files" },
2731
+ { value: "/approvals", label: "Approval mode", detail: "Ask, auto, or restricted for this session" },
2732
+ { value: "/connection", label: "Test connection", detail: "Optional small request to the selected model" },
2733
+ { value: "/credentials", label: "Credentials", detail: "System keychain or temporary API keys" }
2734
+ ] : [],
2735
+ { value: "sessions", label: "Conversations", detail: "Find and resume a saved conversation" },
2736
+ { value: "/status", label: "Status", detail: "Current session and runtime" },
2737
+ { value: "/activity", label: "Activity history", detail: "Recent tools, approvals and applied files" },
2738
+ { value: "/queue", label: "Queued tasks", detail: "Inspect tasks and unsent draft" },
2739
+ { value: "/pending", label: "Pending approvals", detail: "Inspect pending actions" },
2740
+ ...!options.service ? [
2741
+ { value: "/context", label: "Project context", detail: "Rules, skills and attachments" },
2742
+ { value: "/usage", label: "Usage", detail: "Transport usage and estimates" }
2743
+ ] : [],
2744
+ { value: "/help", label: "Help", detail: "All commands and keyboard shortcuts" }
2745
+ ]);
2746
+ if (!action)
2747
+ return;
2748
+ if (action.startsWith("/"))
2749
+ return { command: action };
2750
+ page = action;
2751
+ if (page === "model") {
2752
+ provider = options.current.provider;
2753
+ modelParent = "menu";
2754
+ }
2755
+ } else if (page === "provider") {
2756
+ const selected = await input.select("Zhivex / Providers", options.providers.map((p) => ({
2757
+ value: p.id,
2758
+ label: p.name,
2759
+ detail: `${p.id} · ${p.configured ? "credential present" : "credential missing"}${p.support === "provisional" ? " · provisional" : ""}`
2760
+ })));
2761
+ if (!selected) {
2762
+ if (options.entry === "provider")
2763
+ return;
2764
+ page = "menu";
2765
+ continue;
2766
+ }
2767
+ provider = selected;
2768
+ modelParent = "provider";
2769
+ page = "model";
2770
+ } else if (page === "sessions") {
2771
+ const selected = await input.select("Zhivex / Conversations", await options.sessions());
2772
+ if (selected)
2773
+ return { command: `/resume ${selected}` };
2774
+ page = "menu";
2775
+ } else {
2776
+ const descriptor = options.providers.find((p) => p.id === provider);
2777
+ if (!descriptor)
2778
+ return;
2779
+ const catalog = snapshot?.catalog ?? bundledModelCatalog;
2780
+ const defaultModel = catalog.providers.find((p) => p.id === provider)?.defaultModel ?? descriptor.defaultModel;
2781
+ const choices = consoleModelChoices(provider, defaultModel, options.current.provider === provider ? options.current.model : undefined, catalog);
2782
+ const primary = choices.filter((item) => item.group === "primary" || provider === options.current.provider && item.value === options.current.model);
2783
+ const others = choices.filter((item) => !primary.includes(item));
2784
+ let selected = await input.select(`Zhivex / Providers / ${descriptor.name} / Models
2785
+ Featured models · ${snapshot?.source ?? "bundled"}${snapshot?.stale ? " (offline fallback)" : ""} · account access is not checked`, [
2786
+ ...primary.map((item) => ({ ...item, value: { kind: "model", id: item.value } })),
2787
+ ...others.length ? [{ value: { kind: "other", id: "" }, label: "Other models…", detail: "Previous generations, snapshots and additional models" }] : [],
2788
+ { value: { kind: "custom", id: "" }, label: "Custom model ID…", detail: "Enter a model absent from the local catalog" }
2789
+ ]);
2790
+ if (!selected) {
2791
+ if (!modelParent)
2792
+ return;
2793
+ page = modelParent;
2794
+ continue;
2795
+ }
2796
+ if (selected.kind === "other") {
2797
+ selected = await input.select("Zhivex / Other models · account access is not checked", others.map((item) => ({ ...item, value: { kind: "model", id: item.value } })));
2798
+ if (!selected)
2799
+ continue;
2800
+ }
2801
+ if (selected.kind === "custom") {
2802
+ let prompt = "Model ID (Enter to go back): ";
2803
+ for (;; ) {
2804
+ const model = (await input.question(prompt)).trim();
2805
+ if (!model)
2806
+ break;
2807
+ if (model.length <= 512 && !/[\u0000-\u001f\u007f]/.test(model)) {
2808
+ const reasoningEffort2 = await chooseReasoning(input, provider, model);
2809
+ if (reasoningEffort2)
2810
+ return { provider, model, reasoningEffort: reasoningEffort2 };
2811
+ break;
2812
+ }
2813
+ prompt = "Use 1–512 printable characters. Model ID (Enter to go back): ";
2814
+ }
2815
+ continue;
2816
+ }
2817
+ const reasoningEffort = await chooseReasoning(input, provider, selected.id, provider === options.current.provider && selected.id === options.current.model ? options.current.reasoningEffort : undefined);
2818
+ if (!reasoningEffort)
2819
+ continue;
2820
+ return { provider, model: selected.id, reasoningEffort };
2821
+ }
2822
+ }
2823
+ };
2824
+
2825
+ // packages/core/src/cli/routing.ts
2826
+ var resolvedRouting = (options) => {
2827
+ return resolveHarnessModelRoutes(options.routes);
2828
+ };
2829
+ var assertRoutePricingIsSafe = (routes, costBudget) => {
2830
+ if (routes.size > 0 && costBudget !== undefined) {
2831
+ throw new CliUsageError("Cost budgets cannot be combined with model routes until pricing is configured per role.");
2832
+ }
2833
+ };
2834
+ var withTemporaryHarnessProfiles = async (profiles, configure, operation) => {
2835
+ await configure(profiles);
2836
+ try {
2837
+ return await operation();
2838
+ } finally {
2839
+ await configure([]);
2840
+ }
2841
+ };
2842
+
2843
+ // packages/core/src/cli/qwen-connection.ts
2844
+ var regions = {
2845
+ singapore: ["Singapore", "ap-southeast-1", "dashscope-intl.aliyuncs.com"],
2846
+ beijing: ["Beijing", "cn-beijing", "dashscope.aliyuncs.com"],
2847
+ "hong-kong": ["Hong Kong", "cn-hongkong", "cn-hongkong.dashscope.aliyuncs.com"],
2848
+ tokyo: ["Tokyo", "ap-northeast-1", ""],
2849
+ frankfurt: ["Frankfurt", "eu-central-1", ""],
2850
+ virginia: ["Virginia", "us-east-1", ""]
2851
+ };
2852
+ function qwenEndpoint(connection) {
2853
+ if (connection.service === "token-plan")
2854
+ return "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1";
2855
+ if (connection.service !== "api" || !Object.hasOwn(regions, connection.region))
2856
+ throw new Error("Invalid Qwen connection.");
2857
+ const [, region, legacy] = regions[connection.region];
2858
+ if (connection.workspace !== undefined && !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(connection.workspace))
2859
+ throw new Error("Invalid Qwen workspace ID.");
2860
+ const host = connection.workspace ? `${connection.workspace}.${region}.maas.aliyuncs.com` : legacy;
2861
+ if (!host)
2862
+ throw new Error("This Qwen region requires a workspace ID.");
2863
+ return `https://${host}/compatible-mode/v1`;
2864
+ }
2865
+ function decodeQwenCredential(value) {
2866
+ if (!value.startsWith("{"))
2867
+ return { key: value, connection: { service: "api", region: "singapore" } };
2868
+ const parsed = JSON.parse(value);
2869
+ if (parsed.version !== 1 || typeof parsed.key !== "string" || !parsed.connection)
2870
+ throw new Error("Invalid Qwen credential record.");
2871
+ qwenEndpoint(parsed.connection);
2872
+ return { key: parsed.key, connection: parsed.connection };
2873
+ }
2874
+ async function selectQwenConnection(input) {
2875
+ const service = await input.select("Qwen / Service", [
2876
+ { value: "api", label: "Standard API / Alibaba Cloud Model Studio", detail: "Use the region where your API key was created" },
2877
+ { value: "token-plan", label: "QwenCloud Token Plan", detail: "Separate subscription endpoint and credential" }
2878
+ ]);
2879
+ if (!service)
2880
+ return;
2881
+ if (service === "token-plan")
2882
+ return { service };
2883
+ const region = await input.select("Qwen / API region", Object.entries(regions).map(([value, [label]]) => ({ value, label })));
2884
+ if (!region)
2885
+ return;
2886
+ let workspace;
2887
+ const dedicated = !regions[region][2] || await input.select("Qwen / Endpoint", [
2888
+ { value: false, label: "DashScope endpoint", detail: "Existing regional API endpoint" },
2889
+ { value: true, label: "Workspace endpoint", detail: "Enter your workspace ID" },
2890
+ { value: "cancel", label: "Back" }
2891
+ ]);
2892
+ if (dedicated === undefined || dedicated === "cancel")
2893
+ return;
2894
+ if (dedicated) {
2895
+ if (!input.question)
2896
+ throw new Error("Workspace setup requires interactive input.");
2897
+ workspace = (await input.question("Workspace ID (not the API key): ")).trim();
2898
+ if (!workspace)
2899
+ return;
2900
+ }
2901
+ const connection = { service: "api", region, ...workspace ? { workspace } : {} };
2902
+ qwenEndpoint(connection);
2903
+ return connection;
2904
+ }
2905
+
2906
+ // packages/core/src/cli/cli-credentials.ts
2907
+ class CredentialSetupError extends Error {
2908
+ }
2909
+ var credentialService = "ai.zhivex.harness.cli";
2910
+ var validCredential = (value) => /^[\x21-\x7e]{1,8192}$/.test(value);
2911
+ var nativeCredentialEntry = async (provider) => {
2912
+ if (!PROVIDERS.includes(provider))
2913
+ throw new Error("Unsupported credential provider.");
2914
+ if (!["darwin", "linux"].includes(process.platform) || process.env.ZHIVEX_HARNESS_CREDENTIAL_STORE === "disabled") {
2915
+ throw new Error("Secure credential storage is unavailable.");
2916
+ }
2917
+ const { AsyncEntry } = await import("@napi-rs/keyring");
2918
+ const entry = new AsyncEntry(credentialService, provider, { linux: { store: "secret-service" } });
2919
+ return {
2920
+ getPassword: () => entry.getPassword(AbortSignal.timeout(30000)),
2921
+ setPassword: (value) => entry.setPassword(value, AbortSignal.timeout(30000)),
2922
+ deleteCredential: () => entry.deleteCredential(AbortSignal.timeout(30000))
2923
+ };
2924
+ };
2925
+
2926
+ class CliCredentials {
2927
+ entry;
2928
+ environment;
2929
+ write;
2930
+ temporary = new Map;
2931
+ revision = 0;
2932
+ qwenManaged = false;
2933
+ qwenOverrideAccepted = false;
2934
+ constructor(entry = nativeCredentialEntry, environment = process.env, write = (text) => {
2935
+ process.stderr.write(text);
2936
+ }) {
2937
+ this.entry = entry;
2938
+ this.environment = environment;
2939
+ this.write = write;
2940
+ }
2941
+ environmentKey(provider) {
2942
+ return providerDescriptor(provider).credentialNames.map((name) => this.environment[name]?.trim()).find(Boolean);
2943
+ }
2944
+ validate(value) {
2945
+ if (!validCredential(value))
2946
+ throw new Error("Invalid API key: use 1–8192 printable characters without whitespace.");
2947
+ return value;
2948
+ }
2949
+ async saved(provider) {
2950
+ try {
2951
+ const value = await (await this.entry(provider)).getPassword();
2952
+ if (value == null)
2953
+ return;
2954
+ this.validate(provider === "qwen" ? decodeQwenCredential(value).key : value);
2955
+ return value;
2956
+ } catch {
2957
+ throw new Error("Secure storage is unavailable or locked. Unlock it, use a temporary key, or configure the environment.");
2958
+ }
2959
+ }
2960
+ destinations = new Map;
2961
+ destination(provider) {
2962
+ return this.destinations.get(provider) ?? "environment-defined or provider default";
2963
+ }
2964
+ sources = new Map;
2965
+ source(provider) {
2966
+ return this.sources.get(provider) ?? "missing";
2967
+ }
2968
+ endpointOverride(provider) {
2969
+ const variables = {
2970
+ anthropic: ["ANTHROPIC_BASE_URL"],
2971
+ openai: ["OPENAI_BASE_URL"],
2972
+ meta: ["META_BASE_URL"],
2973
+ gemini: ["GEMINI_BASE_URL"],
2974
+ qwen: ["QWEN_BASE_URL", "QWEN_REGION", "QWEN_WORKSPACE_ID"]
2975
+ };
2976
+ return (variables[provider] ?? []).some((name) => this.environment[name]?.trim());
2977
+ }
2978
+ async inspect(provider) {
2979
+ if (provider === "vertex")
2980
+ return { source: "environment", configured: vertexConfigured(this.environment) };
2981
+ if (provider === "bedrock")
2982
+ return this.inspectBedrock();
2983
+ if (provider === "azure-openai")
2984
+ return this.inspectAzure();
2985
+ if (this.environmentKey(provider) && !(provider === "qwen" && this.qwenManaged))
2986
+ return { source: "environment", configured: true };
2987
+ if (this.endpointOverride(provider) && !(provider === "qwen" && this.qwenOverrideAccepted))
2988
+ return { source: "blocked", configured: false };
2989
+ if (this.temporary.has(provider))
2990
+ return { source: "temporary", configured: true };
2991
+ try {
2992
+ return await this.saved(provider) ? { source: "keychain", configured: true } : { source: "missing", configured: false };
2993
+ } catch {
2994
+ return { source: "unavailable", configured: false };
2995
+ }
2996
+ }
2997
+ async inspectBedrock() {
2998
+ let runtime;
2999
+ try {
3000
+ runtime = bedrockRuntime(this.environment);
3001
+ } catch {
3002
+ return { source: "environment", configured: false };
3003
+ }
3004
+ if (runtime !== "openai")
3005
+ return { source: "environment", configured: bedrockConfigured(this.environment) };
3006
+ try {
3007
+ bedrockOpenAIBaseURL(this.environment);
3008
+ } catch {
3009
+ return { source: "missing", configured: false };
3010
+ }
3011
+ return this.inspectSecret("bedrock");
3012
+ }
3013
+ async inspectAzure() {
3014
+ try {
3015
+ azureOpenAIEndpoint(this.environment);
3016
+ azureOpenAIApiVersion(this.environment);
3017
+ azureOpenAIDeployments(this.environment);
3018
+ } catch {
3019
+ return { source: "environment", configured: false };
3020
+ }
3021
+ return this.inspectSecret("azure-openai");
3022
+ }
3023
+ async inspectSecret(provider) {
3024
+ if (this.environmentKey(provider))
3025
+ return { source: "environment", configured: true };
3026
+ if (this.temporary.has(provider))
3027
+ return { source: "temporary", configured: true };
3028
+ try {
3029
+ return await this.saved(provider) ? { source: "keychain", configured: true } : { source: "missing", configured: false };
3030
+ } catch {
3031
+ return { source: "unavailable", configured: false };
3032
+ }
3033
+ }
3034
+ async configure(provider, input) {
3035
+ if (provider === "vertex") {
3036
+ this.write(`Vertex uses Google Application Default Credentials. Configure ADC, GOOGLE_CLOUD_PROJECT and VERTEX_LOCATION in the launching environment; no API key is stored here.
3037
+ `);
3038
+ return vertexConfigured(this.environment);
3039
+ }
3040
+ if (provider === "bedrock") {
3041
+ let runtime;
3042
+ try {
3043
+ runtime = bedrockRuntime(this.environment);
3044
+ } catch {
3045
+ this.write(`BEDROCK_RUNTIME must be converse or openai.
3046
+ `);
3047
+ return false;
3048
+ }
3049
+ if (runtime !== "openai") {
3050
+ this.write(`Amazon Bedrock Converse uses the AWS credential chain. Set AWS_REGION or AWS_DEFAULT_REGION in the launching environment. Optional AWS_PROFILE selects a profile. No API key is stored here, and credentials are not checked.
3051
+ `);
3052
+ return bedrockConfigured(this.environment);
3053
+ }
3054
+ }
3055
+ if (provider === "azure-openai") {
3056
+ try {
3057
+ azureOpenAIEndpoint(this.environment);
3058
+ azureOpenAIApiVersion(this.environment);
3059
+ azureOpenAIDeployments(this.environment);
3060
+ } catch (error) {
3061
+ this.write(`${error instanceof Error ? error.message : "Azure OpenAI route is not configured."}
3062
+ `);
3063
+ return false;
3064
+ }
3065
+ }
3066
+ for (;; ) {
3067
+ try {
3068
+ return await this.configureOnce(provider, input);
3069
+ } catch (error) {
3070
+ if (!(error instanceof CredentialSetupError) && !(error instanceof Error && error.name === "AbortError"))
3071
+ throw error;
3072
+ this.write(error instanceof CredentialSetupError ? `${error.message}
3073
+ ` : `Key entry cancelled.
3074
+ `);
3075
+ const action = await input.select("Credentials / Recovery", [
3076
+ { value: "temporary", label: "Use a temporary key", detail: "Enter a key for this CLI session only" },
3077
+ { value: "retry", label: "Retry credential setup" },
3078
+ { value: "cancel", label: "Cancel setup" }
3079
+ ]);
3080
+ if (!action || action === "cancel")
3081
+ return false;
3082
+ if (action === "temporary") {
3083
+ try {
3084
+ return await this.configureOnce(provider, input, "temporary");
3085
+ } catch (retryError) {
3086
+ if (!(retryError instanceof CredentialSetupError) && !(retryError instanceof Error && retryError.name === "AbortError"))
3087
+ throw retryError;
3088
+ this.write(`Temporary key entry was not completed. Try again or go back.
3089
+ `);
3090
+ }
3091
+ }
3092
+ }
3093
+ }
3094
+ }
3095
+ async configureOnce(provider, input, mode) {
3096
+ if (provider !== "qwen" && this.environmentKey(provider)) {
3097
+ this.write(`An environment key takes precedence. Remove it from the launching shell to use managed credentials.
3098
+ `);
3099
+ }
3100
+ const action = mode ?? await input.select(`Credentials / ${provider}`, [
3101
+ { value: "save", label: "Save or replace in system keychain" },
3102
+ { value: "temporary", label: "Temporary key for this CLI session" },
3103
+ { value: "delete", label: "Remove saved and temporary key" },
3104
+ { value: "cancel", label: "Back" }
3105
+ ]);
3106
+ if (!action || action === "cancel")
3107
+ return false;
3108
+ if (action === "delete") {
3109
+ const confirm = await input.select(`Remove managed key for ${provider}?`, [
3110
+ { value: false, label: "Keep key" },
3111
+ { value: true, label: "Remove key" }
3112
+ ]);
3113
+ if (!confirm)
3114
+ return false;
3115
+ try {
3116
+ await (await this.entry(provider)).deleteCredential();
3117
+ this.write(`Saved key removed (or already absent).
3118
+ `);
3119
+ } catch {
3120
+ this.write(`Saved key could not be removed: secure storage is unavailable or locked.
3121
+ `);
3122
+ }
3123
+ this.temporary.delete(provider);
3124
+ if (provider === "qwen") {
3125
+ this.qwenManaged = false;
3126
+ this.qwenOverrideAccepted = false;
3127
+ }
3128
+ this.revision++;
3129
+ this.write(`Temporary key cleared. Environment credentials are unchanged.
3130
+ `);
3131
+ return true;
3132
+ }
3133
+ const connection = provider === "qwen" ? await selectQwenConnection(input) : undefined;
3134
+ if (provider === "qwen" && !connection)
3135
+ return false;
3136
+ if (connection)
3137
+ this.write(`Selected Qwen destination: ${qwenEndpoint(connection)}
3138
+ This connection will replace Qwen environment settings for this CLI session.
3139
+ `);
3140
+ let target;
3141
+ if (action === "save") {
3142
+ try {
3143
+ target = await this.entry(provider);
3144
+ } catch {
3145
+ throw new CredentialSetupError("Secure storage is unavailable. Unlock it and retry, or choose temporary use.");
3146
+ }
3147
+ }
3148
+ let secret = await input.secret("API key (hidden; Enter submits, Ctrl+C cancels): ");
3149
+ if (!secret)
3150
+ return false;
3151
+ try {
3152
+ secret = this.validate(secret);
3153
+ } catch {
3154
+ throw new CredentialSetupError("Invalid API key. Enter printable characters without whitespace.");
3155
+ }
3156
+ if (connection)
3157
+ secret = JSON.stringify({ version: 1, key: secret, connection });
3158
+ if (action === "save") {
3159
+ try {
3160
+ await target.setPassword(secret);
3161
+ } catch {
3162
+ throw new CredentialSetupError("API key was not saved: secure storage is unavailable or locked. No plaintext fallback was used.");
3163
+ }
3164
+ this.temporary.delete(provider);
3165
+ this.write(`API key saved in the system keychain.
3166
+ `);
3167
+ } else {
3168
+ this.temporary.set(provider, secret);
3169
+ this.write(`API key is available only for this CLI session.
3170
+ `);
3171
+ }
3172
+ if (connection) {
3173
+ this.qwenManaged = true;
3174
+ this.qwenOverrideAccepted = true;
3175
+ }
3176
+ this.revision++;
3177
+ return true;
3178
+ }
3179
+ async managedSecret(provider, input) {
3180
+ let key = this.temporary.get(provider);
3181
+ if (!key) {
3182
+ try {
3183
+ key = await this.saved(provider);
3184
+ } catch {
3185
+ this.write(`Secure storage is unavailable or locked; temporary use remains available.
3186
+ `);
3187
+ }
3188
+ }
3189
+ if (!key) {
3190
+ this.write(`No API key available for ${provider}.
3191
+ `);
3192
+ if (!await this.configure(provider, input))
3193
+ throw new CredentialSetupError("Credential setup cancelled. No provider request was sent.");
3194
+ key = this.temporary.get(provider) ?? await this.saved(provider);
3195
+ }
3196
+ if (!key)
3197
+ throw new CredentialSetupError("No API key available. No provider request was sent.");
3198
+ return key;
3199
+ }
3200
+ async bedrockProviderEnvironment(input) {
3201
+ let runtime;
3202
+ try {
3203
+ runtime = bedrockRuntime(this.environment);
3204
+ } catch (error) {
3205
+ throw new CredentialSetupError(error instanceof Error ? error.message : "BEDROCK_RUNTIME must be converse or openai.");
3206
+ }
3207
+ if (runtime !== "openai") {
3208
+ try {
3209
+ bedrockRegion(this.environment);
3210
+ } catch (error) {
3211
+ throw new CredentialSetupError(error instanceof Error ? error.message : "Bedrock requires a region.");
3212
+ }
3213
+ this.sources.set("bedrock", "environment");
3214
+ return { ...this.environment };
3215
+ }
3216
+ try {
3217
+ bedrockOpenAIBaseURL(this.environment);
3218
+ } catch (error) {
3219
+ throw new CredentialSetupError(error instanceof Error ? error.message : "BEDROCK_OPENAI_BASE_URL is required.");
3220
+ }
3221
+ if (this.environmentKey("bedrock")) {
3222
+ this.sources.set("bedrock", "environment");
3223
+ return { ...this.environment };
3224
+ }
3225
+ const key = await this.managedSecret("bedrock", input);
3226
+ this.sources.set("bedrock", this.temporary.has("bedrock") ? "temporary" : "keychain");
3227
+ return { ...this.environment, BEDROCK_API_KEY: key };
3228
+ }
3229
+ async azureProviderEnvironment(input) {
3230
+ try {
3231
+ azureOpenAIEndpoint(this.environment);
3232
+ azureOpenAIApiVersion(this.environment);
3233
+ azureOpenAIDeployments(this.environment);
3234
+ } catch (error) {
3235
+ throw new CredentialSetupError(error instanceof Error ? error.message : "Azure OpenAI route is not configured.");
3236
+ }
3237
+ if (this.environmentKey("azure-openai")) {
3238
+ this.sources.set("azure-openai", "environment");
3239
+ return { ...this.environment };
3240
+ }
3241
+ const key = await this.managedSecret("azure-openai", input);
3242
+ this.sources.set("azure-openai", this.temporary.has("azure-openai") ? "temporary" : "keychain");
3243
+ return { ...this.environment, AZURE_OPENAI_API_KEY: key };
3244
+ }
3245
+ async providerEnvironment(provider, input) {
3246
+ if (provider === "vertex") {
3247
+ vertexRoute(this.environment);
3248
+ this.sources.set(provider, "environment");
3249
+ return { ...this.environment };
3250
+ }
3251
+ if (provider === "bedrock")
3252
+ return this.bedrockProviderEnvironment(input);
3253
+ if (provider === "azure-openai")
3254
+ return this.azureProviderEnvironment(input);
3255
+ if (this.environmentKey(provider) && !(provider === "qwen" && this.qwenManaged)) {
3256
+ this.destinations.delete(provider);
3257
+ this.sources.set(provider, "environment");
3258
+ return { ...this.environment };
3259
+ }
3260
+ if (provider !== "qwen" && this.endpointOverride(provider)) {
3261
+ throw new CredentialSetupError("Managed keys require the provider's default endpoint. Remove endpoint overrides or supply an explicit environment key.");
3262
+ }
3263
+ let key = this.temporary.get(provider);
3264
+ if (!key) {
3265
+ try {
3266
+ key = await this.saved(provider);
3267
+ } catch {
3268
+ this.write(`Secure storage is unavailable or locked; temporary use remains available.
3269
+ `);
3270
+ }
3271
+ }
3272
+ if (!key) {
3273
+ this.write(`No API key available for ${provider}.
3274
+ `);
3275
+ if (!await this.configure(provider, input))
3276
+ throw new CredentialSetupError("Credential setup cancelled. No provider request was sent.");
3277
+ key = this.temporary.get(provider) ?? await this.saved(provider);
3278
+ }
3279
+ if (!key)
3280
+ throw new CredentialSetupError("No API key available. No provider request was sent.");
3281
+ if (provider === "qwen") {
3282
+ const record = decodeQwenCredential(key);
3283
+ const endpoint = qwenEndpoint(record.connection);
3284
+ if (this.endpointOverride(provider) && !this.qwenOverrideAccepted) {
3285
+ const useManaged = await input.select("Qwen / Environment conflicts with saved connection", [
3286
+ { value: false, label: "Cancel; keep environment settings" },
3287
+ { value: true, label: "Use saved connection for this session", detail: endpoint }
3288
+ ]);
3289
+ if (!useManaged)
3290
+ throw new CredentialSetupError("Qwen connection selection cancelled. No provider request was sent.");
3291
+ this.qwenOverrideAccepted = true;
3292
+ }
3293
+ const env = { ...this.environment };
3294
+ for (const name2 of ["QWEN_BASE_URL", "QWEN_REGION", "QWEN_WORKSPACE_ID", "QWEN_API_KEY", "DASHSCOPE_API_KEY"])
3295
+ delete env[name2];
3296
+ this.destinations.set(provider, endpoint);
3297
+ env.QWEN_BASE_URL = endpoint;
3298
+ env.DASHSCOPE_API_KEY = record.key;
3299
+ this.sources.set(provider, this.temporary.has(provider) ? "temporary" : "keychain");
3300
+ return env;
3301
+ }
3302
+ this.sources.set(provider, this.temporary.has(provider) ? "temporary" : "keychain");
3303
+ const name = providerDescriptor(provider).credentialNames[0];
3304
+ return { ...this.environment, [name]: key };
3305
+ }
3306
+ clear() {
3307
+ this.destinations.clear();
3308
+ this.temporary.clear();
3309
+ this.sources.clear();
3310
+ this.qwenManaged = false;
3311
+ this.qwenOverrideAccepted = false;
3312
+ }
3313
+ }
3314
+ async function credentialModel(config, env, modelFactory) {
3315
+ const { createProviderModel: createProviderModel2 } = await import("./config-v7s8hp37.js");
3316
+ const { wrapLanguageModel } = await import("@zhivex-ai/core");
3317
+ const secrets = providerDescriptor(config.provider).credentialNames.map((name) => env[name]).filter((value) => !!value);
3318
+ const safeError = (error) => {
3319
+ let message = error instanceof Error ? error.message : "Provider request failed.";
3320
+ for (const secret of secrets)
3321
+ message = message.split(secret).join("[REDACTED]");
3322
+ const safe2 = new Error(message);
3323
+ if (error instanceof Error && error.name === "AbortError")
3324
+ safe2.name = "AbortError";
3325
+ return safe2;
3326
+ };
3327
+ const model = (modelFactory ?? createProviderModel2)(config, env);
3328
+ return wrapLanguageModel(model, [{
3329
+ name: "cli-credential-errors",
3330
+ wrapGenerate: async (_context, next) => {
3331
+ try {
3332
+ return await next();
3333
+ } catch (error) {
3334
+ throw safeError(error);
3335
+ }
3336
+ },
3337
+ wrapStream: async (_context, next) => {
3338
+ let events;
3339
+ try {
3340
+ events = await next();
3341
+ } catch (error) {
3342
+ throw safeError(error);
3343
+ }
3344
+ return async function* () {
3345
+ try {
3346
+ for await (const event of events) {
3347
+ if (event.type === "error")
3348
+ throw safeError(event.error);
3349
+ yield event;
3350
+ }
3351
+ } catch (error) {
3352
+ throw safeError(error);
3353
+ }
3354
+ }();
3355
+ }
3356
+ }]);
3357
+ }
3358
+
3359
+ // packages/core/src/cli/configured-harness.ts
3360
+ import path2 from "node:path";
3361
+ var createConfiguredHarness = async (options, extraProfiles = [], persistedRoutes, credentials) => {
3362
+ const routes = persistedRoutes ?? resolvedRouting(options);
3363
+ const resolvedConfig = resolveHarnessConfig(options);
3364
+ if (options.usageLimitUsd !== undefined && resolvedConfig.costBudget)
3365
+ throw new CliUsageError("Choose one monetary policy: --usage-limit-usd or the legacy cost budget.");
3366
+ assertRoutePricingIsSafe(routes, resolvedConfig.costBudget);
3367
+ const profiles = [...new Set([
3368
+ ...options.subagentProfiles ?? [],
3369
+ ...extraProfiles,
3370
+ ...routes.keys()
3371
+ ])];
3372
+ const quietTelemetry = options.json || options.jsonl;
3373
+ const providerEnv = credentials ? await credentials.store.providerEnvironment(resolvedConfig.provider, credentials.input) : undefined;
3374
+ const transportEnv = { ...process.env };
3375
+ const bindTransport = (env) => {
3376
+ for (const name of ["QWEN_BASE_URL", "QWEN_REGION", "QWEN_WORKSPACE_ID"]) {
3377
+ if (env[name] === undefined)
3378
+ delete transportEnv[name];
3379
+ else
3380
+ transportEnv[name] = env[name];
3381
+ }
3382
+ };
3383
+ if (providerEnv && resolvedConfig.provider === "qwen")
3384
+ bindTransport(providerEnv);
3385
+ const routeModels = {};
3386
+ for (const [role, route] of routes) {
3387
+ const routeEnv = credentials ? await credentials.store.providerEnvironment(route.provider, credentials.input) : process.env;
3388
+ if (route.provider === "qwen")
3389
+ bindTransport(routeEnv);
3390
+ routeModels[role] = credentials ? await credentialModel(route, routeEnv) : createProviderModel(route, routeEnv);
3391
+ }
3392
+ const compactionEnv = resolvedConfig.compaction.model && credentials ? await credentials.store.providerEnvironment(resolvedConfig.compaction.model.provider, credentials.input) : undefined;
3393
+ if (compactionEnv && resolvedConfig.compaction.model?.provider === "qwen")
3394
+ bindTransport(compactionEnv);
3395
+ const compactionModelInstance = resolvedConfig.compaction.model && compactionEnv ? await credentialModel(resolvedConfig.compaction.model, compactionEnv) : undefined;
3396
+ const harness = await createHarness({
3397
+ ...options,
3398
+ ...{ projectMemory: options.projectMemory ?? true },
3399
+ usageAccounting: {
3400
+ ...options.pricingFile ? { pricing: usagePricingSchema.parse(JSON.parse((await readRegularFileNoFollow(path2.resolve(options.pricingFile), { maxBytes: 128 * 1024, label: "Usage pricing" })).contents.toString("utf8"))) } : {},
3401
+ ...options.usageLimitUsd !== undefined ? { limitUsd: options.usageLimitUsd } : {}
3402
+ },
3403
+ subagentProfiles: profiles,
3404
+ subagentModels: routeModels,
3405
+ ...compactionModelInstance ? { compactionModelInstance } : {},
3406
+ ...providerEnv ? { env: transportEnv, modelInstance: await credentialModel(resolvedConfig, providerEnv) } : {},
3407
+ onTelemetryEvent: orchestrationObserver(quietTelemetry)
3408
+ });
3409
+ return { harness, routes };
3410
+ };
3411
+
3412
+ // packages/core/src/cli/policy.ts
3413
+ function formatPolicyInspection(policy) {
3414
+ return [
3415
+ `Policy: ${policy.source} · ${policy.digest ?? "baseline"}`,
3416
+ `Explicit review: ${policy.explicitReviewRequired ? "required for approvals" : "not configured"}`,
3417
+ `Execution backend: ${policy.execution.activeBackend} (configured: ${policy.execution.configuredBackend})`,
3418
+ "Evidence: configuration only; no tool execution is certified by this query.",
3419
+ `Limits: ${policy.limits.maxSteps} steps, ${policy.limits.timeoutMs} ms`,
3420
+ "Tools:",
3421
+ ...policy.tools.map((tool) => ` ${tool.name}: ${tool.requiresApproval ? "approval required" : "no baseline approval"}`),
3422
+ "Additional restrictions:",
3423
+ ...policy.restrictions.map((rule) => ` ${rule.ruleId}: ${rule.decision} · ${rule.tools.join(", ")} · ${rule.reason}${rule.pathCount ? ` (${rule.pathCount} scoped paths omitted)` : ""}`)
3424
+ ].map(sanitizeTerminalText).join(`
3425
+ `);
3426
+ }
3427
+ function printPolicyInspection(policy, json) {
3428
+ process.stdout.write((json ? JSON.stringify(policy, null, 2) : formatPolicyInspection(policy)) + `
3429
+ `);
3430
+ }
3431
+ async function inspectCliPolicy(options) {
3432
+ const { harness } = await createConfiguredHarness(options);
3433
+ try {
3434
+ printPolicyInspection(inspectHarnessPolicy(harness), options.json);
3435
+ } finally {
3436
+ await harness.close();
3437
+ }
3438
+ }
3439
+
3440
+ // packages/core/src/cli/terminal/activity-history.ts
3441
+ import { createRedactionPolicy as createRedactionPolicy4 } from "@zhivex-ai/agents";
3442
+ var redaction2 = createRedactionPolicy4({ includeEmails: true });
3443
+ var toolNames = new Set(["read_file", "read_files", "read_dependency", "search_files", "search_many", "list_files", "git_diff", "run_check", "run_environment_command", "propose_edits", "apply_patch", "apply_reviewed_edits", "apply_reviewed_replacement", "apply_environment_patch", "verify_and_apply_patch", "verify_and_apply_replacement", "move_file", "quarantine_file", "restore_file"]);
3444
+ var safeName = (name) => toolNames.has(name) ? name : "tool";
3445
+ var safePath = (path3) => redaction2.redactText(sanitizeTerminalText(path3)).replace(/[\r\n\t]/g, " ").slice(0, 240);
3446
+
3447
+ class ActivityHistory {
3448
+ lines = [];
3449
+ started = Date.now();
3450
+ dropped = 0;
3451
+ clear() {
3452
+ this.lines = [];
3453
+ this.dropped = 0;
3454
+ this.started = Date.now();
3455
+ }
3456
+ add(text) {
3457
+ this.lines.push(`[${((Date.now() - this.started) / 1000).toFixed(1)}s] ${text.slice(0, 800)}`);
3458
+ if (this.lines.length > 200) {
3459
+ this.lines.shift();
3460
+ this.dropped++;
3461
+ }
3462
+ }
3463
+ observe(event, options = {}) {
3464
+ const includeTools = options.includeTools !== false;
3465
+ if (event.type === "agent-run-start")
3466
+ this.add("Run started / resumed");
3467
+ else if (event.type === "agent-step-start")
3468
+ this.add("Waiting for model response");
3469
+ else if (event.type === "agent-compaction")
3470
+ this.add("Updating context");
3471
+ else if (includeTools && event.type === "tool-call")
3472
+ this.add(`Preparing ${safeName(event.toolCall.name)}`);
3473
+ else if (includeTools && event.type === "tool-result")
3474
+ this.add(compactToolResult(event.toolResult, { includeSuccessEdits: true }) ?? `${event.toolResult.isError ? "Failed" : "Finished"} ${safeName(event.toolResult.toolName)}`);
3475
+ else if (event.type === "tool-approval-request")
3476
+ this.add(`Waiting for approval: ${safeName(event.approval.name)}`);
3477
+ else if (event.type === "agent-approval-resolved")
3478
+ this.add(event.approval.approve ? "Approval granted" : "Approval denied");
3479
+ else if (event.type === "agent-run-finish")
3480
+ this.add(`Run ${event.status}`);
3481
+ }
3482
+ observeService(event) {
3483
+ const name = typeof event.toolName === "string" ? safeName(event.toolName) : "tool";
3484
+ if (event.type === "tool-call")
3485
+ this.add(`Preparing ${name}`);
3486
+ else if (event.type === "tool-result")
3487
+ this.add(`${event.isError ? "Failed" : "Finished"} ${name}`);
3488
+ else if (event.type === "tool-approval-request")
3489
+ this.add(`Waiting for approval: ${name}`);
3490
+ else if (event.type === "agent-step-start")
3491
+ this.add("Waiting for model response");
3492
+ else if (event.type === "agent-compaction")
3493
+ this.add("Updating context");
3494
+ else if (event.type === "agent-run-start")
3495
+ this.add("Run started / resumed");
3496
+ else if (event.type === "agent-run-finish")
3497
+ this.add("Run stopped; inspect /status for outcome");
3498
+ }
3499
+ render() {
3500
+ return this.lines.length ? `Activity history · this console session${this.dropped ? ` · ${this.dropped} earlier entries omitted` : ""}
3501
+ ${this.lines.join(`
3502
+ `)}
3503
+ ` : `No activity recorded in this console session.
3504
+ `;
3505
+ }
3506
+ }
3507
+ var formatAppliedFiles = (entries, reviewHint = "/diff to review", presentation = "block") => {
3508
+ if (!entries.length)
3509
+ return "";
3510
+ if (presentation === "line") {
3511
+ const shown = entries.slice(0, 3).map((entry) => safePath(entry.path)).join(", ");
3512
+ const more = entries.length > 3 ? `, +${entries.length - 3} more` : "";
3513
+ return `✓ Applied ${entries.length} file change${entries.length === 1 ? "" : "s"} · ${shown}${more} · ${reviewHint}
3514
+ `;
3515
+ }
3516
+ const lines = entries.slice(0, 20).map((entry) => ` ${entry.operation} ${safePath(entry.path)}${entry.destination ? ` → ${safePath(entry.destination)}` : ""}`);
3517
+ if (entries.length > 20)
3518
+ lines.push(` … ${entries.length - 20} more files`);
3519
+ return `✓ Applied ${entries.length} file change${entries.length === 1 ? "" : "s"}
3520
+ ${lines.join(`
3521
+ `)}
3522
+ ${reviewHint} · verification reported separately
3523
+ `;
3524
+ };
3525
+
3526
+ // packages/core/src/cli/console/console-welcome.ts
3527
+ var LOGO_PADDING = "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀";
3528
+ var ZHIVEX_TERMINAL_LOGO = [
3529
+ "⠀⠀⠀⠀⠀⠀⠀⣀⣤⣴⡶⠶⠶⠶⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀",
3530
+ "⠀⠀⠀⠀⠀⣠⡾⠋⠉⠀⠀⠀⠀⠀⠀⠈⠙⢷⣄⠀⠀⠀⠀⠀",
3531
+ "⠀⠀⠀⢀⡾⠋⠀⠴⠿⠿⠿⠿⠿⠿⣿⣿⡿⠋⠙⣷⡀⠀⠀⠀",
3532
+ "⠀⠀⢀⣾⠁⠀⠀⠸⠿⠿⠿⠿⣿⡿⠟⠋⠀⠀⠀⠘⣷⡀⠀⠀",
3533
+ "⠀⠀⢸⡏⠀⠀⠀⠀⠀⠀⣠⣾⠟⠁⠀⠀⠀⠀⠀⠀⢸⡇⠀⠀",
3534
+ "⠀⠀⢸⡇⠀⠀⠀⠀⢀⣾⠟⠁⠀⠀⠀⠀⠀⠀⣤⠀⢸⡇⠀⠀",
3535
+ "⠀⠀⠘⣷⡀⠀⠀⢠⣿⡏⠀⠀⠀⠀⠀⠀⢀⣾⡿⠀⣾⠃⠀⠀",
3536
+ "⠀⠀⠀⠈⠻⣿⡟⠁⠀⠀⠀⠀⠀⠀⠈⣿⣿⢀⣴⠟⠀⠀⠀⠀",
3537
+ "⠀⠀⠀⠀⠀⠈⠻⢶⣤⣀⡀⠀⠀⢀⣀⣤⡶⠟⠁⠀⠀⠀⠀⠀",
3538
+ "⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⠛⠛⠛⠛⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀"
3539
+ ].join(`
3540
+ `);
3541
+ var LEGACY_TERMINAL_LOGO = [LOGO_PADDING, ZHIVEX_TERMINAL_LOGO, LOGO_PADDING].join(`
3542
+ `);
3543
+ var projectLabel = (workspace) => {
3544
+ const home = process.env.HOME;
3545
+ const relative = home && (workspace === home || workspace.startsWith(`${home}/`)) ? `~${workspace.slice(home.length)}` : workspace;
3546
+ return sanitizeTerminalText(relative);
3547
+ };
3548
+ var formatLegacyWelcome = (input, options) => {
3549
+ const safe2 = sanitizeTerminalText;
3550
+ const color = options.color ?? terminalSupportsColor(Boolean(process.stdout.isTTY));
3551
+ const columns = options.columns ?? 80;
3552
+ const title = `Zhivex Harness ${safe2(input.version)}`;
3553
+ const logo = columns < 48 || options.compact ? "( Z )" : LEGACY_TERMINAL_LOGO;
3554
+ const logoLines = logo.split(`
3555
+ `);
3556
+ const logoWidth = Math.max(...logoLines.map((line) => line.length));
3557
+ const titleBesideLogo = columns >= logoWidth + 3 + title.length;
3558
+ const context = [
3559
+ "Welcome to Zhivex. Type a message, or /help for commands.",
3560
+ `Project: ${safe2(input.workspace)}`,
3561
+ input.service ? "Runtime: local service · managed by host" : `Model: ${safe2(input.provider ?? "not configured")}/${safe2(input.model ?? "not selected")}`,
3562
+ input.sessionId ? `Conversation: ${safe2(input.sessionTitle || "new")} · session ${safe2(input.sessionId)}` : "Conversation: new"
3563
+ ];
3564
+ const right = [title, ...context];
3565
+ const titleRow = Math.max(0, Math.floor((logoLines.length - right.length) / 2));
3566
+ const header = logoLines.map((line, index) => {
3567
+ const mark = color ? `\x1B[${terminalToneCode("accent")}m${line}\x1B[0m` : line;
3568
+ const label = titleBesideLogo ? right[index - titleRow] : undefined;
3569
+ return label ? `${mark}${" ".repeat(logoWidth - line.length + 3)}${color ? index === titleRow ? "\x1B[1m" : `\x1B[${terminalToneCode("muted")}m` : ""}${consoleLabel(label, columns - logoWidth - 3)}${color ? "\x1B[0m" : ""}` : mark;
3570
+ }).join(`
3571
+ `);
3572
+ return [
3573
+ header,
3574
+ ...titleBesideLogo ? logoLines.length === 1 ? context : [] : [title, ...context]
3575
+ ].join(`
3576
+ `);
3577
+ };
3578
+ var formatCodeWelcome = (input, options) => {
3579
+ const safe2 = sanitizeTerminalText;
3580
+ const color = options.color ?? terminalSupportsColor(Boolean(process.stderr.isTTY));
3581
+ const columns = options.columns ?? (process.stderr.columns || process.stdout.columns || 80);
3582
+ const rows = options.rows ?? (process.stderr.rows || process.stdout.rows || 24);
3583
+ const tty = options.tty ?? Boolean(process.stderr.isTTY);
3584
+ const term = options.term ?? process.env.TERM;
3585
+ const version = safe2(input.version);
3586
+ const title = `Zhivex Code ${version}`;
3587
+ const project = `${projectLabel(input.workspace)} · ${safe2(input.provider ?? "not configured")}/${safe2(input.model ?? "not selected")}`;
3588
+ if (options.restored)
3589
+ return `( Z ) ${title} · ${project}`;
3590
+ const welcome = "Welcome. What would you like to work on?";
3591
+ const policy = options.policy ?? "Zhivex asks before it changes files.";
3592
+ const showLogo = !options.compact && tty && term !== "dumb" && columns >= 48 && rows >= 24;
3593
+ if (!showLogo)
3594
+ return [`( Z ) ${title}`, project, welcome, policy].join(`
3595
+ `);
3596
+ const logoLines = ZHIVEX_TERMINAL_LOGO.split(`
3597
+ `);
3598
+ const logoWidth = Math.max(...logoLines.map((line) => line.length));
3599
+ const side = [title, project, "", welcome, policy];
3600
+ const room = Math.max(1, columns - logoWidth - 3);
3601
+ const paint = (label, index) => {
3602
+ const bounded = consoleLabel(label, room);
3603
+ if (!color || !bounded)
3604
+ return bounded;
3605
+ if (index === 0)
3606
+ return `\x1B[1mZhivex Code \x1B[0m\x1B[${terminalToneCode("muted")}m${version}\x1B[0m`;
3607
+ if (index === 1)
3608
+ return `\x1B[${terminalToneCode("muted")}m${bounded}\x1B[0m`;
3609
+ return bounded;
3610
+ };
3611
+ if (columns < logoWidth + 3 + title.length) {
3612
+ const stacked = side.map((label) => label ? consoleLabel(label, Math.max(1, columns)) : "");
3613
+ return [logoLines.map((line) => color ? `\x1B[${terminalToneCode("accent")}m${line}\x1B[0m` : line).join(`
3614
+ `), ...stacked].join(`
3615
+ `);
3616
+ }
3617
+ const titleRow = Math.max(0, Math.floor((logoLines.length - side.length) / 2));
3618
+ return logoLines.map((line, index) => {
3619
+ const mark = color ? `\x1B[${terminalToneCode("accent")}m${line}\x1B[0m` : line;
3620
+ const label = side[index - titleRow];
3621
+ return label ? `${mark}${" ".repeat(logoWidth - line.length + 3)}${paint(label, index - titleRow)}` : mark;
3622
+ }).join(`
3623
+ `);
3624
+ };
3625
+ var formatConsoleWelcome = (input, options = {}) => options.layout === "code" ? formatCodeWelcome(input, options) : formatLegacyWelcome(input, options);
3626
+
3627
+ export { formatPolicyDecision, observeCliPolicy, ToolActivity, runResultDocument, TerminalMarkdown, HARNESS_RESUME_METADATA_KEY, HARNESS_RESUME_METADATA_SCHEMA_VERSION, harnessConfigInput, persistedCliOptions, createHarnessResumeMetadata, readHarnessResumeConfig, readHarnessResumeRoutes, resumeCommand, annotateCliStreamError, cliStreamErrorSequence, terminalErrorMessage, summarizeApproval, approvalResponses, terminalApprovalResolver, printTerminalResult, flushToolActivity, streamSink, orchestrationObserver, consoleLabel, consoleWidth, consoleStateLines, formatConsoleHelp, ConsoleInput, chooseReasoning, handleConsoleBudget, navigateConsole, CredentialSetupError, CliCredentials, credentialModel, resolvedRouting, assertRoutePricingIsSafe, withTemporaryHarnessProfiles, createConfiguredHarness, printPolicyInspection, inspectCliPolicy, ActivityHistory, formatAppliedFiles, formatConsoleWelcome };