zidane 9.1.1 → 9.1.4

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 (279) hide show
  1. package/dist/{acp-Di9WvMDF.js → acp-Cl4gCZN6.js} +7 -7
  2. package/dist/{acp-Di9WvMDF.js.map → acp-Cl4gCZN6.js.map} +1 -1
  3. package/dist/acp-cli.js +5 -5
  4. package/dist/acp.d.ts +2 -2
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-DJhpTS-B.js → agent-Dh_XZ7fj.js} +74 -19
  7. package/dist/agent-Dh_XZ7fj.js.map +1 -0
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{auth-store-port-DFgf22oo.js → auth-store-port-DBl2JUC6.js} +2 -2
  11. package/dist/{auth-store-port-DFgf22oo.js.map → auth-store-port-DBl2JUC6.js.map} +1 -1
  12. package/dist/{auto-update-restart-BFB7Ek87.js → auto-update-restart-CF_kjcJd.js} +277 -41
  13. package/dist/auto-update-restart-CF_kjcJd.js.map +1 -0
  14. package/dist/{browser-BcoCCB_n.js → browser-BkdeKnxO.js} +56 -2
  15. package/dist/browser-BkdeKnxO.js.map +1 -0
  16. package/dist/{browser-entry-ypi8CyE-.d.ts → browser-entry-BCwruqNa.d.ts} +10 -10
  17. package/dist/{browser-entry-ypi8CyE-.d.ts.map → browser-entry-BCwruqNa.d.ts.map} +1 -1
  18. package/dist/channels.d.ts +5 -5
  19. package/dist/chat/browser.d.ts +4 -4
  20. package/dist/chat/browser.js +6 -6
  21. package/dist/chat/pure.d.ts +5 -5
  22. package/dist/chat/pure.js +8 -8
  23. package/dist/chat.d.ts +5 -5
  24. package/dist/chat.js +55 -55
  25. package/dist/chat.js.map +1 -1
  26. package/dist/{cli-shared-CabruH8Z.js → cli-shared-DIV9c5Nr.js} +4 -4
  27. package/dist/{cli-shared-CabruH8Z.js.map → cli-shared-DIV9c5Nr.js.map} +1 -1
  28. package/dist/cli-style-DBEm6CyT.js +105 -0
  29. package/dist/cli-style-DBEm6CyT.js.map +1 -0
  30. package/dist/{client-core-CIixwznM.d.ts → client-core-C_4m_oL6.d.ts} +4 -4
  31. package/dist/{client-core-CIixwznM.d.ts.map → client-core-C_4m_oL6.d.ts.map} +1 -1
  32. package/dist/{client-CCaIXWue.d.ts → client-ygTASGis.d.ts} +2 -2
  33. package/dist/{client-CCaIXWue.d.ts.map → client-ygTASGis.d.ts.map} +1 -1
  34. package/dist/codemode-worker.js +8 -5
  35. package/dist/codemode-worker.js.map +1 -1
  36. package/dist/codemode.d.ts +16 -0
  37. package/dist/codemode.d.ts.map +1 -1
  38. package/dist/codemode.js +2 -2
  39. package/dist/{connection-loop-QmWL-fJf.d.ts → connection-loop-D_pRONCr.d.ts} +4 -4
  40. package/dist/{connection-loop-QmWL-fJf.d.ts.map → connection-loop-D_pRONCr.d.ts.map} +1 -1
  41. package/dist/contexts/daytona.d.ts +3 -3
  42. package/dist/contexts/docker.d.ts +1 -1
  43. package/dist/contexts/e2b.d.ts +2 -2
  44. package/dist/contexts/sandbox.d.ts +1 -1
  45. package/dist/{contexts-C72b0mMa.js → contexts-DLZTSRHU.js} +17 -106
  46. package/dist/contexts-DLZTSRHU.js.map +1 -0
  47. package/dist/contexts.d.ts +4 -4
  48. package/dist/contexts.js +2 -2
  49. package/dist/{credentials-wwETW8rI.js → credentials-D71duF64.js} +2 -2
  50. package/dist/{credentials-wwETW8rI.js.map → credentials-D71duF64.js.map} +1 -1
  51. package/dist/{cwd-picker-CcekODCt.js → cwd-picker-BsHA6HKv.js} +4 -4
  52. package/dist/{cwd-picker-CcekODCt.js.map → cwd-picker-BsHA6HKv.js.map} +1 -1
  53. package/dist/daemon-cli.js +4 -3
  54. package/dist/daemon-cli.js.map +1 -1
  55. package/dist/{decisions-CXmK0nz9.js → decisions-hsw5XS2g.js} +3 -1
  56. package/dist/decisions-hsw5XS2g.js.map +1 -0
  57. package/dist/{discovery-DycXFxdA.js → discovery-DD4wPWKS.js} +4 -4
  58. package/dist/{discovery-DycXFxdA.js.map → discovery-DD4wPWKS.js.map} +1 -1
  59. package/dist/durable/sqlite.d.ts +2 -2
  60. package/dist/durable.d.ts +1 -1
  61. package/dist/{engine-VQ86XGdG.js → engine-BDmtgr2O.js} +6 -6
  62. package/dist/{engine-VQ86XGdG.js.map → engine-BDmtgr2O.js.map} +1 -1
  63. package/dist/{eval-Bod0I1W_.js → eval-CfGUDAkN.js} +3 -3
  64. package/dist/{eval-Bod0I1W_.js.map → eval-CfGUDAkN.js.map} +1 -1
  65. package/dist/eval.d.ts +1 -1
  66. package/dist/eval.js +1 -1
  67. package/dist/{executor-C7RQrkEq.js → executor-EWOhLyd9.js} +4 -4
  68. package/dist/{executor-C7RQrkEq.js.map → executor-EWOhLyd9.js.map} +1 -1
  69. package/dist/{extension-mark-BqKdEZwF.js → extension-mark-_rhkDWL5.js} +9 -6
  70. package/dist/extension-mark-_rhkDWL5.js.map +1 -0
  71. package/dist/extensions/testing.d.ts +1 -1
  72. package/dist/extensions/testing.js +2 -2
  73. package/dist/{extensions-BCx4QuGB.js → extensions-DklXPjiq.js} +8 -8
  74. package/dist/{extensions-BCx4QuGB.js.map → extensions-DklXPjiq.js.map} +1 -1
  75. package/dist/{extensions-client-D8tEAcMw.d.ts → extensions-client-D4Q2XRKV.d.ts} +31 -5
  76. package/dist/extensions-client-D4Q2XRKV.d.ts.map +1 -0
  77. package/dist/extensions.d.ts +1 -1
  78. package/dist/extensions.js +6 -6
  79. package/dist/{fold-rules-DvLK8pbf.d.ts → fold-rules-1DpDwG9h.d.ts} +2 -2
  80. package/dist/{fold-rules-DvLK8pbf.d.ts.map → fold-rules-1DpDwG9h.d.ts.map} +1 -1
  81. package/dist/{google-Crva32sk.js → google-BtMW9KzL.js} +2 -2
  82. package/dist/{google-Crva32sk.js.map → google-BtMW9KzL.js.map} +1 -1
  83. package/dist/{headless-CCm-jLLT.js → headless-CQm19BL0.js} +4 -4
  84. package/dist/{headless-CCm-jLLT.js.map → headless-CQm19BL0.js.map} +1 -1
  85. package/dist/headless.d.ts +1 -1
  86. package/dist/headless.js +1 -1
  87. package/dist/history-worker.js +1 -1
  88. package/dist/{host-BHMs9jsN.js → host-DEoEzQal.js} +13 -4
  89. package/dist/host-DEoEzQal.js.map +1 -0
  90. package/dist/{host-scoped-settings-CrbcqOkP.js → host-scoped-settings-WBYaCork.js} +2 -2
  91. package/dist/{host-scoped-settings-CrbcqOkP.js.map → host-scoped-settings-WBYaCork.js.map} +1 -1
  92. package/dist/{host-signals-Jsjd_-4g.js → host-signals-91zyko_i.js} +5 -5
  93. package/dist/{host-signals-Jsjd_-4g.js.map → host-signals-91zyko_i.js.map} +1 -1
  94. package/dist/{host-wO_6GW0y.js → host-uP3t08w8.js} +276 -103
  95. package/dist/host-uP3t08w8.js.map +1 -0
  96. package/dist/{host-version-CNAr9pov.js → host-version-_RHlAB29.js} +2 -2
  97. package/dist/{host-version-CNAr9pov.js.map → host-version-_RHlAB29.js.map} +1 -1
  98. package/dist/{index-C6nnKu32.d.ts → index-B0PLo9jn.d.ts} +4 -4
  99. package/dist/{index-C6nnKu32.d.ts.map → index-B0PLo9jn.d.ts.map} +1 -1
  100. package/dist/{index-Djnc8Peh.d.ts → index-De4x-s76.d.ts} +14 -14
  101. package/dist/{index-Djnc8Peh.d.ts.map → index-De4x-s76.d.ts.map} +1 -1
  102. package/dist/{index-CGbOWa7y.d.ts → index-WlE93Q6d.d.ts} +411 -3
  103. package/dist/index-WlE93Q6d.d.ts.map +1 -0
  104. package/dist/{index-CCf_WeTQ.d.ts → index-f-XWIoYo.d.ts} +2 -2
  105. package/dist/{index-CCf_WeTQ.d.ts.map → index-f-XWIoYo.d.ts.map} +1 -1
  106. package/dist/index.d.ts +5 -5
  107. package/dist/index.js +17 -17
  108. package/dist/ipc/browser-types.d.ts +304 -7
  109. package/dist/ipc/browser-types.d.ts.map +1 -1
  110. package/dist/ipc/browser.d.ts +4 -4
  111. package/dist/ipc/browser.js +2 -2
  112. package/dist/ipc/remote.d.ts +6 -6
  113. package/dist/ipc/remote.js +3 -3
  114. package/dist/{ipc-BzWhIybr.js → ipc-CatnsVEd.js} +4 -4
  115. package/dist/{ipc-BzWhIybr.js.map → ipc-CatnsVEd.js.map} +1 -1
  116. package/dist/ipc.d.ts +10 -10
  117. package/dist/ipc.js +8 -8
  118. package/dist/{json-Dj-YATkZ.js → json-BjClr43H.js} +2 -20
  119. package/dist/json-BjClr43H.js.map +1 -0
  120. package/dist/{links-CJG_rFvf.js → links-a8C9eby4.js} +9 -9
  121. package/dist/{links-CJG_rFvf.js.map → links-a8C9eby4.js.map} +1 -1
  122. package/dist/{loaded-entry-DTURJo_R.js → loaded-entry-D6jzt5HQ.js} +2 -2
  123. package/dist/{loaded-entry-DTURJo_R.js.map → loaded-entry-D6jzt5HQ.js.map} +1 -1
  124. package/dist/mcp.d.ts +1 -1
  125. package/dist/{media-type-BtA0cbfI.d.ts → media-type-ZSmAGHvg.d.ts} +188 -7
  126. package/dist/media-type-ZSmAGHvg.d.ts.map +1 -0
  127. package/dist/{memory-DuVGrzbl.js → memory-CJy52DNi.js} +132 -31
  128. package/dist/memory-CJy52DNi.js.map +1 -0
  129. package/dist/model-test-CAtJ76kM.js.map +1 -1
  130. package/dist/{move-session-kylExJ5H.js → move-session-D7ILECs-.js} +4 -4
  131. package/dist/{move-session-kylExJ5H.js.map → move-session-D7ILECs-.js.map} +1 -1
  132. package/dist/{nested-call-record-DlzPeTB7.js → nested-call-record-OayszZBQ.js} +4 -3
  133. package/dist/nested-call-record-OayszZBQ.js.map +1 -0
  134. package/dist/output/stream-json.d.ts +1 -1
  135. package/dist/output/terminal.d.ts +1 -1
  136. package/dist/{path-display-COVV71Yu.js → path-display-CAWz-sMq.js} +3 -3
  137. package/dist/{path-display-COVV71Yu.js.map → path-display-CAWz-sMq.js.map} +1 -1
  138. package/dist/plugins.d.ts +1 -1
  139. package/dist/{prelude-CVKoUzV8.js → prelude-BwiSR1uA.js} +16 -5
  140. package/dist/prelude-BwiSR1uA.js.map +1 -0
  141. package/dist/{presets-CBt6rFfS.js → presets-CMY43nUP.js} +3 -3
  142. package/dist/{presets-CBt6rFfS.js.map → presets-CMY43nUP.js.map} +1 -1
  143. package/dist/presets.d.ts +1 -1
  144. package/dist/presets.js +1 -1
  145. package/dist/{protocol-CEVqBO-q.d.ts → protocol-C2lqKuMd.d.ts} +50 -7
  146. package/dist/protocol-C2lqKuMd.d.ts.map +1 -0
  147. package/dist/protocol-DOGyHgLQ.js.map +1 -1
  148. package/dist/protocol-NSllElLw.js.map +1 -1
  149. package/dist/providers/anthropic.d.ts +1 -1
  150. package/dist/providers/arcee.d.ts +1 -1
  151. package/dist/providers/baseten.d.ts +1 -1
  152. package/dist/providers/cerebras.d.ts +1 -1
  153. package/dist/providers/google.d.ts +1 -1
  154. package/dist/providers/google.js +1 -1
  155. package/dist/providers/local.d.ts +1 -1
  156. package/dist/providers/neuralwatt.d.ts +1 -1
  157. package/dist/providers/openai-compat.d.ts +1 -1
  158. package/dist/providers/openai.d.ts +1 -1
  159. package/dist/providers/openrouter.d.ts +1 -1
  160. package/dist/providers/xai.d.ts +1 -1
  161. package/dist/{providers-Z0TaBp1O.js → providers-zVRxiJDv.js} +5 -5
  162. package/dist/providers-zVRxiJDv.js.map +1 -0
  163. package/dist/providers.d.ts +1 -1
  164. package/dist/providers.js +1 -1
  165. package/dist/{readonly-db-D7Z-k0pQ.js → readonly-db-DrbT8tX6.js} +2 -2
  166. package/dist/{readonly-db-D7Z-k0pQ.js.map → readonly-db-DrbT8tX6.js.map} +1 -1
  167. package/dist/{registry-BKjeBnoy.js → registry-CBoYDIND.js} +2 -2
  168. package/dist/{registry-BKjeBnoy.js.map → registry-CBoYDIND.js.map} +1 -1
  169. package/dist/{registry-B6Ww76iW.js → registry-CQOU5jvF.js} +2 -2
  170. package/dist/{registry-B6Ww76iW.js.map → registry-CQOU5jvF.js.map} +1 -1
  171. package/dist/{registry-B9INJwJR.js → registry-YUUqbYGr.js} +324 -39
  172. package/dist/registry-YUUqbYGr.js.map +1 -0
  173. package/dist/{remote-hosts-BMWoHCWO.js → remote-hosts-CT8Q95dR.js} +4 -4
  174. package/dist/{remote-hosts-BMWoHCWO.js.map → remote-hosts-CT8Q95dR.js.map} +1 -1
  175. package/dist/{repo-url-D4Dr8NfZ.js → repo-url-DLjjuVk_.js} +169 -2
  176. package/dist/repo-url-DLjjuVk_.js.map +1 -0
  177. package/dist/restate.d.ts +2 -2
  178. package/dist/{sandbox-BwiPGKF7.d.ts → sandbox-B4OW6oNx.d.ts} +2 -2
  179. package/dist/{sandbox-BwiPGKF7.d.ts.map → sandbox-B4OW6oNx.d.ts.map} +1 -1
  180. package/dist/script-progress-CrZ507Qq.js +900 -0
  181. package/dist/script-progress-CrZ507Qq.js.map +1 -0
  182. package/dist/session/sqlite.d.ts +1 -1
  183. package/dist/session.d.ts +1 -1
  184. package/dist/{setting-BQBSyUq0.js → setting-_jh2OtiL.js} +6 -6
  185. package/dist/{setting-BQBSyUq0.js.map → setting-_jh2OtiL.js.map} +1 -1
  186. package/dist/{settings-catalog-4IU2i_jG.js → settings-catalog-DEZlXP51.js} +14 -2
  187. package/dist/settings-catalog-DEZlXP51.js.map +1 -0
  188. package/dist/{settings-keys-iI_Y-7MC.js → settings-keys-BT0_oKjO.js} +3 -3
  189. package/dist/{settings-keys-iI_Y-7MC.js.map → settings-keys-BT0_oKjO.js.map} +1 -1
  190. package/dist/{skills-CFXRItJ6.js → skills-CEbosUlM.js} +2 -2
  191. package/dist/{skills-CFXRItJ6.js.map → skills-CEbosUlM.js.map} +1 -1
  192. package/dist/skills.d.ts +1 -1
  193. package/dist/skills.js +1 -1
  194. package/dist/{source-Bl1Z501r.js → source-3ZnEPOSa.js} +3 -2
  195. package/dist/source-3ZnEPOSa.js.map +1 -0
  196. package/dist/{sqlite-runtime-BZ2L4RaG.d.ts → sqlite-runtime-CS_LBaAN.d.ts} +2 -2
  197. package/dist/sqlite-runtime-CS_LBaAN.d.ts.map +1 -0
  198. package/dist/{src-BY_ND2xn.js → src-BmTXDta8.js} +2 -2
  199. package/dist/{src-BY_ND2xn.js.map → src-BmTXDta8.js.map} +1 -1
  200. package/dist/{store-C6gI7FfZ.js → store-ByCDaKgJ.js} +14 -3
  201. package/dist/store-ByCDaKgJ.js.map +1 -0
  202. package/dist/{system-freeze-m5o1sGIM.js → system-freeze-DxJ-lRhu.js} +3 -3
  203. package/dist/{system-freeze-m5o1sGIM.js.map → system-freeze-DxJ-lRhu.js.map} +1 -1
  204. package/dist/{todo-edits-CbukbjyV.js → todo-edits-Dyj32ds6.js} +4 -3
  205. package/dist/todo-edits-Dyj32ds6.js.map +1 -0
  206. package/dist/tools/fetch-url.d.ts +1 -1
  207. package/dist/tools/web-search.d.ts +1 -1
  208. package/dist/{tools-CVTGhggj.js → tools-BsrGQ8K4.js} +2 -2
  209. package/dist/{tools-CVTGhggj.js.map → tools-BsrGQ8K4.js.map} +1 -1
  210. package/dist/tools.d.ts +1 -1
  211. package/dist/tools.js +3 -3
  212. package/dist/{transcript-anchors-CiSi_UBn.js → transcript-anchors-DMjvyUjk.js} +3 -3
  213. package/dist/{transcript-anchors-CiSi_UBn.js.map → transcript-anchors-DMjvyUjk.js.map} +1 -1
  214. package/dist/{transcript-reconcile-jbSBjLq2.js → transcript-reconcile-DpQO85wl.js} +3 -3
  215. package/dist/{transcript-reconcile-jbSBjLq2.js.map → transcript-reconcile-DpQO85wl.js.map} +1 -1
  216. package/dist/tui.d.ts +9 -9
  217. package/dist/tui.d.ts.map +1 -1
  218. package/dist/tui.js +289 -38
  219. package/dist/tui.js.map +1 -1
  220. package/dist/{types-bDQagoiL.d.ts → types-2HrgolQz.d.ts} +20 -8
  221. package/dist/types-2HrgolQz.d.ts.map +1 -0
  222. package/dist/types-4q1bFG53.js +122 -0
  223. package/dist/types-4q1bFG53.js.map +1 -0
  224. package/dist/{types-DnRd9_cA.d.ts → types-SXqk6hLD.d.ts} +3 -3
  225. package/dist/{types-DnRd9_cA.d.ts.map → types-SXqk6hLD.d.ts.map} +1 -1
  226. package/dist/types-myxheQkw.js.map +1 -1
  227. package/dist/types.d.ts +3 -3
  228. package/dist/{usage-summary-BfcXjiSM.js → usage-summary-BM7B3JdI.js} +2 -2
  229. package/dist/{usage-summary-BfcXjiSM.js.map → usage-summary-BM7B3JdI.js.map} +1 -1
  230. package/dist/{version-DqqqvHDP.js → version-DwQI12WA.js} +2 -2
  231. package/dist/{version-DqqqvHDP.js.map → version-DwQI12WA.js.map} +1 -1
  232. package/dist/{wait-task-BX4NcOOm.js → wait-task-BiI5UaZQ.js} +13 -3
  233. package/dist/wait-task-BiI5UaZQ.js.map +1 -0
  234. package/dist/{wire-CLm2rMK0.js → wire-Dxwxb7QQ.js} +2 -2
  235. package/dist/{wire-CLm2rMK0.js.map → wire-Dxwxb7QQ.js.map} +1 -1
  236. package/dist/{write-file-0E6TUJ9A.js → write-file-Dquu7MzB.js} +5 -3
  237. package/dist/write-file-Dquu7MzB.js.map +1 -0
  238. package/dist/{ws-DfGGYQ4W.js → ws-CA3o2nie.js} +4 -4
  239. package/dist/{ws-DfGGYQ4W.js.map → ws-CA3o2nie.js.map} +1 -1
  240. package/dist/{ws-client-CFMbhsNq.js → ws-client-C0iPAAzc.js} +2 -2
  241. package/dist/{ws-client-CFMbhsNq.js.map → ws-client-C0iPAAzc.js.map} +1 -1
  242. package/docs/CHAT.md +55 -0
  243. package/docs/CODEMODE.md +37 -0
  244. package/docs/EXTENSIONS.md +8 -6
  245. package/docs/RELEASE-NOTES-NEXT.md +48 -1
  246. package/docs/RELEASE.md +9 -1
  247. package/package.json +2 -3
  248. package/dist/agent-DJhpTS-B.js.map +0 -1
  249. package/dist/auto-update-restart-BFB7Ek87.js.map +0 -1
  250. package/dist/browser-BcoCCB_n.js.map +0 -1
  251. package/dist/contexts-C72b0mMa.js.map +0 -1
  252. package/dist/decisions-CXmK0nz9.js.map +0 -1
  253. package/dist/extension-mark-BqKdEZwF.js.map +0 -1
  254. package/dist/extensions-client-D8tEAcMw.d.ts.map +0 -1
  255. package/dist/host-BHMs9jsN.js.map +0 -1
  256. package/dist/host-wO_6GW0y.js.map +0 -1
  257. package/dist/index-CGbOWa7y.d.ts.map +0 -1
  258. package/dist/json-Dj-YATkZ.js.map +0 -1
  259. package/dist/media-type-BtA0cbfI.d.ts.map +0 -1
  260. package/dist/memory-DuVGrzbl.js.map +0 -1
  261. package/dist/nested-call-events-BYk8XvGX.js +0 -182
  262. package/dist/nested-call-events-BYk8XvGX.js.map +0 -1
  263. package/dist/nested-call-record-DlzPeTB7.js.map +0 -1
  264. package/dist/prelude-CVKoUzV8.js.map +0 -1
  265. package/dist/protocol-CEVqBO-q.d.ts.map +0 -1
  266. package/dist/providers-Z0TaBp1O.js.map +0 -1
  267. package/dist/registry-B9INJwJR.js.map +0 -1
  268. package/dist/repo-url-D4Dr8NfZ.js.map +0 -1
  269. package/dist/settings-catalog-4IU2i_jG.js.map +0 -1
  270. package/dist/source-Bl1Z501r.js.map +0 -1
  271. package/dist/sqlite-runtime-BZ2L4RaG.d.ts.map +0 -1
  272. package/dist/store-C6gI7FfZ.js.map +0 -1
  273. package/dist/todo-edits-CbukbjyV.js.map +0 -1
  274. package/dist/types-DTMEhKJO.js +0 -14
  275. package/dist/types-DTMEhKJO.js.map +0 -1
  276. package/dist/types-bDQagoiL.d.ts.map +0 -1
  277. package/dist/wait-task-BX4NcOOm.js.map +0 -1
  278. package/dist/write-file-0E6TUJ9A.js.map +0 -1
  279. package/scripts/eval.ts +0 -179
@@ -1 +1 @@
1
- {"version":3,"file":"ws-DfGGYQ4W.js","names":[],"sources":["../src/ipc/hosts/probe.ts","../src/ipc/hosts/saved-hosts.ts","../src/ipc/hosts/ws.ts"],"sourcesContent":["/**\n * The host registry's connection (`src/chat/hosts`): a WebSocket probe that\n * says who answers at a URL with a token, and the registry wired to it.\n */\nimport type { HostErrorCode, HostProbeResult, HostRegistry } from '../../chat/hosts'\nimport { createHostRegistry, displayHostUrl } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { hostCaBundle } from '../transports/tls-trust'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\n\n/** Bound on one probe: the upgrade, the handshake and `daemon.info`. */\nexport const HOST_PROBE_TIMEOUT_MS = 10_000\n\nconst TLS_FAILURE = /certificate|self[- ]signed|\\btls\\b|\\bssl\\b|UNABLE_TO_VERIFY|CERT_|ERR_TLS/i\n\nfunction classify(err: unknown): { error: HostErrorCode, message: string } {\n if (err instanceof HostAuthError) {\n return err.status === 401\n ? { error: 'auth', message: 'The host refused the token (401). Create a new one on the server: zidane server token create --name <device>.' }\n : { error: 'auth', message: err.message }\n }\n if (err instanceof IpcVersionMismatchError)\n return { error: 'protocol', message: err.message }\n const message = err instanceof Error ? err.message : String(err)\n if (TLS_FAILURE.test(message))\n return { error: 'tls', message: `TLS failed: ${message}` }\n return { error: 'unreachable', message }\n}\n\n/**\n * A failed WebSocket says nothing about why. For `wss://`, ask the same\n * address over HTTPS: a certificate or handshake failure there is a TLS\n * problem, anything else stays \"unreachable\".\n */\nasync function tlsFailure(url: string, signal: AbortSignal): Promise<string | null> {\n if (!url.startsWith('wss:'))\n return null\n try {\n // No token, and no redirect followed: only the TLS handshake with this origin matters.\n // The same CAs as the socket (Bun takes them per request; Node uses its process default).\n const ca = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' ? hostCaBundle() : null\n const response = await fetch(`https:${url.slice('wss:'.length)}`, { redirect: 'manual', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]), ...(ca ? { tls: { ca } } : {}) } as RequestInit)\n void response.body?.cancel().catch(() => {})\n return null\n }\n catch (err) {\n const e = err as { code?: unknown, message?: unknown }\n const detail = `${typeof e.code === 'string' ? e.code : ''} ${typeof e.message === 'string' ? e.message : ''}`\n return TLS_FAILURE.test(detail) ? `TLS failed: ${String(e.message ?? e.code)}` : null\n }\n}\n\n/**\n * Connect, read the host's identity and `daemon.info`, disconnect. Never throws.\n * @param target - URL, token and an optional timeout in milliseconds. The timeout defaults to {@link HOST_PROBE_TIMEOUT_MS}.\n * @returns Who answered and how fast, or a classified failure.\n */\nexport async function probeWsHost(target: { url: string, token: string, timeoutMs?: number }): Promise<HostProbeResult> {\n // The OS certificate store is read once per process, synchronously (seconds on a loaded\n // machine): read it before the deadline starts, or that cost is misread as a host with no answer.\n if (typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' && /^wss:/i.test(target.url))\n hostCaBundle()\n const started = performance.now()\n const signal = AbortSignal.timeout(target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS)\n let client: Awaited<ReturnType<typeof connectWsClient>> | undefined\n try {\n client = await connectWsClient({ url: target.url, token: target.token, heartbeatMs: 0, signal })\n const hostRef = hostRefOf(client.hello)\n if (!hostRef)\n return { ok: false, error: 'protocol', message: `${displayHostUrl(target.url)} runs a zidane too old to say which host it is. Upgrade the server.` }\n const info = await client.request('daemon.info', {})\n const serverVersion = info.codeVersion ?? info.appVersion\n return { ok: true, hostRef, ...(serverVersion ? { serverVersion } : {}), latencyMs: Math.round(performance.now() - started) }\n }\n catch (err) {\n if (signal.aborted && !(err instanceof HostAuthError))\n return { ok: false, error: 'unreachable', message: `No answer from ${displayHostUrl(target.url)} within ${target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS} ms.` }\n const classified = classify(err)\n if (classified.error === 'unreachable') {\n const tls = await tlsFailure(target.url, signal).catch(() => null)\n if (tls)\n return { ok: false, error: 'tls', message: tls }\n }\n return { ok: false, ...classified }\n }\n finally {\n client?.close()\n }\n}\n\n/**\n * The registry in `dataDir`, connecting over WebSocket.\n * @param options - Where the registry keeps its data.\n * @returns The host registry.\n */\nexport function createWsHostRegistry(options: { dataDir: string }): HostRegistry {\n return createHostRegistry({ dataDir: options.dataDir, probe: probeWsHost })\n}\n","/**\n * A client's saved servers, kept in its host directory: one directory entry\n * and one app-lifetime connection (`connection-loop`) per server in the\n * registry, in step with it. Shared by the TUI and the GUI main process,\n * which each supply their directory (`SavedHostsDirectory`) and how to dial.\n *\n * Saving a server that is already saved (same host id: a new token, a new\n * URL) reconfigures its entry IN PLACE and reconnects: the entry is never\n * removed, so the sessions routed to it stay routed. Only a server leaving\n * the registry (removed here or by another window) or `stop()` removes an\n * entry, and the directory decides what that means for an open session.\n *\n * Every connection is checked against the saved entry's id (the server's\n * `hostId` when it was added): another host answering at the URL is closed\n * at once, reported as `identity` and not retried, so nothing it says is\n * recorded under the saved id. Dialers may check first (`expectHostId`).\n *\n * No WebSocket import: the WebSocket wiring is `./ws.ts`.\n */\nimport type { HostEntry, HostProbeResult, HostRegistry, HostTestResult } from '../../chat/hosts'\nimport type { HostSignal } from '../protocol'\nimport type { IpcClient } from '../transports/client-core'\nimport type { HostConnectionLoop, HostConnectionPatch, HostFailureKind } from './connection-loop'\nimport { displayHostUrl, HostIdentityError } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { keepHostConnected } from './connection-loop'\n\n/** The client's host directory, as the saved servers see it. Keys are host ids. */\nexport interface SavedHostsDirectory {\n /** The saved servers it holds now, with their URL (a `--host` server excluded). */\n saved: () => { key: string, url: string }[]\n /** Add the entry, or reconfigure the one under its key in place (status `connecting`). */\n upsert: (entry: HostEntry, token: string | undefined) => void\n /** Applies a connection patch, a new name or a server version to the entry. */\n update: (key: string, patch: HostConnectionPatch & { name?: string, serverVersion?: string }) => void\n /** The server left the registry, or the saved servers stopped. */\n remove: (key: string) => void\n}\n\n/** No token is saved for this server (removed by hand, or another window removed it). */\nexport class MissingHostTokenError extends Error {\n constructor() {\n super('No token saved for this server: add it again.')\n this.name = 'MissingHostTokenError'\n }\n}\n\n/** Options for {@link startSavedHosts}: the registry, the host directory, the connect function and callbacks. */\nexport interface SavedHostsOptions {\n /** The registry of saved servers. */\n registry: HostRegistry\n /** The client's host directory the entries are kept in. */\n directory: SavedHostsDirectory\n /** One connect attempt to a saved server, with its token read fresh. */\n connect: (entry: HostEntry, token: string, options: { signal: AbortSignal, onClose: () => void }) => Promise<IpcClient>\n /** `auth`: refused for good. A missing token is always `auth`, another host answering always `identity`. */\n classify?: (err: unknown) => HostFailureKind\n /** The add form's test of an unsaved URL + token (`probeUnsavedHost`). */\n probeUnsaved?: (target: { url: string, token: string }) => Promise<HostProbeResult>\n /** Saved entries the directory already reaches another way (the TUI's `--host` server). */\n skip?: (entry: HostEntry) => boolean\n /** Called with every signal of a connected saved server. */\n onSignal?: (key: string, signal: HostSignal) => void\n /** Called when a saved server connects, also after a reconnect. */\n onConnected?: (key: string, client: IpcClient) => void\n /** Called when a saved server's connection drops. */\n onDisconnected?: (key: string) => void\n /**\n * Lower backoff bound in milliseconds.\n * @default 1000\n */\n minDelayMs?: number\n /**\n * Upper backoff bound in milliseconds.\n * @default 30000\n */\n maxDelayMs?: number\n}\n\n/** Handle returned by {@link startSavedHosts} to list, add, remove, rename, test and retry saved servers. */\nexport interface SavedHostsController {\n /** The saved hosts, read fresh (other windows share the file). */\n list: () => HostEntry[]\n /** Verify, save, connect (in place when already saved). Throws a `HostRegistryError`. */\n add: (input: { url: string, token: string, name?: string }) => Promise<HostEntry>\n /** Removes a server from the registry and its entry from the directory. Returns whether it existed. */\n remove: (id: string) => boolean\n /** Renames a saved server and returns the updated entry. */\n rename: (id: string, name: string) => HostEntry\n /** Move a saved server to a new URL (its saved token; the same server must answer), then reconnect it in place. Throws a `HostRegistryError`. */\n setUrl: (id: string, url: string) => Promise<HostEntry>\n /** A saved server (by id), or an unsaved URL + token (the add form's test). */\n test: (target: string | { id: string } | { url: string, token: string }) => Promise<HostTestResult>\n /** Reconnect now (after an outage or a token fix). */\n retry: (id: string) => void\n /** Reconnect every saved server that is not connected now, its backoff reset (the computer woke up). */\n retryAll: () => void\n /** Disconnects every saved server and removes their directory entries. The registry is not changed. */\n stop: () => void\n}\n\n/**\n * Starts the connections of a client's saved servers and keeps the directory in step with the registry.\n * Each saved server gets a directory entry and a connection loop. A connection whose host id differs from the saved one is closed and reported as `identity`.\n * @param options - Registry, directory and how to dial.\n * @returns A controller over the saved servers.\n */\nexport function startSavedHosts(options: SavedHostsOptions): SavedHostsController {\n const { registry, directory, skip = () => false } = options\n const classify = (err: unknown): HostFailureKind => err instanceof MissingHostTokenError ? 'auth' : err instanceof HostIdentityError ? 'identity' : (options.classify?.(err) ?? 'retry')\n\n /** The saved server, or nobody: a connection from another host is closed before anyone sees it. */\n const dial = async (entry: HostEntry, token: string, attempt: { signal: AbortSignal, onClose: () => void }): Promise<IpcClient> => {\n const client = await options.connect(entry, token, attempt)\n const ref = hostRefOf(client.hello)\n if (ref?.id === entry.id)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(entry.url), ref?.name)\n }\n const loops = new Map<string, HostConnectionLoop>()\n\n const disconnect = (key: string): void => {\n loops.get(key)?.stop()\n loops.delete(key)\n }\n\n /** (Re)connect `entry` with the token saved now, its directory entry kept or created in place. */\n const connect = (entry: HostEntry): void => {\n const key = entry.id\n disconnect(key)\n directory.upsert(entry, registry.token(key))\n loops.set(key, keepHostConnected({\n connect: (attempt) => {\n const token = registry.token(key)\n return token ? dial(entry, token, attempt) : Promise.reject(new MissingHostTokenError())\n },\n update: patch => directory.update(key, patch),\n classify,\n ...(options.onSignal ? { onSignal: (signal: HostSignal) => options.onSignal!(key, signal) } : {}),\n ...(options.onConnected ? { onConnected: (client: IpcClient) => options.onConnected!(key, client) } : {}),\n ...(options.onDisconnected ? { onDisconnected: () => options.onDisconnected!(key) } : {}),\n ...(options.minDelayMs !== undefined ? { minDelayMs: options.minDelayMs } : {}),\n ...(options.maxDelayMs !== undefined ? { maxDelayMs: options.maxDelayMs } : {}),\n }))\n }\n\n /** Bring the directory in line with the saved hosts. */\n const sync = (): void => {\n const entries = registry.list().filter(entry => !skip(entry))\n const saved = new Set(entries.map(entry => entry.id))\n const known = new Map(directory.saved().map(host => [host.key, host.url]))\n for (const key of known.keys()) {\n if (!saved.has(key)) {\n disconnect(key)\n directory.remove(key)\n }\n }\n for (const entry of entries) {\n if (known.get(entry.id) !== entry.url)\n connect(entry)\n else\n directory.update(entry.id, { name: entry.name, ...(entry.serverVersion ? { serverVersion: entry.serverVersion } : {}) })\n }\n }\n\n sync()\n return {\n list: () => registry.list(),\n add: async (input) => {\n const entry = await registry.add(input)\n // Saved again (a new token or URL): reconnect with them, the entry kept.\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n remove: (id) => {\n const removed = registry.remove(id)\n sync()\n return removed\n },\n rename: (id, name) => {\n const entry = registry.rename(id, name)\n sync()\n return entry\n },\n setUrl: async (id, url) => {\n const entry = await registry.setUrl(id, url)\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n test: async (target) => {\n if (typeof target === 'object' && !('id' in target)) {\n if (!options.probeUnsaved)\n throw new Error('Testing an unsaved host is not available here.')\n return options.probeUnsaved(target)\n }\n const id = typeof target === 'string' ? target : target.id\n const result = await registry.test(id)\n if (result.ok) {\n directory.update(id, { serverName: result.hostRef.name, ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}) })\n loops.get(id)?.retry()\n }\n return result\n },\n retry: id => loops.get(id)?.retry(),\n retryAll: () => {\n for (const loop of loops.values())\n loop.retry()\n },\n stop: () => {\n for (const key of [...loops.keys()]) {\n disconnect(key)\n directory.remove(key)\n }\n },\n }\n}\n","/**\n * Saved servers over WebSocket: the registry in `dataDir`, the add form's\n * unsaved test, the refusal classification and (by default) the dial, wired\n * for `startSavedHosts`. Loaded behind each client's remote-hosts gate.\n */\nimport type { HostProbeResult } from '../../chat/hosts'\nimport type { HostFailureKind } from './connection-loop'\nimport type { SavedHostsController, SavedHostsOptions } from './saved-hosts'\nimport { HostIdentityError, probeUnsavedHost } from '../../chat/hosts'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\nimport { createWsHostRegistry, probeWsHost } from './probe'\nimport { startSavedHosts } from './saved-hosts'\n\n/**\n * A refused token stays refused until the user changes something: no retry\n * loop. Another protocol version stays until one side is upgraded: a slow re-check.\n * @param err - The error a connect attempt failed with.\n * @returns `auth` for a refused token, `identity` for another host answering, `protocol` for a version mismatch, `retry` otherwise.\n */\nexport function classifyWsFailure(err: unknown): HostFailureKind {\n if (err instanceof HostAuthError)\n return 'auth'\n if (err instanceof HostIdentityError)\n return 'identity'\n return err instanceof IpcVersionMismatchError ? 'protocol' : 'retry'\n}\n\n/**\n * The add form's \"test\": the registry's own checks and probe over WebSocket, saving nothing.\n * @param target - URL and token to try.\n * @returns The probe result.\n */\nexport function probeUnsavedWsHost(target: { url: string, token: string }): Promise<HostProbeResult> {\n return probeUnsavedHost(probeWsHost, target)\n}\n\n/**\n * Options for {@link startWsSavedHosts}: {@link SavedHostsOptions} with the registry, dialer and classifier filled in.\n * `dataDir` holds the saved-hosts registry file.\n */\nexport type WsSavedHostsOptions = Omit<SavedHostsOptions, 'registry' | 'connect' | 'classify' | 'probeUnsaved'> & {\n dataDir: string\n /** Client version in the server's diagnostics (default dial only). */\n appVersion?: string\n /** Dial another way (the TUI goes through its directory entry's transport). Default: `connectWsClient`. */\n connect?: SavedHostsOptions['connect']\n registry?: SavedHostsOptions['registry']\n}\n\n/**\n * Keeps the saved servers of a client connected over WebSocket.\n * Uses the registry in `dataDir` unless `registry` is given, and dials with {@link connectWsClient} unless `connect` is given.\n * @param options - Data directory, host directory and callbacks.\n * @returns A controller to list, add, remove, test and retry hosts, and to stop them all.\n */\nexport function startWsSavedHosts(options: WsSavedHostsOptions): SavedHostsController {\n const { dataDir, appVersion, connect, registry, ...rest } = options\n return startSavedHosts({\n ...rest,\n registry: registry ?? createWsHostRegistry({ dataDir }),\n classify: classifyWsFailure,\n probeUnsaved: probeUnsavedWsHost,\n connect: connect ?? ((entry, token, attempt) => connectWsClient({\n url: entry.url,\n token,\n expectHostId: entry.id,\n ...(appVersion ? { appVersion } : {}),\n signal: attempt.signal,\n onClose: attempt.onClose,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;AAYA,MAA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,WAAW,IAAI,CAAC;GACnC,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"ws-CA3o2nie.js","names":[],"sources":["../src/ipc/hosts/probe.ts","../src/ipc/hosts/saved-hosts.ts","../src/ipc/hosts/ws.ts"],"sourcesContent":["/**\n * The host registry's connection (`src/chat/hosts`): a WebSocket probe that\n * says who answers at a URL with a token, and the registry wired to it.\n */\nimport type { HostErrorCode, HostProbeResult, HostRegistry } from '../../chat/hosts'\nimport { createHostRegistry, displayHostUrl } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { hostCaBundle } from '../transports/tls-trust'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\n\n/** Bound on one probe: the upgrade, the handshake and `daemon.info`. */\nexport const HOST_PROBE_TIMEOUT_MS = 10_000\n\nconst TLS_FAILURE = /certificate|self[- ]signed|\\btls\\b|\\bssl\\b|UNABLE_TO_VERIFY|CERT_|ERR_TLS/i\n\nfunction classify(err: unknown): { error: HostErrorCode, message: string } {\n if (err instanceof HostAuthError) {\n return err.status === 401\n ? { error: 'auth', message: 'The host refused the token (401). Create a new one on the server: zidane server token create --name <device>.' }\n : { error: 'auth', message: err.message }\n }\n if (err instanceof IpcVersionMismatchError)\n return { error: 'protocol', message: err.message }\n const message = err instanceof Error ? err.message : String(err)\n if (TLS_FAILURE.test(message))\n return { error: 'tls', message: `TLS failed: ${message}` }\n return { error: 'unreachable', message }\n}\n\n/**\n * A failed WebSocket says nothing about why. For `wss://`, ask the same\n * address over HTTPS: a certificate or handshake failure there is a TLS\n * problem, anything else stays \"unreachable\".\n */\nasync function tlsFailure(url: string, signal: AbortSignal): Promise<string | null> {\n if (!url.startsWith('wss:'))\n return null\n try {\n // No token, and no redirect followed: only the TLS handshake with this origin matters.\n // The same CAs as the socket (Bun takes them per request; Node uses its process default).\n const ca = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' ? hostCaBundle() : null\n const response = await fetch(`https:${url.slice('wss:'.length)}`, { redirect: 'manual', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]), ...(ca ? { tls: { ca } } : {}) } as RequestInit)\n void response.body?.cancel().catch(() => {})\n return null\n }\n catch (err) {\n const e = err as { code?: unknown, message?: unknown }\n const detail = `${typeof e.code === 'string' ? e.code : ''} ${typeof e.message === 'string' ? e.message : ''}`\n return TLS_FAILURE.test(detail) ? `TLS failed: ${String(e.message ?? e.code)}` : null\n }\n}\n\n/**\n * Connect, read the host's identity and `daemon.info`, disconnect. Never throws.\n * @param target - URL, token and an optional timeout in milliseconds. The timeout defaults to {@link HOST_PROBE_TIMEOUT_MS}.\n * @returns Who answered and how fast, or a classified failure.\n */\nexport async function probeWsHost(target: { url: string, token: string, timeoutMs?: number }): Promise<HostProbeResult> {\n // The OS certificate store is read once per process, synchronously (seconds on a loaded\n // machine): read it before the deadline starts, or that cost is misread as a host with no answer.\n if (typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined' && /^wss:/i.test(target.url))\n hostCaBundle()\n const started = performance.now()\n const signal = AbortSignal.timeout(target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS)\n let client: Awaited<ReturnType<typeof connectWsClient>> | undefined\n try {\n client = await connectWsClient({ url: target.url, token: target.token, heartbeatMs: 0, signal })\n const hostRef = hostRefOf(client.hello)\n if (!hostRef)\n return { ok: false, error: 'protocol', message: `${displayHostUrl(target.url)} runs a zidane too old to say which host it is. Upgrade the server.` }\n const info = await client.request('daemon.info', {})\n const serverVersion = info.codeVersion ?? info.appVersion\n return { ok: true, hostRef, ...(serverVersion ? { serverVersion } : {}), latencyMs: Math.round(performance.now() - started) }\n }\n catch (err) {\n if (signal.aborted && !(err instanceof HostAuthError))\n return { ok: false, error: 'unreachable', message: `No answer from ${displayHostUrl(target.url)} within ${target.timeoutMs ?? HOST_PROBE_TIMEOUT_MS} ms.` }\n const classified = classify(err)\n if (classified.error === 'unreachable') {\n const tls = await tlsFailure(target.url, signal).catch(() => null)\n if (tls)\n return { ok: false, error: 'tls', message: tls }\n }\n return { ok: false, ...classified }\n }\n finally {\n client?.close()\n }\n}\n\n/**\n * The registry in `dataDir`, connecting over WebSocket.\n * @param options - Where the registry keeps its data.\n * @returns The host registry.\n */\nexport function createWsHostRegistry(options: { dataDir: string }): HostRegistry {\n return createHostRegistry({ dataDir: options.dataDir, probe: probeWsHost })\n}\n","/**\n * A client's saved servers, kept in its host directory: one directory entry\n * and one app-lifetime connection (`connection-loop`) per server in the\n * registry, in step with it. Shared by the TUI and the GUI main process,\n * which each supply their directory (`SavedHostsDirectory`) and how to dial.\n *\n * Saving a server that is already saved (same host id: a new token, a new\n * URL) reconfigures its entry IN PLACE and reconnects: the entry is never\n * removed, so the sessions routed to it stay routed. Only a server leaving\n * the registry (removed here or by another window) or `stop()` removes an\n * entry, and the directory decides what that means for an open session.\n *\n * Every connection is checked against the saved entry's id (the server's\n * `hostId` when it was added): another host answering at the URL is closed\n * at once, reported as `identity` and not retried, so nothing it says is\n * recorded under the saved id. Dialers may check first (`expectHostId`).\n *\n * No WebSocket import: the WebSocket wiring is `./ws.ts`.\n */\nimport type { HostEntry, HostProbeResult, HostRegistry, HostTestResult } from '../../chat/hosts'\nimport type { HostSignal } from '../protocol'\nimport type { IpcClient } from '../transports/client-core'\nimport type { HostConnectionLoop, HostConnectionPatch, HostFailureKind } from './connection-loop'\nimport { displayHostUrl, HostIdentityError } from '../../chat/hosts'\nimport { hostRefOf } from '../protocol'\nimport { keepHostConnected } from './connection-loop'\n\n/** The client's host directory, as the saved servers see it. Keys are host ids. */\nexport interface SavedHostsDirectory {\n /** The saved servers it holds now, with their URL (a `--host` server excluded). */\n saved: () => { key: string, url: string }[]\n /** Add the entry, or reconfigure the one under its key in place (status `connecting`). */\n upsert: (entry: HostEntry, token: string | undefined) => void\n /** Applies a connection patch, a new name or a server version to the entry. */\n update: (key: string, patch: HostConnectionPatch & { name?: string, serverVersion?: string }) => void\n /** The server left the registry, or the saved servers stopped. */\n remove: (key: string) => void\n}\n\n/** No token is saved for this server (removed by hand, or another window removed it). */\nexport class MissingHostTokenError extends Error {\n constructor() {\n super('No token saved for this server: add it again.')\n this.name = 'MissingHostTokenError'\n }\n}\n\n/** Options for {@link startSavedHosts}: the registry, the host directory, the connect function and callbacks. */\nexport interface SavedHostsOptions {\n /** The registry of saved servers. */\n registry: HostRegistry\n /** The client's host directory the entries are kept in. */\n directory: SavedHostsDirectory\n /** One connect attempt to a saved server, with its token read fresh. */\n connect: (entry: HostEntry, token: string, options: { signal: AbortSignal, onClose: () => void }) => Promise<IpcClient>\n /** `auth`: refused for good. A missing token is always `auth`, another host answering always `identity`. */\n classify?: (err: unknown) => HostFailureKind\n /** The add form's test of an unsaved URL + token (`probeUnsavedHost`). */\n probeUnsaved?: (target: { url: string, token: string }) => Promise<HostProbeResult>\n /** Saved entries the directory already reaches another way (the TUI's `--host` server). */\n skip?: (entry: HostEntry) => boolean\n /** Called with every signal of a connected saved server. */\n onSignal?: (key: string, signal: HostSignal) => void\n /** Called when a saved server connects, also after a reconnect. */\n onConnected?: (key: string, client: IpcClient) => void\n /** Called when a saved server's connection drops. */\n onDisconnected?: (key: string) => void\n /**\n * Lower backoff bound in milliseconds.\n * @default 1000\n */\n minDelayMs?: number\n /**\n * Upper backoff bound in milliseconds.\n * @default 30000\n */\n maxDelayMs?: number\n}\n\n/** Handle returned by {@link startSavedHosts} to list, add, remove, rename, test and retry saved servers. */\nexport interface SavedHostsController {\n /** The saved hosts, read fresh (other windows share the file). */\n list: () => HostEntry[]\n /** Verify, save, connect (in place when already saved). Throws a `HostRegistryError`. */\n add: (input: { url: string, token: string, name?: string }) => Promise<HostEntry>\n /** Removes a server from the registry and its entry from the directory. Returns whether it existed. */\n remove: (id: string) => boolean\n /** Renames a saved server and returns the updated entry. */\n rename: (id: string, name: string) => HostEntry\n /** Move a saved server to a new URL (its saved token; the same server must answer), then reconnect it in place. Throws a `HostRegistryError`. */\n setUrl: (id: string, url: string) => Promise<HostEntry>\n /** A saved server (by id), or an unsaved URL + token (the add form's test). */\n test: (target: string | { id: string } | { url: string, token: string }) => Promise<HostTestResult>\n /** Reconnect now (after an outage or a token fix). */\n retry: (id: string) => void\n /** Reconnect every saved server that is not connected now, its backoff reset (the computer woke up). */\n retryAll: () => void\n /** Disconnects every saved server and removes their directory entries. The registry is not changed. */\n stop: () => void\n}\n\n/**\n * Starts the connections of a client's saved servers and keeps the directory in step with the registry.\n * Each saved server gets a directory entry and a connection loop. A connection whose host id differs from the saved one is closed and reported as `identity`.\n * @param options - Registry, directory and how to dial.\n * @returns A controller over the saved servers.\n */\nexport function startSavedHosts(options: SavedHostsOptions): SavedHostsController {\n const { registry, directory, skip = () => false } = options\n const classify = (err: unknown): HostFailureKind => err instanceof MissingHostTokenError ? 'auth' : err instanceof HostIdentityError ? 'identity' : (options.classify?.(err) ?? 'retry')\n\n /** The saved server, or nobody: a connection from another host is closed before anyone sees it. */\n const dial = async (entry: HostEntry, token: string, attempt: { signal: AbortSignal, onClose: () => void }): Promise<IpcClient> => {\n const client = await options.connect(entry, token, attempt)\n const ref = hostRefOf(client.hello)\n if (ref?.id === entry.id)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(entry.url), ref?.name)\n }\n const loops = new Map<string, HostConnectionLoop>()\n\n const disconnect = (key: string): void => {\n loops.get(key)?.stop()\n loops.delete(key)\n }\n\n /** (Re)connect `entry` with the token saved now, its directory entry kept or created in place. */\n const connect = (entry: HostEntry): void => {\n const key = entry.id\n disconnect(key)\n directory.upsert(entry, registry.token(key))\n loops.set(key, keepHostConnected({\n connect: (attempt) => {\n const token = registry.token(key)\n return token ? dial(entry, token, attempt) : Promise.reject(new MissingHostTokenError())\n },\n update: patch => directory.update(key, patch),\n classify,\n ...(options.onSignal ? { onSignal: (signal: HostSignal) => options.onSignal!(key, signal) } : {}),\n ...(options.onConnected ? { onConnected: (client: IpcClient) => options.onConnected!(key, client) } : {}),\n ...(options.onDisconnected ? { onDisconnected: () => options.onDisconnected!(key) } : {}),\n ...(options.minDelayMs !== undefined ? { minDelayMs: options.minDelayMs } : {}),\n ...(options.maxDelayMs !== undefined ? { maxDelayMs: options.maxDelayMs } : {}),\n }))\n }\n\n /** Bring the directory in line with the saved hosts. */\n const sync = (): void => {\n const entries = registry.list().filter(entry => !skip(entry))\n const saved = new Set(entries.map(entry => entry.id))\n const known = new Map(directory.saved().map(host => [host.key, host.url]))\n for (const key of known.keys()) {\n if (!saved.has(key)) {\n disconnect(key)\n directory.remove(key)\n }\n }\n for (const entry of entries) {\n if (known.get(entry.id) !== entry.url)\n connect(entry)\n else\n directory.update(entry.id, { name: entry.name, ...(entry.serverVersion ? { serverVersion: entry.serverVersion } : {}) })\n }\n }\n\n sync()\n return {\n list: () => registry.list(),\n add: async (input) => {\n const entry = await registry.add(input)\n // Saved again (a new token or URL): reconnect with them, the entry kept.\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n remove: (id) => {\n const removed = registry.remove(id)\n sync()\n return removed\n },\n rename: (id, name) => {\n const entry = registry.rename(id, name)\n sync()\n return entry\n },\n setUrl: async (id, url) => {\n const entry = await registry.setUrl(id, url)\n if (!skip(entry))\n connect(entry)\n sync()\n return entry\n },\n test: async (target) => {\n if (typeof target === 'object' && !('id' in target)) {\n if (!options.probeUnsaved)\n throw new Error('Testing an unsaved host is not available here.')\n return options.probeUnsaved(target)\n }\n const id = typeof target === 'string' ? target : target.id\n const result = await registry.test(id)\n if (result.ok) {\n directory.update(id, { serverName: result.hostRef.name, ...(result.serverVersion ? { serverVersion: result.serverVersion } : {}) })\n loops.get(id)?.retry()\n }\n return result\n },\n retry: id => loops.get(id)?.retry(),\n retryAll: () => {\n for (const loop of loops.values())\n loop.retry()\n },\n stop: () => {\n for (const key of [...loops.keys()]) {\n disconnect(key)\n directory.remove(key)\n }\n },\n }\n}\n","/**\n * Saved servers over WebSocket: the registry in `dataDir`, the add form's\n * unsaved test, the refusal classification and (by default) the dial, wired\n * for `startSavedHosts`. Loaded behind each client's remote-hosts gate.\n */\nimport type { HostProbeResult } from '../../chat/hosts'\nimport type { HostFailureKind } from './connection-loop'\nimport type { SavedHostsController, SavedHostsOptions } from './saved-hosts'\nimport { HostIdentityError, probeUnsavedHost } from '../../chat/hosts'\nimport { IpcVersionMismatchError } from '../transports/client-core'\nimport { connectWsClient, HostAuthError } from '../transports/ws-client'\nimport { createWsHostRegistry, probeWsHost } from './probe'\nimport { startSavedHosts } from './saved-hosts'\n\n/**\n * A refused token stays refused until the user changes something: no retry\n * loop. Another protocol version stays until one side is upgraded: a slow re-check.\n * @param err - The error a connect attempt failed with.\n * @returns `auth` for a refused token, `identity` for another host answering, `protocol` for a version mismatch, `retry` otherwise.\n */\nexport function classifyWsFailure(err: unknown): HostFailureKind {\n if (err instanceof HostAuthError)\n return 'auth'\n if (err instanceof HostIdentityError)\n return 'identity'\n return err instanceof IpcVersionMismatchError ? 'protocol' : 'retry'\n}\n\n/**\n * The add form's \"test\": the registry's own checks and probe over WebSocket, saving nothing.\n * @param target - URL and token to try.\n * @returns The probe result.\n */\nexport function probeUnsavedWsHost(target: { url: string, token: string }): Promise<HostProbeResult> {\n return probeUnsavedHost(probeWsHost, target)\n}\n\n/**\n * Options for {@link startWsSavedHosts}: {@link SavedHostsOptions} with the registry, dialer and classifier filled in.\n * `dataDir` holds the saved-hosts registry file.\n */\nexport type WsSavedHostsOptions = Omit<SavedHostsOptions, 'registry' | 'connect' | 'classify' | 'probeUnsaved'> & {\n dataDir: string\n /** Client version in the server's diagnostics (default dial only). */\n appVersion?: string\n /** Dial another way (the TUI goes through its directory entry's transport). Default: `connectWsClient`. */\n connect?: SavedHostsOptions['connect']\n registry?: SavedHostsOptions['registry']\n}\n\n/**\n * Keeps the saved servers of a client connected over WebSocket.\n * Uses the registry in `dataDir` unless `registry` is given, and dials with {@link connectWsClient} unless `connect` is given.\n * @param options - Data directory, host directory and callbacks.\n * @returns A controller to list, add, remove, test and retry hosts, and to stop them all.\n */\nexport function startWsSavedHosts(options: WsSavedHostsOptions): SavedHostsController {\n const { dataDir, appVersion, connect, registry, ...rest } = options\n return startSavedHosts({\n ...rest,\n registry: registry ?? createWsHostRegistry({ dataDir }),\n classify: classifyWsFailure,\n probeUnsaved: probeUnsavedWsHost,\n connect: connect ?? ((entry, token, attempt) => connectWsClient({\n url: entry.url,\n token,\n expectHostId: entry.id,\n ...(appVersion ? { appVersion } : {}),\n signal: attempt.signal,\n onClose: attempt.onClose,\n })),\n })\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAa,wBAAwB;AAErC,MAAM,cAAc;AAEpB,SAAS,SAAS,KAAyD;CACzE,IAAI,eAAe,eACjB,OAAO,IAAI,WAAW,MAClB;EAAE,OAAO;EAAQ,SAAS;CAAgH,IAC1I;EAAE,OAAO;EAAQ,SAAS,IAAI;CAAQ;CAE5C,IAAI,eAAe,yBACjB,OAAO;EAAE,OAAO;EAAY,SAAS,IAAI;CAAQ;CACnD,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CAC/D,IAAI,YAAY,KAAK,OAAO,GAC1B,OAAO;EAAE,OAAO;EAAO,SAAS,eAAe;CAAU;CAC3D,OAAO;EAAE,OAAO;EAAe;CAAQ;AACzC;;;;;;AAOA,eAAe,WAAW,KAAa,QAA6C;CAClF,IAAI,CAAC,IAAI,WAAW,MAAM,GACxB,OAAO;CACT,IAAI;EAGF,MAAM,KAAK,OAAQ,WAAiC,QAAQ,cAAc,aAAa,IAAI;EAE3F,CAAK,MADkB,MAAM,SAAS,IAAI,MAAM,CAAa,KAAK;GAAE,UAAU;GAAU,QAAQ,YAAY,IAAI,CAAC,QAAQ,YAAY,QAAQ,GAAI,CAAC,CAAC;GAAG,GAAI,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC;EAAG,CAAgB,EAAA,CACvL,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,OAAO;CACT,SACO,KAA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mBAAmB,QAAkE;CACnG,OAAO,iBAAiB,aAAa,MAAM;AAC7C;;;;;;;AAqBA,SAAgB,kBAAkB,SAAoD;CACpF,MAAM,EAAE,SAAS,YAAY,SAAS,UAAU,GAAG,SAAS;CAC5D,OAAO,gBAAgB;EACrB,GAAG;EACH,UAAU,YAAY,qBAAqB,EAAE,QAAQ,CAAC;EACtD,UAAU;EACV,cAAc;EACd,SAAS,aAAa,OAAO,OAAO,YAAY,gBAAgB;GAC9D,KAAK,MAAM;GACX;GACA,cAAc,MAAM;GACpB,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;GACnC,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB,CAAC;CACH,CAAC;AACH"}
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.js";
2
2
  import { a as errorResponse, i as createJsonRpcEndpoint, o as successResponse } from "./json-rpc-G0rBfEar.js";
3
3
  import { i as METHOD_NOT_FOUND, t as HostIdentityError } from "./connection-BaHd3T-D.js";
4
- import { a as createSignalListeners, o as openIpcClient } from "./settings-keys-iI_Y-7MC.js";
4
+ import { a as createSignalListeners, o as openIpcClient } from "./settings-keys-BT0_oKjO.js";
5
5
  import { f as hostRefOf } from "./protocol-DOGyHgLQ.js";
6
6
  import { n as displayHostUrl } from "./url-znC3tmKE.js";
7
7
  import tls from "node:tls";
@@ -313,4 +313,4 @@ async function connectWsClient(options) {
313
313
  //#endregion
314
314
  export { hostCaBundle as a, ws_client_exports as i, HostBusyError as n, trustSystemCertificates as o, connectWsClient as r, HostAuthError as t };
315
315
 
316
- //# sourceMappingURL=ws-client-CFMbhsNq.js.map
316
+ //# sourceMappingURL=ws-client-C0iPAAzc.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ws-client-CFMbhsNq.js","names":["BunWebSocket"],"sources":["../src/ipc/transports/tls-trust.ts","../src/ipc/transports/ws-auth.ts","../src/ipc/transports/ws-client.ts"],"sourcesContent":["/**\n * Which certificate authorities a client trusts for a remote zidane-server:\n * the runtime's own roots plus the operating system's store (the macOS\n * keychain, the Linux CA bundle). A server behind a private CA, an mkcert\n * certificate or a self-signed one the user trusted in the OS then works\n * like a public one. `NODE_EXTRA_CA_CERTS` adds certificates at launch, in\n * both runtimes.\n *\n * Bun's WebSocket and fetch ignore `tls.setDefaultCACertificates`, so Bun\n * clients (the TUI, `zidane machine share`) pass the bundle with each\n * connection (`hostCaBundle`). Node honors it, so the desktop app's main\n * process trusts the store once, when it turns remote hosts on\n * (`trustSystemCertificates`).\n */\nimport tls from 'node:tls'\n\ntype CaKind = 'default' | 'system' | 'extra'\nconst api = tls as unknown as {\n getCACertificates?: (kind: CaKind) => string[]\n setDefaultCACertificates?: (certs: readonly string[]) => void\n}\n\nfunction certificates(kind: CaKind): string[] {\n try {\n return api.getCACertificates?.(kind) ?? []\n }\n catch {\n return []\n }\n}\n\nlet bundle: string[] | null | undefined\n\n/**\n * The runtime's roots, the OS store's and `NODE_EXTRA_CA_CERTS`'s, read once.\n * `null` when the OS store adds nothing (or can't be read): the runtime's\n * default then applies as it is.\n */\nexport function hostCaBundle(): string[] | null {\n if (bundle === undefined) {\n const system = certificates('system')\n bundle = system.length === 0 ? null : [...new Set([...certificates('default'), ...system, ...certificates('extra')])]\n }\n return bundle\n}\n\n/**\n * Node: every TLS client of this process trusts {@link hostCaBundle} from now\n * on (the desktop app's main process). Whether it applied.\n */\nexport function trustSystemCertificates(): boolean {\n const ca = hostCaBundle()\n if (!ca || !api.setDefaultCACertificates || typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined')\n return false\n api.setDefaultCACertificates(ca)\n return true\n}\n","/**\n * How a WebSocket client's token reaches the server, shared by both ends.\n *\n * Preferred: `Authorization: Bearer <token>` (Bun's WebSocket can set it).\n * Fallback for clients that can't set handshake headers (Node's and the\n * browser's WebSocket): a `zidane.bearer.<token>` entry in\n * `Sec-WebSocket-Protocol`, offered next to `zidane`, the subprotocol the\n * server selects. A token sent this way must be a valid subprotocol token\n * (base64url is).\n */\n\nimport type { ClientScope } from '../scopes'\n\n/** The subprotocol clients offer and the server selects. */\nexport const WS_SUBPROTOCOL = 'zidane'\n/** Prefix of the subprotocol entry carrying the bearer token. */\nexport const WS_BEARER_PREFIX = 'zidane.bearer.'\n\nexport type WsTokenCarrier = 'header' | 'subprotocol'\n\n/**\n * What an accepted connection is: a `client` (a window: the whole method\n * table, signals) or a `machine` lending its execution (`docs/MACHINES.md`:\n * only `ipc.hello`, `$/ping`, `machine.register`, never a peer). Default `client`.\n */\nexport type WsConnectionScope = 'client' | 'machine'\n\n/**\n * A server's answer to an upgrade's token. Accepted: `principal` names what\n * authenticated (a token id), so connections can be dropped by it later, and\n * `grant` is a client connection's reach (`../scopes`; absent: everything).\n * Refused: the HTTP status, sent before any JSON-RPC (401 no valid\n * credential, 403 a credential not allowed here).\n */\nexport type WsAuthVerdict\n = | { ok: true, principal?: string, scope?: WsConnectionScope, grant?: ClientScope }\n | { ok: false, status: 401 | 403, reason?: WsRefusalReason }\n\n/**\n * Why a server refused an upgrade with a 403, as a machine-readable code in\n * {@link WS_REFUSAL_HEADER}. Clients show a fixed text per code (never the\n * response body, which a proxy may fill with anything, the request's own\n * headers included) and ignore codes they don't know.\n */\nexport const WS_REFUSAL_HEADER = 'X-Zidane-Refusal'\nconst WS_REFUSAL_REASONS = ['origin', 'insecure-transport', 'untrusted-proxy', 'scope'] as const\nexport type WsRefusalReason = typeof WS_REFUSAL_REASONS[number]\n\nexport function isWsRefusalReason(value: unknown): value is WsRefusalReason {\n return typeof value === 'string' && (WS_REFUSAL_REASONS as readonly string[]).includes(value)\n}\n\n/** Subprotocols offered in `Sec-WebSocket-Protocol`. */\nexport function offeredSubprotocols(request: Request): string[] {\n return (request.headers.get('sec-websocket-protocol') ?? '').split(',').map(p => p.trim()).filter(Boolean)\n}\n\n/** The client's token: `Authorization: Bearer`, else the subprotocol entry. */\nexport function requestToken(request: Request): string | undefined {\n const auth = request.headers.get('authorization')\n const bearer = auth && /^Bearer\\s+(\\S+)$/i.exec(auth.trim())\n if (bearer)\n return bearer[1]\n const entry = offeredSubprotocols(request).find(p => p.startsWith(WS_BEARER_PREFIX))\n return entry ? entry.slice(WS_BEARER_PREFIX.length) : undefined\n}\n","/**\n * `IpcClient` over a WebSocket (a remote `zidane-server`, `./ws-server`):\n * one JSON-RPC message per text frame, the same handshake, deadlines and\n * signal delivery as the unix-socket client (`./client-core`).\n *\n * Uses the runtime's global `WebSocket` (Bun; Node >= 22), so it is safe in\n * the Node-imported `zidane/ipc` barrel. Unlike a local daemon client it\n * never asks the host to drain on a version mismatch (a remote server's\n * lifetime is not a client's to end) and opts out of the dev build fence.\n *\n * Opening is bounded (`openTimeoutMs`) and abortable (`signal`, up to the\n * end of the handshake). A refused upgrade is opaque to a WebSocket (no\n * status, just \"expected 101\", close 1002), so on failure the client asks\n * the same URL over plain HTTP, with the same token, why: a 401 or 403\n * becomes a {@link HostAuthError}, a 429 a {@link HostBusyError}, each with a\n * fixed message (the response body\n * is never read: a proxy may echo the request's headers, the token\n * included, and the message reaches a GUI renderer). That request never\n * follows a redirect: a 3xx is reported as a misconfigured URL, and the\n * token goes nowhere but the URL's own origin.\n *\n * Messages name the URL by scheme, host and path only (`displayHostUrl`).\n *\n * Certificates: the runtime's roots and the OS store (`./tls-trust`). Under\n * Bun the bundle goes with each socket and refusal probe; under Node the\n * process default applies (the desktop app sets it).\n */\nimport type { IpcClient } from './client-core'\nimport type { WsRefusalReason, WsTokenCarrier } from './ws-auth'\nimport { createJsonRpcEndpoint, errorResponse, successResponse } from '../../acp/json-rpc'\nimport { HostIdentityError, METHOD_NOT_FOUND } from '../../chat/hosts/connection'\nimport { displayHostUrl } from '../../chat/hosts/url'\nimport { hostRefOf } from '../protocol'\nimport { createSignalListeners, openIpcClient } from './client-core'\nimport { hostCaBundle } from './tls-trust'\nimport { isWsRefusalReason, WS_BEARER_PREFIX, WS_REFUSAL_HEADER, WS_SUBPROTOCOL } from './ws-auth'\n\n/** Options for {@link connectWsClient}. */\nexport interface WsClientOptions {\n /** `ws://` or `wss://` URL of the server. */\n url: string\n /** Bearer token for the server, see `./ws-auth`. */\n token?: string\n /**\n * How the token travels. Default: the `Authorization` header where the\n * runtime's WebSocket can set one (Bun), else the subprotocol fallback.\n */\n tokenCarrier?: WsTokenCarrier\n /** Client zidane version, surfaced in the host's diagnostics. */\n appVersion?: string\n /**\n * Certificate authorities (PEM) a `wss://` server's certificate may chain\n * to. Default: the runtime's roots and the OS store (`hostCaBundle`). Bun\n * only: under Node the process default applies.\n */\n ca?: readonly string[]\n /** The connection dropped (server exit, network error, a missed deadline or heartbeat). Not called for `close()`. */\n onClose?: () => void\n /** `$/ping` interval (`./client-core`). Default {@link WS_HEARTBEAT_MS}; `0` disables. */\n heartbeatMs?: number\n /** Bound on the upgrade (not the handshake, which has its own). Default {@link WS_OPEN_TIMEOUT_MS}. */\n openTimeoutMs?: number\n /** Abandon the connect (upgrade and handshake): it rejects with the signal's reason. */\n signal?: AbortSignal\n /**\n * The host id a saved host answered with when it was added: a hello with\n * any other id closes the connection and rejects with a\n * {@link HostIdentityError} (nothing is read from that host).\n */\n expectHostId?: string\n /**\n * Answer the host's requests and notifications on this connection: a\n * machine serving its host (`docs/MACHINES.md`). A throw becomes a\n * JSON-RPC error (its `code` when it carries one). Default: a client\n * refuses requests and reads only `ipc.signal`.\n */\n serve?: {\n request: (method: string, params: unknown) => Promise<unknown>\n notification?: (method: string, params: unknown) => void\n }\n}\n\n/** Heartbeat interval on both ends of a WebSocket by default. */\nexport const WS_HEARTBEAT_MS = 20_000\n/** How long an upgrade may take by default. */\nconst WS_OPEN_TIMEOUT_MS = 15_000\n\nconst FORBIDDEN: Record<WsRefusalReason, string> = {\n 'origin': 'this client\\'s origin is not allowed by the server (allowedOrigins)',\n 'insecure-transport': 'the server only accepts connections through its HTTPS proxy',\n 'untrusted-proxy': 'the server only accepts connections from its trusted proxies',\n 'scope': 'this token\\'s scope cannot open a client connection',\n}\n\n/**\n * The server refused this client's credential: 401 (no valid token) or 403\n * (not allowed here). `reason` only when the server sent a code clients know.\n */\nexport class HostAuthError extends Error {\n /** The server URL, scheme, host and path only. */\n readonly url: string\n /**\n * @param url - The server URL.\n * @param status - HTTP status of the refusal.\n * @param reason - Refusal code the server sent, when any.\n */\n constructor(url: string, readonly status: 401 | 403, readonly reason?: WsRefusalReason) {\n const shown = displayHostUrl(url)\n super(`WebSocket connection to ${shown} failed: ${status === 401\n ? 'token refused (401): the server does not know this token, or it was revoked. Create a new one on the server (zidane server token create --name <device>) and use it here'\n : `forbidden (403): ${reason ? FORBIDDEN[reason] : 'refused by the server or a proxy in front of it (origin, token scope or proxy rules)'}`}.`)\n this.name = 'HostAuthError'\n this.url = shown\n }\n}\n\n/** The server turned the upgrade down with a 429: too many open connections (per token, per address) or upgrades (per address). Transient. */\nexport class HostBusyError extends Error {\n /** @param url - The server URL. */\n constructor(url: string) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: too many connections or connection attempts (429). The server caps open connections per token and per address: close other windows that use this token, or wait a few seconds.`)\n this.name = 'HostBusyError'\n }\n}\n\n/** The URL answered with a redirect: not followed (the token would go along). */\nexport class HostRedirectError extends Error {\n constructor(url: string, status: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: the server redirects (${status}); not following it with the token. Check the URL (scheme, host, path) or the proxy in front of the server.`)\n this.name = 'HostRedirectError'\n }\n}\n\n/** Bun's WebSocket and fetch take handshake headers and TLS options; the WHATWG ones (Node, browsers) do not. */\nconst isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n\n/** Under Bun, the CAs to pass along for a `wss:` / `https:` URL; `null`: the runtime's default. */\nfunction bunCa(options: WsClientOptions): readonly string[] | null {\n return isBun() && /^(?:wss|https):/i.test(options.url) ? options.ca ?? hostCaBundle() : null\n}\n\nfunction createSocket(options: WsClientOptions): WebSocket {\n const protocols = [WS_SUBPROTOCOL]\n const carrier = options.tokenCarrier ?? (isBun() ? 'header' : 'subprotocol')\n if (options.token && carrier === 'subprotocol')\n protocols.push(`${WS_BEARER_PREFIX}${options.token}`)\n const headers = options.token && carrier === 'header' ? { Authorization: `Bearer ${options.token}` } : null\n const ca = bunCa(options)\n if (headers || ca) {\n // Bun's constructor extension: `{ headers, protocols, tls }` in place of the protocol list.\n const BunWebSocket = WebSocket as unknown as new (url: string, init: { headers?: Record<string, string>, protocols: string[], tls?: { ca: readonly string[] } }) => WebSocket\n return new BunWebSocket(options.url, { ...(headers ? { headers } : {}), protocols, ...(ca ? { tls: { ca } } : {}) })\n }\n return new WebSocket(options.url, protocols)\n}\n\n/** The upgrade took longer than `openTimeoutMs`: nothing answered, so there is no refusal to ask about. */\nclass WsOpenTimeoutError extends Error {\n constructor(url: string, timeoutMs: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} timed out after ${timeoutMs} ms.`)\n this.name = 'WsOpenTimeoutError'\n }\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new DOMException('The connect was aborted.', 'AbortError')\n}\n\n/** Resolves on `open`; rejects on failure, timeout or abort (closing the socket). */\nfunction opened(ws: WebSocket, url: string, timeoutMs: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const done = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (err?: Error): void => {\n if (done.signal.aborted)\n return\n done.abort()\n clearTimeout(timer)\n if (!err)\n return resolve()\n ws.close()\n reject(err)\n }\n const fail = (detail: string) => () => settle(new Error(`WebSocket connection to ${displayHostUrl(url)} failed${detail}.`))\n ws.addEventListener('open', () => settle(), { signal: done.signal })\n ws.addEventListener('error', fail(''), { signal: done.signal })\n ws.addEventListener('close', event => fail(` (close ${event.code}${event.reason ? `: ${event.reason}` : ''})`)(), { signal: done.signal })\n signal?.addEventListener('abort', () => settle(abortError(signal)), { signal: done.signal })\n timer = setTimeout(() => settle(new WsOpenTimeoutError(url, timeoutMs)), timeoutMs)\n })\n}\n\n/** Why an upgrade failed, asked over plain HTTP: a {@link HostAuthError} for 401 / 403, a {@link HostBusyError} for 429, a {@link HostRedirectError} for 3xx, else `null`. */\nasync function refusal(options: WsClientOptions): Promise<Error | null> {\n try {\n const url = new URL(options.url)\n url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'\n const timeout = AbortSignal.timeout(5000)\n const ca = bunCa(options)\n const response = await fetch(url, {\n headers: options.token ? { Authorization: `Bearer ${options.token}` } : {},\n redirect: 'manual',\n signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,\n // Bun's fetch extension, as for the socket.\n ...(ca ? { tls: { ca } } : {}),\n } as RequestInit)\n void response.body?.cancel().catch(() => {})\n if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400))\n return new HostRedirectError(options.url, response.status)\n if (response.status === 429)\n return new HostBusyError(options.url)\n if (response.status !== 401 && response.status !== 403)\n return null\n const reason = response.headers.get(WS_REFUSAL_HEADER)\n return new HostAuthError(options.url, response.status, response.status === 403 && isWsRefusalReason(reason) ? reason : undefined)\n }\n catch {\n return null\n }\n}\n\n/** Close a connection whose host is not the one expected, and say so. */\nfunction checkIdentity(client: IpcClient, options: WsClientOptions): IpcClient {\n if (options.expectHostId === undefined)\n return client\n const ref = hostRefOf(client.hello)\n if (ref?.id === options.expectHostId)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(options.url), ref?.name)\n}\n\n/**\n * Connects to a remote zidane server over WebSocket and completes the `ipc.hello` handshake.\n * A refused upgrade rejects with {@link HostAuthError} for a 401 or 403, and {@link HostBusyError} for a 429. A hello from another host than `expectHostId` rejects with `HostIdentityError`. A version mismatch rejects with {@link IpcVersionMismatchError} and leaves the server running.\n * @param options - Server URL, token and connection settings.\n * @returns A typed client.\n * @example\n * ```ts\n * import { connectWsClient } from 'zidane/ipc/remote'\n *\n * const client = await connectWsClient({\n * url: 'wss://zidane.example.com/',\n * token: process.env.ZIDANE_HOST_TOKEN,\n * })\n * const sessions = await client.request('sessions.list', {})\n * console.log(sessions.length)\n * client.close()\n * ```\n */\nexport async function connectWsClient(options: WsClientOptions): Promise<IpcClient> {\n const { signal } = options\n signal?.throwIfAborted()\n const ws = createSocket(options)\n ws.binaryType = 'arraybuffer'\n try {\n await opened(ws, options.url, options.openTimeoutMs ?? WS_OPEN_TIMEOUT_MS, signal)\n }\n catch (err) {\n if (signal?.aborted || err instanceof WsOpenTimeoutError)\n throw err\n throw (await refusal(options)) ?? err\n }\n\n const signals = createSignalListeners()\n let closed = false\n\n const rpc = createJsonRpcEndpoint({\n send: (json) => {\n try {\n ws.send(json)\n }\n catch {\n // A closing socket: the close handler fails what is pending.\n }\n },\n // The host never sends requests to clients, only notifications; a machine serves them.\n onRequest: async (message) => {\n const serve = options.serve\n if (!serve)\n return errorResponse(message.id, METHOD_NOT_FOUND, 'Clients do not accept requests.')\n try {\n return successResponse(message.id, (await serve.request(message.method, message.params)) ?? null)\n }\n catch (err) {\n const code = (err as { code?: unknown }).code\n return errorResponse(message.id, typeof code === 'number' ? code : -32000, err instanceof Error ? err.message : String(err))\n }\n },\n onNotification: (message) => {\n if (message.method === 'ipc.signal' || !options.serve?.notification)\n return signals.onNotification(message)\n options.serve.notification(message.method, (message as { params?: unknown }).params)\n },\n })\n\n const decoder = new TextDecoder()\n ws.addEventListener('message', (event: MessageEvent) => {\n if (closed)\n return\n rpc.receive(typeof event.data === 'string' ? event.data : decoder.decode(event.data as ArrayBuffer))\n })\n\n /** The host went away (or the connection was given up): fail what is pending, tell the owner. */\n const lost = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n options.onClose?.()\n }\n ws.addEventListener('close', lost)\n ws.addEventListener('error', () => {\n // 'close' follows.\n })\n\n const close = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n ws.close(1000)\n }\n\n // Aborted mid-handshake: the close fails the pending hello, and the connect rejects with the signal's reason.\n const onAbort = (): void => close()\n signal?.addEventListener('abort', onAbort, { once: true })\n try {\n return checkIdentity(await openIpcClient(\n {\n rpc,\n close,\n abort: () => {\n lost()\n ws.close(1000)\n },\n where: displayHostUrl(options.url),\n },\n signals.listeners,\n {\n ...(options.appVersion ? { appVersion: options.appVersion } : {}),\n drain: 'never',\n buildFence: false,\n heartbeatMs: options.heartbeatMs ?? WS_HEARTBEAT_MS,\n },\n ), options)\n }\n catch (err) {\n throw signal?.aborted ? abortError(signal) : err\n }\n finally {\n signal?.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,MAAM;AAKZ,SAAS,aAAa,MAAwB;CAC5C,IAAI;EACF,OAAO,IAAI,oBAAoB,IAAI,KAAK,CAAC;CAC3C,QACM;EACJ,OAAO,CAAC;CACV;AACF;AAEA,IAAI;;;;;;AAOJ,SAAgB,eAAgC;CAC9C,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,SAAS,aAAa,QAAQ;EACpC,SAAS,OAAO,WAAW,IAAI,OAAO,CAAC,mBAAG,IAAI,IAAI;GAAC,GAAG,aAAa,SAAS;GAAG,GAAG;GAAQ,GAAG,aAAa,OAAO;EAAC,CAAC,CAAC;CACtH;CACA,OAAO;AACT;;;;;AAMA,SAAgB,0BAAmC;CACjD,MAAM,KAAK,aAAa;CACxB,IAAI,CAAC,MAAM,CAAC,IAAI,4BAA4B,OAAQ,WAAiC,QAAQ,aAC3F,OAAO;CACT,IAAI,yBAAyB,EAAE;CAC/B,OAAO;AACT;;;;AC1CA,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;;;;;;AA4BhC,MAAa,oBAAoB;AACjC,MAAM,qBAAqB;CAAC;CAAU;CAAsB;CAAmB;AAAO;AAGtF,SAAgB,kBAAkB,OAA0C;CAC1E,OAAO,OAAO,UAAU,YAAa,mBAAyC,SAAS,KAAK;AAC9F;;;;;;;;;;;ACiCA,MAAa,kBAAkB;;AAE/B,MAAM,qBAAqB;AAE3B,MAAM,YAA6C;CACjD,UAAU;CACV,sBAAsB;CACtB,mBAAmB;CACnB,SAAS;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C;CAED,MAAM,cAAoB;EACxB,IAAI,QACF;EACF,SAAS;EACT,IAAI,MAAM;EACV,GAAG,MAAM,GAAI;CACf;CAGA,MAAM,gBAAsB,MAAM;CAClC,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CACzD,IAAI;EACF,OAAO,cAAc,MAAM,cACzB;GACE;GACA;GACA,aAAa;IACX,KAAK;IACL,GAAG,MAAM,GAAI;GACf;GACA,OAAO,eAAe,QAAQ,GAAG;EACnC,GACA,QAAQ,WACR;GACE,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;GAC/D,OAAO;GACP,YAAY;GACZ,aAAa,QAAQ,eAAA;EACvB,CACF,GAAG,OAAO;CACZ,SACO,KAAK;EACV,MAAM,QAAQ,UAAU,WAAW,MAAM,IAAI;CAC/C,UACQ;EACN,QAAQ,oBAAoB,SAAS,OAAO;CAC9C;AACF"}
1
+ {"version":3,"file":"ws-client-C0iPAAzc.js","names":["BunWebSocket"],"sources":["../src/ipc/transports/tls-trust.ts","../src/ipc/transports/ws-auth.ts","../src/ipc/transports/ws-client.ts"],"sourcesContent":["/**\n * Which certificate authorities a client trusts for a remote zidane-server:\n * the runtime's own roots plus the operating system's store (the macOS\n * keychain, the Linux CA bundle). A server behind a private CA, an mkcert\n * certificate or a self-signed one the user trusted in the OS then works\n * like a public one. `NODE_EXTRA_CA_CERTS` adds certificates at launch, in\n * both runtimes.\n *\n * Bun's WebSocket and fetch ignore `tls.setDefaultCACertificates`, so Bun\n * clients (the TUI, `zidane machine share`) pass the bundle with each\n * connection (`hostCaBundle`). Node honors it, so the desktop app's main\n * process trusts the store once, when it turns remote hosts on\n * (`trustSystemCertificates`).\n */\nimport tls from 'node:tls'\n\ntype CaKind = 'default' | 'system' | 'extra'\nconst api = tls as unknown as {\n getCACertificates?: (kind: CaKind) => string[]\n setDefaultCACertificates?: (certs: readonly string[]) => void\n}\n\nfunction certificates(kind: CaKind): string[] {\n try {\n return api.getCACertificates?.(kind) ?? []\n }\n catch {\n return []\n }\n}\n\nlet bundle: string[] | null | undefined\n\n/**\n * The runtime's roots, the OS store's and `NODE_EXTRA_CA_CERTS`'s, read once.\n * `null` when the OS store adds nothing (or can't be read): the runtime's\n * default then applies as it is.\n */\nexport function hostCaBundle(): string[] | null {\n if (bundle === undefined) {\n const system = certificates('system')\n bundle = system.length === 0 ? null : [...new Set([...certificates('default'), ...system, ...certificates('extra')])]\n }\n return bundle\n}\n\n/**\n * Node: every TLS client of this process trusts {@link hostCaBundle} from now\n * on (the desktop app's main process). Whether it applied.\n */\nexport function trustSystemCertificates(): boolean {\n const ca = hostCaBundle()\n if (!ca || !api.setDefaultCACertificates || typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined')\n return false\n api.setDefaultCACertificates(ca)\n return true\n}\n","/**\n * How a WebSocket client's token reaches the server, shared by both ends.\n *\n * Preferred: `Authorization: Bearer <token>` (Bun's WebSocket can set it).\n * Fallback for clients that can't set handshake headers (Node's and the\n * browser's WebSocket): a `zidane.bearer.<token>` entry in\n * `Sec-WebSocket-Protocol`, offered next to `zidane`, the subprotocol the\n * server selects. A token sent this way must be a valid subprotocol token\n * (base64url is).\n */\n\nimport type { ClientScope } from '../scopes'\n\n/** The subprotocol clients offer and the server selects. */\nexport const WS_SUBPROTOCOL = 'zidane'\n/** Prefix of the subprotocol entry carrying the bearer token. */\nexport const WS_BEARER_PREFIX = 'zidane.bearer.'\n\nexport type WsTokenCarrier = 'header' | 'subprotocol'\n\n/**\n * What an accepted connection is: a `client` (a window: the whole method\n * table, signals) or a `machine` lending its execution (`docs/MACHINES.md`:\n * only `ipc.hello`, `$/ping`, `machine.register`, never a peer). Default `client`.\n */\nexport type WsConnectionScope = 'client' | 'machine'\n\n/**\n * A server's answer to an upgrade's token. Accepted: `principal` names what\n * authenticated (a token id), so connections can be dropped by it later, and\n * `grant` is a client connection's reach (`../scopes`; absent: everything).\n * Refused: the HTTP status, sent before any JSON-RPC (401 no valid\n * credential, 403 a credential not allowed here).\n */\nexport type WsAuthVerdict\n = | { ok: true, principal?: string, scope?: WsConnectionScope, grant?: ClientScope }\n | { ok: false, status: 401 | 403, reason?: WsRefusalReason }\n\n/**\n * Why a server refused an upgrade with a 403, as a machine-readable code in\n * {@link WS_REFUSAL_HEADER}. Clients show a fixed text per code (never the\n * response body, which a proxy may fill with anything, the request's own\n * headers included) and ignore codes they don't know.\n */\nexport const WS_REFUSAL_HEADER = 'X-Zidane-Refusal'\nconst WS_REFUSAL_REASONS = ['origin', 'insecure-transport', 'untrusted-proxy', 'scope'] as const\nexport type WsRefusalReason = typeof WS_REFUSAL_REASONS[number]\n\nexport function isWsRefusalReason(value: unknown): value is WsRefusalReason {\n return typeof value === 'string' && (WS_REFUSAL_REASONS as readonly string[]).includes(value)\n}\n\n/** Subprotocols offered in `Sec-WebSocket-Protocol`. */\nexport function offeredSubprotocols(request: Request): string[] {\n return (request.headers.get('sec-websocket-protocol') ?? '').split(',').map(p => p.trim()).filter(Boolean)\n}\n\n/** The client's token: `Authorization: Bearer`, else the subprotocol entry. */\nexport function requestToken(request: Request): string | undefined {\n const auth = request.headers.get('authorization')\n const bearer = auth && /^Bearer\\s+(\\S+)$/i.exec(auth.trim())\n if (bearer)\n return bearer[1]\n const entry = offeredSubprotocols(request).find(p => p.startsWith(WS_BEARER_PREFIX))\n return entry ? entry.slice(WS_BEARER_PREFIX.length) : undefined\n}\n","/**\n * `IpcClient` over a WebSocket (a remote `zidane-server`, `./ws-server`):\n * one JSON-RPC message per text frame, the same handshake, deadlines and\n * signal delivery as the unix-socket client (`./client-core`).\n *\n * Uses the runtime's global `WebSocket` (Bun; Node >= 22), so it is safe in\n * the Node-imported `zidane/ipc` barrel. Unlike a local daemon client it\n * never asks the host to drain on a version mismatch (a remote server's\n * lifetime is not a client's to end) and opts out of the dev build fence.\n *\n * Opening is bounded (`openTimeoutMs`) and abortable (`signal`, up to the\n * end of the handshake). A refused upgrade is opaque to a WebSocket (no\n * status, just \"expected 101\", close 1002), so on failure the client asks\n * the same URL over plain HTTP, with the same token, why: a 401 or 403\n * becomes a {@link HostAuthError}, a 429 a {@link HostBusyError}, each with a\n * fixed message (the response body\n * is never read: a proxy may echo the request's headers, the token\n * included, and the message reaches a GUI renderer). That request never\n * follows a redirect: a 3xx is reported as a misconfigured URL, and the\n * token goes nowhere but the URL's own origin.\n *\n * Messages name the URL by scheme, host and path only (`displayHostUrl`).\n *\n * Certificates: the runtime's roots and the OS store (`./tls-trust`). Under\n * Bun the bundle goes with each socket and refusal probe; under Node the\n * process default applies (the desktop app sets it).\n */\nimport type { IpcClient } from './client-core'\nimport type { WsRefusalReason, WsTokenCarrier } from './ws-auth'\nimport { createJsonRpcEndpoint, errorResponse, successResponse } from '../../acp/json-rpc'\nimport { HostIdentityError, METHOD_NOT_FOUND } from '../../chat/hosts/connection'\nimport { displayHostUrl } from '../../chat/hosts/url'\nimport { hostRefOf } from '../protocol'\nimport { createSignalListeners, openIpcClient } from './client-core'\nimport { hostCaBundle } from './tls-trust'\nimport { isWsRefusalReason, WS_BEARER_PREFIX, WS_REFUSAL_HEADER, WS_SUBPROTOCOL } from './ws-auth'\n\n/** Options for {@link connectWsClient}. */\nexport interface WsClientOptions {\n /** `ws://` or `wss://` URL of the server. */\n url: string\n /** Bearer token for the server, see `./ws-auth`. */\n token?: string\n /**\n * How the token travels. Default: the `Authorization` header where the\n * runtime's WebSocket can set one (Bun), else the subprotocol fallback.\n */\n tokenCarrier?: WsTokenCarrier\n /** Client zidane version, surfaced in the host's diagnostics. */\n appVersion?: string\n /**\n * Certificate authorities (PEM) a `wss://` server's certificate may chain\n * to. Default: the runtime's roots and the OS store (`hostCaBundle`). Bun\n * only: under Node the process default applies.\n */\n ca?: readonly string[]\n /** The connection dropped (server exit, network error, a missed deadline or heartbeat). Not called for `close()`. */\n onClose?: () => void\n /** `$/ping` interval (`./client-core`). Default {@link WS_HEARTBEAT_MS}; `0` disables. */\n heartbeatMs?: number\n /** Bound on the upgrade (not the handshake, which has its own). Default {@link WS_OPEN_TIMEOUT_MS}. */\n openTimeoutMs?: number\n /** Abandon the connect (upgrade and handshake): it rejects with the signal's reason. */\n signal?: AbortSignal\n /**\n * The host id a saved host answered with when it was added: a hello with\n * any other id closes the connection and rejects with a\n * {@link HostIdentityError} (nothing is read from that host).\n */\n expectHostId?: string\n /**\n * Answer the host's requests and notifications on this connection: a\n * machine serving its host (`docs/MACHINES.md`). A throw becomes a\n * JSON-RPC error (its `code` when it carries one). Default: a client\n * refuses requests and reads only `ipc.signal`.\n */\n serve?: {\n request: (method: string, params: unknown) => Promise<unknown>\n notification?: (method: string, params: unknown) => void\n }\n}\n\n/** Heartbeat interval on both ends of a WebSocket by default. */\nexport const WS_HEARTBEAT_MS = 20_000\n/** How long an upgrade may take by default. */\nconst WS_OPEN_TIMEOUT_MS = 15_000\n\nconst FORBIDDEN: Record<WsRefusalReason, string> = {\n 'origin': 'this client\\'s origin is not allowed by the server (allowedOrigins)',\n 'insecure-transport': 'the server only accepts connections through its HTTPS proxy',\n 'untrusted-proxy': 'the server only accepts connections from its trusted proxies',\n 'scope': 'this token\\'s scope cannot open a client connection',\n}\n\n/**\n * The server refused this client's credential: 401 (no valid token) or 403\n * (not allowed here). `reason` only when the server sent a code clients know.\n */\nexport class HostAuthError extends Error {\n /** The server URL, scheme, host and path only. */\n readonly url: string\n /**\n * @param url - The server URL.\n * @param status - HTTP status of the refusal.\n * @param reason - Refusal code the server sent, when any.\n */\n constructor(url: string, readonly status: 401 | 403, readonly reason?: WsRefusalReason) {\n const shown = displayHostUrl(url)\n super(`WebSocket connection to ${shown} failed: ${status === 401\n ? 'token refused (401): the server does not know this token, or it was revoked. Create a new one on the server (zidane server token create --name <device>) and use it here'\n : `forbidden (403): ${reason ? FORBIDDEN[reason] : 'refused by the server or a proxy in front of it (origin, token scope or proxy rules)'}`}.`)\n this.name = 'HostAuthError'\n this.url = shown\n }\n}\n\n/** The server turned the upgrade down with a 429: too many open connections (per token, per address) or upgrades (per address). Transient. */\nexport class HostBusyError extends Error {\n /** @param url - The server URL. */\n constructor(url: string) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: too many connections or connection attempts (429). The server caps open connections per token and per address: close other windows that use this token, or wait a few seconds.`)\n this.name = 'HostBusyError'\n }\n}\n\n/** The URL answered with a redirect: not followed (the token would go along). */\nexport class HostRedirectError extends Error {\n constructor(url: string, status: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} failed: the server redirects (${status}); not following it with the token. Check the URL (scheme, host, path) or the proxy in front of the server.`)\n this.name = 'HostRedirectError'\n }\n}\n\n/** Bun's WebSocket and fetch take handshake headers and TLS options; the WHATWG ones (Node, browsers) do not. */\nconst isBun = (): boolean => typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined'\n\n/** Under Bun, the CAs to pass along for a `wss:` / `https:` URL; `null`: the runtime's default. */\nfunction bunCa(options: WsClientOptions): readonly string[] | null {\n return isBun() && /^(?:wss|https):/i.test(options.url) ? options.ca ?? hostCaBundle() : null\n}\n\nfunction createSocket(options: WsClientOptions): WebSocket {\n const protocols = [WS_SUBPROTOCOL]\n const carrier = options.tokenCarrier ?? (isBun() ? 'header' : 'subprotocol')\n if (options.token && carrier === 'subprotocol')\n protocols.push(`${WS_BEARER_PREFIX}${options.token}`)\n const headers = options.token && carrier === 'header' ? { Authorization: `Bearer ${options.token}` } : null\n const ca = bunCa(options)\n if (headers || ca) {\n // Bun's constructor extension: `{ headers, protocols, tls }` in place of the protocol list.\n const BunWebSocket = WebSocket as unknown as new (url: string, init: { headers?: Record<string, string>, protocols: string[], tls?: { ca: readonly string[] } }) => WebSocket\n return new BunWebSocket(options.url, { ...(headers ? { headers } : {}), protocols, ...(ca ? { tls: { ca } } : {}) })\n }\n return new WebSocket(options.url, protocols)\n}\n\n/** The upgrade took longer than `openTimeoutMs`: nothing answered, so there is no refusal to ask about. */\nclass WsOpenTimeoutError extends Error {\n constructor(url: string, timeoutMs: number) {\n super(`WebSocket connection to ${displayHostUrl(url)} timed out after ${timeoutMs} ms.`)\n this.name = 'WsOpenTimeoutError'\n }\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new DOMException('The connect was aborted.', 'AbortError')\n}\n\n/** Resolves on `open`; rejects on failure, timeout or abort (closing the socket). */\nfunction opened(ws: WebSocket, url: string, timeoutMs: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n const done = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const settle = (err?: Error): void => {\n if (done.signal.aborted)\n return\n done.abort()\n clearTimeout(timer)\n if (!err)\n return resolve()\n ws.close()\n reject(err)\n }\n const fail = (detail: string) => () => settle(new Error(`WebSocket connection to ${displayHostUrl(url)} failed${detail}.`))\n ws.addEventListener('open', () => settle(), { signal: done.signal })\n ws.addEventListener('error', fail(''), { signal: done.signal })\n ws.addEventListener('close', event => fail(` (close ${event.code}${event.reason ? `: ${event.reason}` : ''})`)(), { signal: done.signal })\n signal?.addEventListener('abort', () => settle(abortError(signal)), { signal: done.signal })\n timer = setTimeout(() => settle(new WsOpenTimeoutError(url, timeoutMs)), timeoutMs)\n })\n}\n\n/** Why an upgrade failed, asked over plain HTTP: a {@link HostAuthError} for 401 / 403, a {@link HostBusyError} for 429, a {@link HostRedirectError} for 3xx, else `null`. */\nasync function refusal(options: WsClientOptions): Promise<Error | null> {\n try {\n const url = new URL(options.url)\n url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'\n const timeout = AbortSignal.timeout(5000)\n const ca = bunCa(options)\n const response = await fetch(url, {\n headers: options.token ? { Authorization: `Bearer ${options.token}` } : {},\n redirect: 'manual',\n signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,\n // Bun's fetch extension, as for the socket.\n ...(ca ? { tls: { ca } } : {}),\n } as RequestInit)\n void response.body?.cancel().catch(() => {})\n if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400))\n return new HostRedirectError(options.url, response.status)\n if (response.status === 429)\n return new HostBusyError(options.url)\n if (response.status !== 401 && response.status !== 403)\n return null\n const reason = response.headers.get(WS_REFUSAL_HEADER)\n return new HostAuthError(options.url, response.status, response.status === 403 && isWsRefusalReason(reason) ? reason : undefined)\n }\n catch {\n return null\n }\n}\n\n/** Close a connection whose host is not the one expected, and say so. */\nfunction checkIdentity(client: IpcClient, options: WsClientOptions): IpcClient {\n if (options.expectHostId === undefined)\n return client\n const ref = hostRefOf(client.hello)\n if (ref?.id === options.expectHostId)\n return client\n client.close()\n throw new HostIdentityError(displayHostUrl(options.url), ref?.name)\n}\n\n/**\n * Connects to a remote zidane server over WebSocket and completes the `ipc.hello` handshake.\n * A refused upgrade rejects with {@link HostAuthError} for a 401 or 403, and {@link HostBusyError} for a 429. A hello from another host than `expectHostId` rejects with `HostIdentityError`. A version mismatch rejects with {@link IpcVersionMismatchError} and leaves the server running.\n * @param options - Server URL, token and connection settings.\n * @returns A typed client.\n * @example\n * ```ts\n * import { connectWsClient } from 'zidane/ipc/remote'\n *\n * const client = await connectWsClient({\n * url: 'wss://zidane.example.com/',\n * token: process.env.ZIDANE_HOST_TOKEN,\n * })\n * const sessions = await client.request('sessions.list', {})\n * console.log(sessions.length)\n * client.close()\n * ```\n */\nexport async function connectWsClient(options: WsClientOptions): Promise<IpcClient> {\n const { signal } = options\n signal?.throwIfAborted()\n const ws = createSocket(options)\n ws.binaryType = 'arraybuffer'\n try {\n await opened(ws, options.url, options.openTimeoutMs ?? WS_OPEN_TIMEOUT_MS, signal)\n }\n catch (err) {\n if (signal?.aborted || err instanceof WsOpenTimeoutError)\n throw err\n throw (await refusal(options)) ?? err\n }\n\n const signals = createSignalListeners()\n let closed = false\n\n const rpc = createJsonRpcEndpoint({\n send: (json) => {\n try {\n ws.send(json)\n }\n catch {\n // A closing socket: the close handler fails what is pending.\n }\n },\n // The host never sends requests to clients, only notifications; a machine serves them.\n onRequest: async (message) => {\n const serve = options.serve\n if (!serve)\n return errorResponse(message.id, METHOD_NOT_FOUND, 'Clients do not accept requests.')\n try {\n return successResponse(message.id, (await serve.request(message.method, message.params)) ?? null)\n }\n catch (err) {\n const code = (err as { code?: unknown }).code\n return errorResponse(message.id, typeof code === 'number' ? code : -32000, err instanceof Error ? err.message : String(err))\n }\n },\n onNotification: (message) => {\n if (message.method === 'ipc.signal' || !options.serve?.notification)\n return signals.onNotification(message)\n options.serve.notification(message.method, (message as { params?: unknown }).params)\n },\n })\n\n const decoder = new TextDecoder()\n ws.addEventListener('message', (event: MessageEvent) => {\n if (closed)\n return\n rpc.receive(typeof event.data === 'string' ? event.data : decoder.decode(event.data as ArrayBuffer))\n })\n\n /** The host went away (or the connection was given up): fail what is pending, tell the owner. */\n const lost = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n options.onClose?.()\n }\n ws.addEventListener('close', lost)\n ws.addEventListener('error', () => {\n // 'close' follows.\n })\n\n const close = (): void => {\n if (closed)\n return\n closed = true\n rpc.close()\n ws.close(1000)\n }\n\n // Aborted mid-handshake: the close fails the pending hello, and the connect rejects with the signal's reason.\n const onAbort = (): void => close()\n signal?.addEventListener('abort', onAbort, { once: true })\n try {\n return checkIdentity(await openIpcClient(\n {\n rpc,\n close,\n abort: () => {\n lost()\n ws.close(1000)\n },\n where: displayHostUrl(options.url),\n },\n signals.listeners,\n {\n ...(options.appVersion ? { appVersion: options.appVersion } : {}),\n drain: 'never',\n buildFence: false,\n heartbeatMs: options.heartbeatMs ?? WS_HEARTBEAT_MS,\n },\n ), options)\n }\n catch (err) {\n throw signal?.aborted ? abortError(signal) : err\n }\n finally {\n signal?.removeEventListener('abort', onAbort)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,MAAM;AAKZ,SAAS,aAAa,MAAwB;CAC5C,IAAI;EACF,OAAO,IAAI,oBAAoB,IAAI,KAAK,CAAC;CAC3C,QACM;EACJ,OAAO,CAAC;CACV;AACF;AAEA,IAAI;;;;;;AAOJ,SAAgB,eAAgC;CAC9C,IAAI,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UAAU,WAAW,MAAM,IAAI;CAC/C,UACQ;EACN,QAAQ,oBAAoB,SAAS,OAAO;CAC9C;AACF"}
package/docs/CHAT.md CHANGED
@@ -40,6 +40,7 @@ A bundler that targets the web (Vite, webpack, esbuild, rolldown) resolves `zida
40
40
  - [Edit-diff rendering](#edit-diff-rendering)
41
41
  - [Per-edit approval](#per-edit-approval)
42
42
  - [Tool call display](#tool-call-display)
43
+ - [Running a reply's shell blocks](#running-a-replys-shell-blocks)
43
44
  - [Session reconstruction](#session-reconstruction)
44
45
  - [Streaming buffer](#streaming-buffer)
45
46
  - [`StreamEvent`](#streamevent)
@@ -705,6 +706,60 @@ Todos 5 items · 2 done · 1 in progress · 2 pending
705
706
  - `TOOL_DISPLAY` is the registry. Hosts add entries by spreading: `{ ...TOOL_DISPLAY, my_tool: { displayName, format } }`.
706
707
  - The render path needs `tool: string` (registry key) and `input?: Record<string, unknown>` on the event. `tool:before` and `child:tool:before` populate them live, and `eventsFromTurns` populates them on replay. A persisted event without `input` falls back to `↳ <name>`.
707
708
 
709
+ ## Running a reply's shell blocks
710
+
711
+ A shell block in a settled reply (a fence tagged `bash`, `sh`, `shell`,
712
+ `zsh` or `console`) has a Play button, shown on hover. Its menu runs the
713
+ block in one of two ways:
714
+
715
+ - **Run here** runs the block on the session's host, in the session's folder,
716
+ with no input (`</dev/null`). The output streams into a panel under the
717
+ block. The host saves the last run of each block in the session's metadata
718
+ (`blockRuns`), so the panel comes back after a reload. A run never enters
719
+ the conversation, and the model never sees it.
720
+ - **Run in a terminal** opens a new terminal of the session and types the
721
+ block into it. Use it for a command that asks for input.
722
+
723
+ What runs comes from `shellBlockPlan` (`src/chat/shell-blocks.ts`). When
724
+ some lines of a block start with `$ `, only those lines run, without the
725
+ prompt: the other lines are output. A one-line block runs as `<shell> -c`. A block of several lines
726
+ runs as one temporary script (`mktemp`, removed after). The shell is `zsh`
727
+ or `sh` when the fence names it, else `bash`.
728
+
729
+ The host (`createBlockRunMethods`, `src/chat/host/block-runs.ts`) stops a
730
+ run after 10 minutes (`BLOCK_RUN_TIMEOUT_MS`) and keeps the last 64 KB of its
731
+ output (`BLOCK_RUN_OUTPUT_CAP`). A session keeps at most 50 runs
732
+ (`BLOCK_RUNS_MAX`), and a run whose turn is gone is dropped. A run's key is
733
+ its turn id and a hash of its code (`blockRunKey`). Saving a run does not
734
+ change the session's `updatedAt`.
735
+
736
+ Over IPC: `sessions.runBlock` starts a run and answers `{ runId }`. The
737
+ output comes as `block-run:data` signals, and the end as `block-run:end`
738
+ with the saved run. `sessions.runBlockCancel` stops a run.
739
+ `sessions.blockRuns` and `sessions.removeBlockRun` read and remove saved
740
+ runs, and `block-runs:changed` tells clients to read them again. Running and
741
+ stopping need the `admin` scope, as `workspaceExec` does. Reading and
742
+ removing need `chat`. `runBlockOnHost` (`zidane/ipc`, `zidane/ipc/browser`)
743
+ is the client side.
744
+
745
+ The UI kit reads runs from `ChatHost.blockRuns` (`createChatBlockRuns`). Its
746
+ `start` and `live` keep the runs this window started, so a block that
747
+ scrolls away and back still shows its output. Run in a terminal is the app's
748
+ `TranscriptActions.runInTerminal` (`TerminalStore.runIn` in both apps).
749
+
750
+ ### Terminal output
751
+
752
+ Output keeps its colors. `zidane/chat/pure` reads ANSI codes into styled
753
+ spans (`createAnsiLines`, `parseAnsi`). A carriage return rewrites its line,
754
+ as in a terminal, so a progress bar shows its last state. Other escapes are
755
+ dropped. The UI kit draws spans with `AnsiText` (the 16 base colors come from
756
+ the theme), and parses only text that holds an escape. The shell tool strips
757
+ ANSI codes from what the model reads (`stripAnsi`).
758
+
759
+ Every output in the transcript (a tool's output, a `!` run, a script's live
760
+ lines, a block's run) uses one look (`.zg-output`). Live lines and the saved
761
+ output that replaces them read the same.
762
+
708
763
  ## Session reconstruction
709
764
 
710
765
  `eventsFromTurns(turns, runs)` rebuilds the visible event stream from persisted turns. It is pure, with no I/O.
package/docs/CODEMODE.md CHANGED
@@ -57,6 +57,43 @@ codemode tool calls setting (`codemodeShowCalls`, default off) controls that.
57
57
  Calls that run a subagent show either way. Hidden rows are not broadcast at
58
58
  all.
59
59
 
60
+ ### Live progress
61
+
62
+ The Stream progress setting (`codemodeStreamProgress`, default off) shows a
63
+ script's progress while it runs. It sets `behavior.codemode.streamProgress`,
64
+ and a change rebuilds live agents. The model's result does not change.
65
+
66
+ When the setting is on, the sandbox records the line of each call
67
+ (`trackLines`). The line comes from the innermost `codemode.js` frame of the
68
+ stack, so a call inside a helper reports the helper's line. The call passes
69
+ the line on (`NestedToolCallOptions.line`). Its hooks carry it as
70
+ `scriptLine`, and its saved record carries it as `line`.
71
+
72
+ The script reports what it prints (`onOutput`) through
73
+ `ToolContext.reportProgress`, as the `tool:progress` hook. Its shell calls
74
+ report their output chunks the same way. Only the process context streams
75
+ command output (`ExecOptions.onOutput`). Docker, sandbox and remote machine
76
+ contexts give the result at the end, as before.
77
+
78
+ The host (`src/chat/host/transcript/script-progress.ts`) builds one state per
79
+ script: the status of the latest call of each line, the counts, and the last
80
+ 8 output lines. It sends this state as a live `tool-progress` event, at most
81
+ every 150 ms and once more at the end. Clients keep one such event per script
82
+ (`upsertToolProgress`). On reload, `eventsFromTurns` builds the final line
83
+ states from the saved records. The live output is not saved.
84
+
85
+ The output lines come from `createOutputTail` (`src/chat/output-tail.ts`),
86
+ which Run here on a reply's shell blocks uses too. Each line keeps a stable
87
+ id while it shows, and a colored line carries its spans. In the GUI, the live
88
+ lines (`LiveOutput`) and the script's result share one box: when the script
89
+ ends, its result takes the place of the live lines.
90
+
91
+ `scriptProgressView` (`src/chat/script-progress.ts`) gives what the GUI
92
+ (`CodemodeScript`) and the TUI draw. It shows a percent only when each call
93
+ of the script can run once at most (`countOnceCallSites`). A call in a loop,
94
+ in a callback or in a helper hides the percent. The count then shows done and
95
+ running calls.
96
+
60
97
  ### Subagents
61
98
 
62
99
  `tools.spawn` works like a direct spawn. The child records the script call
@@ -70,9 +70,11 @@ Contents: [Modules](#modules), [Definition and discovery](#definition-and-discov
70
70
 
71
71
  **Load pipeline.** `validateDefinition` (`runtime/validate-definition.ts`) collects errors such as "Missing `apiVersion: 1`.", "Unsupported apiVersion X. This zidane runs apiVersion 1.", "Missing `id`.", an invalid id (`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`), an id that differs from the folder (not checked for `inline` / `builtin`), a missing `setup`, a bad semver, bad dependencies, and settings schema errors, joined as `apiVersion: …; id: …`. Unknown fields and the removed `name`, `teardown`, `permissions`, `capabilities` are warnings. A duplicate id fails (the earlier one wins). Then a topological sort (`load-order.ts`), then each extension in order: a guard, a root owner, settings and storage domains, `user` and `project` storage preloaded, then `setup`. Disabled entries get status `disabled` and `setup` does not run. `load`, `unload` and `reload` go through one serial queue.
72
72
 
73
- **Owner** (`owner.ts`). Every registration is tracked on an owner and returns a `Disposable`. `ctx.scope()` creates a child owner with its own signal and rebuilds every domain on it. Dispose aborts the signal with `DisposedError` and runs cleanups and children in reverse order, each started synchronously. Using a disposed owner throws `DisposedError`. Registrations are allowed any time until unload, not only during `setup`.
73
+ **Owner** (`owner.ts`). Every registration is tracked on an owner and returns a `Disposable`. `ctx.scope()` creates a child owner with its own signal and rebuilds every domain on it. Dispose has two phases, each running its cleanups and children in reverse order, each started synchronously. Withdraw: registrations go (`onCleanup`), so nothing new routes to the extension, and new registrations throw `DisposedError`. Teardown: the signal aborts with `DisposedError`, then the domains the extension's own work uses are released (`onTeardown`: storage, the cleanup `setup` returned, `ctx.onCleanup`). Registrations are allowed any time until unload, not only during `setup`.
74
74
 
75
- **Lifecycle** (`lifecycle.ts`). `setup` has 10 s (`SETUP_TIMEOUT_MS`). On failure (`threw`, `timeout`, `context`, `disposed`, `refused`) the owner is disposed, which rolls back what setup registered; a cleanup returned after the timeout runs at once. The cleanup returned by `setup` runs through the guard (10 s), also once the guard has tripped (a `teardown` call). Unload waits at most 5 s (`UNLOAD_TIMEOUT_MS`), then logs and leaves running cleanups alone. Runtime dispose deactivates every extension in parallel.
75
+ **Calls in flight** (`owner.lease`). Each call into the extension holds a lease on its root owner while it runs: every `guard.call` / `callSync` (hooks, interceptors, RPC handlers, panel load and action, settings actions), a command run (one lease for a whole `steps` pipeline, from the first step to the last, a throw or an abort), and a tool `execute` (`Guard.lease`). Disposing an owner without leases runs both phases at once. With leases it withdraws at once and defers the teardown until the last lease ends: storage, settings, `sessions`, `generate`, `workspace`, `artifacts` and `ctx.ui` dialogs keep working for those calls (they check `assertUsable` / `isTornDown`, not `disposed`). The wait is bounded by the longest call's own timeout, or `drainTimeoutMs` (default `DEFAULT_DRAIN_MS`, 30 min) for a call without one (a command, a tool); then the teardown runs anyway. The runtime logs once when it defers (`unloaded with N calls in flight (…)`) and again at the bound. A call that starts after dispose does not run: a command or a tool throws `DisposedError` (`[<id>] command <id>.<cmd>: the extension or scope was disposed`), a guarded callback returns its fallback. This holds on every host: unload, reload, a guard trip and a registry dispose all go through it.
76
+
77
+ **Lifecycle** (`lifecycle.ts`). `setup` has 10 s (`SETUP_TIMEOUT_MS`). On failure (`threw`, `timeout`, `context`, `disposed`, `refused`) the owner is disposed, which rolls back what setup registered; a cleanup returned after the timeout runs at once. The cleanup returned by `setup` runs through the guard (10 s), also once the guard has tripped (a `teardown` call). Unload waits at most 5 s (`UNLOAD_TIMEOUT_MS`), then logs and leaves running cleanups alone; with calls in flight it waits only for the withdrawal (`draining`), and the teardown cleanups get the 5 s once the calls end. A reload sets the new instance up meanwhile. Runtime dispose deactivates every extension in parallel and releases the shared registries (dialogs, commands, RPC) once every extension tore down.
76
78
 
77
79
  **Guard** (`guard.ts`).
78
80
 
@@ -157,7 +159,7 @@ The seven bridged hooks are `AGENT_BRIDGED_HOOKS` (`agent-interceptors.ts`), ins
157
159
  - A providers change reloads models (`catalog-ports.ts`). MCP status (`ctx.mcp.list`) adds `url`, `command` and `toolPrefix` (`mcp_<name>_`) from the catalog's configs, and includes servers connected inside sessions. `ctx.mcp.call` connects on demand through the host pool and closes after 60 s idle.
158
160
  - `ctx.plugins.load(dir | options)` (`runtime/domains/plugins.ts`) loads an Agent Plugin and registers its skills and MCP servers through these catalogs; the result is a `Disposable`.
159
161
 
160
- **How chat overlays them.** `catalog-ports.ts` gives each catalog a lazy base from `BUILTIN_PROVIDERS`, `BUILTIN_AGENTS`, `discoverProjectMcps` and `discoverSkills`. `overlayCatalog` (`src/chat/agents-catalog.ts`) applies only what extensions changed, by provenance: removed ids leave, edited ids take the catalog's item, added ids append, and ids the host left out on purpose (a disabled MCP server) stay out. It is used by `applyExtensionAgents`, `applyExtensionProviders` / `applyExtensionModels` (`src/chat/providers-catalog.ts`) and `applyExtensionMcpServers` (`agent-build/catalogs.ts`). A resolved config's `agents` is overlaid once; hosts cache configs, so agent builds, the protocol's `agents.list`, the desktop's `agents:list` and the TUI's picker read `liveAgentProfiles(config)` (or overlay the window registry's runtime), which takes profiles an extension registers later (a bot). `withExtensionCatalogs` marks a session's build stale when a catalog value changes, which rebuilds the agent. The agent reads the tools catalog in `applyCatalogTools` (`agent-tool-registry.ts` for runs, `agent-context.ts` for estimates).
162
+ **How chat overlays them.** `catalog-ports.ts` gives each catalog a lazy base from `BUILTIN_PROVIDERS`, `BUILTIN_AGENTS`, `discoverProjectMcps` and `discoverSkills`. `overlayCatalog` (`src/chat/agents-catalog.ts`) applies only what extensions changed, by provenance: removed ids leave, edited ids take the catalog's item, added ids append, and ids the host left out on purpose (a disabled MCP server) stay out. It is used by `applyExtensionAgents`, `applyExtensionProviders` / `applyExtensionModels` (`src/chat/providers-catalog.ts`) and `applyExtensionMcpServers` (`agent-build/catalogs.ts`). A resolved config's `agents` is overlaid once; hosts cache configs, so agent builds, the protocol's `agents.list`, the desktop's `agents:list` and the TUI's picker read `liveAgentProfiles(config)` (or overlay the window registry's runtime), which takes profiles an extension registers later (a bot). `withExtensionCatalogs` marks a session's build stale when a catalog value changes, or when registrations were withdrawn (`ExtensionRuntimeOutputs.withdrawals`: an extension unloaded, reloaded or disabled by its guard, or the registry disposed, such as a folder evicted from a host's cache), which rebuilds the agent against the host's live registry before its next run (`ensureAgent({ fresh })`; daemon, TUI local and desktop main alike): an idle agent never runs on withdrawn tools and hooks. The agent reads the tools catalog in `applyCatalogTools` (`agent-tool-registry.ts` for runs, `agent-context.ts` for estimates).
161
163
 
162
164
  ## Commands and keymap
163
165
 
@@ -169,7 +171,7 @@ Keymap (`commands/keymap.ts`): scopes `global`, `composer`, `transcript`, `sideb
169
171
 
170
172
  ## Storage
171
173
 
172
- `storage/`: `ctx.storage.kv(scope)` (`user | project | session`) reads synchronously from a cache (`cache.ts`); `kv.ready()` awaits a scope not loaded yet. `store(name, schema, initial, { scope, version, migrate })` keeps a `{ v, value }` record: an older version is migrated, validated and written back, a newer one yields the initial value. `memory` survives reloads, not restarts. `path(scope, …)` returns a folder (`user | project | session | cache | data`) under `<configDir|dataDir>/extensions/<id>` or the project root; `..` cannot escape it.
174
+ `storage/`: `ctx.storage.kv(scope)` (`user | project | session`) reads synchronously from a cache (`cache.ts`); `kv.ready()` awaits a scope not loaded yet. `store(name, schema, initial, { scope, version, migrate })` keeps a `{ v, value }` record: an older version is migrated, validated and written back, a newer one yields the initial value. `memory` survives reloads, not restarts. `path(scope, …)` (`storage/paths.ts`) returns a path in the extension's files folder, next to its kv data in the storage port's folders (`StoragePort.folderOf`, so every host's own): `user` and `data` in `<dataDir>/extension-storage/<id>/files`, `project` and `session` in `<project>/.zidane/extension-storage/<id>/files` (the data dir's without a project), `cache` in `<cacheDir>/extension-storage/<id>`; `..` cannot escape it. Earlier builds used `<base>/extensions/<id>` (`legacyStoragePath`: the config dir for `user`, the data dir for `data`, the project root for `project` / `session`), which is also an install folder (`~/.zidane/extensions/<id>`). A call moves what it asks for from there first: from an install or source folder (it holds `index.*`, `extension.json`, `package.json` or `.install.json`, or is the extension's `dir`) only the top entry the call names, never one of the extension's files (sources, `node_modules`, manifests, dot entries), and only when the new folder lacks it; any other old folder moves whole, entry by entry, then goes. A failed move logs a warning and returns the old path while the file is only there. The cache is not moved. `ctx.plugins` puts `${PLUGIN_DATA}` in `path('data', 'plugin-data')`.
173
175
 
174
176
  File port (`file-port.ts`): `<dataDir>/extension-storage/<id>/user.json`, `<project>/.zidane/extension-storage/<id>/project.json`, `…/sessions/<sessionId>.json`, format `{ version: 1, kv, stores }`, written atomically, owner-only. Hosts create it with `watch: false`. JSON depth is capped at 64. In daemon mode stores sync to every client (`src/ipc/daemon/extensions/storage-sync.ts`, `extensions.storage.load` / `.set`, `extensions:storage` signal with a `version`); a write is checked against the store's version and schema and may come back `{ accepted: false, reason }`.
175
177
 
@@ -262,7 +264,7 @@ Components run only in the client: `ui.tsx` exports React components for zidane-
262
264
 
263
265
  ## Daemon mode
264
266
 
265
- The daemon or server runs `setup`, one runtime per folder (`src/ipc/daemon/extensions/host.ts`: `prepare` builds the ports, `adopt` wires the signals). A TUI in daemon or server mode builds only its inline extensions (`window-registry.ts`) and loads each extension's `tuiEntry`. The desktop app runs its own runtimes in Electron main only while the daemon is off; switching drops main's cached registries (`gui/src/main/extensions/index.ts`), and main then reads models, agents, panels, palette, references, badges and settings from the daemon.
267
+ The daemon or server runs `setup`, one runtime per folder (`src/ipc/daemon/extensions/host.ts`: `prepare` builds the ports, `adopt` wires the signals). Its runtime cache (`src/ipc/daemon/environment.ts`) keeps 16 folders, least recently used out, but never evicts a folder with a run in flight (`gateExtensionReloads`, the same check live reload waits on; the desktop's cache asks `hasActiveRunsIn(cwd, scopeCwd)`, so a session without a folder matches the home folder its registry is cached under): a window listing more folders than that would otherwise dispose the registry a `/review` waiting on its workers still calls into. A TUI in daemon or server mode builds only its inline extensions (`window-registry.ts`) and loads each extension's `tuiEntry`. The desktop app runs its own runtimes in Electron main only while the daemon is off; switching drops main's cached registries (`gui/src/main/extensions/index.ts`), and main then reads models, agents, panels, palette, references, badges and settings from the daemon.
266
268
 
267
269
  Protocol (`src/ipc/protocol.ts`, handlers in `handlers/extensions.ts`, wire in `src/chat/host/extensions-wire.ts`):
268
270
 
@@ -292,7 +294,7 @@ In-repo extensions (`extensions/`): `ai-autocomplete`, `antigravity`, `bolt`, `g
292
294
 
293
295
  **Imperative** (`install.ts`, the Settings install / update / remove actions): fetch the source (GitHub, npm, folder; a `:subdir` cannot escape the repo) into a temp folder, pick the candidate, install dependencies, run the version check and an import (10 s), then copy into place as a transaction (the old folder is parked and restored on failure) with `.install.json` provenance. Update and remove refuse folders that are not direct children of a known extensions root. `changeExtensionOrigin({ dir, source })` installs an installed folder again from another source: the source must hold an extension of the same name (else `name-mismatch`, with the names found in `candidates`), the folder is replaced only once the new copy validated, and `.install.json` records the new source, which later updates follow. `readExtensionInstallOrigin(dir)` reads the recorded source (`{ spec, label, source, commit?, installedAt? }`, `label` from `extensionSourceLabel`: `Tahul/zidane@v9.0.4`, `@scope/pkg`); `catalog.extensions` rows and the desktop's `extensions:list` carry it as `origin`, with `displayName` and `icon`. A private GitHub repository fails the clone with how to reach it (`gh auth login` then `gh auth setup-git`, or an SSH key: git does not read `GITHUB_TOKEN`).
294
296
 
295
- **Browsing a source** (`src/chat/extension-browse.ts`, `listExtensionSource`, `zidane/chat`; the shapes in `src/chat/extension-sources.ts`, `zidane/chat/pure`): the extensions of a GitHub repository (the skills browser's API access, with the host's gh token), an npm package (its packument) or a folder, read from `package.json#zidane` / `extension.json`; no code runs. Folders: the root when it has an entry, else `extensions/*` with an entry, else any folder with an entry and a manifest. Failures come back as `error` (`not-found`, `private`: also a GitHub 404 without a token, `rate-limit`, `network`, `invalid`); the default source (`DEFAULT_EXTENSION_SOURCE`, `defaultExtensionSource(version)`) that cannot be read lists `nativeExtensionListing(version)` (`builtin: true`). Each row's `install` is the spec and extension name `installExtensionFromSpec` takes. Hosts: `extensions.browse` (daemon), `extensions:browse` (desktop main), `browseExtensions` (`src/tui/extension-sources.ts`). Every extension's mark is `extensionMark({ id, name?, icon?, nativeName? })`: its `icon.gui`, else the native catalog's `brand`, else its `icon`, else a letter.
297
+ **Browsing a source** (`src/chat/extension-browse.ts`, `listExtensionSource`, `zidane/chat`; the shapes in `src/chat/extension-sources.ts`, `zidane/chat/pure`): the extensions of a GitHub repository (the skills browser's API access, with the host's gh token), an npm package (its packument) or a folder, read from `package.json#zidane` / `extension.json`; no code runs. Folders: the root when it has an entry, else `extensions/*` with an entry, else any folder with an entry and a manifest. Failures come back as `error` (`not-found`, `private`: also a GitHub 404 without a token, `rate-limit`, `network`, `invalid`); the default source (`DEFAULT_EXTENSION_SOURCE`, `defaultExtensionSource(version)`) that cannot be read lists `nativeExtensionListing(version)` (`builtin: true`). Each row's `install` is the spec and extension name `installExtensionFromSpec` takes. Hosts: `extensions.browse` (daemon), `extensions:browse` (desktop main), `browseExtensions` (`src/tui/extension-sources.ts`). Every extension's mark is `extensionMark({ id, name?, icon?, nativeName? })`: its `icon.gui` (the catalog's own icon gives way to its `brand`), else the native catalog's `brand`, else its `icon`, else a letter.
296
298
 
297
299
  **In the apps.** Settings › Extensions (zidane-ui `ExtensionsSection`, desktop; `HostCatalogSection`, a server's from the web app, installs into its user scope) and the TUI's Extensions & Plugins tab (`src/tui/settings/extensions-tab.tsx`) share one behavior. A row is named and marked by the definition's `displayName` and `icon`, else the manifest's (`package.json#zidane`, `extension.json`). A failed row has no switch and a red `error` chip; its reason shows on hover or focus (TUI: while the row is focused). Update shows only for an extension with a recorded source (`.install.json`) and runs it; its menu (right click or the arrow; TUI `ctrl+u` / `ctrl+o`) reads "Update from <label>" and "Change origin…", which calls `changeExtensionOrigin` and lists `candidates` on `name-mismatch` (over the protocol, the error's `data`). A failed install keeps the form, or the browser with the picks left, open. Install opens the source browser (`ExtensionSourceBrowser` on zidane-ui's generic `SourceBrowser`; TUI `ctrl+g`, `src/tui/source-browse-dialog.tsx`, shared with Skills) on `DEFAULT_EXTENSION_SOURCE`: native rows always, the unreachable note when the repository cannot be read, multi-pick into User or This project, one install per pick with its row's `install`. End-to-end tests: `gui/src/renderer/src/extensions/extension-sources.e2e.test.tsx`, `web/e2e/extension-sources.spec.ts`, `test/tui/settings-extensions-e2e.test.tsx`.
298
300
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Draft notes for the release after v8.2.5. It brings extensions, durable runs, Slack and GitHub channels, MCP server sharing and a reworked performance monitor in the desktop app. It also brings a guided server setup with Tailscale and Cloudflare Tunnel, and automatic installs in the apps. The end lists smaller changes and fixes.
4
4
 
5
- Contents: [Extensions](#extensions-zidane-100), [Sidebar](#sidebar-extension-spaces-saved-views-agent-grouping), [Google providers](#google-providers-on-zidanes-own-client), [Durable runs](#durable-runs), [Channels](#channels-slack-and-github-experimental), [Session policy and other protocol additions](#session-policy-and-other-protocol-additions), [MCP server sharing](#mcp-server-sharing), [Performance monitor](#performance-monitor), [Tool output in the chat profiles](#tool-output-in-the-chat-profiles), [Server setup](#server-setup-tunnels-and-safer-exposure), [Automatic installs](#automatic-installs-in-the-apps), [Main server and machines](#main-server-and-machines), [Servers and machines](#servers-and-machines), [Orchestration](#orchestration-for-extensions-clients-and-mcp), [Terminals](#terminals), [Diagrams in the chat](#diagrams-in-the-chat), [Fixes](#fixes)
5
+ Contents: [Extensions](#extensions-zidane-100), [Sidebar](#sidebar-extension-spaces-saved-views-agent-grouping), [Google providers](#google-providers-on-zidanes-own-client), [Durable runs](#durable-runs), [Channels](#channels-slack-and-github-experimental), [Session policy and other protocol additions](#session-policy-and-other-protocol-additions), [MCP server sharing](#mcp-server-sharing), [Performance monitor](#performance-monitor), [Tool output in the chat profiles](#tool-output-in-the-chat-profiles), [Server setup](#server-setup-tunnels-and-safer-exposure), [Automatic installs](#automatic-installs-in-the-apps), [Main server and machines](#main-server-and-machines), [Servers and machines](#servers-and-machines), [Orchestration](#orchestration-for-extensions-clients-and-mcp), [Terminals](#terminals), [Diagrams in the chat](#diagrams-in-the-chat), [Codemode progress](#codemode-progress), [Run shell blocks from a reply](#run-shell-blocks-from-a-reply), [Fixes](#fixes)
6
6
 
7
7
  ## Extensions (zidane 10.0)
8
8
 
@@ -433,6 +433,53 @@ theme, which @pierre/highlights has no grammar for. A streaming fence
433
433
  draws every 120 ms from what parses, keeping the last drawing.
434
434
  ```
435
435
 
436
+ ## Codemode progress
437
+
438
+ A new setting, Stream progress (`codemodeStreamProgress`, off by default, under Codemode), shows a codemode script's progress while it runs. Each line of the script shows the state of its latest call: running, done or failed. Lines the script has not reached yet stay dim. The row shows how many calls are done, with a percent and a bar when each call of the script runs once at most. Under the script, the last lines it printed and the output of its shell calls show while it runs. A failed script shows its error under the line it threw at. After a reload, the line states come back. The model's result does not change.
439
+
440
+ The script view has line numbers for everyone, counted from its first line of code. A script's `// @options` line no longer shows in the code: a button beside Copy lists its settings in words (time limit, output budget). The terminal app shows the counts, the running line and the last output lines under the script's row, and a gutter with each line's state when you open it.
441
+
442
+ For developers: `behavior.codemode.streamProgress`, `ToolContext.reportProgress`, the `tool:progress` and `child:tool:progress` hooks, `scriptLine` on the hooks of a script's calls, `line` on `NestedToolCallRecord`, `ExecOptions.onOutput` (the process context only), the `tool-progress` event and the progress model in `zidane/chat/pure` (`scriptProgressView`, `upsertToolProgress`). The codemode sandbox takes `trackLines` and `onOutput`. For the UI kit: `CodemodeScript` (`zidane-ui/chat/transcript`), and `ToolInput` takes a script's progress.
443
+
444
+ ### Suggested commit message
445
+
446
+ ```
447
+ feat(codemode): stream a script's progress
448
+
449
+ A long script showed a spinner and nothing else until it ended. With
450
+ the new codemodeStreamProgress setting, the sandbox records the script
451
+ line of each call, and the script's output and its shell calls' output
452
+ reach the host as tool:progress while it runs. The host sends one
453
+ throttled tool-progress state per script, and clients replace it in
454
+ place. The GUI and the TUI draw each line's state, the call counts
455
+ (a percent only when each call runs once at most) and the last output
456
+ lines. Off by default; the model's result is unchanged.
457
+ ```
458
+
459
+ ## Run shell blocks from a reply
460
+
461
+ A shell block in a reply has a Play button, shown on hover. Run here runs the block in the session's folder and shows its output under the block, live. The output stays after a reload, and you can copy it, add it to your message, run the block again or remove the output. The run does not change the conversation. Run in a terminal opens a new terminal of the session and types the block into it, for a command that asks for input. A block with several commands runs as one temporary script. A run stops after 10 minutes, and its output keeps its last 64 KB.
462
+
463
+ Command output now shows its colors (ANSI codes) in the transcript, in the theme's colors, instead of codes such as `[33m`. The model reads shell output without the codes. Every output in the transcript has one look, so live output no longer changes tone when it ends. A codemode script's result now takes the place of its live output, in the same box.
464
+
465
+ For developers: the `sessions.runBlock`, `sessions.runBlockCancel`, `sessions.blockRuns` and `sessions.removeBlockRun` methods, the `block-run:data`, `block-run:end` and `block-runs:changed` signals, and `runBlockOnHost` (`zidane/ipc`). In `zidane/chat/pure`: the ANSI reader (`parseAnsi`, `stripAnsi`, `createAnsiLines`), `createOutputTail` and the shell block helpers (`shellBlockPlan`, `blockRunKey`). For the UI kit: `ChatHost.blockRuns` (`createChatBlockRuns`), `TranscriptActions.runInTerminal`, `HostTranscript`'s `onRunInTerminal`, `AnsiText`, `LiveOutput`, `RunnableCodeBlock`, `ShellBlockProvider`, `TerminalStore.runIn` and `useOptionalTerminalStore`. The `CodeBlock` slot takes `actions`. See [CHAT.md](CHAT.md#running-a-replys-shell-blocks).
466
+
467
+ ### Suggested commit message
468
+
469
+ ```
470
+ feat(chat): run a reply's shell blocks
471
+
472
+ Trying a command the agent suggested meant copying it to a terminal.
473
+ Shell blocks in a settled reply now have a Play button: Run here runs
474
+ the block on the session's host and streams its output under it,
475
+ saved per block in the session's metadata and kept out of the
476
+ conversation; Run in a terminal types it into a new session terminal.
477
+ Output in the transcript keeps its ANSI colors (parsed in
478
+ zidane/chat/pure, drawn in the theme) and shares one look, so live
479
+ output no longer changes tone when it ends. The shell tool strips
480
+ the codes from what the model reads.
481
+ ```
482
+
436
483
  ## Fixes
437
484
 
438
485
  - `zidane-server machine share` exited with 0 when its main server restarted, so the systemd service (`Restart=on-failure`) stayed stopped. It now keeps trying to reconnect.
package/docs/RELEASE.md CHANGED
@@ -92,9 +92,17 @@ The site runs on Coolify from `website/Dockerfile` (Caddy, `website/Caddyfile`).
92
92
  sudo chown zidane-dl /var/lib/docker/volumes/<name>/_data
93
93
  sudo apt install rsync # rrsync ships with rsync 3.2.4+ (/usr/bin/rrsync)
94
94
  ```
95
+ `/var/lib/docker` is root-only (`drwx--x---`), so `zidane-dl` cannot reach
96
+ the volume there (rrsync fails in `lock_or_die`). Bind-mount it to a path it
97
+ can reach; do not open up `/var/lib/docker`:
98
+ ```bash
99
+ sudo mkdir -p /srv/zidane-dl
100
+ echo '/var/lib/docker/volumes/<name>/_data /srv/zidane-dl none bind 0 0' | sudo tee -a /etc/fstab
101
+ sudo mount /srv/zidane-dl
102
+ ```
95
103
  3. **Pin the key to rsync in that folder.** `~zidane-dl/.ssh/authorized_keys`:
96
104
  ```text
97
- command="rrsync /var/lib/docker/volumes/<name>/_data",restrict ssh-ed25519 AAAA… zidane-release
105
+ command="/usr/bin/rrsync /srv/zidane-dl",restrict ssh-ed25519 AAAA… zidane-release
98
106
  ```
99
107
  rrsync refuses anything but rsync, and every path outside that folder.
100
108
  `DIST_PATH` is then `.`. Check it from your machine:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zidane",
3
- "version": "9.1.1",
3
+ "version": "9.1.4",
4
4
  "description": "an agent that goes straight to the goal",
5
5
  "type": "module",
6
6
  "private": false,
@@ -297,8 +297,7 @@
297
297
  "dist",
298
298
  "docs",
299
299
  "THIRD_PARTY_NOTICES.md",
300
- "!docs/PROJECT-SCOPE-AUDIT.md",
301
- "scripts/eval.ts"
300
+ "!docs/PROJECT-SCOPE-AUDIT.md"
302
301
  ],
303
302
  "workspaces": [
304
303
  "tui",