kiki-agent 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/README.md +3 -3
  2. package/dist/cpu-worker.mjs +52744 -0
  3. package/dist/docs/en/configuration/config-files.md +92 -30
  4. package/dist/docs/en/configuration/data-locations.md +14 -9
  5. package/dist/docs/en/configuration/env-vars.md +32 -2
  6. package/dist/docs/en/configuration/overrides.md +1 -1
  7. package/dist/docs/en/configuration/providers.md +44 -10
  8. package/dist/docs/en/customization/agent-profiles.md +1 -1
  9. package/dist/docs/en/customization/agents-and-subagents.md +49 -10
  10. package/dist/docs/en/customization/hooks.md +3 -3
  11. package/dist/docs/en/customization/personas.md +1 -1
  12. package/dist/docs/en/customization/plugins.md +16 -3
  13. package/dist/docs/en/customization/prompt-fields.md +62 -6
  14. package/dist/docs/en/customization/recipes.md +77 -0
  15. package/dist/docs/en/customization/skins.md +2 -2
  16. package/dist/docs/en/customization/themes.md +1 -1
  17. package/dist/docs/en/features/browser-and-computer.md +5 -5
  18. package/dist/docs/en/features/daily.md +3 -3
  19. package/dist/docs/en/features/ecosystem.md +1 -1
  20. package/dist/docs/en/features/extend.md +2 -2
  21. package/dist/docs/en/features/freedom.md +1 -1
  22. package/dist/docs/en/features/index.md +15 -1
  23. package/dist/docs/en/features/long-work.md +9 -5
  24. package/dist/docs/en/features/look.md +1 -1
  25. package/dist/docs/en/features/phone.md +11 -3
  26. package/dist/docs/en/features/spaces.md +5 -5
  27. package/dist/docs/en/getting-started/desktop-app.md +4 -8
  28. package/dist/docs/en/getting-started/first-launch.md +1 -1
  29. package/dist/docs/en/guides/goals.md +4 -2
  30. package/dist/docs/en/guides/interface.md +18 -8
  31. package/dist/docs/en/guides/memory.md +64 -10
  32. package/dist/docs/en/guides/sessions.md +15 -7
  33. package/dist/docs/en/guides/settings.md +49 -38
  34. package/dist/docs/en/index.md +3 -1
  35. package/dist/docs/en/reference/command.md +35 -33
  36. package/dist/docs/en/reference/model-vocabulary.md +2 -2
  37. package/dist/docs/en/reference/slash-commands.md +1 -1
  38. package/dist/docs/en/reference/tools.md +40 -15
  39. package/dist/docs/en/server/acp.md +6 -2
  40. package/dist/docs/en/server/local-server.md +19 -27
  41. package/dist/docs/en/server/mcp.md +4 -4
  42. package/dist/docs/en/server/rest-api.md +240 -23
  43. package/dist/docs/en/server/script-tools.md +268 -0
  44. package/dist/docs/zh/configuration/config-files.md +92 -30
  45. package/dist/docs/zh/configuration/data-locations.md +14 -9
  46. package/dist/docs/zh/configuration/env-vars.md +32 -2
  47. package/dist/docs/zh/configuration/overrides.md +1 -1
  48. package/dist/docs/zh/configuration/providers.md +44 -10
  49. package/dist/docs/zh/customization/agent-profiles.md +1 -1
  50. package/dist/docs/zh/customization/agents-and-subagents.md +49 -10
  51. package/dist/docs/zh/customization/hooks.md +3 -3
  52. package/dist/docs/zh/customization/personas.md +1 -1
  53. package/dist/docs/zh/customization/plugins.md +16 -3
  54. package/dist/docs/zh/customization/prompt-fields.md +62 -6
  55. package/dist/docs/zh/customization/recipes.md +77 -0
  56. package/dist/docs/zh/customization/skins.md +2 -2
  57. package/dist/docs/zh/customization/themes.md +1 -1
  58. package/dist/docs/zh/features/browser-and-computer.md +5 -5
  59. package/dist/docs/zh/features/daily.md +3 -3
  60. package/dist/docs/zh/features/ecosystem.md +1 -1
  61. package/dist/docs/zh/features/extend.md +2 -2
  62. package/dist/docs/zh/features/freedom.md +1 -1
  63. package/dist/docs/zh/features/index.md +16 -2
  64. package/dist/docs/zh/features/long-work.md +9 -5
  65. package/dist/docs/zh/features/look.md +1 -1
  66. package/dist/docs/zh/features/phone.md +11 -3
  67. package/dist/docs/zh/features/spaces.md +5 -5
  68. package/dist/docs/zh/getting-started/desktop-app.md +4 -8
  69. package/dist/docs/zh/getting-started/first-launch.md +1 -1
  70. package/dist/docs/zh/guides/goals.md +4 -2
  71. package/dist/docs/zh/guides/interface.md +18 -8
  72. package/dist/docs/zh/guides/memory.md +64 -10
  73. package/dist/docs/zh/guides/sessions.md +15 -7
  74. package/dist/docs/zh/guides/settings.md +49 -38
  75. package/dist/docs/zh/index.md +4 -2
  76. package/dist/docs/zh/reference/command.md +35 -33
  77. package/dist/docs/zh/reference/model-vocabulary.md +2 -2
  78. package/dist/docs/zh/reference/slash-commands.md +1 -1
  79. package/dist/docs/zh/reference/tools.md +40 -15
  80. package/dist/docs/zh/server/acp.md +6 -2
  81. package/dist/docs/zh/server/local-server.md +19 -27
  82. package/dist/docs/zh/server/mcp.md +4 -4
  83. package/dist/docs/zh/server/rest-api.md +229 -23
  84. package/dist/docs/zh/server/script-tools.md +268 -0
  85. package/dist/external-harness/agy-cli-acp.mjs +168 -162
  86. package/dist/external-harness/agy-hook-registration.mjs +69 -30
  87. package/dist/external-harness/agy-mcp-plugin.mjs +19 -0
  88. package/dist/external-harness/agy-permission-hook.mjs +29 -2
  89. package/dist/hostRunner.mjs +24 -6
  90. package/dist/mailbox-worker.mjs +111 -5
  91. package/dist/main.mjs +2 -2
  92. package/dist/memory-worker.mjs +1008 -0
  93. package/dist/native/windows-process-helper.exe +0 -0
  94. package/dist/query-store-worker.mjs +52 -11
  95. package/dist/sqlite-indexer.mjs +32 -2
  96. package/dist/sqlite-query-worker.mjs +35 -0
  97. package/dist/usage-parser-worker.mjs +3953 -4
  98. package/dist/usage-read-model-worker.mjs +761 -0
  99. package/dist/web/assets/{AppErrorBoundary-BN6IDdP1.js → AppErrorBoundary-B5Fc4f6-.js} +1 -1
  100. package/dist/web/assets/NavScopeBoundary-C7MnGQio.js +1 -0
  101. package/dist/web/assets/{arc-C7IAvCCJ.js → arc-DGB9OVgQ.js} +1 -1
  102. package/dist/web/assets/{architectureDiagram-3BPJPVTR-CbwFBxn7.js → architectureDiagram-3BPJPVTR-glnQCMub.js} +1 -1
  103. package/dist/web/assets/{blockDiagram-GPEHLZMM-B20N4t8r.js → blockDiagram-GPEHLZMM-bM0tnGby.js} +1 -1
  104. package/dist/web/assets/{c4Diagram-AAUBKEIU-3BYtlcP-.js → c4Diagram-AAUBKEIU-DMf_rTtt.js} +1 -1
  105. package/dist/web/assets/channel-Cj8SKJ38.js +1 -0
  106. package/dist/web/assets/{chunk-2J33WTMH-CpjgczxM.js → chunk-2J33WTMH-mTccJ3tW.js} +1 -1
  107. package/dist/web/assets/{chunk-4BX2VUAB-BScxUF5G.js → chunk-4BX2VUAB-DhqPYMjY.js} +1 -1
  108. package/dist/web/assets/{chunk-55IACEB6-CrcLYJXd.js → chunk-55IACEB6-BujrYRoO.js} +1 -1
  109. package/dist/web/assets/{chunk-727SXJPM-BwlyIOjw.js → chunk-727SXJPM-ciMmSI4G.js} +1 -1
  110. package/dist/web/assets/{chunk-AQP2D5EJ-DKKIRkRv.js → chunk-AQP2D5EJ-CZW9pKTc.js} +1 -1
  111. package/dist/web/assets/{chunk-FMBD7UC4-CVDMj2kX.js → chunk-FMBD7UC4-hdALNnnU.js} +1 -1
  112. package/dist/web/assets/{chunk-ND2GUHAM-CL-PM6r8.js → chunk-ND2GUHAM-CgKyqUdb.js} +1 -1
  113. package/dist/web/assets/{chunk-QZHKN3VN-DPV2KbKZ.js → chunk-QZHKN3VN-B2mmUz_E.js} +1 -1
  114. package/dist/web/assets/classDiagram-4FO5ZUOK-f8V9p-dD.js +1 -0
  115. package/dist/web/assets/classDiagram-v2-Q7XG4LA2-f8V9p-dD.js +1 -0
  116. package/dist/web/assets/client-ClWQBErG.js +3 -0
  117. package/dist/web/assets/connection-C0J3BPgk.js +1 -0
  118. package/dist/web/assets/{cose-bilkent-S5V4N54A-D1CEiQM6.js → cose-bilkent-S5V4N54A-UV3uPjkK.js} +1 -1
  119. package/dist/web/assets/{dagre-BM42HDAG-BlFV941E.js → dagre-BM42HDAG-Zjy-gQ6C.js} +1 -1
  120. package/dist/web/assets/{diagram-2AECGRRQ-BC0ldkFY.js → diagram-2AECGRRQ-DL-kilIf.js} +1 -1
  121. package/dist/web/assets/{diagram-5GNKFQAL-B22Iej6G.js → diagram-5GNKFQAL-CjB_xR5B.js} +1 -1
  122. package/dist/web/assets/{diagram-KO2AKTUF-B75UNw6D.js → diagram-KO2AKTUF-CjN4i3b9.js} +1 -1
  123. package/dist/web/assets/{diagram-LMA3HP47-CypI7IJM.js → diagram-LMA3HP47-CPCAMndo.js} +1 -1
  124. package/dist/web/assets/{diagram-OG6HWLK6-OsXumvcD.js → diagram-OG6HWLK6-DVeBWBKd.js} +1 -1
  125. package/dist/web/assets/{erDiagram-TEJ5UH35-3756GOvS.js → erDiagram-TEJ5UH35-CHKzBHrr.js} +1 -1
  126. package/dist/web/assets/export-CXoWon32.js +2 -0
  127. package/dist/web/assets/{flowDiagram-I6XJVG4X-DB6Y_UDg.js → flowDiagram-I6XJVG4X-C5rQa2pq.js} +1 -1
  128. package/dist/web/assets/{ganttDiagram-6RSMTGT7-CHJeuoAY.js → ganttDiagram-6RSMTGT7-BrLjEsNJ.js} +1 -1
  129. package/dist/web/assets/{gitGraphDiagram-PVQCEYII-Dj85554Y.js → gitGraphDiagram-PVQCEYII-3DRR5VZj.js} +1 -1
  130. package/dist/web/assets/highlighted-body-OFNGDK62-Bdj5SJfv.js +1 -0
  131. package/dist/web/assets/index-2Vx5mHRn.js +1 -0
  132. package/dist/web/assets/index-B1UXw2C9.js +1 -0
  133. package/dist/web/assets/{index-C6qeLCPw.js → index-BJxtlf4P.js} +4 -4
  134. package/dist/web/assets/{index-DxUmR9aV.js → index-BY7jPurv.js} +1 -1
  135. package/dist/web/assets/index-Bq79v-Sa.js +1 -0
  136. package/dist/web/assets/index-BqD3iTIl.js +1 -0
  137. package/dist/web/assets/index-Br3AlBrQ.js +1 -0
  138. package/dist/web/assets/{index-DZMkZKhW.js → index-BvRBCpc6.js} +2 -2
  139. package/dist/web/assets/index-BxYCSNg_.js +3 -0
  140. package/dist/web/assets/{index-CJqIcuAl.js → index-C62wjCF_.js} +1 -1
  141. package/dist/web/assets/index-CBvwNH_H.js +1 -0
  142. package/dist/web/assets/{index-DRMjjql1.js → index-CG9e6lgq.js} +1 -1
  143. package/dist/web/assets/{index-C7mOS2T4.js → index-CPSWYh_R.js} +2 -2
  144. package/dist/web/assets/index-CS4xJLZV.js +1 -0
  145. package/dist/web/assets/index-CjvqtF2I.js +1 -0
  146. package/dist/web/assets/index-CprdjRRk.js +13 -0
  147. package/dist/web/assets/{index-bYtKyBMB.js → index-CypTtrCB.js} +1 -1
  148. package/dist/web/assets/{index-DqK8MfQN.js → index-DDJQGcUL.js} +1 -1
  149. package/dist/web/assets/index-DLWzxUOO.js +1 -0
  150. package/dist/web/assets/index-DQxkxZmn.js +7 -0
  151. package/dist/web/assets/index-DRo5Y_9p.js +1 -0
  152. package/dist/web/assets/index-De_LkTZx.js +1 -0
  153. package/dist/web/assets/{index-0tHq8zh2.js → index-DfUpwUTM.js} +2 -2
  154. package/dist/web/assets/{index-D--cw39y.js → index-Dkbz748K.js} +2 -2
  155. package/dist/web/assets/index-DmwFFSkV.js +1 -0
  156. package/dist/web/assets/index-DpcWEDhW.js +1 -0
  157. package/dist/web/assets/index-Dqq1RDP4.js +1 -0
  158. package/dist/web/assets/index-H1uMvIoa.css +1 -0
  159. package/dist/web/assets/index-ICHWJ2SM.js +1 -0
  160. package/dist/web/assets/index-O5fSd569.js +229 -0
  161. package/dist/web/assets/index-odjtqLLS.js +1 -0
  162. package/dist/web/assets/index-v_yAQ0Am.js +1 -0
  163. package/dist/web/assets/{infoDiagram-5YYISTIA-DeDPIdEH.js → infoDiagram-5YYISTIA-CCwV4Z0v.js} +1 -1
  164. package/dist/web/assets/{ishikawaDiagram-YF4QCWOH-ButuBiBW.js → ishikawaDiagram-YF4QCWOH-BwwZcGyZ.js} +1 -1
  165. package/dist/web/assets/{journeyDiagram-JHISSGLW-Dlbmqm-j.js → journeyDiagram-JHISSGLW-Dc6WqniQ.js} +1 -1
  166. package/dist/web/assets/{kanban-definition-UN3LZRKU-tlQK1cOz.js → kanban-definition-UN3LZRKU-DVUqULOS.js} +1 -1
  167. package/dist/web/assets/{linear-iXuNfUWp.js → linear-d6rWsNOU.js} +1 -1
  168. package/dist/web/assets/memoryAdvisor-DBQXJB1o.js +1 -0
  169. package/dist/web/assets/mermaid-GHXKKRXX-Ik6SkVDT.js +642 -0
  170. package/dist/web/assets/{mindmap-definition-RKZ34NQL-2qPv-mwT.js → mindmap-definition-RKZ34NQL-_JHAkhHL.js} +1 -1
  171. package/dist/web/assets/navViewState-DaCMIYWA.js +1 -0
  172. package/dist/web/assets/{pieDiagram-4H26LBE5-CrLe1C-O.js → pieDiagram-4H26LBE5-BlhlygGy.js} +1 -1
  173. package/dist/web/assets/{quadrantDiagram-W4KKPZXB-DfeIFxc0.js → quadrantDiagram-W4KKPZXB-jn6R_C0S.js} +1 -1
  174. package/dist/web/assets/{requirementDiagram-4Y6WPE33-BWtjdxie.js → requirementDiagram-4Y6WPE33-B9fXCHBr.js} +1 -1
  175. package/dist/web/assets/{sankeyDiagram-5OEKKPKP-B5TxJ6mb.js → sankeyDiagram-5OEKKPKP-fPJwIxkl.js} +1 -1
  176. package/dist/web/assets/{sequenceDiagram-3UESZ5HK-Cf92ZCl1.js → sequenceDiagram-3UESZ5HK-1v1DTNGt.js} +1 -1
  177. package/dist/web/assets/{spaces-DqMTtCXX.js → spaces-CvL2DRZM.js} +1 -1
  178. package/dist/web/assets/{stateDiagram-AJRCARHV-NR9I-Q4d.js → stateDiagram-AJRCARHV-CEc_PLov.js} +1 -1
  179. package/dist/web/assets/stateDiagram-v2-BHNVJYJU-iAMctzaT.js +1 -0
  180. package/dist/web/assets/theme-LRSmy8mD.js +1 -0
  181. package/dist/web/assets/{timeline-definition-PNZ67QCA-CBAOVMfm.js → timeline-definition-PNZ67QCA-CEjhuitj.js} +1 -1
  182. package/dist/web/assets/{vennDiagram-CIIHVFJN-C68x6TdS.js → vennDiagram-CIIHVFJN-CActt9h9.js} +1 -1
  183. package/dist/web/assets/{wardley-L42UT6IY-DuZZr5jm.js → wardley-L42UT6IY-Bp3q2izt.js} +1 -1
  184. package/dist/web/assets/{wardleyDiagram-YWT4CUSO-D6dVGtHd.js → wardleyDiagram-YWT4CUSO-C_zutiQ2.js} +1 -1
  185. package/dist/web/assets/{xychartDiagram-2RQKCTM6-DYLUhZX4.js → xychartDiagram-2RQKCTM6-CRafvv33.js} +1 -1
  186. package/dist/web/icons/apple-touch-icon.png +0 -0
  187. package/dist/web/icons/icon-192.png +0 -0
  188. package/dist/web/icons/icon-512.png +0 -0
  189. package/dist/web/icons/maskable-512.png +0 -0
  190. package/dist/web/index.html +12 -2
  191. package/dist/web/manifest.webmanifest +16 -0
  192. package/native/auth-native/prebuilds/linux-arm64/auth-native.node +0 -0
  193. package/native/auth-native/prebuilds/linux-x64/auth-native.node +0 -0
  194. package/native/auth-native/prebuilds/win32-arm64/auth-native.node +0 -0
  195. package/native/auth-native/prebuilds/win32-x64/auth-native.node +0 -0
  196. package/package.json +22 -3
  197. package/dist/web/assets/LifeMark-UBMVaTWr.js +0 -1
  198. package/dist/web/assets/NavScopeBoundary-BCryw-UG.js +0 -1
  199. package/dist/web/assets/channel-BJs5vJuh.js +0 -1
  200. package/dist/web/assets/classDiagram-4FO5ZUOK-BookeACB.js +0 -1
  201. package/dist/web/assets/classDiagram-v2-Q7XG4LA2-BookeACB.js +0 -1
  202. package/dist/web/assets/client-CXcrCawx.js +0 -3
  203. package/dist/web/assets/connection-C8nwzwXB.js +0 -1
  204. package/dist/web/assets/export-Bn8PqPg4.js +0 -2
  205. package/dist/web/assets/highlighted-body-OFNGDK62-DMgPHetp.js +0 -1
  206. package/dist/web/assets/index-7ySDqvaN.css +0 -1
  207. package/dist/web/assets/index-B0KPRi1U.js +0 -166
  208. package/dist/web/assets/index-B599VnpP.js +0 -1
  209. package/dist/web/assets/index-BFK-GypQ.js +0 -1
  210. package/dist/web/assets/index-BPX8gmpB.js +0 -1
  211. package/dist/web/assets/index-BSGYc1tb.js +0 -1
  212. package/dist/web/assets/index-BTt9Q5iv.js +0 -1
  213. package/dist/web/assets/index-BWzUsoY_.js +0 -1
  214. package/dist/web/assets/index-BYlSV3FO.js +0 -3
  215. package/dist/web/assets/index-BpXQ1q-u.js +0 -1
  216. package/dist/web/assets/index-BqPxpGUh.js +0 -1
  217. package/dist/web/assets/index-C8OFfbEs.js +0 -1
  218. package/dist/web/assets/index-CI7yuMGZ.js +0 -1
  219. package/dist/web/assets/index-CTRJmDep.js +0 -1
  220. package/dist/web/assets/index-CXGCKoId.js +0 -1
  221. package/dist/web/assets/index-CsY571EL.js +0 -13
  222. package/dist/web/assets/index-CwQG_9rB.js +0 -1
  223. package/dist/web/assets/index-D260jsUJ.js +0 -1
  224. package/dist/web/assets/index-DJjmEXx4.js +0 -1
  225. package/dist/web/assets/index-DUxOVxHS.js +0 -1
  226. package/dist/web/assets/index-GK8aa9pT.js +0 -7
  227. package/dist/web/assets/index-wxHFHTgD.js +0 -1
  228. package/dist/web/assets/mermaid-GHXKKRXX-sDJax95P.js +0 -624
  229. package/dist/web/assets/stateDiagram-v2-BHNVJYJU-BiegFWxE.js +0 -1
  230. package/dist/web/assets/theme-6OL1RXgY.js +0 -1
@@ -1,3 +0,0 @@
1
- import{as as L,at as Pt,au as ce,av as c,aw as g,ax as li,ay as s,az as d,aA as ho,aB as pi,aC as mi,aD as hi,aE as gi,aF as vi,aG as Si,aH as h,aI as K,aJ as A,aK as b,aL as l,aM as v,aN as fi,aO as yi,aP as k,aQ as R,aR as Vt,aS as bi,aT as Oe,aU as _i,aV as Ii,aW as Ti,aX as wi,aY as Ei,aZ as ki,a_ as Ci,a$ as go,b0 as Ri,b1 as vo,b2 as Pi,b3 as Oi,b4 as Ai,b5 as Mi,b6 as xi,b7 as Ui,b8 as Di,b9 as Ni,ba as mt,bb as ht,bc as vn,bd as ji,be as Li,bf as qi,bg as $i,bh as Gi,bi as Fi,bj as Bi,bk as Vi,bl as Se,bm as Wi,bn as Hi,bo as zi,bp as Ki,bq as So,br as Qi,bs as Yi,bt as Xi,bu as Ji,bv as Zi,bw as er,bx as gt,by as vt,bz as Ue,bA as tr,bB as or,bC as nr,bD as sr,bE as ir,bF as fo,bG as rr,bH as ar,bI as cr,bJ as dr,bK as ur,bL as Qe,bM as lr,bN as pr,bO as De,bP as yo,bQ as mr,bR as St,bS as hr,bT as gr,bU as vr,bV as ft,bW as Sr,bX as B,bY as fr,bZ as yr,b_ as br,b$ as _r,c0 as Ir,c1 as Tr,c2 as wr,c3 as Er,c4 as z,c5 as kr,c6 as Cr,c7 as Rr,c8 as Pr,c9 as Or,ca as yt,cb as Ar,cc as Mr,cd as xr,ce as Ze,cf as Ur,cg as Dr,ch as Nr,ci as jr,cj as Lr,ck as qr,cl as $r,cm as Gr,cn as Fr,co as Sn,cp as Br,cq as Vr,cr as Wr,cs as Hr,ct as zr,cu as Kr,cv as fn,cw as Qr,cx as Yr,cy as Xr,cz as Ae,cA as yn,cB as Jr,cC as Zr,cD as et,cE as ea,cF as ta,cG as oa,cH as na,cI as sa,cJ as ia,cK as ra,cL as aa,cM as ca,cN as da,cO as ua,cP as la,cQ as pa,cR as ma,cS as ha,cT as bo,cU as _o,cV as ga,cW as va,cX as Sa,cY as fa,cZ as ya,c_ as ba,c$ as _a,d0 as Ia,d1 as Ta,d2 as wa,d3 as bn,d4 as _n,d5 as In,d6 as Ea,d7 as Tn,d8 as wn,d9 as ka,da as Ca,db as Io,dc as Ra,dd as bt,de as Pa,df as Ne,dg as Oa,dh as Aa,di as fe,dj as Ma,dk as X,dl as To,dm as xa,dn as _t,dp as Ua,dq as It,dr as Da,ds as Na,dt as Tt,du as ja,dv as La,dw as qa,dx as $a,dy as wo,dz as Ga,dA as Fa,dB as Eo,dC as Ba,dD as Va,dE as Wa,a as Ha,B as ko,dF as za,dG as Ka,dH as Qa,dI as Co,dJ as Ya,dK as Xa,dL as Ja,dM as Za,dN as wt,dO as ec,dP as Ro,dQ as tc,dR as oc}from"./index-B0KPRi1U.js";const Wt="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Ye=32,En=16,Ht=10,Po=0xffffffffffff;var se;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID"})(se||(se={}));class we extends Error{constructor(e,o){super(`${o} (${e})`),this.name="ULIDError",this.code=e}}function nc(t){const e=Math.floor(t()*Ye)%Ye;return Wt.charAt(e)}function sc(t){const e=ic(),o=e&&(e.crypto||e.msCrypto)||null;if(typeof o?.getRandomValues=="function")return()=>{const n=new Uint8Array(1);return o.getRandomValues(n),n[0]/256};if(typeof o?.randomBytes=="function")return()=>o.randomBytes(1).readUInt8()/256;throw new we(se.PRNGDetectFailure,"Failed to find a reliable PRNG")}function ic(){return cc()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function rc(t,e){let o="";for(;t>0;t--)o=nc(e)+o;return o}function ac(t,e=Ht){if(isNaN(t))throw new we(se.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>Po)throw new we(se.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Po}: ${t}`);if(t<0)throw new we(se.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===!1)throw new we(se.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let o,n="";for(let i=e;i>0;i--)o=t%Ye,n=Wt.charAt(o)+n,t=(t-o)/Ye;return n}function cc(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Oo(t){return typeof t=="string"&&t.length===Ht+En&&t.toUpperCase().split("").every(e=>Wt.indexOf(e)!==-1)}function dc(t,e){const o=sc(),n=Date.now();return ac(n,Ht)+rc(En,o)}const Ao={off:0,turn:1,block:2,delta:3};function Mo(t,e){return t?t[e]??t["*"]??"off":"off"}function uc(t,e){const o=e.path[0];if(e.path.length!==1||!(e.source.kind==="frame"&&(o==="input"||o==="output")||e.source.kind==="task"&&o==="outputTail"))return;const n=JSON.stringify([t,e.source.kind,e.source.id,e.source.turnId??"",e.source.stepId??"",o,e.revision]),i=new TextEncoder().encode(n);let a="";for(const r of i)a+=String.fromCharCode(r);return`raw:${btoa(a).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}`}const xo=512*1024,lc={meta:["GET","/meta"],spaceSummary:["GET","/space-summary"],sessions:["GET","/sessions"],sessionQuery:["GET","/sessions/query"],ephemeralSessions:["GET","/sessions/ephemeral"],sessionCreate:["POST","/sessions"],session:["GET","/sessions/{sessionId}"],sessionUpdate:["PATCH","/sessions/{sessionId}"],sessionArchive:["POST","/sessions/{sessionId}:archive"],sessionRestore:["POST","/sessions/{sessionId}:restore"],sessionFork:["POST","/sessions/{sessionId}:fork"],saveEphemeral:["POST","/sessions/{sessionId}/ephemeral/save"],endEphemeral:["POST","/sessions/{sessionId}/ephemeral/end"],compact:["POST","/sessions/{sessionId}:compact"],undo:["POST","/sessions/{sessionId}:undo"],autoCompact:["GET","/sessions/{sessionId}/agents/{agentId}/auto-compact"],autoCompactUpdate:["PATCH","/sessions/{sessionId}/agents/{agentId}/auto-compact"],agentHooks:["GET","/sessions/{sessionId}/agents/{agentId}/hooks"],sessionProfile:["POST","/sessions/{sessionId}/profile"],personaSettings:["GET","/sessions/{sessionId}/persona-settings"],personaSettingsApply:["POST","/sessions/{sessionId}/persona-settings"],goal:["GET","/sessions/{sessionId}/goal"],messages:["GET","/sessions/{sessionId}/messages"],snapshot:["GET","/klient/session-view/{sessionId}/snapshot"],transcript:["GET","/klient/session-view/{sessionId}/transcript"],content:["POST","/klient/session-view/{sessionId}/transcript/content"],catchUp:["GET","/klient/session-view/{sessionId}/transcript/catch-up"],transcriptPage:["GET","/sessions/{sessionId}/transcript"],transcriptDetail:["GET","/sessions/{sessionId}/transcript/detail"],transcriptDetails:["GET","/sessions/{sessionId}/transcript/details"],transcriptOps:["GET","/sessions/{sessionId}/transcript/ops"],transcriptPlan:["GET","/sessions/{sessionId}/transcript/plan"],procedure:["POST","/klient/call"],prompts:["GET","/sessions/{sessionId}/prompts"],prompt:["POST","/sessions/{sessionId}/prompts"],promptRead:["GET","/sessions/{sessionId}/prompts/{promptId}"],promptResume:["POST","/sessions/{sessionId}/prompts/{promptId}:resume"],promptAbort:["POST","/sessions/{sessionId}/prompts/{promptId}:abort"],steer:["POST","/sessions/{sessionId}/prompts/steer"],abort:["POST","/sessions/{sessionId}/abort"],approvals:["GET","/sessions/{sessionId}/approvals"],approval:["POST","/sessions/{sessionId}/approvals/{interactionId}"],questions:["GET","/sessions/{sessionId}/questions"],question:["POST","/sessions/{sessionId}/questions/{interactionId}"],taskList:["GET","/sessions/{sessionId}/tasks"],task:["GET","/sessions/{sessionId}/tasks/{taskId}"],agentTaskList:["GET","/sessions/{sessionId}/agent-tasks"],userMessages:["GET","/sessions/{sessionId}/user-messages"],skills:["GET","/sessions/{sessionId}/skills"],skillActivate:["POST","/sessions/{sessionId}/skills/{skillName}:activate"],context:["GET","/sessions/{sessionId}/context"],metrics:["GET","/sessions/{sessionId}/metrics"],media:["GET","/sessions/{sessionId}/media/{fileId}"],mediaPreview:["GET","/sessions/{sessionId}/media/{fileId}/preview"],fileUpload:["POST","/files"],file:["GET","/files/{fileId}"],tools:["GET","/tools"],models:["GET","/models"],providers:["GET","/providers"],auth:["GET","/auth"],configRead:["GET","/config"],usage:["GET","/usage"],requestGovernance:["GET","/usage/realtime"],agentActivity:["GET","/usage/realtime/agents"],usagePricing:["GET","/usage/pricing"],usageRescanStatus:["GET","/usage/rescan"],providerQuotaRead:["GET","/usage/provider-quotas"],workspaces:["GET","/workspaces"],workspace:["GET","/workspaces/{workspaceId}"],workspaceSkills:["GET","/workspaces/{workspaceId}/skills"],worktrees:["GET","/worktrees"],worktree:["GET","/worktrees/{worktreeId}"],worktreeInspect:["POST","/worktrees/{worktreeId}:inspect"],fsSearch:["POST","/sessions/{sessionId}/fs:search"],draftFsSearch:["POST","/workspace/fs:search"],htmlPreviewOpen:["POST","/fs:html-preview"],htmlPreviewClose:["DELETE","/fs:html-preview/{previewId}"],htmlPreviewResource:["GET","/html-preview/{previewId}/resource"],commands:["GET","/sessions/{sessionId}/commands"],agentCapabilities:["GET","/agents/capabilities"],agentConfig:["GET","/sessions/{sessionId}/agent-config"],agentConfigUpdate:["PATCH","/sessions/{sessionId}/agent-config"],profiles:["GET","/agents"],shippedProfiles:["GET","/agents/shipped"],previewModelMenu:["POST","/agents/{profileId}/model-menu:preview"],previewExecutorPrompt:["POST","/agents/{profileId}/executor-prompt:preview"],plugins:["GET","/plugins"],plugin:["GET","/plugins/{pluginId}"],pluginSettings:["GET","/plugins/{pluginId}/settings"],pluginCommands:["GET","/plugins/commands"],pluginPanels:["GET","/plugins/panels"],pluginPanelDocument:["GET","/plugins/{pluginId}/panels/{panelId}/document"],pluginPanelBridge:["POST","/plugins/{pluginId}/panels/{panelId}/bridge"],pluginMarketplace:["GET","/plugins/marketplace"],pluginRecommendations:["POST","/plugins/recommendations/match"],skins:["GET","/skins"],skin:["GET","/skins/{skinId}"],appearancePacks:["GET","/appearance/packs"],appearancePack:["GET","/appearance/packs/{packId}"],appearanceAsset:["GET","/appearance/packs/{packId}/files/{fileName}"],spacePreferences:["GET","/homes/{spaceId}/settings"],personas:["GET","/personas"],persona:["GET","/personas/{personaId}"],personaAvatar:["GET","/personas/{personaId}/avatar"],personaHome:["POST","/personas/{personaId}/home"],personaState:["PATCH","/personas/{personaId}/state"],bots:["GET","/bots"],botHome:["POST","/bots/{botId}/home"],rooms:["GET","/rooms"],roomItems:["GET","/rooms/items"],roomThreads:["GET","/rooms/threads"],room:["GET","/rooms/{roomId}"],roomLog:["GET","/rooms/{roomId}/log"],roomUsage:["GET","/rooms/{roomId}/usage"],roomMessage:["POST","/rooms/{roomId}/messages"],roomPause:["POST","/rooms/{roomId}/pause"],roomContinue:["POST","/rooms/{roomId}/continue"],roomStop:["POST","/rooms/{roomId}/stop"],cron:["GET","/cron"],threadMessages:["GET","/threads/messages"],search:["POST","/search"],searchStatus:["GET","/search/status"],mcpRuntime:["GET","/mcp/runtime/servers"],executors:["GET","/executors"],catalogProviders:["GET","/catalog/providers"],catalogProvider:["GET","/catalog/providers/{providerId}"],oauthUsage:["GET","/oauth/usage"],nbSearchCapabilities:["GET","/nb-search/capabilities"],requestIdentity:["GET","/request-identity"],notificationsSettings:["GET","/notifications/settings"],notificationsProviders:["GET","/notifications/providers"],notificationsDeliveries:["GET","/notifications/deliveries"],memorySources:["GET","/memory/sources"],memoryEntries:["GET","/memory/{scope}"],memoryEntry:["GET","/memory/{scope}/{entryId}"],memoryJournal:["GET","/memory/{scope}/journal"],memoryInbox:["GET","/memory/{scope}/inbox"]},pc=t=>!t||t==="."||t===".."||t.includes("/")||t.includes("\\");function mc(t,e){const o=Object.entries(lc).toSorted((n,i)=>(n[1][1].match(/\{/g)?.length??0)-(i[1][1].match(/\{/g)?.length??0));for(const[n,[i,a]]of o){if(i!==t)continue;const r=[],u=a.split(/(\{[A-Za-z]+\})/).map(f=>f.startsWith("{")?(r.push(f.slice(1,-1)),"([^/]+)"):f.replaceAll(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(""),m=new RegExp("^/api"+u+"$").exec(e.startsWith("/api/")?e:"/api"+e);if(m===null)continue;const p={};let S=!0;for(let f=0;f<r.length;f+=1){let y;try{y=decodeURIComponent(m[f+1])}catch{S=!1;break}if(pc(y)){S=!1;break}p[r[f]]=y}if(S)return{operation:n,params:p}}}function hc(t){if(t!==void 0)return t;const e=()=>{throw new Error("terminal capability is unsupported on this transport")},o=async()=>e();return{listTerminals:o,createTerminal:o,getTerminal:o,closeTerminal:o,terminalAttach:o,terminalDetach:e,terminalInput:e,terminalResize:e,onTerminalSignal:e,onStatus:e,nudge:e}}const gc=t=>c({items:g(t),nextCursor:s().optional()}),O=t=>L([t,ce(),li()]).transform(e=>e??void 0),_=L([Pt(),ce()]).transform(()=>{}),Uo=c({added:g(s()),removed:g(s()),changed:g(s())}),vc={catalog:{input:d([]),output:Si},export:{input:d([mi]),output:vi},preview:{input:d([pi]),output:gi},apply:{input:d([ho]),output:hi},cancel:{input:d([ho]),output:_}},U=s().min(1).max(512),zt=s().min(1).max(4096),Xe=g(U).max(256),Je=h(["active","in_progress","paused","done","cancelled","superseded"]),Ce=K({root:zt,storageId:U,kind:h(["workspace","embedded"])}),Sc=K({root:zt,storageId:U.optional(),kind:h(["workspace","embedded"])}),fc=K({mode:h(["auto","global","fixed"]),path:s().trim().max(4096).refine(t=>!/[\u0000-\u001F]/u.test(t),"Storage path contains control characters.").optional()}).refine(t=>t.mode!=="fixed"||!!t.path,{message:"Fixed storage requires a path.",path:["path"]}),yc=K({title:s().trim().min(1).max(1e3).optional(),description:s().max(1e5).optional(),priority:h(["P0","P1","P2","P3"]).optional(),category:s().max(256).optional(),sessionIds:Xe.optional(),executionIds:Xe.optional(),status:Je.optional()}).refine(t=>Object.keys(t).length>0,"An update requires a changed field."),bc=A("action",[K({action:b("preview"),workspaceId:U.optional(),configuration:fc.optional()}),K({action:b("list"),workspaceId:U.optional(),storage:Ce.optional(),sessionId:U.optional(),status:Je.optional(),archived:v().optional(),cursor:U.optional(),limit:l().int().min(1).max(100).optional()}),K({action:b("show"),workspaceId:U,storage:Ce,id:U}),K({action:b("overview"),workspaceIds:g(U).min(1).max(32),status:Je.optional(),limit:l().int().min(1).max(100).optional()})]),_c=A("action",[K({action:b("create"),workspaceId:U.optional(),requestKey:U,target:Sc.optional(),title:s().trim().min(1).max(1e3),description:s().max(1e5).optional(),priority:h(["P0","P1","P2","P3"]).optional(),category:s().max(256).optional(),sessionIds:Xe.optional(),executionIds:Xe.optional()}),K({action:b("update"),workspaceId:U,storage:Ce,id:U,expectedRevision:l().int().nonnegative().max(Number.MAX_SAFE_INTEGER),patch:yc})]),kn=c({id:U,workspaceId:U,storage:Ce,title:s(),priority:s(),status:Je,revision:l().int().nonnegative(),createdAt:s(),updatedAt:s(),completedAt:s().nullable(),archived:v(),category:s(),sessionIds:g(s()),executionIds:g(s())}),Cn=kn.extend({description:s(),prd:s(),handoff:s().optional()}),Rn=c({code:s(),message:s()}),tt=t=>A("ok",[c({ok:b(!0),value:t}),c({ok:b(!1),error:Rn})]),Pn=c({workspaceId:U,storage:Ce.optional(),cards:g(kn),issues:g(Rn),nextCursor:s().optional()}),Ic=c({mode:h(["auto","global","fixed"]),workspaceId:U,root:zt,tasksDirectory:s(),existing:v(),kind:h(["workspace","embedded"]),storageId:U.optional(),selectionOnly:b(!0)}),On=c({workspaceId:U,result:tt(Pn)}),Tc=tt(L([Cn,Pn,Ic,g(On)])),wc=tt(Cn),Ec=tt(g(On)),kc={read:{input:d([bc]),output:Tc},write:{input:d([_c]),output:wc},overview:{input:d([]),output:Ec}},Cc={read:{input:d([fi]),output:yi}},Rc=h(["running","streaming","tool_call","retrying"]),Pc=c({approvalId:s(),toolCallId:s().optional(),since:l()}),Oc=c({toolCallId:s(),name:s(),since:l()}),Ac=c({failedAttempt:l(),nextAttempt:l(),maxAttempts:l(),delayMs:l(),errorName:s().optional(),statusCode:l().optional()}),Mc=c({turnId:l(),origin:k(),phase:Rc,stream:h(["assistant","thinking","tool_call"]).optional(),step:l(),ending:v(),endingReason:h(["aborted","max_steps","error"]).optional(),retry:Ac.optional(),pendingApprovals:g(Pc),activeToolCalls:g(Oc),since:l()}),xc=h(["completed","cancelled","failed","blocked"]),Uc=c({turnId:l(),reason:xc,durationMs:l().optional(),at:l()}),Dc=c({kind:s(),id:s(),since:l()}),Nc=h(["ready","disposed"]),jc=c({lifecycle:Nc,turn:Mc.optional(),lastTurn:Uc.optional(),background:g(Dc)}),Lc={state:{input:d([]),output:jc}},Kt=R(s(),s()),Do=l().int().min(1).max(2147483647),Qt={enabled:v().optional(),startupTimeoutMs:Do.optional(),toolTimeoutMs:Do.optional(),enabledTools:g(s()).optional(),disabledTools:g(s()).optional()},Yt=c({transport:b("stdio"),runtime_id:s().min(1).optional(),command:s().min(1),args:g(s()).optional(),env:Kt.optional(),cwd:s().optional(),executor:h(["local","kaos"]).optional(),...Qt}),Xt=c({transport:b("http"),url:s().url(),headers:Kt.optional(),auth:b("oauth").optional(),bearerTokenEnvVar:s().min(1).optional(),...Qt}),Jt=c({transport:b("sse"),url:s().url(),headers:Kt.optional(),auth:b("oauth").optional(),bearerTokenEnvVar:s().min(1).optional(),...Qt}),ot=A("transport",[Yt,Xt,Jt]),An=h(["global","plugin","caller"]),qc=c({id:s(),name:s()}),Y=c({cwd:s().min(1).optional()}),$c=c({cwd:s().min(1).optional(),verify:v().optional()}),Ot=A("transport",[Yt.extend({name:s().min(1)}),Xt.extend({name:s().min(1)}),Jt.extend({name:s().min(1)})]),Ee=A("transport",[Yt.extend({envKeys:g(s()).optional()}),Xt.extend({headerKeys:g(s()).optional()}),Jt.extend({headerKeys:g(s()).optional()})]),ye=c({name:s(),config:Ee,source:An,origin:s(),mutable:v(),plugin:qc.optional()}),Gc=c({name:s().min(1).optional(),server:Ot.optional(),cwd:s().min(1).optional()}),Fc=c({success:v(),output:s()}),Bc=c({name:s().min(1),cwd:s().min(1).optional()}),Vc=c({state:h(["idle","stopped","unconfirmed"]),output:s()}),ie=A("source",[c({source:b("global"),name:s().min(1)}),c({source:b("plugin"),pluginId:s().min(1),serverName:s().min(1)})]),Zt=h(["not-applicable","bearer-token","oauth-required","oauth-authorized","oauth-expired","unavailable"]),Wc=c({serverId:s(),locator:ie,runtimeName:s(),canonicalUrl:s().optional(),origin:An,config:Ee,enabled:v(),editable:v()}),Hc=Wc.extend({authStatus:Zt,checkedAt:l().optional(),error:s().optional()}),zc=c({name:s(),authStatus:Zt}),At=c({credentialId:s().regex(/^[a-f0-9]{64}$/)}),Kc=At.extend({serverName:s().min(1),displayUrl:s().min(1),origin:b("unknown")}),Qc=c({canonicalUrl:Vt()}),Yc=A("status",[c({status:b("authorization-required"),flowId:s(),authorizationUrl:s()}),c({status:b("already-authorized")})]),Xc=c({flowId:s().min(1),timeoutMs:l().int().min(1).max(2**31-1).optional()}),Jc={listServers:{input:d([Y.optional()]),output:g(ye)},getServer:{input:d([s().min(1),Y.optional()]),output:ye},addServer:{input:d([Ot,Y.optional()]),output:g(ye)},updateServer:{input:d([Ot,Y.optional()]),output:g(ye)},removeServer:{input:d([s().min(1),Y.optional()]),output:g(ye)},testServer:{input:d([Gc]),output:Fc},stopServer:{input:d([Bc]),output:Vc},listAuthStatuses:{input:d([$c.optional()]),output:g(zc)},inspectServers:{input:d([g(ie).optional(),Y.optional()]),output:g(Hc)},resolveServerByName:{input:d([s().min(1),Y.optional()]),output:ie},beginServerAuth:{input:d([ie,Y.optional()]),output:Yc},completeServerAuth:{input:d([Xc]),output:_},cancelServerAuth:{input:d([c({flowId:s().min(1)})]),output:_},resetServerAuth:{input:d([ie,Y.optional(),Vt().optional()]),output:_},listStoredOAuthCredentials:{input:d([]),output:g(Kc)},revealStoredOAuthCredential:{input:d([At]),output:Qc},revokeStoredOAuthCredential:{input:d([At]),output:_}},eo=h(["direct","compact","fresh"]),Mt=c({operationId:s().min(1),model:s().min(1),mode:eo,thinking:s().optional(),selectedFromModel:s().optional()}),ne=c({operationId:s(),agentId:s(),state:h(["pending","preparing","completed","failed","cancelled"]),fromModel:s(),toModel:s(),mode:eo,binding:c({model:s(),thinking:s()}).optional(),windowEpoch:l().int().nonnegative().optional(),summaryGenerated:v().optional(),error:c({code:s(),message:s()}).optional()}),Mn=c({input:Mt,receipt:ne,revision:l().int().nonnegative(),originalBinding:c({model:s(),thinking:s()}),queueIndex:l().int()}),Zc=c({type:b("prompt.model_switch_queued"),time:l().optional(),entry:Mn.omit({queueIndex:!0}),queueIndex:l().int().nonnegative()}),ed=c({type:b("prompt.model_switch_status"),time:l().optional(),operationId:s(),receipt:ne}),td=c({type:b("turn.step.started"),time:l().optional(),turnId:l(),step:l(),stepId:s().optional()}),od=c({type:b("turn.step.interrupted"),time:l().optional(),turnId:l(),step:l(),stepId:s().optional(),reason:s(),message:s().optional()}),nd=c({type:b("turn.step.retrying"),time:l().optional(),turnId:l(),step:l(),stepId:s().optional(),failedAttempt:l(),nextAttempt:l(),maxAttempts:l(),delayMs:l(),errorName:s(),errorMessage:s(),statusCode:l().optional()}),sd=c({type:b("hook.result"),time:l().optional(),turnId:l().optional(),hookEvent:s(),content:s(),blocked:v().optional()}),Z=c({goalId:s(),objective:s(),completionCriterion:s().optional(),status:h(["active","paused","blocked","complete"]),followUpTiming:h(["subagents_done","tasks_done"]).optional(),controlRevision:l().int().nonnegative().optional(),turnsUsed:l(),tokensUsed:l(),wallClockMs:l(),terminalReason:s().optional(),budget:c({tokenBudget:l().nullable(),turnBudget:l().nullable(),wallClockBudgetMs:l().nullable(),remainingTokens:l().nullable(),remainingTurns:l().nullable(),remainingWallClockMs:l().nullable(),tokenBudgetReached:v(),turnBudgetReached:v(),wallClockBudgetReached:v(),overBudget:v()})}),id=c({type:b("goal.updated"),time:l().optional(),snapshot:Z.nullable(),change:c({kind:h(["lifecycle","completion"]),status:Z.shape.status.optional(),reason:s().optional(),actor:h(["user","model","runtime","system"]).optional(),stats:c({turnsUsed:l(),tokensUsed:l(),wallClockMs:l()}).optional()}).optional()}),rd=c({type:b("turn.started"),time:l().optional(),turnId:l(),origin:k(),prompt:s().optional(),promptId:s().optional()}),ad=c({type:b("turn.ended"),time:l().optional(),turnId:l(),reason:h(["completed","cancelled","failed","blocked"]),error:k().optional(),durationMs:l().optional(),interruptReason:h(["user_cancelled","aborted","max_steps","error","filtered","blocked"]).optional()}),cd=c({type:b("assistant.delta"),time:l().optional(),turnId:l(),step:l().optional(),stepId:s().optional(),partId:s().optional(),delta:s(),part:bi.optional()}),dd=c({type:b("thinking.delta"),time:l().optional(),turnId:l(),delta:s()}),ud=c({type:b("tool.call.started"),time:l().optional(),turnId:l(),toolCallId:s(),name:s(),args:k(),description:s().optional(),display:k().optional()}),ld=c({type:b("tool.call.delta"),time:l().optional(),turnId:l(),toolCallId:s(),name:s().optional(),argumentsPart:s().optional()}),pd=c({type:b("tool.progress"),time:l().optional(),turnId:l(),toolCallId:s(),update:c({kind:h(["stdout","stderr","progress","status","custom"]),text:s().optional(),percent:l().optional(),customKind:s().optional(),customData:k().optional(),replace:v().optional()})}),md=c({type:b("tool.result"),time:l().optional(),turnId:l(),toolCallId:s(),output:k(),isError:v().optional(),synthetic:v().optional()}),nt=k(),to=h(["agent_idle","subagents_done","tasks_done"]),hd=c({type:b("prompt.submitted"),time:l().optional(),promptId:s(),userMessageId:s(),status:h(["running","queued","blocked"]),content:g(nt),createdAt:s(),appendTiming:to.optional(),revision:l().int().nonnegative().optional()}),gd=c({type:b("prompt.queued"),time:l().optional(),promptId:s(),content:g(nt),queueLength:l().int().nonnegative(),appendTiming:to.optional(),revision:l().int().nonnegative().optional()}),vd=c({type:b("prompt.started"),time:l().optional(),promptId:s()}),Sd=c({type:b("prompt.replaced"),time:l().optional(),promptId:s(),content:g(nt),replacedAt:s(),message:k().optional(),revision:l().int().nonnegative().optional()}),fd=c({type:b("prompt.timing_changed"),time:l().optional(),promptId:s(),appendTiming:to,revision:l().int().nonnegative(),changedAt:s()}),yd=c({type:b("prompt.steered"),time:l().optional(),activePromptId:s(),promptIds:g(s()),content:g(nt),steeredAt:s()}),bd=c({type:b("prompt.completed"),time:l().optional(),promptId:s(),finishedAt:s(),reason:h(["completed","failed","blocked"]).optional()}),_d=c({type:b("prompt.aborted"),time:l().optional(),promptId:s(),abortedAt:s(),beforeStart:v().optional()}),Id=c({type:b("prompt.moved"),time:l().optional(),promptId:s(),targetIndex:l().int().nonnegative(),queuedPromptIds:g(s()),movedAt:s()}),Td=c({type:b("compaction.started"),time:l().optional(),trigger:h(["manual","auto"]),instruction:s().optional(),phase:h(["queued","running"]).optional()}),wd=c({type:b("compaction.blocked"),time:l().optional(),turnId:l().optional()}),Ed=c({type:b("compaction.cancelled"),time:l().optional(),trigger:h(["manual","auto"]).optional(),reason:s().optional()}),kd=c({type:b("compaction.completed"),time:l().optional(),trigger:h(["manual","auto"]).optional(),result:c({summary:s(),compactedCount:l(),tokensBefore:l(),tokensAfter:l(),keptUserMessageCount:l().optional(),keptHeadUserMessageCount:l().optional(),droppedCount:l().optional(),strategy:h(["summarize","relay"]).optional(),shapeVersion:l().int().positive().optional(),reasonCodes:g(s()).optional(),fallbackFrom:h(["relay","summarize"]).optional()})}),Cd=Oe({time:l().optional(),turnId:l(),toolCallId:s(),toolName:s(),action:s()}),Rd=Oe({time:l().optional(),turnId:l(),toolCallId:s()}),Pd=Oe({time:l().optional(),message:s()}),Od=c({type:b("warning"),time:l().optional(),message:s(),code:s().optional()}),Ad=Oe({time:l().optional(),phase:s().optional(),autoCompactTokens:l().optional(),autoCompactSource:h(["session","profile","model","global","legacy"]).optional(),contextStrategy:h(["summarize","auto","fresh"]).optional(),contextStrategySource:h(["session","profile","global","default","subagent","executor"]).optional(),effectiveMaxContextTokens:l().optional(),reservedContextTokens:l().optional()}),Md={"prompt.model_switch_queued":{kind:"stream",name:"events",type:"prompt.model_switch_queued",schema:Zc},"prompt.model_switch_status":{kind:"stream",name:"events",type:"prompt.model_switch_status",schema:ed},"turn.step.started":{kind:"stream",name:"events",type:"turn.step.started",schema:td},"turn.step.interrupted":{kind:"stream",name:"events",type:"turn.step.interrupted",schema:od},"turn.step.retrying":{kind:"stream",name:"events",type:"turn.step.retrying",schema:nd},"hook.result":{kind:"stream",name:"events",type:"hook.result",schema:sd},"goal.updated":{kind:"stream",name:"events",type:"goal.updated",schema:id},"turn.started":{kind:"stream",name:"events",type:"turn.started",schema:rd},"turn.ended":{kind:"stream",name:"events",type:"turn.ended",schema:ad},"assistant.delta":{kind:"stream",name:"events",type:"assistant.delta",schema:cd},"thinking.delta":{kind:"stream",name:"events",type:"thinking.delta",schema:dd},"tool.call.started":{kind:"stream",name:"events",type:"tool.call.started",schema:ud},"tool.call.delta":{kind:"stream",name:"events",type:"tool.call.delta",schema:ld},"tool.progress":{kind:"stream",name:"events",type:"tool.progress",schema:pd},"tool.result":{kind:"stream",name:"events",type:"tool.result",schema:md},"prompt.submitted":{kind:"stream",name:"events",type:"prompt.submitted",schema:hd},"prompt.queued":{kind:"stream",name:"events",type:"prompt.queued",schema:gd},"prompt.started":{kind:"stream",name:"events",type:"prompt.started",schema:vd},"prompt.replaced":{kind:"stream",name:"events",type:"prompt.replaced",schema:Sd},"prompt.moved":{kind:"stream",name:"events",type:"prompt.moved",schema:Id},"prompt.timing_changed":{kind:"stream",name:"events",type:"prompt.timing_changed",schema:fd},"prompt.steered":{kind:"stream",name:"events",type:"prompt.steered",schema:yd},"prompt.completed":{kind:"stream",name:"events",type:"prompt.completed",schema:bd},"prompt.aborted":{kind:"stream",name:"events",type:"prompt.aborted",schema:_d},"compaction.started":{kind:"stream",name:"events",type:"compaction.started",schema:Td},"compaction.blocked":{kind:"stream",name:"events",type:"compaction.blocked",schema:wd},"compaction.cancelled":{kind:"stream",name:"events",type:"compaction.cancelled",schema:Ed},"compaction.completed":{kind:"stream",name:"events",type:"compaction.completed",schema:kd},"permission.approval.requested":{kind:"stream",name:"events",type:"permission.approval.requested",schema:Cd},"permission.approval.resolved":{kind:"stream",name:"events",type:"permission.approval.resolved",schema:Rd},error:{kind:"stream",name:"events",type:"error",schema:Pd},warning:{kind:"stream",name:"events",type:"warning",schema:Od},"agent.status.updated":{kind:"stream",name:"events",type:"agent.status.updated",schema:Ad}};function xn(t){const e=t.overrides;return{...t,overrides:e===void 0?void 0:{...e,kiki_context:e.kiki_context===null||e.kiki_context===void 0?e.kiki_context:[...e.kiki_context]}}}const Un=_i.transform(xn),xd=Ii.transform(t=>({...t,selection:xn(t.selection),effective:{...t.effective,kiki_context:[...t.effective.kiki_context]}})),Ud=c({type:b("text"),text:s()}),Dd=c({type:b("image_url"),imageUrl:c({url:s(),id:s().optional()})}),Nd=c({type:b("video_url"),videoUrl:c({url:s(),id:s().optional()})}),Dn=A("type",[Ud,Dd,Nd]);c({});const jd=c({execution:Un.optional(),afterModelSwitch:s().min(1).optional(),modelSwitchMode:h(["direct","compact","fresh"]).optional(),personaGreetingReply:v().optional(),profile:s().optional(),model:s().optional(),thinking:s().min(1).nullable().optional(),planMode:v().optional(),goalObjective:s().optional(),goalFollowUpTiming:h(["subagents_done","tasks_done"]).optional(),goalInitialStatus:h(["active","paused"]).optional(),goalControl:h(["pause","resume","cancel"]).optional()}),xt=c({input:g(Dn),execution:jd.optional(),appendTiming:h(["agent_idle","subagents_done","tasks_done"]).optional(),disabledTools:g(s()).optional(),promptId:s().min(1).optional()}),Ld=c({name:s(),args:s().optional()}),qd=xt.extend({skills:g(Ld).min(1)}),No=c({turn_id:l().optional(),prompt_id:s(),created_at:s(),state:h(["running","queued","blocked"]),append_timing:h(["agent_idle","subagents_done","tasks_done"]),revision:l().int().nonnegative()}),$d=c({input:g(Dn)}),Gd=c({name:s(),args:s().optional(),afterModelSwitch:s().min(1).optional()}),Ut=c({turn_id:l()}),Dt=c({code:s(),message:s(),name:s().optional(),details:R(s(),k()).optional(),retryable:v(),get cause(){return Dt.optional()}}),Fd=c({promptId:s(),turnId:l().optional(),state:h(["completed","failed","cancelled","blocked"]),result:A("type",[c({type:b("completed"),steps:l(),truncated:v()}),c({type:b("failed"),steps:l(),error:Dt}),c({type:b("cancelled"),steps:l(),reason:Dt})]).optional()});c({turnId:l().optional()});const Bd=c({command:s(),commandId:s().optional()}),Vd=c({stdout:s(),stderr:s(),isError:v().optional(),backgrounded:v().optional()});c({commandId:s()});c({model:s()});const Wd=c({model:s(),providerName:s().optional()});c({effort:s().min(1)});const Hd=c({effort:s()}),oo=h(["profile","prompt_fields","skills","instructions","plugins","mcp","injections"]),Nn=c({profile:v(),promptFields:v(),skills:v(),instructions:v(),plugins:v(),mcp:v(),injections:v()}),jn=c({surface:L([oo,b("executor_session")]),reason:s()}),zd=c({rebuilt:g(oo),changed:v(),changes:Nn.optional(),outcome:h(["applied","partial","failed"]),unsupported:g(jn),appliesOn:b("next_request"),readiness:c({mcp:g(c({runtimeName:s(),connection:h(["enabled","disabled","connecting","connected","failed","unavailable"]),error:s().optional()})),plugins:c({state:h(["ready","pending","failed","unavailable"]),errors:g(s())})})}),Kd=c({enabled:v(),outcome:h(["applied","partial","failed"]).optional(),trigger:h(["manual","compaction","fresh_start","summary","restore","model_switch_fresh","model_switch_compact","context_clear"]).optional(),at:s().optional(),error:s().optional(),changes:Nn.optional(),rebuilt:g(oo),unsupported:g(jn)}),Ln=h(["summarize","auto","fresh"]),Qd=c({strategy:Ln,source:h(["session","profile","global","default","subagent","executor"]),shadow:v()}),je=c({workspaceId:s(),runtimeId:s()}),Yd=c({image_in:v(),video_in:v(),audio_in:v(),thinking:v(),tool_use:v(),max_context_tokens:l(),max_input_tokens:l().optional(),dynamically_loaded_tools:v().optional()}),He=h(["manual","auto","review","yolo"]);c({mode:He});const Xd=c({state:h(["idle","running"]),activeTurnId:l().optional(),pendingTurnIds:g(l()),hasPendingRequests:v(),activeTraceId:s().optional()}),ze=c({inputOther:l(),output:l(),inputCacheRead:l(),inputCacheCreation:l()}),Jd=c({byModel:R(s(),ze).optional(),currentTurn:ze.optional(),total:ze.optional()});c({history:g(k()),tokenCount:l()});const Zd=c({name:s(),description:s().optional(),source:s()});c({name:s(),args:s().optional()});const eu=L([ce(),c({id:s(),content:s(),path:s()})]);c({id:s().optional()});c({activeOnly:v().optional(),limit:l().optional()});const tu=h(["running","completed","failed","timed_out","killed","lost"]),Le={taskId:s(),description:s(),status:tu,detached:v().optional(),startedAt:l(),endedAt:L([l(),ce()]),stopReason:s().optional(),terminalNotificationSuppressed:v().optional(),timeoutMs:l().optional(),receipt:Ti.optional(),receiptVerification:h(["verified","legacy_unverified","invalid"]).optional()},qe=A("kind",[c({kind:b("process"),command:s(),pid:l(),exitCode:L([l(),ce()]),...Le}),c({kind:b("agent"),agentId:s().optional(),profile:s().optional(),model:s().optional(),thinkingEffort:s().optional(),...Le}),c({kind:b("question"),questionCount:l(),toolCallId:s().optional(),...Le}),c({kind:b("media"),jobId:s(),...Le})]);c({taskId:s(),reason:s().optional()});c({taskId:s(),tail:l().optional()});const ou={getGoal:{input:d([]),output:c({goal:Z.nullable()})},createGoal:{input:d([c({objective:s(),completionCriterion:s().optional(),followUpTiming:h(["subagents_done","tasks_done"]).optional(),initialStatus:h(["active","paused"]).optional(),replace:v().optional()})]),output:Z},updateGoal:{input:d([c({goalId:s(),expectedRevision:l().int().nonnegative().optional(),objective:s().optional(),completionCriterion:s().nullable().optional(),followUpTiming:h(["subagents_done","tasks_done"]).optional(),budgetLimits:wi.optional()})]),output:Z},pauseGoal:{input:d([]),output:Z},resumeGoal:{input:d([c({reason:s().optional(),continueIfPaused:v().optional(),continueIfBlocked:v().optional()}).optional()]),output:Z},cancelGoal:{input:d([]),output:Z}},nu={switchModel:{input:d([Mt]),output:ne},getModelSwitch:{input:d([s()]),output:O(ne)},listModelSwitches:{input:d([]),output:g(Mn)},updateModelSwitch:{input:d([Mt,l().int().nonnegative().optional()]),output:ne},cancelModelSwitch:{input:d([s()]),output:ne},recoverModelSwitch:{input:L([d([s(),b("retry"),eo.optional()]),d([s(),b("keep_original")])]),output:ne},submit:{input:d([xt]),output:O(Ut)},submitAndWait:{input:d([xt]),output:Fd},submitSteer:{input:d([$d]),output:O(Ut)},resumeRecoveredQueue:{input:d([]),output:_}},su={activate:{input:d([Gd]),output:L([No,Ut])},promptWithSkills:{input:d([qd]),output:No}},iu={reconcileWhenIdle:{input:d([s()]),output:_}},ru={rebuild:{input:d([]),output:zd},control:{input:d([]),output:Kd},setEnabled:{input:d([v()]),output:_}},au={undo:{input:d([l().int().positive().max(Number.MAX_SAFE_INTEGER)]),output:l()}},cu={activate:{input:d([c({pluginId:s(),commandName:s(),args:s().optional()})]),output:_}},du={refreshSessionStart:{input:d([]),output:_}},uu={shutdown:{input:d([s().optional()]),output:_}},lu={cancelFromUser:{input:d([l().optional()]),output:_},status:{input:d([]),output:Xd}},pu={mode:{input:d([]),output:He},setMode:{input:d([He]),output:_},setModeAndBroadcast:{input:d([He]),output:_}},mu={list:{input:d([]),output:g(Zd)},run:{input:d([s(),s().optional()]),output:_}},hu={get:{input:d([]),output:je},set:{input:d([je]),output:je},switch:{input:d([s()]),output:je}},gu={get:{input:d([]),output:g(k())},append:{input:d([k()]),output:_},clear:{input:d([]),output:_}},vu={appendImported:{input:d([k()]),output:_}},Su={statusSize:{input:d([]),output:l()}},fu={run:{input:d([Bd]),output:Vd},cancel:{input:d([s()]),output:_}},jo=c({definitionId:s().optional(),source:h(["declared","inherited-default","builtin-default"]).optional(),activeTools:g(s()).readonly().optional(),currentTools:g(s()).readonly().optional(),revision:s().optional(),canRefresh:v(),reason:h(["main_only","binding_restricted","source_changed","source_unavailable"]).optional()}),yu={isToolActive:{input:d([s(),h(["builtin","user","mcp","plugin"]).optional()]),output:v()}},bu={inspectToolPolicy:{input:d([]),output:jo},refreshToolPolicy:{input:d([s().min(1)]),output:jo},getModel:{input:d([]),output:s()},setModel:{input:d([s()]),output:Wd},setEffort:{input:d([s()]),output:Hd},setThinking:{input:d([s()]),output:_},getEffectiveThinkingLevel:{input:d([]),output:s()},getModelCapabilities:{input:d([]),output:Yd},getAgentsMdWarning:{input:d([]),output:O(s())}},_u={status:{input:d([]),output:Jd}},Iu={status:{input:d([]),output:eu},enter:{input:d([]),output:_},clear:{input:d([]),output:_},cancel:{input:d([s().optional()]),output:_}},Tu=c({name:s(),transport:h(["stdio","http","sse"]),status:h(["pending","connected","failed","disabled","needs-auth","removed"]),toolCount:l(),error:s().optional()}),wu=c({locator:ie,override:h(["on","off","inherit"])}),Lo=c({locator:ie,runtimeName:s(),origin:h(["global","plugin","caller"]),config:A("transport",[Ee.options[0].omit({env:!0}),Ee.options[1].omit({headers:!0}),Ee.options[2].omit({headers:!0})]),authStatus:Zt,connection:h(["enabled","disabled","connecting","connected","failed","unavailable"]),override:h(["on","off","inherit"]),error:s().optional(),errorCode:b("tool_catalog_refresh_failed").optional()}),Eu={list:{input:d([]),output:g(Tu)},waitForInitialLoad:{input:d([]),output:_},initialLoadDurationMs:{input:d([]),output:l()},reconnect:{input:d([s()]),output:_},connect:{input:d([s(),ot]),output:_},listMcpSessionCapabilities:{input:d([]),output:g(Lo)},setMcpSessionOverride:{input:d([wu]),output:Lo}},ku=c({source:h(["manual","auto"]),instruction:s().optional()}),Cu={begin:{input:d([ku]),output:v()},cancel:{input:d([]),output:_},isCompacting:{input:d([]),output:v()},getAutoCompact:{input:d([]),output:c({tokens:l(),source:h(["session","profile","model","global","legacy"]),effectiveMaxContextTokens:l(),reservedContextTokens:l()})},getDefaultAutoCompact:{input:d([]),output:c({tokens:l(),source:h(["session","profile","model","global","legacy"]),effectiveMaxContextTokens:l(),reservedContextTokens:l()})},setAutoCompactOverride:{input:d([l().int().positive().safe().nullable()]),output:_},getContextStrategy:{input:d([]),output:Qd},setContextStrategyOverride:{input:d([Ln.nullable()]),output:_}},Ru={list:{input:d([v().optional(),l().optional()]),output:g(qe)},stopByUser:{input:d([s()]),output:O(qe)},stop:{input:d([s(),s().optional()]),output:O(qe)},detach:{input:d([s()]),output:O(qe)},readOutput:{input:d([s(),l().optional()]),output:s()}},qn=h(["pending","authenticated","denied","failed","expired","cancelled"]),Pu=A("status",[c({flow_id:s(),provider:s(),status:b("pending"),verification_uri:s(),verification_uri_complete:s(),user_code:s(),expires_in:l(),interval:l(),expires_at:s()}),c({flow_id:s(),provider:s(),status:b("authenticated")})]),Ou=c({flow_id:s(),provider:s(),status:qn,verification_uri:s(),verification_uri_complete:s(),user_code:s(),expires_in:l(),expires_at:s(),interval:l(),resolved_at:s().optional(),error_message:s().optional()}),Au=c({cancelled:v(),status:qn}),Mu=c({logged_out:b(!0),provider:s()}),$n=c({loggedIn:v(),provider:s().optional()}),xu=c({changed:g(c({provider_id:s(),provider_name:s(),added:l(),removed:l()})),unchanged:g(s()),failed:g(c({provider:s(),reason:s()}))}),Uu=c({region:h(["mainland-cn","global"]).optional()}),Du=c({id:s(),label:s(),provider:s(),protocol:s(),signed_in:v(),auth_source:Ei.optional(),connection_state:h(["ready","refresh_required","reconnect_required","signed_out"]).optional(),account:A("state",[c({state:b("known"),id:s()}),c({state:b("unknown")})]),quota:A("state",[c({state:b("known"),label:s(),remaining:l(),unit:h(["count","percent"]),reset_at:s().optional()}),c({state:b("unknown")})])}),Nu={probeOriginal:{input:d([Ci]),output:go},connectOriginal:{input:d([ki]),output:go},listMethods:{input:d([]),output:g(Du)},startLogin:{input:d([s().optional(),Uu.optional()]),output:Pu},getFlow:{input:d([s().optional()]),output:O(Ou)},cancelLogin:{input:d([s().optional()]),output:Au},logout:{input:d([s().optional()]),output:Mu},status:{input:d([s().optional()]),output:$n},refreshOAuthProviderModels:{input:d([]),output:xu}},ju={summarize:{input:d([]),output:g($n)},ensureReady:{input:d([s().optional()]),output:_}},Lu=c({id:s(),state:h(["ok","missing","failed"]),reason:s().optional(),detail:s().optional(),optional:v().optional()}),qu=c({running:v(),step:s().optional(),percent:l().optional(),error:s().optional(),note:s().optional()}),$e=c({id:h(["kimi-cu","kimi-webbridge","kiki-computer","kiki-browser"]),pluginId:s().optional(),displayName:s(),description:s(),supported:v(),state:h(["not_installed","partial","ready","unsupported"]),version:s().optional(),steps:g(Lu),plan:c({artifact:c({version:s(),url:s(),sha256:s(),metadataUrl:s(),maxBytes:l()}),destination:s(),browserExtensionUrl:s().optional(),note:s()}).optional(),install:qu}),$u={listCapabilities:{input:d([]),output:g($e)},getCapability:{input:d([s()]),output:$e},installCapability:{input:d([s(),s().optional(),h(["driver-only","managed-browser"]).optional()]),output:$e},cancelCapability:{input:d([s()]),output:$e}},qo=new Map,Gu=new Set;function E(t){for(const e of Object.values(t.codes)){const o=qo.get(e);if(o!==void 0&&o!==t.codes)throw new Error(`error code '${e}' is registered by two different domains`);qo.set(e,t.codes)}for(const e of t.retryable??[])Gu.add(e);for(const[e,o]of Object.entries(t.info??{}));}const Gn={codes:{INTERNAL:"internal",NOT_IMPLEMENTED:"not_implemented",VALIDATION_FAILED:"validation.failed"},info:{internal:{title:"Internal error",retryable:!1,public:!0,action:"Inspect logs or report the issue with diagnostics."},not_implemented:{title:"Not implemented",retryable:!1,public:!0,action:"This feature is not implemented yet."}}};E(Gn);class Re extends Error{code;details;constructor(e,o,n){super(o,n?.cause===void 0?void 0:{cause:n.cause}),this.name=n?.name??"Error2",this.code=e,this.details=n?.details}}const Fn={codes:{REQUEST_IDENTITY_UNSUPPORTED:"request_identity.unsupported",REQUEST_IDENTITY_CONFLICT:"request_identity.conflict",REQUEST_IDENTITY_INVALID:"request_identity.invalid",REQUEST_IDENTITY_NOT_FOUND:"request_identity.not_found",REQUEST_IDENTITY_UPDATE_FAILED:"request_identity.update_failed"},info:{"request_identity.unsupported":{title:"Request identity unsupported",retryable:!1,public:!0,action:"Choose a request identity policy supported by the selected protocol."},"request_identity.conflict":{title:"Request identity conflict",retryable:!1,public:!0,action:"Remove conflicting legacy fields or custom headers."},"request_identity.invalid":{title:"Invalid request identity",retryable:!1,public:!0,action:"Correct the request identity policy values."},"request_identity.not_found":{title:"Request identity not found",retryable:!1,public:!0,action:"Reload the identity list and pick an existing identity."},"request_identity.update_failed":{title:"Request identity update check failed",retryable:!0,public:!0,action:"Check the network or the installed CLI, then check again. The current version stays in use."}}};E(Fn);const Fu=/^(?:[a-z][a-z0-9_]{0,31}|custom:[a-z0-9][a-z0-9_-]{0,47})$/u,Bn=h(["codex_compatible","claude_code_compatible","grok_build_compatible","opencode_compatible","kimi_code","none"]),Vn=s().regex(Fu),Wn=A("mode",[c({mode:b("none")}).strict(),c({mode:b("codex_default")}).strict(),c({mode:b("custom"),value:s().min(1).refine(t=>!/[\u0000-\u001F\u007F]/u.test(t))}).strict()]),Bu=c({lineage:c({format:h(["codex","claude_code","grok_build","opencode","kimi_code","none"]).optional(),sessionScope:h(["shared_session","agent_session","none"]).optional(),threadIdentity:h(["agent","none"]).optional(),parentThread:h(["immediate_agent","none"]).optional(),subagentMarker:h(["enabled","none"]).optional(),turnAncestry:h(["spawn_context","none"]).optional()}).strict().optional(),client:c({installationIdentity:h(["persistent_local","none"]).optional(),originator:Wn.optional(),userAgent:h(["codex","claude_code","grok_build","opencode","kimi_code","host","none"]).optional()}).strict().optional(),request:c({logicalId:h(["turn","none"]).optional(),turnIndex:h(["agent_session","none"]).optional()}).strict().optional(),cache:c({source:h(["session","none"]).optional(),responses:h(["prompt_cache_key","none"]).optional(),messages:h(["metadata_user_id","none"]).optional()}).strict().optional(),responsesMetadata:h(["codex","none"]).optional()}).strict().refine(so,{message:"request identity overrides must contain a leaf value"}),no=c({preset:Bn.optional(),profile:Vn.optional(),overrides:Bu.optional()}).strict().refine(Hn,{message:"request identity policy must contain preset, profile or overrides"}).refine(t=>t.preset===void 0||t.profile===void 0,{message:"request identity policy cannot set both preset and profile"}),Vu=c({lineage:c({format:h(["codex","claude_code","grok_build","opencode","kimi_code","none"]).optional(),session_scope:h(["shared_session","agent_session","none"]).optional(),thread_identity:h(["agent","none"]).optional(),parent_thread:h(["immediate_agent","none"]).optional(),subagent_marker:h(["enabled","none"]).optional(),turn_ancestry:h(["spawn_context","none"]).optional()}).strict().optional(),client:c({installation_identity:h(["persistent_local","none"]).optional(),originator:Wn.optional(),user_agent:h(["codex","claude_code","grok_build","opencode","kimi_code","host","none"]).optional()}).strict().optional(),request:c({logical_id:h(["turn","none"]).optional(),turn_index:h(["agent_session","none"]).optional()}).strict().optional(),cache:c({source:h(["session","none"]).optional(),responses:h(["prompt_cache_key","none"]).optional(),messages:h(["metadata_user_id","none"]).optional()}).strict().optional(),responses_metadata:h(["codex","none"]).optional()}).strict().refine(so,{message:"request identity overrides must contain a leaf value"});c({preset:Bn.optional(),profile:Vn.optional(),overrides:Vu.optional()}).strict().refine(Hn,{message:"request identity policy must contain preset, profile or overrides"}).refine(t=>t.preset===void 0||t.profile===void 0,{message:"request identity policy cannot set both preset and profile"});function Hn(t){return t.preset!==void 0||t.profile!==void 0||t.overrides!==void 0}function so(t){return t===void 0?!1:t===null||typeof t!="object"?!0:Object.values(t).some(so)}h(["connected","error","unconfigured"]);const Wu=c({systemPrompt:s(),messages:g(k()),tools:g(k()).optional(),responseFormat:k().optional()}),Hu=c({cacheKey:s().optional(),temperature:l().optional(),topP:l().optional(),thinkingEffort:s().optional(),maxCompletionTokens:l().optional()}).optional(),zu=c({type:s()}).passthrough(),Ku={listModels:{input:d([]),output:g(Pi)},listProviders:{input:d([]),output:g(vo)},getProvider:{input:d([s()]),output:vo},setDefaultModel:{input:d([s()]),output:Ri},generate:{input:d([s(),Wu,Hu]),chunk:zu,streaming:!0}},Qu=c({scope:h(["all","oauth"]).optional(),providerId:s().optional(),apiKey:s().min(1).optional()}),Yu={listDiscoveredModels:{input:d([]),output:Ai},refreshProviderModels:{input:d([Qu.optional()]),output:Oi}},me="config.invalid",Xu="provider.api_error",Ju="provider.filtered",Zu="provider.rate_limit",el="provider.auth_error",tl="provider.connection_error",ol="provider.overloaded",nl="context.overflow",st=g(Vt().refine(t=>{const e=new URL(t);return(e.protocol==="https:"||e.protocol==="http:")&&e.username===""&&e.password===""&&e.search===""&&e.hash===""},"Use an HTTP(S) API base URL without credentials, query, or fragment")).min(1),zn=l().int().nonnegative().safe().optional(),Kn=c({encoding:h(["off","gzip","zstd"]).optional(),targets:st.optional(),minBytes:zn,dictionary:v().optional()}).strict(),it=Kn.superRefine((t,e)=>{const o=t.targets!==void 0||t.minBytes!==void 0||t.dictionary!==void 0;if(t.encoding==="off"){o&&e.addIssue({code:"custom",message:"encoding off cannot include other request_compression fields"});return}!o&&t.encoding===void 0&&e.addIssue({code:"custom",message:"request_compression needs encoding, targets, min_bytes, or dictionary"}),t.encoding==="gzip"&&t.dictionary!==void 0&&e.addIssue({code:"custom",message:"dictionary applies only to encoding zstd",path:["dictionary"]})}),Qn=c({off:b(!0).optional(),targets:st.optional()}).strict(),rt=Qn.superRefine((t,e)=>{if(t.off===!0){t.targets!==void 0&&e.addIssue({code:"custom",message:"responses_web_socket off cannot include targets",path:["targets"]});return}t.targets===void 0&&e.addIssue({code:"custom",message:"responses_web_socket needs targets or off"})});function sl(t,e){return $o(e)?{encoding:"off"}:t===void 0?void 0:$o(t)?{encoding:"off"}:rl(t)}function il(t,e){const o=t;if(!(o===void 0||o.off===!0)){if(o.targets===void 0)throw new Re(me,"responses_web_socket needs targets");return{targets:[...o.targets]}}}function $o(t){return t!==void 0&&t.encoding==="off"}function rl(t){if(t.encoding===void 0||t.encoding==="off"||t.targets===void 0)throw new Re(me,"request_compression needs encoding and targets");const e=[...t.targets];if(t.encoding==="gzip"){if(t.dictionary!==void 0)throw new Re(me,"request_compression dictionary requires encoding zstd");return t.minBytes===void 0?{encoding:"gzip",targets:e}:{encoding:"gzip",targets:e,minBytes:t.minBytes}}const o=t.minBytes===void 0?{encoding:"zstd",targets:e}:{encoding:"zstd",targets:e,minBytes:t.minBytes};return t.dictionary===void 0?o:{...o,dictionary:t.dictionary}}function Yn(t){return t.issues.map(e=>e.message).join("; ")}const Xn=Kn.superRefine(t=>{const e=it.safeParse(t);if(!e.success)throw new Re(me,Yn(e.error));sl(e.data,void 0)}),Jn=Qn.superRefine(t=>{const e=rt.safeParse(t);if(!e.success)throw new Re(me,Yn(e.error));il(e.data)});c({encoding:h(["off","gzip","zstd"]).optional(),targets:st.optional(),min_bytes:zn,dictionary:v().optional()}).strict().superRefine((t,e)=>{const o=it.safeParse(al(t));if(!o.success)for(const n of o.error.issues)e.addIssue({code:"custom",message:n.message,path:n.path})});c({off:b(!0).optional(),targets:st.optional()}).strict().superRefine((t,e)=>{const o=rt.safeParse(cl(t));if(!o.success)for(const n of o.error.issues)e.addIssue({code:"custom",message:n.message,path:n.path})});function al(t){const e={};return t.encoding!==void 0&&(e.encoding=t.encoding),t.targets!==void 0&&(e.targets=[...t.targets]),t.min_bytes!==void 0&&(e.minBytes=t.min_bytes),t.dictionary!==void 0&&(e.dictionary=t.dictionary),e}function cl(t){const e={};return t.off!==void 0&&(e.off=t.off),t.targets!==void 0&&(e.targets=[...t.targets]),e}const io=h(["user","memory"]),dl=c({value:k().optional(),defaultValue:k().optional(),userValue:k().optional(),memoryValue:k().optional()}),ul=c({domain:s().optional(),severity:h(["warning","error"]),message:s()}),ll=d([s(),k(),io.optional()]).superRefine(([t,e],o)=>{t==="requestIdentity"&&ro(e,o,[1],!1),t==="requestCompression"&&ae(it,e,o,[1],!1),t==="responsesWebSocket"&&ae(rt,e,o,[1],!1)}),pl=d([s(),k(),io.optional()]).superRefine(([t,e],o)=>{t==="requestIdentity"&&ro(e,o,[1],!0),t==="requestCompression"&&ae(Xn,e,o,[1],!0),t==="responsesWebSocket"&&ae(Jn,e,o,[1],!0)}),ml=d([R(s(),k()),io.optional()]).superRefine(([t],e)=>{Object.hasOwn(t,"requestIdentity")&&ro(t.requestIdentity,e,[0,"requestIdentity"],!0),Object.hasOwn(t,"requestCompression")&&ae(Xn,t.requestCompression,e,[0,"requestCompression"],!0),Object.hasOwn(t,"responsesWebSocket")&&ae(Jn,t.responsesWebSocket,e,[0,"responsesWebSocket"],!0)});function ro(t,e,o,n){ae(no,t,e,o,n)}function ae(t,e,o,n,i){if(!(i&&e==null))try{t.parse(e)}catch(a){if(a instanceof Mi){for(const r of a.issues)o.addIssue({...r,path:[...n,...r.path]});return}o.addIssue({code:"custom",message:a instanceof Error?a.message:String(a),path:n})}}const hl={get:{input:d([s()]),output:k()},inspect:{input:d([s()]),output:dl},getAll:{input:d([]),output:R(s(),k())},set:{input:ll,output:_},replace:{input:pl,output:_},replaceSections:{input:ml,output:_},reload:{input:d([]),output:_},diagnostics:{input:d([]),output:g(ul)}},G={input:d([]),output:s()},gl={input:d([]),output:c({productName:s(),version:s(),platform:s(),userAgentSuffix:s().optional()})},vl={platform:G,arch:G,cwd:G,osHomeDir:G,homeDir:G,configPath:G,clientVersion:G,clientIdentity:gl,sessionsDir:G,blobsDir:G,storeDir:G,cacheDir:G,logsDir:G},Zn=c({id:s().min(1),name:s().min(1),media_type:s().min(1),size:l().int().nonnegative(),created_at:s(),expires_at:s().optional()}),Sl=c({name:s().optional(),mimeType:s().optional(),expiresInSec:l().optional()}),fl=c({meta:Zn,data:s()}),yl={save:{input:d([s(),s().min(1),Sl]),output:Zn},get:{input:d([s().min(1)]),output:fl},delete:{input:d([s().min(1)]),output:_}},Go=c({id:s(),title:s(),description:s(),surface:h(["core","tui","both"]),env:s(),defaultEnabled:v(),enabled:v(),source:h(["master-env","env","config","default"]),configValue:v().optional()}),bl={enabled:{input:d([s()]),output:v()},snapshot:{input:d([]),output:R(s(),v())},enabledIds:{input:d([]),output:g(s())},explain:{input:d([s()]),output:O(Go)},explainAll:{input:d([]),output:g(Go)}},_l=c({name:s().min(1),path:s().min(1),is_dir:b(!0)}),Il=c({path:s().min(1),parent:s().min(1).nullable(),entries:g(_l)}),Tl=c({home:s().min(1),recent_roots:g(s().min(1))}),wl={browse:{input:d([s().optional()]),output:Il},home:{input:d([]),output:Tl}},El=h(["openai-codex","grok-build","kimi-code"]),kl=h(["file","keyring","encrypted"]),Cl=c({kind:b("local_original"),provider:El,homeDir:s().min(1),storageBackend:kl,authFile:s().min(1).optional(),accountId:s().min(1).optional(),userId:s().min(1).optional(),scope:s().min(1).optional()}).strict().superRefine((t,e)=>{t.provider!=="kimi-code"&&t.accountId===void 0&&e.addIssue({code:"custom",path:["accountId"],message:"An original account identity is required."}),t.provider==="kimi-code"&&(t.storageBackend==="encrypted"||t.accountId!==void 0||t.userId!==void 0||t.scope!==void 0)&&e.addIssue({code:"custom",message:"Kimi Code sources select a credential slot, not an account identity."})}),es=c({storage:h(["file","keyring"]),key:s().min(1),oauthHost:s().min(1).optional(),source:Cl.optional()}),Rl=h(["anthropic","openai","openai_responses","google-genai"]),ts=c({providerId:s().optional(),baseUrl:s().optional(),apiKey:s().optional(),oauth:es.optional(),protocol:Rl.optional(),name:s().optional(),aliases:g(s()).optional(),provider:s().optional(),model:s().optional(),maxContextSize:l().int().min(1).optional(),maxOutputSize:l().int().min(1).optional(),capabilities:g(s()).optional(),displayName:s().optional(),reasoningKey:s().optional(),adaptiveThinking:v().optional(),betaApi:v().optional(),supportEfforts:g(s()).optional(),defaultEffort:s().optional(),requestIdentity:no.optional()}),Pl=ts.omit({providerId:!0,baseUrl:!0,apiKey:!0,oauth:!0,protocol:!0,name:!0,aliases:!0,provider:!0,model:!0,betaApi:!0,requestIdentity:!0}).partial(),Et=ts.extend({overrides:Pl.optional(),pricingModel:s().trim().min(1).optional()}).passthrough(),Ol={get:{input:d([s()]),output:O(Et)},list:{input:d([]),output:R(s(),Et)},set:{input:d([s(),Et]),output:_},delete:{input:d([s()]),output:_}},Al=c({baseRevision:s().min(1).optional()}),Ml={readModel:{input:d([s()]),output:ht},createModel:{input:d([Ni]),output:ht},updateModel:{input:d([s(),Di]),output:ht},deleteModel:{input:d([s(),Al.optional()]),output:Pt()},readProvider:{input:d([s()]),output:mt},createProvider:{input:d([Ui]),output:mt},updateProvider:{input:d([s(),xi]),output:mt},deleteProvider:{input:d([s()]),output:Pt()}},xl=c({severity:h(["error","warn","info"]),message:s()}),Ul=c({name:s().optional(),email:s().optional()}),Dl=c({skill:s()}),Nl=c({displayName:s().optional(),shortDescription:s().optional(),longDescription:s().optional(),developerName:s().optional(),websiteURL:s().optional()}),jl=c({event:h(["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","PermissionResult","UserPromptSubmit","UserPromptQueued","TurnStarted","Stop","StopFailure","Interrupt","SessionStart","SessionEnd","SessionHeartbeat","SubagentStart","SubagentStop","TaskStarted","PreCompact","PostCompact","Notification"]),matcher:s().optional(),command:s().min(1),timeout:l().int().min(1).max(600).optional()}),Ll=c({path:s(),name:s()}),ql=h(["kimi-plugin-root","kimi-plugin-dir","claude-code"]),Nt=h(["local-path","zip-url","github"]),$l=h(["ok","error"]),jt=c({kind:h(["branch","tag","sha"]),value:s()}),Gl=c({name:s(),version:s().optional(),description:s().optional(),keywords:g(s()).optional(),author:Ul.optional(),homepage:s().optional(),license:s().optional(),icon:s().optional(),skills:g(s()).optional(),agents:g(s()).optional(),sessionStart:Dl.optional(),mcpServers:R(s(),ot).optional(),hooks:g(jl).optional(),commands:g(Ll).optional(),interface:Nl.optional(),skillInstructions:s().optional(),systemPrompt:s().optional(),unsupportedComponents:g(s()).optional()}),Fl=c({name:s(),runtimeName:s(),enabled:v(),transport:h(["stdio","http","sse"]),command:s().optional(),args:g(s()).optional(),cwd:s().optional(),url:s().optional(),envKeys:g(s()).optional(),headerKeys:g(s()).optional()}),Fo=c({owner:s(),repo:s(),ref:jt,installedSha:s().optional()}),Ke=c({id:s(),displayName:s(),version:s().optional(),icon:s().optional(),enabled:v(),globalEnabled:v(),state:$l,skillCount:l(),mcpServerCount:l(),enabledMcpServerCount:l(),hookCount:l(),commandCount:l(),hasErrors:v(),source:Nt,originalSource:s().optional(),github:Fo.optional(),zipSha256:s().optional(),rollback:c({version:s().optional(),source:Nt,originalSource:s().optional(),github:Fo.optional(),zipSha256:s().optional()}).optional()}),Bl=Ke.extend({root:s(),installedAt:s(),updatedAt:s().optional(),manifestKind:ql.optional(),manifestPath:s().optional(),manifest:Gl.optional(),mcpServers:g(Fl),shadowedManifestPath:s().optional(),diagnostics:g(xl)}),Vl=c({added:g(s()),removed:g(s()),errors:g(c({id:s(),message:s()}))}),Wl=c({id:s(),source:Nt,current:jt.optional(),latest:jt,displayVersion:s(),updateAvailable:v()}),Hl=c({pluginId:s(),name:s(),description:s(),body:s(),path:s()}),zl=vn.extend({fingerprint:s().optional(),consent:v().optional(),defaultEnabled:v().optional()}),Kl=c({id:s(),enabled:v()}),Ql=c({id:s(),server:s(),enabled:v()}),Yl=c({id:s(),deleteData:v().optional()}),Xl=c({id:s()}),Jl={listPlugins:{input:d([]),output:g(Ke)},previewPlugin:{input:d([vn]),output:ji},installPlugin:{input:d([zl]),output:Ke},rollbackPlugin:{input:d([c({id:s()})]),output:Ke},setPluginEnabled:{input:d([Kl]),output:_},setPluginMcpServerEnabled:{input:d([Ql]),output:_},removePlugin:{input:d([Yl]),output:_},reloadPlugins:{input:d([]),output:Vl},getPluginInfo:{input:d([Xl]),output:Bl},listPluginCommands:{input:d([]),output:g(Hl)},checkUpdates:{input:d([]),output:g(Wl)}},Zl={sources:{input:d([]),output:g(Ki)},discover:{input:d([Bi]),output:Hi},preview:{input:d([Fi]),output:Wi},start:{input:d([Gi]),output:Se},jobs:{input:d([$i.optional()]),output:c({items:g(Se),cursor:s().nullable()})},job:{input:d([s()]),output:Se},cancel:{input:d([s()]),output:Se},resume:{input:d([s()]),output:Se},archives:{input:d([qi.optional()]),output:c({items:g(zi),cursor:s().nullable()})},read:{input:d([Li]),output:Vi}},ep={list:{input:d([]),output:g(Ue)},get:{input:d([s()]),output:O(gt)},export:{input:d([s()]),output:or},preview:{input:d([er]),output:tr},install:{input:d([Zi]),output:Ue},checkUpdates:{input:d([]),output:g(Ue)},update:{input:d([Ji]),output:Ue},fork:{input:d([Xi]),output:gt},saveLocal:{input:d([Yi]),output:gt},remove:{input:d([Qi]),output:_},listMarkets:{input:d([]),output:g(vt)},addMarket:{input:d([So]),output:vt},updateMarket:{input:d([So]),output:vt},removeMarket:{input:d([s()]),output:_}},tp={managedSources:{input:d([]),output:g(De)},sourceSettings:{input:d([ur]),output:De},updateSource:{input:d([dr]),output:De},addScriptSource:{input:d([cr]),output:De},sources:{input:d([]),output:g(yo)},setSources:{input:d([ar]),output:g(yo)},catalog:{input:d([c({id:s().min(1)}).strict()]),output:pr},providers:{input:d([]),output:fo},capabilities:{input:d([rr]),output:L([ir,c({providers:fo}).strict()])},voices:{input:d([sr]),output:lr},jobs:{input:d([nr.optional()]),output:g(Qe)},job:{input:d([s().min(1)]),output:Qe}},op={cancel:{input:d([s().min(1)]),output:Qe},resume:{input:d([s().min(1)]),output:Qe}},np=c({definition:mr.optional(),id:s().optional(),name:s().optional(),title:s().optional(),job:s().optional(),profile:s().optional(),modelAlias:s().optional(),thinkingEffort:s().optional(),greeting:s().optional(),greetings:g(s()).optional(),roomGreeting:s().optional(),delivery:h(["reply","message"]).optional(),memory:c({shared:g(h(["global","workspace"]))}).optional(),skills:g(s()).optional(),tags:g(s()).optional(),notes:s().optional(),homeWorkspace:s().optional(),description:s().optional(),examples:s().optional(),extensions:k().optional(),expectedRevision:s().optional()}).strict(),sp=c({memory:c({status:h(["committed","pending","failed"]),error:s().optional()}).strict()}).strict(),ip={list:{input:d([hr.optional()]),output:g(vr)},get:{input:d([s()]),output:O(St)},put:{input:d([np]),output:St},duplicate:{input:d([s(),c({id:s().optional(),name:s().optional()}).optional()]),output:St},archive:{input:d([s(),v().optional()]),output:gr},delete:{input:d([s(),s().optional()]),output:sp}},rp={list:{input:d([]),output:g(yt)},enable:{input:d([ft]),output:yt},ensureHomeSession:{input:d([ft]),output:yt},update:{input:d([ft,Sr]),output:Or}},ap={list:{input:d([]),output:g(z)},listItems:{input:d([]),output:g(Ar)},get:{input:d([B]),output:O(z)},create:{input:d([Er]),output:z},createFromThreads:{input:d([wr]),output:z},searchThreads:{input:d([Tr.optional()]),output:Pr},addMember:{input:d([B,Ir]),output:z},removeMember:{input:d([B,_r]),output:z},update:{input:d([B,br]),output:z},delete:{input:d([B]),output:_},postUserMessage:{input:d([B,yr]),output:Rr},pause:{input:d([B]),output:z},continue:{input:d([B]),output:z},stop:{input:d([B]),output:z},log:{input:d([B,fr.optional()]),output:Cr},usage:{input:d([B]),output:kr}},cp=s(),Bo=R(s(),s()),dp=h(["static","discover","oauth-catalog"]),up=no,lp=c({modelSource:dp.optional(),baseUrl:s().optional(),customHeaders:Bo.optional(),defaultModel:s().optional(),requestIdentity:up.optional(),requestCompression:it.optional(),responsesWebSocket:rt.optional(),type:cp.optional(),apiKey:s().optional(),oauth:es.optional(),env:Bo.optional(),source:R(s(),k()).optional()}),kt=Mr((t,e)=>{if(t!==null&&typeof t=="object")for(const o of["requestAttribution","requestOriginator"])o in t&&e.addIssue({code:"custom",message:`${o} was removed; use requestIdentity`,path:[o]});return t},lp),pp={get:{input:d([s()]),output:O(kt)},list:{input:d([]),output:R(s(),kt)},set:{input:d([s(),kt]),output:_},delete:{input:d([s()]),output:_}},os=c({agentVersion:s().optional(),image:v().optional(),audio:v().optional(),fork:v().optional(),nativeSteering:v().optional(),questionForm:v().optional(),planApproval:v().optional(),models:g(s()).optional(),thinkingLevels:g(s()).optional(),authMethods:g(s()).optional(),resume:v().optional(),load:v().optional(),permissionModes:g(s()).optional()}),ao=c({execution:xd.optional(),homedir:s().optional(),type:h(["main","sub","independent"]).optional(),parentAgentId:L([s(),ce()]).optional(),delegator:A("kind",[c({kind:b("agent"),agentId:s()}),c({kind:b("external"),delegationId:s()})]).optional(),forkedFrom:s().optional(),labels:R(s(),s()).optional(),displayName:s().optional(),userLabel:s().optional(),model:s().optional(),thinkingEffort:s().optional(),executor:s().optional(),executorProtocol:s().optional(),negotiated:os.optional(),executorAuth:xr.optional(),allowKikiSubagents:v().optional(),status:h(["completed","failed","cancelled"]).optional(),completedAt:l().optional(),resultSummary:s().optional(),error:s().optional(),usage:ze.optional(),contextTokens:l().optional(),toolCallCount:l().int().nonnegative().optional()}),ns=c({worktreeId:s(),branch:s(),sourceRoot:s(),baseRef:s()}),mp=c({id:s(),version:l().optional(),title:s().optional(),titleKind:h(["replaceable","generated","custom"]).optional(),lastPrompt:s().optional(),delivery:h(["reply","message"]).optional(),createdAt:l(),updatedAt:l(),activityUpdatedAt:l().optional(),archived:v(),archivedAt:l().optional(),cwd:s().optional(),worktree:ns.optional(),forkedFrom:s().optional(),agents:R(s(),ao).optional(),custom:R(s(),k()).optional(),sshHosts:R(s(),s()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),hp=c({version:l().optional(),title:s().optional(),titleKind:h(["replaceable","generated","custom"]).optional(),lastPrompt:s().optional(),delivery:h(["reply","message"]).optional(),updatedAt:l().optional(),activityUpdatedAt:l().optional(),archived:v().optional(),archivedAt:l().optional(),cwd:s().optional(),worktree:ns.optional(),forkedFrom:s().optional(),agents:R(s(),ao).optional(),custom:R(s(),k()).optional(),sshHosts:R(s(),s()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),gp=h(["id","version","title","titleKind","lastPrompt","delivery","createdAt","updatedAt","activityUpdatedAt","archived","archivedAt","cwd","worktree","forkedFrom","agents","custom","sshHosts","lastTurnReason","usage"]),vp=c({changed:g(gp)}),Sp={read:{input:d([]),output:mp},getAgentExecutor:{input:d([s().min(1)]),output:O(s())},update:{input:d([hp]),output:_},setTitle:{input:d([s()]),output:_},setArchived:{input:d([v()]),output:_},registerAgent:{input:d([s(),ao]),output:_}},Vo=c({id:s(),workspaceId:s(),cwd:s().optional(),title:s().optional(),lastPrompt:s().optional(),delivery:h(["reply","message"]).optional(),createdAt:l(),updatedAt:l(),archived:v(),archivedAt:l().optional(),custom:R(s(),k()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional(),executorId:s().optional(),negotiated:os.optional(),allowKikiSubagents:v().optional()}),fp=c({workspaceIds:g(s()).optional(),sessionId:s().optional(),includeArchived:v().optional(),limit:l().optional(),childOf:s().optional(),before:s().optional(),after:s().optional()}),yp=c({workspaceIds:g(s()).optional(),includeArchived:v().optional()}),bp={listRecent:{input:d([fp]),output:gc(Vo)},get:{input:d([s()]),output:O(Vo)},count:{input:d([yp]),output:l()}},Ge=c({id:s(),root:s(),name:s(),createdAt:l(),lastOpenedAt:l(),pinned:v()}),_p=c({name:s().optional(),pinned:v().optional()}),Ip={list:{input:d([]),output:g(Ge)},get:{input:d([s()]),output:O(Ge)},createOrTouch:{input:d([s(),s().optional()]),output:Ge},update:{input:d([s(),_p]),output:O(Ge)},delete:{input:d([s()]),output:_}},Q=c({hostId:s().trim().min(1),workspaceId:s().trim().min(1),sessionId:s().trim().min(1),personaId:s().optional(),name:s().optional(),bridgeId:s().uuid().optional(),connectionId:s().uuid().optional()}),Tp=c({ref:Q,title:s().optional(),updatedAt:l().int().nonnegative(),createdAt:l().int().nonnegative(),state:h(["cold","idle","running"])}),wp=c({workspaceId:s().trim().min(1).optional(),cursor:s().min(1).optional(),limit:l().int().min(1).max(100).optional()}),Ep=c({threads:g(Tp),nextCursor:s().optional()}),kp=c({turnId:l().int().nonnegative(),startedAt:l().int().nonnegative().optional(),endedAt:l().int().nonnegative(),reason:h(["completed","cancelled","failed","blocked"]),origin:h(["user","peer","bridged_peer","external","mixed","unknown","thread_created"]),bridgedPeer:c({source:Q,sourceHomeId:s().uuid(),targetHomeId:s().uuid(),bridgeId:s().uuid(),revision:l().int().positive(),location:h(["local","network"]),createdAt:l(),expiresAt:l(),sourceSeq:l(),causeId:s(),hop:l(),messageId:s()}).optional(),peer:c({source:Q,messageId:s().min(1)}).optional(),input:s(),output:s(),contentRefs:g(Ze).optional()}),Cp=c({thread:Q,contentRef:Ze.optional(),cursor:s().min(1).optional(),limit:l().int().min(1).max(100).optional()}),F=g(Ze).optional(),Rp=Ur.extend({contentRefs:F,attachmentIds:g(s()).optional()}),Pp=Dr.extend({contentRefs:F}),Op=Nr.extend({contentRefs:F,agentRefs:g(Qr).optional()}),Ap=jr.extend({contentRefs:F}),Mp=A("kind",[Rp,Pp,Op,Ap]),xp=Lr.extend({frames:g(Mp)}),Up=qr.extend({contentRefs:F,attachmentIds:g(s()).optional(),steps:g(xp),execution:$r.extend({losses:g(s())}).optional()}),Dp=A("kind",[Up,Fr.extend({contentRefs:F}),Gr]),Np=Sn.extend({items:g(Dp),tasks:g(Kr.extend({contentRefs:F})),interactions:g(zr.extend({contentRefs:F})).default([]),attachments:g(Hr.extend({contentRefs:F})).default([]),todos:g(Wr.extend({contentRefs:F})).default([]),prompts:g(Vr.extend({contentRefs:F})).default([]),meta:Br.extend({contentRefs:F})}),jp=c({thread:Q,turns:g(kp),nextCursor:s().optional(),incomplete:b("history_preparing").optional(),view:c({transcript:Np.optional(),segment:fn.optional()}).optional()}),Lp=c({target:Q,content:s().min(1).max(1e5),idempotencyKey:s().min(1).max(256)}).strict(),qp=c({messageId:s().min(1),targetSeq:l().int().nonnegative(),acceptedAt:l().int().nonnegative(),deduplicated:v(),delivery:h(["pending","delivered","undeliverable"])}),$p=c({ref:Q,seq:l().int().nonnegative(),kind:h(["terminal","attention","lifecycle","message_undeliverable"]),at:l().int().nonnegative(),reason:s(),turnId:l().int().nonnegative().optional(),messageId:s().min(1).optional()}),Gp=c({thread:Q,cursor:s().min(1).optional()}),Fp=c({threads:g(Gp).min(1).max(8),timeoutMs:l().int().min(0).max(6e4).optional()}).superRefine((t,e)=>{const o=new Set;t.threads.forEach((n,i)=>{const{hostId:a,workspaceId:r,sessionId:u}=n.thread,m=`${a}\0${r}\0${u}`;o.has(m)&&e.addIssue({code:"custom",path:["threads",i],message:"duplicate thread reference"}),o.add(m)})}),Bp=c({thread:Q,cursor:s().min(1),activities:g($p)}),Vp=c({threads:g(Bp),timedOut:v()}),Wo=c({ref:Q,title:s().optional(),deleted:v(),archived:v()}),Wp=c({messageId:s().describe("Stable recipient main-agent prompt id and user-message id, including steered delivery and retries; navigate only delivered records."),source:A("kind",[c({kind:b("thread"),thread:Wo}),c({kind:b("room"),roomId:s()})]),target:Wo,content:s(),acceptedAt:l(),targetSeq:l(),delivery:h(["pending","delivered","undeliverable"]),reason:s().optional(),reasonCode:h(["thread_not_found","thread_archived","communication_disabled","cross_host","prompt_rejected","session_unavailable","workspace_unavailable","executor_unavailable","cancelled","delivery_failed"]).optional(),reasonDetail:s().optional()}),Hp=c({workspaceId:s().trim().min(1).optional(),sessionId:s().trim().min(1).optional(),peerSessionId:s().trim().min(1).optional(),cursor:s().min(1).max(4096).optional(),limit:l().int().min(1).max(100).optional()}).strict().refine(t=>t.peerSessionId===void 0||t.sessionId!==void 0),zp=c({items:g(Wp),nextCursor:s().optional(),incomplete:h(["scan_budget","history_preparing"]).optional(),history:c({generation:s(),state:h(["complete","preparing","error"]),processedMessages:l().int().nonnegative(),completedShards:l().int().nonnegative(),totalShards:l().int().positive(),pending:h(["room","all"]).optional(),error:s().optional()}).optional()}),Kp={listMessages:{input:d([Hp.optional()]),output:zp},hostId:{input:d([]),output:s().min(1)},listThreads:{input:d([wp.optional()]),output:Ep},readThread:{input:d([Cp]),output:jp},sendMessage:{input:d([Lp]),output:qp},waitThreads:{input:d([Fp]),output:Vp},getWorkspaceOverride:{input:d([s().trim().min(1)]),output:O(v())},setWorkspaceOverride:{input:d([s().trim().min(1),v()]),output:_},clearWorkspaceOverride:{input:d([s().trim().min(1)]),output:_},isWorkspaceEnabled:{input:d([s().trim().min(1)]),output:v()}},Qp=c({busy:v(),executing:v().optional(),mainTurnActive:v(),pendingInteraction:h(["none","approval","question"]),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),Yp={state:{input:d([]),output:Qp}},Ho=d([c({targetAgentId:s().min(1),content:s().min(1),idempotencyKey:s().min(1).max(256)}).strict()]),Xp={sendUserMessage:{input:Ho,output:c({message:c({messageId:s(),sessionId:s(),sourceAgentId:s(),sourceTaskName:s(),senderKind:b("user").optional(),targetAgentId:s(),targetTaskName:s(),content:s(),acceptedAt:l(),targetSeq:l()}),deduplicated:v(),delivery:h(["queued","delivered"]),payloadConflict:v(),resumed:v().optional()})},sendUserMessageReceipt:{input:Ho,output:c({message:c({messageId:s(),sessionId:s(),sourceAgentId:s(),sourceTaskName:s(),senderKind:b("user").optional(),targetAgentId:s(),targetTaskName:s(),acceptedAt:l(),targetSeq:l()}),deduplicated:v(),delivery:h(["queued","delivered"]),payloadConflict:v(),resumed:v().optional()})}},Jp=c({id:s().optional(),sessionId:s().optional(),agentId:s().optional(),turnId:l().optional(),toolCallId:s().optional(),toolName:s(),action:s(),display:k(),approvalRule:s().optional()}),Zp=c({decision:h(["approved","rejected","cancelled"]),scope:b("session").optional(),feedback:s().optional(),selectedLabel:s().optional(),selectedOptionId:s().optional()}),em={listPending:{input:d([]),output:g(Jp)},decide:{input:d([s(),Zp]),output:_}},ss=h(["approval","question","user_tool"]),tm=c({agentId:s().optional(),turnId:l().optional()}),is=c({id:s(),kind:ss,payload:k(),origin:tm,createdAt:l()}),om=c({id:s(),response:k()}),nm={listPending:{input:d([ss.optional()]),output:g(is)},respond:{input:d([s(),k()]),output:_},acquireConsumer:{input:d([s()]),output:_},releaseConsumer:{input:d([s()]),output:_},hasConsumer:{input:d([]),output:v()},isRecentlyResolved:{input:d([s()]),output:v()}},sm=c({sessionId:s().optional(),localSession:c({localId:s(),executorId:s(),engine:h(["claude","codex"]),externalId:s(),home:s()}).optional(),workDir:s(),ephemeral:v().optional(),delivery:h(["reply","message"]).optional(),additionalDirs:g(s()).optional(),waitForSessionMs:l().nonnegative().finite().optional(),mainAgentBinding:c({execution:Un.optional(),persona:s().optional(),profile:s().optional(),model:s().optional(),thinking:s().nullable().optional()}).optional(),mcpServers:R(s(),ot).optional()}),zo=c({additionalDirs:g(s()).optional(),waitForSessionMs:l().nonnegative().finite().optional(),mcpServers:R(s(),ot).optional()}),rs=c({sourceSessionId:s(),newSessionId:s().optional(),title:s().optional(),metadata:R(s(),k()).optional(),turnIndex:l().optional()}),im=rs.omit({turnIndex:!0}),be=Oe({id:s(),kind:s()}),rm={countPendingBackgroundTasks:{input:d([]),output:l()},drainBackgroundTasks:{input:d([l().positive().finite()]),output:_}},am={create:{input:d([sm]),output:be},resume:{input:d([s(),zo.optional()]),output:O(be)},close:{input:d([s()]),output:_},archive:{input:d([s()]),output:_},restore:{input:d([s(),zo.optional()]),output:O(be)},delete:{input:d([s()]),output:_},fork:{input:d([rs]),output:be},createChild:{input:d([im]),output:be}},as=h(["browser","computer","memory","thread","web","send_message"]),cs=h(["on","off","inherit"]),cm=c({id:as,choice:cs,effective:v(),source:h(["session","default","off"]),reason:s(),allowed:v(),hostLocked:v(),defaultOn:v(),unresolved:v(),applies:h(["next-model-request","next-step"])}).strict(),Ko=c({revision:l().int().nonnegative(),hostId:s().min(1),rows:g(cm)}).strict(),dm={read:{input:d([]),output:Ko},set:{input:d([as,cs]),output:Ko}},um=c({label:s(),description:s().optional()}),lm=c({question:s(),header:s().optional(),body:s().optional(),options:g(um),multiSelect:v().optional(),otherLabel:s().optional(),otherDescription:s().optional()}),ds=R(s(),L([s(),b(!0)])),pm=c({answers:ds,method:h(["enter","space","number_key"]).optional()}),mm=L([ce(),ds,pm]),hm=c({id:s().optional(),turnId:l().optional(),toolCallId:s().optional(),questions:g(lm)}),gm={listPending:{input:d([]),output:g(hm)},answer:{input:d([s(),mm]),output:_},dismiss:{input:d([s()]),output:_}},vm=c({name:s(),description:s(),path:s(),source:h(["project","user","extra","builtin"]),type:s().optional(),disableModelInvocation:v().optional(),isSubSkill:v().optional()}),Sm={list:{input:d([]),output:g(vm)}},fm={generateTitle:{input:d([c({force:v().optional(),source:h(["user_prompts","first_turn","digest"]).optional()}).optional()]),output:O(s())}},ym={start:{input:d([]),output:s()}},bm=c({id:s(),cron:s(),prompt:s(),createdAt:l(),recurring:v().optional(),deliveryMode:h(["queue","steer","idle"]).optional(),paused:v().optional(),lastFiredAt:l().optional(),tags:R(s(),s()).optional()}),_m={list:{input:d([]),output:g(bm)},getNextFireTime:{input:d([]),output:l().nullable()},getNextFireForTask:{input:d([s()]),output:l().nullable()}},Im={generateAgentsMd:{input:d([]),output:_},cancelInit:{input:d([]),output:_}},Tm=c({title:s(),status:h(["pending","in_progress","done"])}),wm={getTodos:{input:d([s().optional()]),output:g(Tm)}};function Qo(t){return"streaming"in t&&t.streaming===!0}const Yo={settingsTransferService:vc,agentGoalService:ou,agentLifecycleService:rm,sessionCronService:_m,sessionBtwService:ym,sessionInitService:Im,sessionTodoService:wm,taskBoardService:kc,agentPanelService:Cc,sessionIndex:bp,workspaceService:Ip,configService:hl,providerService:pp,modelService:Ol,modelResolver:Ku,modelCatalogMutation:Ml,providerDiscovery:Yu,oauthService:Nu,authSummaryService:ju,flagService:bl,pluginService:Jl,recipeService:ep,pluginImportService:Zl,pluginMediaService:tp,agentPluginMediaService:op,personaStore:ip,botService:rp,roomService:ap,capabilityService:$u,hostFolderBrowser:wl,bootstrapService:vl,threadCommunicationService:Kp,fileService:yl,mcpManagementService:Jc,sessionManager:am,sessionMetadata:Sp,sessionOptionalCapabilityService:dm,agentCollaborationMessagingService:Xp,sessionActivityView:Yp,sessionInteractionService:nm,sessionApprovalService:em,sessionQuestionService:gm,sessionSkillCatalog:Sm,sessionTitleService:fm,agentPromptService:nu,agentSkillService:su,agentLoopService:lu,agentExecutionService:uu,agentContextInjectorService:iu,agentContextMemoryService:gu,agentContextMutationService:vu,agentContextRebuildService:ru,agentConversationUndoService:au,agentPluginCommandService:cu,agentPluginService:du,agentPermissionModeService:pu,agentCommandService:mu,agentRuntimeBindingService:hu,agentTokenCountingService:Su,agentActivityView:Lc,agentShellCommandService:fu,agentProfileService:bu,agentToolPolicyService:yu,agentUsageService:_u,agentPlanService:Iu,agentTaskService:Ru,agentMcpService:Eu,agentFullCompactionService:Cu},Xo=c({domain:s(),source:h(["load","reload","set"]),value:k(),previousValue:k()}),Em=c({added:g(s()),removed:g(s()),errors:g(c({id:s(),message:s()}))}),km=c({sessionId:s(),busy:v(),executing:v().optional(),main_turn_active:v().optional(),pending_interaction:h(["none","approval","question"]).optional(),last_turn_reason:h(["completed","cancelled","failed"]).optional()}),Cm=c({agentId:s(),sessionId:s(),title:s().optional(),patch:c({title:s().optional(),isCustomTitle:v().optional(),lastPrompt:s().optional()})}),Rm=c({changed:g(c({provider_id:s(),provider_name:s(),added:l(),removed:l()})),unchanged:g(s()),failed:g(c({provider:s(),reason:s()}))}),Pm=c({state:h(["building","ready","readonly","unavailable"]),indexed_sessions:l(),total_sessions:l(),documents:l(),stale:v().optional(),degraded:s().optional(),reason:h(["disabled","indexer_backoff","memory_budget","wal_stuck","disk_low","corrupt_rebuilding","sqlite_unavailable","runtime_disabled"]).optional()}),_e={installId:s().min(1),version:s().min(1)},Om=A("stage",[c({..._e,stage:b("download"),receivedBytes:l().nonnegative(),totalBytes:l().positive().optional()}),c({..._e,stage:b("extract")}),c({..._e,stage:b("activate")}),c({..._e,stage:b("done")}),c({..._e,stage:b("failed"),error:s(),timedOut:v()})]),Am={"usage.settled":{kind:"bus",type:"event.usage.settled",schema:c({sessionId:s().optional(),agentId:s().optional()})},"room.changed":{kind:"emitter",service:"roomService",event:"onDidChange",schema:Yr},"search.indexStateChanged":{kind:"bus",type:"event.search.index_state_changed",schema:Pm},"executors.antigravityInstallProgress":{kind:"bus",type:"event.executor.antigravity_install_progress",schema:Om},"config.changed":{kind:"emitter",service:"configService",event:"onDidChangeConfiguration",schema:Xo},"config.sectionChanged":{kind:"emitter",service:"configService",event:"onDidSectionChange",schema:Xo},"kosong.providers.changed":{kind:"emitter",service:"providerService",event:"onDidChangeProviders",schema:Uo},"kosong.models.changed":{kind:"emitter",service:"modelService",event:"onDidChangeModels",schema:Uo},"plugins.reloaded":{kind:"emitter",service:"pluginService",event:"onDidReload",schema:Em},"plugins.changed":{kind:"bus",type:"event.plugin.changed",schema:c({}).strict()},"session.archived":{kind:"bus",type:"event.session.archived",schema:c({sessionId:s()})},"session.metaUpdated":{kind:"bus",type:"session.meta.updated",schema:Cm},"session.workChanged":{kind:"bus",type:"event.session.work_changed",schema:km},"kosong.changed":{kind:"bus",type:"event.model_catalog.changed",schema:Rm}},Mm={"metadata.changed":{kind:"emitter",service:"sessionMetadata",event:"onDidChangeMetadata",schema:vp},"skills.changed":{kind:"emitter",service:"sessionSkillCatalog",event:"onDidChange",schema:s()},"interactions.changed":{kind:"stream",name:"interactions",schema:g(is)},"interactions.resolved":{kind:"stream",name:"interactions:resolved",schema:om}};class ve extends Error{constructor(e,o,n,i){super(`${e} validation failed for ${o}: ${n.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}`),this.phase=e,this.procedure=o,this.issues=n,this.payload=i,this.name="KlientValidationError"}}function Jo(t,e,o){const n=e.input.safeParse(o);if(!n.success)throw new ve("input",t,n.error.issues,o);return n.data}function xm(t,e,o){const n=e.output.safeParse(o);if(!n.success)throw new ve("output",t,n.error.issues,o);return n.data}function Um(t,e,o){const n=e.chunk.safeParse(o);if(!n.success)throw new ve("chunk",t,n.error.issues,o);return n.data}function Dm(t,e,o){const n=e.safeParse(o);return n.success?{ok:!0,data:n.data}:{ok:!1,error:new ve("event",t,n.error.issues,o)}}function Fe(t){switch(t.kind){case"bus":return"bus";case"stream":return`stream:${t.name}`;case"emitter":return`emitter:${t.service}:${t.event}`}}function Zo(t){if(typeof t!="object"||t===null)return;const e=t.type;return typeof e=="string"?e:void 0}class Nm{constructor(e,o,n,i){this.channel=e,this.validate=o,this.scope=n,this.registrations=i}listeners=new Map;subs=new Map;errorListeners=new Set;closed=!1;on(e,o){if(this.closed)throw new Error("event hub is closed");if(this.registrations[e]===void 0)throw new Error(`unknown event: ${e}`);let n=this.listeners.get(e);n===void 0&&(n=new Set,this.listeners.set(e,n));const i=o;n.add(i);let a,r;const m={promise:new Promise((f,y)=>{a=f,r=y}),resolve:a,reject:r};m.promise.catch(()=>{});let p;try{p=this.acquire(e,m)}catch(f){throw n.delete(i),n.size===0&&this.listeners.delete(e),f}let S=!1;return{ready:m.promise,dispose:()=>{S||(S=!0,p.waiters.delete(m),m.reject(new Error("event subscription disposed before attachment")),n.delete(i),n.size===0&&this.listeners.delete(e),this.release(e))}}}observations=new Set;observe(e,o){if(this.closed)throw new Error("event hub is closed");if(e.events.length===0)throw new Error("observe requires at least one event");if(typeof e.read!="function")throw new Error("observe requires a snapshot reader");const n=new Map;for(const y of e.events){const I=this.registrations[y];if(I===void 0)throw new Error(`unknown event: ${y}`);n.set(Fe(I),I)}const i=new Set,a=[];let r=!1,u=0,m=!1,p;const S={dispose:()=>{if(!r){r=!0,u+=1,p?.abort();for(const y of a)y.dispose();this.observations.delete(S)}}},f=()=>{u+=1,p?.abort(),!(r||m||i.size!==n.size)&&(m=!0,queueMicrotask(()=>{if(m=!1,r||i.size!==n.size)return;const y=u;p=new AbortController;const I=p.signal;Promise.resolve().then(()=>{if(!(r||y!==u))return e.read(I)}).then(w=>{if(!(r||y!==u))try{o(w)}catch(C){this.reportError(C instanceof Error?C:new Error(String(C)))}},w=>{r||y!==u||(S.dispose(),this.reportError(w instanceof Error?w:new Error(String(w))))})}))};this.observations.add(S);try{for(const[y,I]of n){const w=I.kind==="emitter"?{kind:"emitter",service:I.service,event:I.event}:{kind:"stream",name:I.kind==="bus"?"events":I.name};a.push(this.channel.listen(this.scope,w,()=>{f()},C=>{r||(i.delete(y),f(),this.reportError(C))},()=>{r||(i.add(y),f())}))}}catch(y){throw S.dispose(),y}return S}onError(e){return this.errorListeners.add(e),{dispose:()=>{this.errorListeners.delete(e)}}}close(){this.closed=!0;for(const e of this.observations)e.dispose();for(const e of this.subs.values()){for(const o of e.waiters)o.reject(new Error("event hub closed before attachment"));e.waiters.clear(),e.disposable.dispose()}this.subs.clear(),this.listeners.clear()}acquire(e,o){const n=this.registrations[e],i=Fe(n);let a=this.subs.get(i);if(a===void 0){a={reg:n,disposable:{dispose(){}},refs:0,attached:!1,waiters:new Set([o])},this.subs.set(i,a);try{a.disposable=this.subscribe(i,a)}catch(r){throw this.subs.delete(i),r}}else a.attached?o.resolve():a.waiters.add(o);return a.refs+=1,a}release(e){const o=this.registrations[e];if(o===void 0)return;const n=Fe(o),i=this.subs.get(n);i!==void 0&&(i.refs-=1,i.refs<=0&&(i.disposable.dispose(),this.subs.delete(n)))}subscribe(e,o){const n=o.reg,i=n.kind==="emitter"?{kind:"emitter",service:n.service,event:n.event}:{kind:"stream",name:n.kind==="bus"?"events":n.name};return this.channel.listen(this.scope,i,a=>{this.deliver(e,a)},a=>{o.attached=!1;for(const r of o.waiters)r.reject(a);o.waiters.clear(),this.reportError(a)},()=>{o.attached=!0;for(const a of o.waiters)a.resolve();o.waiters.clear()})}deliver(e,o){for(const[n,i]of Object.entries(this.registrations))if(!(Fe(i)!==e||!this.listeners.has(n))){if(i.kind==="bus"){if(Zo(o)!==i.type)continue;this.deliverValidated(n,i,o.payload);continue}if(i.kind==="stream"&&i.type!==void 0){if(Zo(o)!==i.type)continue;this.deliverValidated(n,i,o);continue}this.deliverValidated(n,i,o)}}deliverValidated(e,o,n){let i=n;if(this.validate){const r=Dm(e,o.schema,n);if(!r.ok){this.reportError(r.error);return}i=r.data}const a=this.listeners.get(e);if(a!==void 0)for(const r of a)try{r(i)}catch(u){this.reportError(u instanceof Error?u:new Error(String(u)))}}reportError(e){for(const o of this.errorListeners)try{o(e)}catch{}}}function jm(t){return{catalog:()=>t("settingsTransferService","catalog",[]),export:e=>t("settingsTransferService","export",[e]),preview:e=>t("settingsTransferService","preview",[e]),apply:e=>t("settingsTransferService","apply",[e]),cancel:e=>t("settingsTransferService","cancel",[e])}}function Lm(t){return{list:()=>t("botService","list",[]),enable:e=>t("botService","enable",[e]),ensureHomeSession:e=>t("botService","ensureHomeSession",[e]),update:(e,o)=>t("botService","update",[e,o])}}function qm(t){return{list:()=>t("roomService","list",[]),listItems:()=>t("roomService","listItems",[]),get:e=>t("roomService","get",[e]),create:e=>t("roomService","create",[e]),createFromThreads:e=>t("roomService","createFromThreads",[e]),searchThreads:e=>t("roomService","searchThreads",[e]),addMember:(e,o)=>t("roomService","addMember",[e,o]),removeMember:(e,o)=>t("roomService","removeMember",[e,o]),update:(e,o)=>t("roomService","update",[e,o]),delete:e=>t("roomService","delete",[e]),postUserMessage:(e,o)=>t("roomService","postUserMessage",[e,o]),pause:e=>t("roomService","pause",[e]),continue:e=>t("roomService","continue",[e]),stop:e=>t("roomService","stop",[e]),log:(e,o)=>t("roomService","log",o===void 0?[e]:[e,o]),usage:e=>t("roomService","usage",[e])}}function $m(t){return{list:()=>t("recipeService","list",[]),get:e=>t("recipeService","get",[e]),export:e=>t("recipeService","export",[e]),preview:e=>t("recipeService","preview",[e]),install:e=>t("recipeService","install",[e]),checkUpdates:()=>t("recipeService","checkUpdates",[]),update:e=>t("recipeService","update",[e]),fork:e=>t("recipeService","fork",[e]),saveLocal:e=>t("recipeService","saveLocal",[e]),remove:e=>t("recipeService","remove",[e]),markets:{list:()=>t("recipeService","listMarkets",[]),add:e=>t("recipeService","addMarket",[e]),update:e=>t("recipeService","updateMarket",[e]),remove:e=>t("recipeService","removeMarket",[e])}}}function Gm(t){return{sources:()=>t("pluginImportService","sources",[]),discover:e=>t("pluginImportService","discover",[e]),preview:e=>t("pluginImportService","preview",[e]),start:e=>t("pluginImportService","start",[e]),jobs:e=>t("pluginImportService","jobs",[e]),job:e=>t("pluginImportService","job",[e]),cancel:e=>t("pluginImportService","cancel",[e]),resume:e=>t("pluginImportService","resume",[e]),archives:e=>t("pluginImportService","archives",[e]),read:e=>t("pluginImportService","read",[e])}}function Fm(t){return{managedSources:()=>t("pluginMediaService","managedSources",[]),sourceSettings:e=>t("pluginMediaService","sourceSettings",[e]),updateSource:e=>t("pluginMediaService","updateSource",[e]),addScriptSource:e=>t("pluginMediaService","addScriptSource",[e]),sources:()=>t("pluginMediaService","sources",[]),setSources:e=>t("pluginMediaService","setSources",[e]),catalog:e=>t("pluginMediaService","catalog",[e]),providers:()=>t("pluginMediaService","providers",[]),capabilities:e=>t("pluginMediaService","capabilities",[e]),voices:e=>t("pluginMediaService","voices",[e]),jobs:e=>t("pluginMediaService","jobs",[e]),job:e=>t("pluginMediaService","job",[e])}}function Bm(t){return{cancel:e=>t("agentPluginMediaService","cancel",[e]),resume:e=>t("agentPluginMediaService","resume",[e])}}const en=32768;function Vm(t){let e="";for(let o=0;o<t.length;o+=en)e+=String.fromCodePoint(...t.subarray(o,o+en));return btoa(e)}function Wm(t){const e=atob(t),o=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)o[n]=e.codePointAt(n)??0;return o}function Hm(t){return{id:t.id,name:t.name,avatarUrl:t.avatarMime===void 0?void 0:`/api/personas/${encodeURIComponent(t.id)}/avatar`,avatarShape:t.avatarMime===void 0?void 0:t.avatarShape}}const zm=7e4,tn=["platform","arch","cwd","osHomeDir","homeDir","configPath","sessionsDir","blobsDir","storeDir","cacheDir","logsDir"],Km=15*6e4,Qm=3e4;function Ym(t,e){const o=(r,u,m,p)=>t({},r,u,m,p),n=(r,u,m)=>e({},r,u,m);let i;const a=()=>(i??=Promise.all([...tn.map(r=>o("bootstrapService",r,[])),o("bootstrapService","clientIdentity",[])]).then(r=>{const u=Object.fromEntries(tn.map((p,S)=>[p,r[S]])),m=r[r.length-1];return{...u,clientVersion:m.version}}),i);return{settingsTransfer:jm(o),board:{read:(r,u)=>o("taskBoardService","read",[r],u),write:r=>o("taskBoardService","write",[r]),overview:r=>o("taskBoardService","overview",[],r)},agentPanel:{read:(r,u)=>o("agentPanelService","read",[r],u)},sessions:{list:r=>o("sessionIndex","listRecent",[r]),get:r=>o("sessionIndex","get",[r]),countActive:r=>o("sessionIndex","count",[{workspaceIds:r}]),create:async({sessionId:r,workDir:u,ephemeral:m,additionalDirs:p,waitForSessionMs:S,title:f,persona:y,delivery:I,mcpServers:w,mainAgentBinding:C})=>{const P=y===void 0?C:{...C,persona:y},$={sessionId:(await t({},"sessionManager","create",[{sessionId:r,workDir:u,ephemeral:m,delivery:I,additionalDirs:p,waitForSessionMs:S,mcpServers:w,mainAgentBinding:P}])).id};return f!==void 0&&await t($,"sessionMetadata","setTitle",[f]),t($,"sessionMetadata","read",[])}},bots:Lm(o),rooms:qm(o),personas:{list:r=>o("personaStore","list",r===void 0?[]:[r]),get:r=>o("personaStore","get",[r]),put:r=>o("personaStore","put",[{...r.definition,examples:r.examples,expectedRevision:r.revision}]),duplicate:(r,u)=>o("personaStore","duplicate",u===void 0?[r]:[r,u]),archive:(r,u)=>o("personaStore","archive",u===void 0?[r]:[r,u]),delete:async(r,u)=>{const m=await o("personaStore","delete",u?.expectedRevision===void 0?[r]:[r,u.expectedRevision]);if(m.memory.status!=="committed")throw new Error(m.memory.error??"Persona memory deletion is incomplete; retry deletion");return{deleted:!0,memory:m.memory}},avatar:Hm},workspaces:{list:()=>o("workspaceService","list",[]),get:r=>o("workspaceService","get",[r]),createOrTouch:({root:r,name:u})=>o("workspaceService","createOrTouch",[r,u]),update:({id:r,patch:u})=>o("workspaceService","update",[r,u]),delete:r=>o("workspaceService","delete",[r])},config:{get:r=>o("configService","get",[r]),getAll:()=>o("configService","getAll",[]),inspect:r=>o("configService","inspect",[r]),set:({domain:r,patch:u,target:m})=>o("configService","set",[r,u,m]),replace:({domain:r,value:u,target:m})=>o("configService","replace",[r,u===void 0?null:u,m]),replaceSections:({sections:r,target:u})=>o("configService","replaceSections",[Object.fromEntries(Object.entries(r).map(([m,p])=>[m,p===void 0?null:p])),u]),reload:()=>o("configService","reload",[]),diagnostics:()=>o("configService","diagnostics",[])},kosong:{listProviders:()=>o("modelResolver","listProviders",[]),getProvider:r=>o("modelResolver","getProvider",[r]),addProvider:((r,u)=>{if(typeof r=="string"){const f=u;Xm(f);const y={type:f.type,baseUrl:f.baseUrl,defaultModel:f.defaultModel,requestIdentity:f.requestIdentity,requestCompression:f.requestCompression,responsesWebSocket:f.responsesWebSocket,apiKey:f.auth.method==="api-key"?f.auth.apiKey:""};return o("providerService","set",[r,y])}const m=r,p=m.capabilities?Object.entries(m.capabilities).filter(([,f])=>f).map(([f])=>f):void 0,S={model:m.model,protocol:m.protocol,baseUrl:m.baseUrl,apiKey:m.auth.method==="api-key"?m.auth.apiKey:"",displayName:m.displayName,maxContextSize:m.maxContextSize,capabilities:p,requestIdentity:m.requestIdentity};return o("modelService","set",[m.id,S])}),removeProvider:async r=>await o("providerService","get",[r])!==void 0?o("providerService","delete",[r]):o("modelService","delete",[r]),refreshProviders:r=>o("providerDiscovery","refreshProviderModels",[r]),listDiscoveredModels:()=>o("providerDiscovery","listDiscoveredModels",[]),listModels:()=>o("modelResolver","listModels",[]),setDefaultModel:r=>o("modelResolver","setDefaultModel",[r]),readModel:r=>o("modelCatalogMutation","readModel",[r]),createModel:r=>o("modelCatalogMutation","createModel",[r]),updateModel:(r,u)=>o("modelCatalogMutation","updateModel",[r,u]),deleteModel:(r,u)=>o("modelCatalogMutation","deleteModel",[r,u]),readProviderEntity:r=>o("modelCatalogMutation","readProvider",[r]),createProvider:r=>o("modelCatalogMutation","createProvider",[r]),updateProvider:(r,u)=>o("modelCatalogMutation","updateProvider",[r,u]),deleteProviderEntity:r=>o("modelCatalogMutation","deleteProvider",[r]),generate:(r,u,m)=>n("modelResolver","generate",[r,u,m])},auth:{probeOriginal:r=>o("oauthService","probeOriginal",[r]),connectOriginal:r=>o("oauthService","connectOriginal",[r]),status:r=>o("oauthService","status",[r]),summarize:()=>o("authSummaryService","summarize",[]),ensureReady:r=>o("authSummaryService","ensureReady",[r]),startLogin:(r,u)=>o("oauthService","startLogin",[r,u]),flow:r=>o("oauthService","getFlow",[r]),cancelLogin:r=>o("oauthService","cancelLogin",[r]),logout:r=>o("oauthService","logout",[r]),methods:()=>o("oauthService","listMethods",[])},flags:{list:()=>o("flagService","explainAll",[]),enabled:r=>o("flagService","enabled",[r]),enabledIds:()=>o("flagService","enabledIds",[]),explain:r=>o("flagService","explain",[r]),snapshot:()=>o("flagService","snapshot",[])},recipes:$m(o),imports:Gm(o),media:Fm(o),plugins:{list:()=>o("pluginService","listPlugins",[]),info:r=>o("pluginService","getPluginInfo",[{id:r}]),preview:r=>o("pluginService","previewPlugin",[r]),install:async r=>{if(typeof r!="string")return o("pluginService","installPlugin",[r]);const u=await o("pluginService","previewPlugin",[{source:r}]);if(u.consentRequired)throw new Error(`Plugin ${u.id} requires one-time consent to trusted code with full account permissions. Preview its contributions and pass { source, fingerprint, consent: true }.`);return o("pluginService","installPlugin",[{source:r,fingerprint:u.fingerprint,consent:!1}])},setEnabled:r=>o("pluginService","setPluginEnabled",[r]),setMcpServerEnabled:r=>o("pluginService","setPluginMcpServerEnabled",[r]),remove:r=>o("pluginService","removePlugin",[{id:r}]),reload:()=>o("pluginService","reloadPlugins",[]),checkUpdates:()=>o("pluginService","checkUpdates",[]),listCommands:()=>o("pluginService","listPluginCommands",[])},capabilities:{list:()=>o("capabilityService","listCapabilities",[]),get:r=>o("capabilityService","getCapability",[r]),install:(r,u,m)=>o("capabilityService","installCapability",m!==void 0?[r,u,m]:u===void 0?[r]:[r,u]),cancel:r=>o("capabilityService","cancelCapability",[r])},hostFs:{browse:r=>o("hostFolderBrowser","browse",[r]),home:()=>o("hostFolderBrowser","home",[])},threads:{messages:r=>o("threadCommunicationService","listMessages",[r]),hostId:()=>o("threadCommunicationService","hostId",[]),list:r=>o("threadCommunicationService","listThreads",[r]),read:r=>o("threadCommunicationService","readThread",[r]),send:r=>o("threadCommunicationService","sendMessage",[r]),wait:r=>o("threadCommunicationService","waitThreads",[r],{timeoutMs:zm}),getWorkspaceOverride:r=>o("threadCommunicationService","getWorkspaceOverride",[r]),setWorkspaceOverride:(r,u)=>o("threadCommunicationService","setWorkspaceOverride",[r,u]),clearWorkspaceOverride:r=>o("threadCommunicationService","clearWorkspaceOverride",[r]),isWorkspaceEnabled:r=>o("threadCommunicationService","isWorkspaceEnabled",[r])},files:{save:({data:r,filename:u,name:m,mimeType:p,expiresInSec:S},f)=>o("fileService","save",[Vm(r),u,{name:m,mimeType:p,expiresInSec:S}],f),get:async r=>{const u=await o("fileService","get",[r]);return{meta:u.meta,data:Wm(u.data)}},delete:r=>o("fileService","delete",[r])},mcp:{list:r=>o("mcpManagementService","listServers",[r===void 0?void 0:{cwd:r.cwd}]),get:({name:r,cwd:u})=>o("mcpManagementService","getServer",[r,u===void 0?void 0:{cwd:u}]),add:({server:r,cwd:u})=>o("mcpManagementService","addServer",[r,u===void 0?void 0:{cwd:u}]),update:({server:r,cwd:u})=>o("mcpManagementService","updateServer",[r,u===void 0?void 0:{cwd:u}]),remove:({name:r,cwd:u})=>o("mcpManagementService","removeServer",[r,u===void 0?void 0:{cwd:u}]),test:r=>o("mcpManagementService","testServer",[r]),stop:r=>o("mcpManagementService","stopServer",[r]),inspect:r=>o("mcpManagementService","inspectServers",[r?.targets,r===void 0?void 0:{cwd:r.cwd}]),authStatuses:r=>o("mcpManagementService","listAuthStatuses",[r===void 0?void 0:{cwd:r.cwd,verify:r.verify}]),resolveByName:({name:r,cwd:u})=>o("mcpManagementService","resolveServerByName",[r,{cwd:u}]),beginAuth:({locator:r,cwd:u})=>o("mcpManagementService","beginServerAuth",[r,{cwd:u}]),completeAuth:({flowId:r,timeoutMs:u},m)=>o("mcpManagementService","completeServerAuth",[{flowId:r,timeoutMs:u}],{signal:m?.signal,timeoutMs:Math.min((u??Km)+Qm,2**31-1)}),cancelAuth:({flowId:r})=>o("mcpManagementService","cancelServerAuth",[{flowId:r}]),resetAuth:({locator:r,cwd:u,expectedCanonicalUrl:m})=>o("mcpManagementService","resetServerAuth",m===void 0?[r,{cwd:u}]:[r,{cwd:u},m]),listStoredOAuthCredentials:()=>o("mcpManagementService","listStoredOAuthCredentials",[]),revealStoredOAuthCredential:r=>o("mcpManagementService","revealStoredOAuthCredential",[r]),revokeStoredOAuthCredential:r=>o("mcpManagementService","revokeStoredOAuthCredential",[r])},env:a}}function Xm(t){const e=t;for(const o of["requestAttribution","requestOriginator"])if(o in e)throw new TypeError(`${o} was removed; use requestIdentity`)}function Jm(t,e){const o={sessionId:e},n=()=>t(o,"sessionMetadata","read",[]),i=async(a,r={})=>{const u=await t({},"sessionManager",a,[{...r,sourceSessionId:e}]);return t({sessionId:u.id},"sessionMetadata","read",[])};return{get:n,setTitle:a=>t(o,"sessionMetadata","setTitle",[a]),generateTitle:a=>t(o,"sessionTitleService","generateTitle",[a]),update:a=>t(o,"sessionMetadata","update",[a]),setArchived:a=>t(o,"sessionMetadata","setArchived",[a]),status:async()=>{const a=await t(o,"sessionActivityView","state",[]);return a.pendingInteraction==="approval"?"awaiting_approval":a.pendingInteraction==="question"?"awaiting_question":a.busy?"running":"idle"},close:()=>t({},"sessionManager","close",[e]),archive:()=>t({},"sessionManager","archive",[e]),resume:async a=>{const r=await t({},"sessionManager","resume",a===void 0?[e]:[e,a],{timeoutMs:0});return r!=null},restore:async a=>{const r=await t({},"sessionManager","restore",[e,a]);return r!=null},countPendingBackgroundTasks:()=>t(o,"agentLifecycleService","countPendingBackgroundTasks",[]),drainBackgroundTasks:a=>t(o,"agentLifecycleService","drainBackgroundTasks",[a],{timeoutMs:0}),nextCronFireAt:()=>t(o,"sessionCronService","getNextFireTime",[]),todos:{get:a=>t(o,"sessionTodoService","getTodos",a===void 0?[]:[a])},init:{generateAgentsMd:()=>t(o,"sessionInitService","generateAgentsMd",[]),cancelInit:()=>t(o,"sessionInitService","cancelInit",[])},btw:{start:()=>t(o,"sessionBtwService","start",[])},cron:{list:()=>t(o,"sessionCronService","list",[]),nextFireAt:a=>t(o,"sessionCronService","getNextFireForTask",[a])},optionalCapabilities:{read:()=>t(o,"sessionOptionalCapabilityService","read",[]),set:(a,r)=>t(o,"sessionOptionalCapabilityService","set",[a,r])},delete:()=>t({},"sessionManager","delete",[e]),fork:a=>i("fork",a),createChild:a=>i("createChild",a),approvals:{list:()=>t(o,"sessionApprovalService","listPending",[]),decide:(a,r)=>t(o,"sessionApprovalService","decide",[a,r])},questions:{list:()=>t(o,"sessionQuestionService","listPending",[]),answer:(a,r)=>t(o,"sessionQuestionService","answer",[a,r]),dismiss:a=>t(o,"sessionQuestionService","dismiss",[a])},interactions:{list:a=>t(o,"sessionInteractionService","listPending",[a]),respond:(a,r)=>t(o,"sessionInteractionService","respond",[a,r]),acquireConsumer:a=>t(o,"sessionInteractionService","acquireConsumer",[a]),releaseConsumer:a=>t(o,"sessionInteractionService","releaseConsumer",[a])},skills:{list:()=>t(o,"sessionSkillCatalog","list",[])},agents:async()=>(await n()).agents??{},getAgentExecutor:async a=>await t(o,"sessionMetadata","getAgentExecutor",[a])??void 0,sendUserAgentMessage:a=>t(o,"agentCollaborationMessagingService","sendUserMessage",[a],{timeoutMs:0}),sendUserAgentMessageReceipt:a=>t(o,"agentCollaborationMessagingService","sendUserMessageReceipt",[a],{timeoutMs:0})}}c({});const Zm=c({agentId:s().min(1),beforeTurn:s().min(1).optional(),beforeItem:s().min(1).max(512).optional(),afterTurn:s().min(1).optional(),afterItem:s().min(1).optional(),pageSize:l().int().min(1).max(100).optional()}).refine(t=>[t.beforeTurn,t.beforeItem,t.afterTurn,t.afterItem].filter(e=>e!==void 0).length<=1,{message:"beforeTurn, beforeItem, afterTurn and afterItem are mutually exclusive"}).refine(t=>et(t.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),eh=c({agentId:s().min(1),since:yn,grade:h(["turn","block","delta"]).optional()}).refine(t=>et(t.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),th=c({agentId:s().min(1),kind:h(["task","attachment","prompt","tool"]),id:s().min(1)}).refine(t=>et(t.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),oh=c({agentId:s().min(1),ref:Ze,range:v().optional()}).refine(t=>et(t.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),nh=fn,sh=c({sessionCursor:Ae,transcriptGrades:Xr,transcriptSince:R(s(),yn).optional()}),de=l().int().nonnegative(),ih=c({type:b("status"),status:h(["connecting","open","closed"]),generation:de,detail:s().optional()}),rh=c({type:b("ready"),currentSessionCursor:Ae,reconnected:v(),generation:de}),ah=c({type:b("sessionCursorAdvanced"),cursor:Ae,generation:de,rosterAgentId:s().min(1).optional(),title:s().optional()}),ch=c({type:b("historyRewritten"),reason:h(["edit_resend","regenerate"]),targetMessageId:s().min(1),cursor:Ae,generation:de}),dh=c({type:b("transcript"),event:Jr,generation:de}),uh=c({type:b("resyncRequired"),reason:Zr,currentSessionCursor:Ae,generation:de}),lh=c({type:b("protocolError"),detail:s(),recoverable:v(),generation:de}),ph=A("type",[lh,ih,rh,ah,ch,dh,uh]),mh=oa,hh=Sn,gh=ta,vh=ea;function Sh(t,e,o){let n=0,i=0;const a=()=>{if(t===void 0)throw new Error("session view is unavailable on this transport");return t},r=(u,m,p,S)=>{const f=p.safeParse(S);if(!f.success)throw new ve(u,m,f.error.issues,S);return f.data};return{async snapshot(u){const m=await a().snapshot(e,u);return o?r("output","session.view.snapshot",mh,m):m},transcript:{async page(u,m){const p=o?r("input","session.view.transcript.page",Zm,u):u,S=await a().transcriptPage(e,p,m);return o?r("output","session.view.transcript.page",hh,S):S},async catchUp(u,m){const p=o?r("input","session.view.transcript.catchUp",eh,u):u,S=await a().transcriptCatchUp(e,p,m);return o?r("output","session.view.transcript.catchUp",gh,S):S},...t?.transcriptEntities===void 0?{}:{async entities(u,m){const p=r("input","session.view.transcript.entities",na,{agent_id:u.agentId,kind:u.kind,cursor:u.cursor,limit:u.limit}),S=await a().transcriptEntities(e,{agentId:p.agent_id,kind:p.kind,cursor:p.cursor,limit:p.limit},m);return r("output","session.view.transcript.entities",sa,S)}},...t?.transcriptContent===void 0?{}:{async content(u,m){const p=r("input","session.view.transcript.content",oh,u),S=await a().transcriptContent(e,p,m);return r("output","session.view.transcript.content",nh,S)}},...t?.transcriptDetail===void 0?{}:{async detail(u,m){const p=o?r("input","session.view.transcript.detail",th,u):u,S=await a().transcriptDetail(e,p,m);return o?r("output","session.view.transcript.detail",vh,S):S}}},subscribe(u,m){const p=o?r("input","session.view.subscribe",sh,u):u;return a().subscribe(e,p,S=>{if(!o){m(S);return}const f=ph.safeParse(S);if(!f.success){n+=1,m({type:"protocolError",generation:i,recoverable:n===1,detail:"Invalid session view signal; the transcript must be refreshed."});return}i=Math.max(i,f.data.generation),f.data.type==="transcript"&&f.data.event.type==="transcript.reset"&&(n=0),m(f.data)})}}}const at=s().min(1),on=t=>c({body:t}),nn=c({target:at}),J=t=>c({target:at,body:t}),sn=c({target:at,query:c({agent_id:s().min(1).optional()}).optional()}),us={read:{method:"GET",suffix:"",input:c({}),output:bo,okCodes:[0]},submit:{method:"POST",suffix:"/prompts",input:on(Ea),output:ga,okCodes:[0],timeoutMs:0},edit:{method:"POST",suffix:"/messages/{target}:edit",input:J(In),output:_o,okCodes:[0]},regenerate:{method:"POST",suffix:"/messages/{target}:regenerate",input:J(_n),output:_o,okCodes:[0]},fork:{method:"POST",suffix:":fork",input:on(bn),output:bo,okCodes:[0]},abort:{method:"POST",suffix:"/prompts/{target}:abort",input:sn,output:ha,okCodes:[0,40903]},abortTurn:{method:"POST",suffix:"/turns/{target}:abort",input:nn,output:ma,okCodes:[0]},move:{method:"POST",suffix:"/prompts/{target}:move",input:J(wa),output:pa,okCodes:[0]},replace:{method:"POST",suffix:"/prompts/{target}:replace",input:J(Ta),output:la,okCodes:[0]},timing:{method:"POST",suffix:"/prompts/{target}:timing",input:J(Ia),output:ua,okCodes:[0]},hold:{method:"POST",suffix:"/prompts/{target}:hold",input:J(_a),output:da,okCodes:[0]},steer:{method:"POST",suffix:"/prompts/{target}:steer",input:sn,output:ca,okCodes:[0]},approve:{method:"POST",suffix:"/approvals/{target}",input:J(ba),output:aa,okCodes:[0]},answer:{method:"POST",suffix:"/questions/{target}",input:J(ya),output:ra,okCodes:[0]},dismiss:{method:"POST",suffix:"/questions/{target}:dismiss",input:nn,output:ia,okCodes:[0,40909]},cancelTask:{method:"POST",suffix:"/tasks/{target}:cancel",input:c({target:at,query:fa.optional()}),output:L([va,Sa]),okCodes:[0,40904]}};function rn(t,e){return e===void 0||e==="main"?{target:t}:{target:t,query:{agent_id:e}}}function fh(t,e,o){const n=(a,r,u,m)=>{const p=u.safeParse(m);if(!p.success)throw new ve(a,r,p.error.issues,m);return p.data},i=async(a,r)=>{if(t===void 0)throw new Error("session commands are unavailable on this transport");const u=us[a],m=`session.commands.${a}`,p=o?n("input",m,u.input,r):r,S=await t.execute(e,a,p);return o?n("output",m,u.output,S):S};return{read:()=>i("read",{}),submit:a=>i("submit",{body:a}),edit:(a,r)=>i("edit",{target:a,body:r}),regenerate:(a,r)=>i("regenerate",{target:a,body:r}),fork:(a={})=>i("fork",{body:a}),abort:(a,r)=>i("abort",rn(a,r)),abortTurn:a=>i("abortTurn",{target:String(a)}),move:(a,r)=>i("move",{target:a,body:r}),replace:(a,r)=>i("replace",{target:a,body:r}),timing:(a,r)=>i("timing",{target:a,body:r}),hold:(a,r)=>i("hold",{target:a,body:r}),steer:(a,r)=>i("steer",rn(a,r)),approve:(a,r)=>i("approve",{target:a,body:r}),answer:(a,r)=>i("answer",{target:a,body:r}),dismiss:a=>i("dismiss",{target:a}),cancelTask:(a,r={})=>i("cancelTask",{target:a,query:r})}}function yh(t,e){function o(n,i){return t(e,"agentPromptService",i?.waitFor==="terminal"?"submitAndWait":"submit",[n],i===void 0?void 0:{timeoutMs:0,signal:i.signal})}return{media:Bm((n,i,a,r)=>t(e,n,i,a,r)),switchModel:n=>t(e,"agentPromptService","switchModel",[n]),getModelSwitch:n=>t(e,"agentPromptService","getModelSwitch",[n]),listModelSwitches:n=>t(e,"agentPromptService","listModelSwitches",[],n),updateModelSwitch:(n,i)=>t(e,"agentPromptService","updateModelSwitch",i===void 0?[n]:[n,i]),cancelModelSwitch:n=>t(e,"agentPromptService","cancelModelSwitch",[n]),recoverModelSwitch:(n,i,a)=>t(e,"agentPromptService","recoverModelSwitch",a===void 0?[n,i]:[n,i,a]),prompt:o,promptWithSkills:n=>t(e,"agentSkillService","promptWithSkills",[n]),steer:n=>t(e,"agentPromptService","submitSteer",[n]),resumeRecoveredPromptQueue:()=>t(e,"agentPromptService","resumeRecoveredQueue",[]),activateSkill:n=>t(e,"agentSkillService","activate",[n]),activatePluginCommand:n=>t(e,"agentPluginCommandService","activate",[n]),refreshPluginSessionStart:()=>t(e,"agentPluginService","refreshSessionStart",[]),cancel:n=>t(e,"agentLoopService","cancelFromUser",n?.turnId===void 0?[]:[n.turnId]),shutdownExecution:n=>t(e,"agentExecutionService","shutdown",n===void 0?[]:[n]),getLoopStatus:()=>t(e,"agentLoopService","status",[]),runShellCommand:n=>t(e,"agentShellCommandService","run",[n]),cancelShellCommand:n=>t(e,"agentShellCommandService","cancel",[n.commandId]),getModel:()=>t(e,"agentProfileService","getModel",[]),setModel:n=>t(e,"agentProfileService","setModel",[n]),setEffort:n=>t(e,"agentProfileService","setEffort",[n]),getThinking:()=>t(e,"agentProfileService","getEffectiveThinkingLevel",[]),setThinking:n=>t(e,"agentProfileService","setThinking",[n]),getModelCapabilities:()=>t(e,"agentProfileService","getModelCapabilities",[]),getAgentsMdWarning:()=>t(e,"agentProfileService","getAgentsMdWarning",[]),inspectToolPolicy:()=>t(e,"agentProfileService","inspectToolPolicy",[]),refreshToolPolicy:n=>t(e,"agentProfileService","refreshToolPolicy",[n]),isToolEnabled:(n,i)=>t(e,"agentToolPolicyService","isToolActive",[n,i]),getPermission:()=>t(e,"agentPermissionModeService","mode",[]),setPermission:(n,i)=>t(e,"agentPermissionModeService",i?.broadcast===!1?"setMode":"setModeAndBroadcast",[n]),getGoal:()=>t(e,"agentGoalService","getGoal",[]),createGoal:n=>t(e,"agentGoalService","createGoal",[n]),updateGoal:n=>t(e,"agentGoalService","updateGoal",[n]),pauseGoal:()=>t(e,"agentGoalService","pauseGoal",[]),resumeGoal:n=>t(e,"agentGoalService","resumeGoal",n===void 0?[]:[n]),cancelGoal:()=>t(e,"agentGoalService","cancelGoal",[]),getUsage:()=>t(e,"agentUsageService","status",[]),getContext:async()=>{const[n,i]=await Promise.all([t(e,"agentContextMemoryService","get",[]),t(e,"agentTokenCountingService","statusSize",[])]);return{history:n,tokenCount:i}},appendContext:n=>t(e,"agentContextMemoryService","append",[n]),appendImportedContext:n=>t(e,"agentContextMutationService","appendImported",[n]),clearContext:()=>t(e,"agentContextMemoryService","clear",[]),rebuildContext:()=>t(e,"agentContextRebuildService","rebuild",[]),contextRebuildControl:()=>t(e,"agentContextRebuildService","control",[]),setContextRebuildEnabled:n=>t(e,"agentContextRebuildService","setEnabled",[n]),undo:n=>t(e,"agentConversationUndoService","undo",[n]),listCommands:()=>t(e,"agentCommandService","list",[]),runCommand:n=>t(e,"agentCommandService","run",n.args===void 0?[n.name]:[n.name,n.args]),getRuntime:()=>t(e,"agentRuntimeBindingService","get",[]),switchRuntime:n=>t(e,"agentRuntimeBindingService","switch",[n]),getPlan:()=>t(e,"agentPlanService","status",[]),enterPlan:()=>t(e,"agentPlanService","enter",[]),clearPlan:()=>t(e,"agentPlanService","clear",[]),cancelPlan:n=>t(e,"agentPlanService","cancel",[n?.id]),reconcileContextWhenIdle:n=>t(e,"agentContextInjectorService","reconcileWhenIdle",[n]),getTasks:n=>t(e,"agentTaskService","list",[n?.activeOnly??!1,n?.limit]),stopTask:async n=>{if(n.reason===void 0){await t(e,"agentTaskService","stopByUser",[n.taskId]);return}await t(e,"agentTaskService","stop",[n.taskId,n.reason])},stopTaskWithReason:n=>t(e,"agentTaskService","stop",n.reason===void 0?[n.taskId]:[n.taskId,n.reason]).then(()=>{}),detachTask:n=>t(e,"agentTaskService","detach",[n]),getTaskOutput:n=>t(e,"agentTaskService","readOutput",[n.taskId,n.tail]),getMcpServers:()=>t(e,"agentMcpService","list",[]),waitForMcpInitialLoad:()=>t(e,"agentMcpService","waitForInitialLoad",[]),getMcpStartupDuration:()=>t(e,"agentMcpService","initialLoadDurationMs",[]),reconnectMcpServer:n=>t(e,"agentMcpService","reconnect",[n]),connectMcpServer:n=>t(e,"agentMcpService","connect",[n.name,n.config]),listMcpSessionCapabilities:()=>t(e,"agentMcpService","listMcpSessionCapabilities",[]),setMcpSessionOverride:n=>t(e,"agentMcpService","setMcpSessionOverride",[n]),compact:n=>t(e,"agentFullCompactionService","begin",[{source:"manual",instruction:n?.instruction}]),cancelCompaction:()=>t(e,"agentFullCompactionService","cancel",[]),isCompacting:()=>t(e,"agentFullCompactionService","isCompacting",[]),getAutoCompact:()=>t(e,"agentFullCompactionService","getAutoCompact",[]),getDefaultAutoCompact:()=>t(e,"agentFullCompactionService","getDefaultAutoCompact",[]),setAutoCompactOverride:n=>t(e,"agentFullCompactionService","setAutoCompactOverride",[n]),getContextStrategy:()=>t(e,"agentFullCompactionService","getContextStrategy",[]),setContextStrategyOverride:n=>t(e,"agentFullCompactionService","setContextStrategyOverride",[n])}}function bh(t,e={}){const o=e.validate??!0,n=async(u,m,p,S,f)=>{const y=Yo[m]?.[p];if(y===void 0)throw new Error(`no contract registered for ${m}.${p}`);if(Qo(y))throw new Error(`${m}.${p} is a streaming procedure — use callStream instead`);const I=`${m}.${p}`,w=o?Jo(I,y,S):S,C=await t.call(u,m,p,w,f);return o?xm(I,y,C):C},i=(u,m,p,S)=>{const f=Yo[m]?.[p];if(f===void 0)throw new Error(`no contract registered for ${m}.${p}`);if(!Qo(f))throw new Error(`${m}.${p} is not a streaming procedure — use call instead`);const y=`${m}.${p}`,I=o?Jo(y,f,S):S,w=t.stream(u,m,p,I);if(!o)return w;const C=f;return{[Symbol.asyncIterator](){const P=w[Symbol.asyncIterator]();return{async next(){const D=await P.next();return D.done?{done:!0,value:void 0}:{done:!1,value:Um(y,C,D.value)}},async return(D){return await P.return?.(D),{done:!0,value:void 0}}}}}},a=new Set,r=(u,m)=>{const p=new Nm(t,o,u,m);return a.add(p),p};return{rest:t.rest,terminal:hc(t.terminal),global:Ym(n,i),events:r({},Am),session(u){const m={sessionId:u};return{...Jm(n,u),events:r(m,Mm),view:Sh(t.sessionView,u,o),commands:fh(t.sessionCommands,u,o),agent(p){const S={sessionId:u,agentId:p};return{...yh(n,S),events:r(S,Md)}}}},close:()=>{for(const u of a)u.close();return a.clear(),t.close()}}}const co={kind:"unknown",hasMoreOlder:!0};function _h(t){if(t===null||typeof t!="object")return t;const e=t;if(e.type!=="transcript")return t;const o=e.event;if(o===null||typeof o!="object")return t;const n=o.type;if(n==="transcript.reset")return{...t,event:{...o,coverage:co,read:uo(o.read),snapshot:ps(o.snapshot)}};if(n==="transcript.ops"){const i=o.ops;return Array.isArray(i)?{...t,event:{...o,ops:i.map(ls)}}:t}return t}function Ih(t){return t===null||typeof t!="object"?t:{...t,coverage:co,read:uo(t.read),tool_call_count:void 0}}function Th(t){if(t===null||typeof t!="object")return t;const e=t.batches;return Array.isArray(e)?{...t,batches:e.map(wh)}:t}function wh(t){if(t===null||typeof t!="object")return t;const e=t.ops;return Array.isArray(e)?{...t,ops:e.map(ls)}:t}function ls(t){if(t===null||typeof t!="object")return t;const e=t;return e.op==="reset"?{...e,coverage:co,read:uo(e.read),snapshot:ps(e.snapshot)}:e.op==="tool.count.set"?{...e,count:void 0}:t}function uo(t){return{source:t!==null&&typeof t=="object"&&(t.source==="live"||t.source==="cold"||t.source==="derived")?t.source:"derived",readiness:"partial",reason:"source_unverified"}}function ps(t){return t===null||typeof t!="object"?t:{...t,toolCallCount:void 0,toolCallCountKnown:!1}}const Eh=250;function kh(t,e){let o=!1;for(const[n,i]of Object.entries(e)){const a=t[n];if(a===void 0){if(i!=="turn")return!1;o=!0}else if(a!==i)return!1}return o&&Object.keys(t).every(n=>Object.hasOwn(e,n))}class Ch{constructor(e){this.host=e}views=new Map;generation=0;get hasDemand(){return this.views.size>0}subscribe(e,o,n){const i=this.host.nextId(),a={id:i,sessionId:e,input:o,handler:n,attachCount:0};this.views.set(i,a);try{n({type:"status",status:"connecting",generation:this.generation}),this.host.connect(),this.host.isOpen()&&this.attach(a)}catch(r){throw this.views.delete(i),r}return{updateSessionCursor:r=>{a.input={...a.input,sessionCursor:r}},setTranscriptGrades:r=>{if(!this.views.has(i))return;const u=a.input.transcriptGrades,m=a.input.transcriptSince===void 0?void 0:Object.fromEntries(Object.entries(a.input.transcriptSince).filter(([p])=>Ao[Mo(r,p)]<=Ao[Mo(u,p)]));a.input={...a.input,transcriptGrades:r,transcriptSince:m},this.host.isOpen()&&(kh(u,r)?this.scheduleAttach(a):(this.clearAttachTimer(a),this.attach(a)))},updateTranscriptCursor:(r,u)=>{a.input={...a.input,transcriptSince:{...a.input.transcriptSince,[r]:u}}},restart:()=>{this.views.has(i)&&this.host.restart()},nudge:()=>{this.views.has(i)&&this.host.nudge()},close:()=>{this.views.delete(i)&&(this.clearAttachTimer(a),this.host.isOpen()&&this.host.send({type:"view_detach",id:i}),n({type:"status",status:"closed",generation:this.generation}))}}}opened(){this.generation+=1;for(const e of this.views.values())this.clearAttachTimer(e),e.handler({type:"status",status:"open",generation:this.generation}),this.attach(e)}disconnected(e){for(const o of this.views.values())o.handler({type:"status",status:"closed",detail:e.message,generation:this.generation})}connecting(){for(const e of this.views.values())e.handler({type:"status",status:"connecting",generation:this.generation})}close(){for(const e of this.views.values())this.clearAttachTimer(e);this.views.clear()}receive(e){if(e.type!=="view_signal"&&e.type!=="view_error")return!1;const o=typeof e.id=="string"?this.views.get(e.id):void 0;if(o===void 0)return!0;if(e.type==="view_error")this.views.delete(o.id),this.clearAttachTimer(o),o.handler({type:"protocolError",generation:this.generation,recoverable:!1,detail:(e.msg??"Session view subscription failed").slice(0,512)});else{const n=e.data,i=n!==null&&typeof n=="object"?n.generation:void 0;if(typeof i=="number"&&i!==this.generation)return!0;const a=Tn(n)?n:_h(n);o.handler(a)}return!0}scheduleAttach(e){this.clearAttachTimer(e),e.attachTimer=setTimeout(()=>{e.attachTimer=void 0,this.views.has(e.id)&&this.host.isOpen()&&this.attach(e)},Eh)}clearAttachTimer(e){e.attachTimer!==void 0&&(clearTimeout(e.attachTimer),e.attachTimer=void 0)}attach(e){this.clearAttachTimer(e),this.host.send({type:"view_attach",id:e.id,sessionId:e.sessionId,data:{input:e.input,generation:this.generation,reconnected:e.attachCount>0,transcript_coverage_version:wn}}),e.attachCount+=1}}const Be=(t,e)=>JSON.stringify([t,e]);class Rh{constructor(e){this.socket=e}tracked=new Map;pending=new Map;listeners=new Set;statuses=new Set;status="connecting";closed=!1;get hasDemand(){return this.tracked.size>0||this.statuses.size>0}onStatus=e=>{if(this.closed)throw new Error("http closed");return this.statuses.add(e),e(this.status),this.socket.connect(),()=>{this.statuses.delete(e)}};onTerminalSignal=e=>{if(this.closed)throw new Error("http closed");return this.listeners.add(e),()=>{this.listeners.delete(e)}};nudge=()=>{this.socket.nudge()};terminalAttach=(e,o)=>{if(this.closed)return Promise.reject(new Error("http closed"));const n=Be(e,o);let i=this.tracked.get(n);return i===void 0&&(i={sessionId:e,terminalId:o,lastSeq:0},this.tracked.set(n,i)),this.socket.connect(),this.socket.isOpen()?this.attach(i):Promise.reject(new Error("socket is not connected"))};terminalDetach=(e,o)=>{this.tracked.delete(Be(e,o));for(const[n,i]of this.pending)i.sessionId!==e||i.terminalId!==o||(this.pending.delete(n),clearTimeout(i.timer),i.reject(new Error("terminal detached before the attach ack arrived")));this.send("terminal_detach",{session_id:e,terminal_id:o})};terminalInput=(e,o,n)=>{this.send("terminal_input",{session_id:e,terminal_id:o,data:n})};terminalResize=(e,o,n,i)=>{this.send("terminal_resize",{session_id:e,terminal_id:o,cols:n,rows:i})};send(e,o){!this.closed&&this.socket.isOpen()&&this.socket.send({type:e,id:this.socket.nextId(),data:o})}attach(e){const o=this.socket.nextId();return new Promise((n,i)=>{const a=setTimeout(()=>{this.pending.delete(o),i(new Error("terminal attach timed out — the server does not answer terminal frames"))},8e3);this.pending.set(o,{...e,resolve:n,reject:i,timer:a}),this.socket.send({type:"terminal_attach",id:o,data:{session_id:e.sessionId,terminal_id:e.terminalId,since_seq:e.lastSeq>0?e.lastSeq:void 0}})})}opened(){this.setStatus("open");for(const e of this.tracked.values())this.attach(e).catch(()=>{!this.socket.isOpen()||!this.tracked.has(Be(e.sessionId,e.terminalId))||this.emit({kind:"unavailable",sessionId:e.sessionId,terminalId:e.terminalId})})}connecting(){this.setStatus("connecting")}disconnected(e){for(const o of this.pending.values())clearTimeout(o.timer),o.reject(e);this.pending.clear(),this.setStatus("closed")}close(){this.closed=!0,this.disconnected(new Error("http event socket closed before the terminal attach ack arrived")),this.tracked.clear(),this.listeners.clear(),this.statuses.clear()}setStatus(e){this.status=e;for(const o of this.statuses)o(e)}emit(e){for(const o of this.listeners)try{o(e)}catch{}}receive(e){if(!e.type.startsWith("terminal_"))return!1;if(e.type==="terminal_ack"){const u=this.pending.get(e.id??"");if(u===void 0)return!0;if(this.pending.delete(e.id),clearTimeout(u.timer),e.code!==0)return u.reject(new Error(`terminal attach rejected: ${e.msg??"unknown error"} (code ${String(e.code)})`)),!0;const m=e.data,p={replayed:typeof m?.replayed=="number"?m.replayed:0,earliestSeq:typeof m?.earliest_seq=="number"?m.earliest_seq:null,truncated:m?.truncated===!0};return u.resolve(p),this.emit({kind:"attached",sessionId:u.sessionId,terminalId:u.terminalId,...p}),!0}const o=e.data;if(typeof o?.session_id!="string"||typeof o.terminal_id!="string")return!0;const n=o.session_id,i=o.terminal_id,a=Be(n,i),r=this.tracked.get(a);return r===void 0||(e.type==="terminal_output"&&typeof o.seq=="number"&&Number.isSafeInteger(o.seq)&&o.seq>r.lastSeq?(r.lastSeq=o.seq,this.emit({kind:"output",sessionId:n,terminalId:i,seq:o.seq,data:typeof o.payload?.data=="string"?o.payload.data:""})):e.type==="terminal_exit"&&(this.tracked.delete(a),this.emit({kind:"exit",sessionId:n,terminalId:i,exitCode:typeof o.payload?.exit_code=="number"?o.payload.exit_code:null}))),!0}}const Ph=Math.ceil((8<<20)*4/3)+65536,ms={codes:{REQUEST_LIMIT_REJECTED:"request.limit_rejected",REQUEST_QUEUE_TIMEOUT:"request.queue_timeout",REQUEST_QUEUE_FULL:"request.queue_full",AGENT_ANCESTOR_LIMIT:"request.agent_ancestor_limit"},info:{"request.agent_ancestor_limit":{title:"Parent occupies this agent limit",public:!0,retryable:!1,action:"Select subagents only, separate main and subagent rules, or increase the matching rule limit."},"request.limit_rejected":{title:"Local request limit reached",public:!0,retryable:!1,action:"Wait for active requests to finish or change the matching concurrency rule."},"request.queue_timeout":{title:"Local request queue timed out",public:!0,retryable:!1,action:"Retry the turn or adjust the local waiting budget."},"request.queue_full":{title:"Local request queue full",public:!0,retryable:!1,action:"Wait for queued requests to drain before retrying."}}};E(ms);const hs={codes:{DISPATCH_LIMIT_EXCEEDED:"dispatch.limit_exceeded"}};E(hs);const gs={codes:{AGENT_NOT_FOUND:"agent.not_found",AGENT_REMOVED:"agent.removed",AGENT_ALREADY_EXISTS:"agent.already_exists",AGENT_ALREADY_RUNNING:"agent.already_running",AGENT_NOT_A_SUBAGENT:"agent.not_a_subagent",AGENT_NOT_OWNED:"agent.not_owned",AGENT_TYPE_NOT_ALLOWED:"agent.type_not_allowed",AGENT_MAX_TOKENS_EXCEEDED:"agent.max_tokens_exceeded"}};E(gs);const vs={codes:{AUTH_LOGIN_REQUIRED:"auth.login_required",AUTH_PROVISIONING_REQUIRED:"auth.provisioning_required",AUTH_TOKEN_MISSING:"auth.token_missing",AUTH_TOKEN_UNAUTHORIZED:"auth.token_unauthorized",AUTH_MODEL_NOT_RESOLVED:"auth.model_not_resolved"},info:{"auth.login_required":{title:"Login required",retryable:!1,public:!0,action:"Run /login to authenticate with the OAuth provider."},"auth.provisioning_required":{title:"Provider provisioning required",retryable:!1,public:!0,action:"Configure a provider via /login or the providers endpoint."},"auth.token_missing":{title:"Provider credential missing",retryable:!1,public:!0,action:"Configure an API key or complete OAuth login for the provider."},"auth.token_unauthorized":{title:"Provider credential unauthorized",retryable:!1,public:!0,action:"Re-authenticate with the OAuth provider."},"auth.model_not_resolved":{title:"Model not resolved",retryable:!1,public:!0,action:"Set a default model or configure the requested model alias."}}};E(vs);const Ss={codes:{TASK_ID_EMPTY:"task.task_id_empty",TASK_EMPTY_AGENT_RECEIPT:"task.empty_agent_receipt",TASK_LIMIT_EXCEEDED:"task.limit_exceeded"},retryable:["task.limit_exceeded"],info:{"task.empty_agent_receipt":{title:"Missing agent receipt",retryable:!1,public:!0,action:"Inspect preserved work and the original turn, then resume the same agent with a new prompt ID and request a final receipt."}}};E(Ss);const fs={codes:{THREAD_NOT_FOUND:"thread.not_found",THREAD_ARCHIVED:"thread.archived",THREAD_DISABLED:"thread.disabled",THREAD_CROSS_HOST:"thread.cross_host",THREAD_SELF_SEND:"thread.self_send",THREAD_CURSOR_INVALID:"thread.cursor_invalid",THREAD_IDEMPOTENCY_CONFLICT:"thread.idempotency_conflict",THREAD_LIMIT_EXCEEDED:"thread.limit_exceeded",THREAD_DELIVERY_FAILED:"thread.delivery_failed",MAILBOX_LEGACY_WRITER_ACTIVE:"mailbox.legacy_writer_active",MAILBOX_MIGRATION_REQUIRED:"mailbox.migration_required"},retryable:["thread.delivery_failed","mailbox.legacy_writer_active"]};E(fs);const ys={codes:{PROVIDER_API_ERROR:Xu,PROVIDER_FILTERED:Ju,PROVIDER_RATE_LIMIT:Zu,PROVIDER_AUTH_ERROR:el,PROVIDER_CONNECTION_ERROR:tl,PROVIDER_OVERLOADED:ol,CONTEXT_OVERFLOW:nl},retryable:["provider.rate_limit","provider.connection_error","provider.overloaded","context.overflow"],info:{"provider.rate_limit":{title:"Provider rate limit",retryable:!0,public:!0,action:"Retry after the provider rate limit resets."},"provider.filtered":{title:"Provider filtered response",retryable:!1,public:!0,action:"Revise the prompt or model configuration to avoid provider safety filtering."},"provider.auth_error":{title:"Provider authentication failed",retryable:!1,public:!0,action:"Check provider credentials and authentication configuration."},"provider.overloaded":{title:"Provider overloaded",retryable:!0,public:!0,action:"Retry after the provider recovers from overload."},"context.overflow":{title:"Context overflow",retryable:!0,public:!0,action:"Compact the conversation or retry with fewer tokens."}}};E(ys);const bs={codes:{CONFIG_INVALID:me,CONFIG_PERSIST_BLOCKED:"config.persist_blocked"}};E(bs);const _s={codes:{BROWSER_INVALID:"browser.invalid",BROWSER_NOT_FOUND:"browser.not_found",BROWSER_DISABLED:"browser.disabled",BROWSER_DISCONNECTED:"browser.disconnected",BROWSER_EXECUTION_FAILED:"browser.execution_failed",BROWSER_BUSY:"browser.busy",BROWSER_VERSION:"browser.version",BROWSER_TARGET:"browser.target",BROWSER_REQUIRES_ACTION:"browser.requires_action",BROWSER_UNSUPPORTED:"browser.unsupported"},info:{"browser.invalid":{title:"Invalid browser configuration or request",retryable:!1,public:!0},"browser.not_found":{title:"Browser connection not found",retryable:!1,public:!0},"browser.disabled":{title:"Browser connection is disabled",retryable:!1,public:!0},"browser.disconnected":{title:"Browser connection is disconnected",retryable:!1,public:!0},"browser.execution_failed":{title:"Browser command failed",retryable:!1,public:!0},"browser.busy":{title:"Browser connection is busy",retryable:!1,public:!0},"browser.version":{title:"Unsupported browser driver version",retryable:!1,public:!0},"browser.target":{title:"Browser target is no longer available",retryable:!1,public:!0},"browser.requires_action":{title:"Browser setup or approval required",retryable:!1,public:!0},"browser.unsupported":{title:"Unsupported browser provider or operation",retryable:!1,public:!0}}};E(_s);const Is={codes:{CAPABILITY_NOT_FOUND:"capability.not_found",CAPABILITY_UNSUPPORTED:"capability.unsupported",CAPABILITY_INSTALL_IN_PROGRESS:"capability.install_in_progress"}};E(Is);const Ts={codes:{CRON_EXPRESSION_INVALID:"cron.expression_invalid"}};E(Ts);const ws={codes:{DEBUG_SCOPE_NOT_FOUND:"debug.scope_not_found",DEBUG_TOKEN_NOT_FOUND:"debug.token_not_found"}};E(ws);const Es={codes:{EVENT_DUPLICATE_EVENT:"event.duplicate_event",EVENT_SCHEMA_MISSING:"event.schema_missing"},info:{"event.duplicate_event":{title:"Duplicate event type",retryable:!1,public:!0,action:"Two event classes registered the same type; rename one. This is a build-time bug."},"event.schema_missing":{title:"Durable event without schema",retryable:!1,public:!0,action:"A durable event class must declare a zod payload schema for replay."}}};E(Es);const ks={codes:{EXECUTOR_BUSY:"executor.busy",EXECUTOR_CANCELLED:"executor.cancelled",EXECUTOR_CLOSED:"executor.closed",EXECUTOR_DISCONNECTED:"executor.disconnected",EXECUTOR_INVALID_SESSION_REF:"executor.invalid_session_ref",EXECUTOR_PROTOCOL_ERROR:"executor.protocol_error",EXECUTOR_SESSION_OPEN_FAILED:"executor.session_open_failed",EXECUTOR_SESSION_FAILED:"executor.session_failed",EXECUTOR_AUTHENTICATION_REQUIRED:"executor.authentication_required",EXECUTOR_SPAWN_FAILED:"executor.spawn_failed",EXECUTOR_STARTUP_TIMEOUT:"executor.startup_timeout"},retryable:["executor.disconnected","executor.startup_timeout"],info:{"executor.session_failed":{title:"External session failed",retryable:!1,public:!0,action:"Use the recovery actions reported by the external harness; do not replay the prompt automatically."}}};E(ks);var ee;(t=>{t.serviceIds=new Map,t.DI_TARGET="$di$target",t.DI_DEPENDENCIES="$di$dependencies";function e(n){return n[t.DI_DEPENDENCIES]||[]}t.getServiceDependencies=e;function o(n){return e(n).filter(i=>i.kind==="instance")}t.getInstanceDependencies=o})(ee||(ee={}));function Oh(t,e,o,n="instance"){const i=e;i[ee.DI_TARGET]===e?i[ee.DI_DEPENDENCIES].push({id:t,index:o,kind:n}):(i[ee.DI_DEPENDENCIES]=[{id:t,index:o,kind:n}],i[ee.DI_TARGET]=e)}function ct(t){const e=ee.serviceIds.get(t);if(e)return e;const o=function(i,a,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Oh(o,i,r)};return Object.defineProperty(o,"toString",{value:function(){return t},enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(o,Ah,{value:!0,enumerable:!1}),ee.serviceIds.set(t,o),o}const Ah=Symbol("serviceIdentifier");ct("instantiationService");const Mh=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}(?::?\d{2})?)$/,an=s().refine(t=>Mh.test(t),{message:"must be an ISO 8601 datetime string"}).transform((t,e)=>{const o=Date.parse(t);return Number.isNaN(o)?(e.addIssue({code:"custom",message:"invalid ISO 8601 datetime"}),ka):new Date(o).toISOString()});c({id:s().min(1),name:s().min(1),media_type:s().min(1),size:l().int().nonnegative(),created_at:an,expires_at:an.optional()});ct("fileService");const Cs={codes:{FILE_NOT_FOUND:"file.not_found"},info:{"file.not_found":{title:"File not found",retryable:!1,public:!0,action:"Check the file_id or upload the file again."}}};E(Cs);const Rs={codes:{FS_PATH_NOT_FOUND:"fs.path_not_found",FS_PERMISSION_DENIED:"fs.permission_denied",FS_PATH_ESCAPES:"fs.path_escapes",FS_IS_DIRECTORY:"fs.is_directory",FS_IS_BINARY:"fs.is_binary",FS_TOO_LARGE:"fs.too_large",FS_ALREADY_EXISTS:"fs.already_exists",FS_TOO_MANY_RESULTS:"fs.too_many_results",FS_GREP_TIMEOUT:"fs.grep_timeout",FS_GIT_UNAVAILABLE:"fs.git_unavailable"}};E(Rs);const Ps={codes:{COMPACTION_FAILED:"compaction.failed",COMPACTION_UNABLE:"compaction.unable"}};E(Ps);const Os={codes:{GOAL_ALREADY_EXISTS:"goal.already_exists",GOAL_NOT_FOUND:"goal.not_found",GOAL_OBJECTIVE_EMPTY:"goal.objective_empty",GOAL_OBJECTIVE_TOO_LONG:"goal.objective_too_long",GOAL_STATUS_INVALID:"goal.status_invalid",GOAL_METADATA_RESERVED:"goal.metadata_reserved",GOAL_NOT_RESUMABLE:"goal.not_resumable",GOAL_UNSUPPORTED_AGENT:"goal.unsupported_agent"},info:{"goal.already_exists":{title:"A goal is already active",retryable:!1,public:!0,action:"Use `/goal replace <objective>` to replace the current goal."},"goal.not_found":{title:"No goal found",retryable:!1,public:!0,action:"Start a goal with `/goal <objective>` first."},"goal.objective_empty":{title:"Goal objective is empty",retryable:!1,public:!0,action:"Provide a non-empty objective."},"goal.objective_too_long":{title:"Goal objective is too long",retryable:!1,public:!0,action:"Keep the objective under 4000 characters; reference long details by file path."},"goal.status_invalid":{title:"Invalid goal status transition",retryable:!1,public:!0,action:"Only an active goal can be paused; resume a blocked goal with `/goal resume`."},"goal.metadata_reserved":{title:"Goal metadata is reserved",retryable:!1,public:!0,action:"Do not write metadata.custom.goal directly; use the goal lifecycle methods."},"goal.not_resumable":{title:"Goal is not resumable",retryable:!1,public:!0,action:"Only paused or blocked goals can be resumed."},"goal.unsupported_agent":{title:"Goals are unavailable for subagents",retryable:!1,public:!0,action:"Run goal lifecycle commands on the main agent."}}};E(Os);const As={codes:{LOOP_MAX_STEPS_EXCEEDED:"loop.max_steps_exceeded",LOOP_EMPTY_COMPLETION:"loop.empty_completion",TURN_AGENT_BUSY:"turn.agent_busy"},retryable:["turn.agent_busy"],info:{"loop.empty_completion":{title:"Empty subagent completion",retryable:!1,public:!0,action:"Inspect the original turn and preserved work, then resume the same agent with a new prompt ID. An empty provider completion is not a task receipt."},"loop.max_steps_exceeded":{title:"Loop max steps exceeded",retryable:!1,public:!0,action:'Raise loop_control.max_steps_per_turn in config.toml, or run "/kiki-ops update loop_control.max_steps_per_turn" then "/reload".'}}};E(As);const Ms={codes:{MCP_SERVER_NOT_FOUND:"mcp.server_not_found",MCP_SERVER_DISABLED:"mcp.server_disabled",MCP_STARTUP_FAILED:"mcp.startup_failed",MCP_TOOL_NAME_COLLISION:"mcp.tool_name_collision",MCP_OAUTH_FAILED:"mcp.oauth_failed",MCP_COMPUTER_BUSY:"mcp.computer_busy",MCP_COMPUTER_OUTCOME_UNKNOWN:"mcp.computer_outcome_unknown",MCP_COMPUTER_STOP_UNCONFIRMED:"mcp.computer_stop_unconfirmed"}};E(Ms);const xs={codes:{PROVIDER_NOT_FOUND:"provider.not_found",PROVIDER_ALREADY_EXISTS:"provider.already_exists",MODEL_NOT_FOUND:"model.not_found",MODEL_ALREADY_EXISTS:"model.already_exists",REVISION_CONFLICT:"model_catalog.revision_conflict"},info:{"provider.not_found":{title:"Provider not found",retryable:!1,public:!0,action:"Check the provider id or configure the provider first."},"provider.already_exists":{title:"Provider already exists",retryable:!1,public:!0,action:"Choose another provider id or edit the existing connection."},"model.not_found":{title:"Model not found",retryable:!1,public:!0,action:"Check the model alias or configure the model first."},"model.already_exists":{title:"Model already exists",retryable:!1,public:!0,action:"Choose another local model id; an existing model is never overwritten."},"model_catalog.revision_conflict":{title:"Configuration changed",retryable:!0,public:!0,action:"Re-read the entity and reapply the edit against the current revision."}}};E(xs);const Us={codes:{OS_FS_NOT_FOUND:"os.fs.not_found",OS_FS_IS_DIRECTORY:"os.fs.is_directory",OS_FS_NOT_DIRECTORY:"os.fs.not_directory",OS_FS_ALREADY_EXISTS:"os.fs.already_exists",OS_FS_PERMISSION_DENIED:"os.fs.permission_denied",OS_FS_NOT_EMPTY:"os.fs.not_empty",OS_FS_UNAVAILABLE:"os.fs.unavailable",OS_FS_UNKNOWN:"os.fs.unknown"},retryable:["os.fs.unavailable","os.fs.unknown"],info:{"os.fs.not_found":{title:"Path not found",retryable:!1,public:!0},"os.fs.is_directory":{title:"Path is a directory",retryable:!1,public:!0},"os.fs.not_directory":{title:"Path is not a directory",retryable:!1,public:!0},"os.fs.already_exists":{title:"Path already exists",retryable:!1,public:!0},"os.fs.permission_denied":{title:"Permission denied",retryable:!1,public:!0,action:"Check the file permissions of the target path."},"os.fs.not_empty":{title:"Directory not empty",retryable:!1,public:!0},"os.fs.unavailable":{title:"Filesystem unavailable",retryable:!0,public:!0},"os.fs.unknown":{title:"Filesystem error",retryable:!0,public:!0}}};E(Us);ct("hostProcessService");const ke={codes:{OS_PROCESS_SPAWN_FAILED:"os.process.spawn_failed",OS_PROCESS_KILL_FAILED:"os.process.kill_failed",SHELL_GIT_BASH_NOT_FOUND:"shell.git_bash_not_found"},info:{"os.process.spawn_failed":{title:"Failed to spawn process",retryable:!1,public:!0,action:"Check that the command exists and is executable."},"os.process.kill_failed":{title:"Failed to kill process",retryable:!1,public:!0},"shell.git_bash_not_found":{title:"Git Bash not found",retryable:!1,public:!0,action:"Install Git for Windows so shell commands can run under Git Bash."}}};E(ke);ke.codes.OS_PROCESS_SPAWN_FAILED,ke.codes.OS_PROCESS_KILL_FAILED,ke.codes.SHELL_GIT_BASH_NOT_FOUND;const Ds={codes:{PLUGIN_NOT_FOUND:"plugin.not_found",PLUGIN_LOAD_FAILED:"plugin.load_failed",PLUGIN_READ_ONLY:"plugin.read_only"}};E(Ds);const Ns={codes:{MODEL_NOT_CONFIGURED:"model.not_configured",MODEL_CONFIG_INVALID:"model.config_invalid",PROFILE_CONSTRAINT_VIOLATION:"profile.constraint_violation",THINKING_ALIAS_CONFLICT:"profile.thinking_alias_conflict",PROFILE_UNKNOWN:"profile.unknown",PERSONA_UNKNOWN:"persona.unknown",PROFILE_ALREADY_BOUND:"profile.already_bound",PROFILE_NOT_BOUND:"profile.not_bound",COGNITION_FILE_MISSING:"profile.cognition_file_missing",COGNITION_PATH_INVALID:"profile.cognition_path_invalid",TOOL_PATTERN_INACTIVE:"profile.tool_pattern_inactive"}};E(Ns);const js={codes:{REQUEST_INVALID:"request.invalid",REQUEST_WORK_DIR_REQUIRED:"request.work_dir_required",REQUEST_PROMPT_INPUT_EMPTY:"request.prompt_input_empty",PROMPT_ID_CONFLICT:"prompt.id_conflict",PROMPT_NOT_FOUND:"prompt.not_found",PROMPT_ALREADY_COMPLETED:"prompt.already_completed",SESSION_BUSY:"session.busy"}};E(js);const Ls={codes:{CATALOG_UNAVAILABLE:"modelsDev.catalog_unavailable",CATALOG_ENTRY_NOT_FOUND:"modelsDev.catalog_entry_not_found",CATALOG_IMPORT_INVALID:"modelsDev.import_invalid",REGISTRY_IMPORT_INVALID:"modelsDev.registry_import_invalid",PROVIDER_OAUTH_MANAGED:"provider.oauth_managed"},info:{"modelsDev.catalog_unavailable":{title:"models.dev directory unavailable",retryable:!0,public:!0,action:"Check the network connection to models.dev and try again."},"modelsDev.catalog_entry_not_found":{title:"Directory entry not found",retryable:!1,public:!0,action:"Check the catalog id against the models.dev directory listing."},"modelsDev.import_invalid":{title:"Directory entry not importable",retryable:!1,public:!0,action:"Pick another entry or supply the required base_url."},"modelsDev.registry_import_invalid":{title:"Custom registry not importable",retryable:!1,public:!0,action:"Check the registry URL and credentials."},"provider.oauth_managed":{title:"Provider managed by OAuth login",retryable:!1,public:!0,action:"Log out via the OAuth flow instead of editing the provider."}}};E(Ls);const qs={codes:{SESSION_EXPORT_NOT_FOUND:"session.export_not_found",SESSION_EXPORT_MISSING_VERSION:"session.export_missing_version",SESSION_EXPORT_OUTPUT_CONFLICT:"session.export_output_conflict",SESSION_EXPORT_TOO_LARGE:"session.export_too_large"}};E(qs);const $s={codes:{SESSION_INDEX_BUILDING:"session.index_building"},retryable:["session.index_building"]};E($s);const Gs={codes:{SESSION_NOT_FOUND:"session.not_found",SESSION_ALREADY_EXISTS:"session.already_exists",SESSION_ID_INVALID:"session.id_invalid",SESSION_CLOSED:"session.closed",SESSION_FORK_ACTIVE_TURN:"session.fork_active_turn",SESSION_FORK_EXTERNAL_DELEGATION:"session.fork_external_delegation",SESSION_UNDO_UNAVAILABLE:"session.undo_unavailable",SESSION_CURSOR_MISMATCH:"session.cursor_mismatch",MESSAGE_ACTION_UNAVAILABLE:"message.action_unavailable",SESSION_INIT_FAILED:"session.init_failed",SESSION_PLAN_MODE_INVALID:"session.plan_mode_invalid",SESSION_TITLE_GENERATION_FAILED:"session.title_generation_failed"},retryable:["session.fork_active_turn"]};E(Gs);const Fs={codes:{SKILL_NOT_FOUND:"skill.not_found",SKILL_TYPE_UNSUPPORTED:"skill.type_unsupported",SKILL_NAME_EMPTY:"skill.name_empty",SKILL_PARSE_FAILED:"skill.parse_failed",SKILL_NESTED_TOO_DEEP:"skill.nested_too_deep"}};E(Fs);const Bs={codes:{STATE_DUPLICATE_FOLD:"state.duplicate_fold",STATE_DURABILITY_MISMATCH:"state.durability_mismatch",STATE_CYCLE:"state.cycle"},info:{"state.duplicate_fold":{title:"Duplicate state fold",retryable:!1,public:!0,action:"A state registered two folds for the same event; merge them."},"state.durability_mismatch":{title:"Transient state folds durable event",retryable:!1,public:!0,action:"A non-durable state cannot fold a durable event; mark the state durable."},"state.cycle":{title:"Event dispatch cycle",retryable:!1,public:!0,action:"A subscriber re-dispatches endlessly; break the event cycle."}}};E(Bs);const Vs={codes:{STORAGE_NOT_FOUND:"storage.not_found",STORAGE_DECODE_FAILED:"storage.decode_failed",STORAGE_CORRUPTED:"storage.corrupted",STORAGE_IO_FAILED:"storage.io_failed",STORAGE_LOCKED:"storage.locked",STORAGE_PERMISSION_DENIED:"storage.permission_denied",STORAGE_DISK_FULL:"storage.disk_full"},retryable:["storage.io_failed","storage.locked"],info:{"storage.not_found":{title:"Stored value not found",retryable:!1,public:!0},"storage.decode_failed":{title:"Stored value could not be decoded",retryable:!1,public:!0,action:"Inspect the stored document; it is not valid for its declared format."},"storage.corrupted":{title:"Stored data is corrupted",retryable:!1,public:!0,action:"Inspect the backing store; the corrupted entry must be repaired or dropped."},"storage.io_failed":{title:"Storage I/O failed",retryable:!0,public:!0},"storage.locked":{title:"Storage is locked",retryable:!0,public:!0,action:"Another process holds the store; close it or retry later."},"storage.permission_denied":{title:"Storage permission denied",retryable:!1,public:!0,action:"Check the permissions of the storage directory."},"storage.disk_full":{title:"Storage disk full",retryable:!1,public:!0,action:"Free up disk space and retry."}}};E(Vs);ct("fileSystemStorageService");const Ws={codes:{TERMINAL_NOT_FOUND:"terminal.not_found"}};E(Ws);const Hs={codes:{TURN_ID_CONFLICT:"usage.turn_id_conflict"}};E(Hs);const zs={codes:{WIRE_UNKNOWN_RECORD:"wire.unknown_record",WIRE_MIGRATION_MISSING:"wire.migration_missing",RECORDS_WRITE_FAILED:"records.write_failed"},info:{"wire.unknown_record":{title:"Unknown wire record",retryable:!1,public:!0,action:"The record was written by a newer version; upgrade or drop it."},"wire.migration_missing":{title:"Wire migration missing",retryable:!1,public:!0,action:"The wire file predates the supported migration chain; start a new session."},"records.write_failed":{title:"Wire journal write failed",retryable:!1,public:!0}}};E(zs);const Ks={codes:{WORKSPACE_NOT_FOUND:"workspace.not_found"}};E(Ks);const Qs={codes:{ROUTE_FEATURE_DISABLED:"agent_profile_route.feature_disabled",ROUTE_INVALID_ID:"agent_profile_route.invalid_id",ROUTE_UNKNOWN:"agent_profile_route.unknown",ROUTE_BASE_MISMATCH:"agent_profile_route.base_mismatch",ROUTE_BASE_MISSING:"agent_profile_route.base_missing",ROUTE_BINDING_CONFLICT:"agent_profile_route.binding_conflict",ROUTE_MODEL_ALIAS_MISSING:"agent_profile_route.model_alias_missing",ROUTE_SWITCH_FORBIDDEN:"agent_profile_route.switch_forbidden",ROUTE_INVALID_SIDECAR:"agent_profile_route.invalid_sidecar",ROUTE_DUPLICATE:"agent_profile_route.duplicate",SCOPED_PROFILE_UNAVAILABLE:"agent_profile_source.unavailable"}};E(Qs);const Ys={codes:{PROFILE_NOT_FOUND:"agent_profile_write.not_found",PROFILE_READ_ONLY:"agent_profile_write.read_only",PROFILE_ALREADY_EXISTS:"agent_profile_write.already_exists"}};E(Ys);({...ms.codes,...Gn.codes,...hs.codes,...gs.codes,...vs.codes,...Ss.codes,...fs.codes,...ys.codes,...bs.codes,..._s.codes,...Is.codes,...Ts.codes,...ws.codes,...ks.codes,...Cs.codes,...Rs.codes,...Ps.codes,...Os.codes,...As.codes,...Ms.codes,...xs.codes,...Fn.codes,...Us.codes,...ke.codes,...Ds.codes,...Ns.codes,...js.codes,...Ls.codes,...qs.codes,...$s.codes,...Gs.codes,...Fs.codes,...Vs.codes,...Ws.codes,...Hs.codes,...zs.codes,...Ks.codes,...Qs.codes,...Ys.codes,...Es.codes,...Bs.codes});class j extends Error{constructor(e,o,n,i,a,r,u){super(o),this.code=e,this.details=n,this.reason=i,this.requestId=a,this.data=r,this.source=u,this.name="RPCError"}}const Xs=1024*1024+64*1024;async function xh(t,e=Xs){if(t.body===null)throw new SyntaxError("Empty response body");const o=t.body.getReader(),n=[];let i=0;try{for(;;){const u=await o.read();if(u.done)break;if(i+=u.value.byteLength,i>e)throw await o.cancel("decoded response budget exceeded"),new j(50001,`Session response exceeded ${e} decoded bytes`);n.push(u.value)}const a=new Uint8Array(i);let r=0;for(const u of n)a.set(u,r),r+=u.byteLength;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}finally{o.releaseLock()}}function cn(t){const e=t.format??Dh(t.filename),o=t.filename??`persona.${e}`,n=new FormData;return n.append("file",new Blob([Js(t.data)],{type:Nh(e)}),o),e!==void 0&&n.append("format",e),"id"in t&&t.id!==void 0&&n.append("id",t.id),"name"in t&&t.name!==void 0&&n.append("name",t.name),n}function Uh(t,e,o){const n=e??"application/octet-stream",i=n==="image/jpeg"?"jpg":n==="image/webp"?"webp":"png",a=new FormData;return o!==void 0&&a.append("shape",o),a.append("file",new Blob([Js(t)],{type:n}),`avatar.${i}`),a}function Js(t){return t.slice().buffer}function Dh(t){const e=t?.toLowerCase();if(e?.endsWith(".png"))return"png";if(e?.endsWith(".charx"))return"charx";if(e?.endsWith(".json"))return"json"}function Nh(t){return t==="png"?"image/png":t==="charx"?"application/zip":"application/json"}function jh(t){return{configuration:async e=>Io.parse(await t.json("/output-layer/configuration",{...e,query:{session_id:e?.sessionId}})),configure:async(e,o)=>Io.parse(await t.json("/output-layer/configuration",{...o,method:"PUT",body:e})),stream:(e,o,n)=>t.raw("/output-layer/stream",{...n,method:"POST",body:Ca.parse(e),timeoutMs:n?.timeoutMs??0},async i=>{if(!i.ok)throw new Error(`Output layer request failed (${i.status})`);if(!i.headers.get("content-type")?.includes("application/x-ndjson")){const S=await i.json();throw new Error(S.msg??"Output layer stream unavailable")}if(i.body===null)throw new Error("Output layer response has no body");const a=i.body.getReader(),r=new TextDecoder;let u="",m=!1;const p=S=>{if(!S.trim())return;const f=Ra.parse(JSON.parse(S));m||=["completed","cancelled","failed"].includes(f.type),o(f)};try{for(;;){const{value:S,done:f}=await a.read();u+=r.decode(S,{stream:!f});let y;for(;(y=u.indexOf(`
2
- `))>=0;)p(u.slice(0,y)),u=u.slice(y+1);if(f)break}if(p(u),!m)throw new Error("Output layer stream ended before completion")}finally{await a.cancel(),a.releaseLock()}})}}function Lh(t){const e="/remote-connections",o=encodeURIComponent;return{list:()=>t.json(e),inbound:()=>t.json(e+"/inbound"),setInbound:n=>t.json(e+"/inbound",{method:"PUT",body:{enabled:n}}),invite:n=>t.json(e+"/inbound/invitations",{method:"POST",body:n}),revoke:n=>t.json(e+"/inbound/grants/"+o(n)+"/revoke",{method:"POST",body:{}}),add:n=>t.json(e,{method:"POST",body:n}),remove:n=>t.json(e+"/"+o(n),{method:"DELETE"}),setEnabled:(n,i)=>t.json(e+"/"+o(n)+"/enabled",{method:"PUT",body:{enabled:i}}),retry:n=>t.json(e+"/"+o(n)+"/retry",{method:"POST",body:{}}),summary:(n,i)=>t.json(e+"/"+o(n)+"/call",{...i,method:"POST",body:{operation:"spaceSummary"}}),handshake:()=>t.json(e+"/handshake"),sshPlan:(n,i)=>t.json(e+"/ssh/plan",{...i,method:"POST",body:n}),sshExecute:(n,i,a)=>t.json(e+"/ssh/plans/"+o(n)+"/execute",{...a,method:"POST",body:i}),sshRegister:(n,i)=>t.json(e+"/ssh/register",{...i,method:"POST",body:n}),sshStatus:()=>t.json(e+"/ssh/status")}}function qh(t){if(!/^[0-9a-f-]{36}$/.test(t.connectionId))throw new Error("Invalid connectionId");const e=t.endpoint.replace(/\/+$/,""),o=e+"/api/remote-connections/"+encodeURIComponent(t.connectionId),n=t.fetch??globalThis.fetch,i=async(r,u={})=>{const m=new URL(r instanceof Request?r.url:String(r)),p=u.method??(r instanceof Request?r.method:"GET");if(p==="POST"&&m.pathname==="/api/fs:html-preview"||p==="DELETE"&&/^\/api\/fs:html-preview\/[^/]+$/.test(m.pathname)){const D=new Headers({"content-type":"application/json"});t.token!==void 0&&D.set("authorization",`Bearer ${t.token}`);const $=p==="POST"?o+"/html-preview":e+m.pathname;return n($,{...u,headers:D,method:p,redirect:"error",credentials:"same-origin"})}const S=mc(p,m.pathname);if(S===void 0)throw new j(40301,"Operation is not available to a remote space");const f={};for(const[D,$]of m.searchParams){const H=f[D];f[D]=H===void 0?$:Array.isArray(H)?[...H,$]:[H,$]}const y=["media","mediaPreview","file","appearanceAsset","personaAvatar"].includes(S.operation),I=new Headers(u.headers??(r instanceof Request?r.headers:void 0));if(S.operation==="fileUpload")return I.delete("authorization"),t.token!==void 0&&I.set("authorization",`Bearer ${t.token}`),n(o+"/upload",{...u,headers:I,method:"POST",redirect:"error"});const w=typeof u.body=="string"?JSON.parse(u.body):void 0,C={operation:S.operation,params:S.params,query:f,body:w,headers:{ifNoneMatch:I.get("if-none-match")??void 0,range:I.get("range")??void 0}},P=new Headers({"content-type":"application/json"});return t.token!==void 0&&P.set("authorization",`Bearer ${t.token}`),n(o+(y?"/download":"/call"),{method:"POST",headers:P,body:JSON.stringify(C),signal:u.signal,redirect:"error",credentials:"same-origin"})},a=new URL(o+"/events");return a.protocol=a.protocol==="https:"?"wss:":"ws:",{fetch:i,eventsUrl:a.toString()}}function $h(t){const e="/web-access";return{status:async()=>Ne.parse(await t.json(e)),enable:async o=>Ne.parse(await t.json(e,{method:"PUT",body:Aa.parse(o)})),disable:async()=>Ne.parse(await t.json(e,{method:"DELETE"})),issueLink:async()=>Oa.parse(await t.json(e+"/links",{method:"POST",body:{}})),revoke:async o=>Ne.parse(await t.json(e+"/revoke",{method:"POST",body:{sessionId:o}})),current:async()=>bt.parse(await t.json(e+"/session",{skipAuth:!0})),exchange:async o=>bt.parse(await t.json(e+"/exchange",{method:"POST",body:Pa.parse(o),skipAuth:!0})),logout:async()=>bt.parse(await t.json(e+"/logout",{method:"POST",body:{},skipAuth:!0}))}}function Gh(t){const e="/thread-bridges",o=(n,i)=>e+"/"+n+"/"+encodeURIComponent(i);return{status:n=>t.json(e,n),approve:(n,i)=>t.json(e+"/inbound",{...i,method:"POST",body:n}),registerTarget:(n,i)=>t.json(e+"/targets",{...i,method:"POST",body:n}),provisionLocal:(n,i)=>t.json(e+"/local",{...i,method:"POST",body:n}),install:(n,i)=>t.json(e+"/outbound",{...i,method:"POST",body:n}),setEnabled:(n,i,a,r)=>t.json(o(n,i)+"/enabled",{...r,method:"PUT",body:{enabled:a}}),revoke:(n,i,a)=>t.json(o(n,i)+"/revoke",{...a,method:"POST",body:{}}),receipts:(n,i)=>t.json(e+"/receipts",{...i,query:n}),retry:n=>t.json(e+"/retry",{...n,method:"POST",body:{}})}}function Fh(t){const e="/usage-export",o=(n,i)=>`${e}/destinations/${encodeURIComponent(n)}/${i}`;return{status:async()=>X.parse(await t.json(e)),saveDraft:async n=>_t.parse(await t.json(e+"/destinations",{method:"POST",body:Na.parse(n)})),beginVibeAuth:async(n,i)=>It.parse(await t.json(o(n,"auth/begin"),{method:"POST",body:Da.parse(i)})),pollVibeAuth:async n=>It.parse(await t.json(`${e}/auth/${encodeURIComponent(n)}/poll`,{method:"POST",body:{}})),cancelVibeAuth:async n=>It.parse(await t.json(`${e}/auth/${encodeURIComponent(n)}/cancel`,{method:"POST",body:{}})),preview:async n=>To.parse(await t.json(o(n,"preview"))),testProtocol:n=>t.json(o(n,"test"),{method:"POST",body:{}}),enable:async(n,i)=>_t.parse(await t.json(o(n,"enable"),{method:"POST",body:Ua.parse(i)})),disable:async n=>_t.parse(await t.json(o(n,"disable"),{method:"POST",body:{}})),remove:(n,i)=>t.json(o(n,"remove"),{method:"POST",body:{discard_pending:i}}),syncNow:async n=>X.parse(await t.json(o(n,"sync"),{method:"POST",body:{}})),backfill:async(n,i)=>To.parse(await t.json(o(n,"backfill"),{method:"POST",body:xa.parse(i)})),diagnostics:async()=>X.parse(await t.json(e+"/diagnostics")),exportLocal:n=>t.json(o(n,"export")),rebuild:async n=>X.parse(await t.json(e+"/rebuild",{method:"POST",body:{force:n}})),retry:async n=>X.parse(await t.json(o(n,"retry"),{method:"POST",body:{}})),setQueueCapacity:async n=>X.parse(await t.json(e+"/queue-capacity",{method:"PUT",body:{bytes:n}})),clearQueue:async(n,i)=>X.parse(await t.json(o(n,"clear-queue"),{method:"POST",body:{acknowledge:i}})),withdraw:async(n,i)=>X.parse(await t.json(o(n,"withdraw"),{method:"POST",body:{acknowledge:i}})),handoff:async n=>fe.nullable().parse(await t.json(o(n,"handoff"))),planHandoff:async(n,i)=>fe.parse(await t.json(o(n,"handoff/plan"),{method:"POST",body:{cutoff_at:i}})),armHandoff:async(n,i)=>fe.parse(await t.json(o(n,"handoff/arm"),{method:"POST",body:Ma.parse(i)})),refreshHandoff:async n=>fe.nullable().parse(await t.json(o(n,"handoff/refresh"),{method:"POST",body:{}})),rollbackHandoff:async(n,i,a)=>fe.parse(await t.json(o(n,"handoff/rollback"),{method:"POST",body:{cutoff_at:i,acknowledge:a}}))}}function Bh(t){const e="/usage/provider-quotas";return{snapshot:async()=>Tt.parse(await t.json(e)),refresh:async o=>Tt.parse(await t.json(e+"/refresh",{method:"POST",body:La.parse({source_id:o})})),setEnabled:async(o,n)=>Tt.parse(await t.json(e+"/enabled",{method:"PUT",body:ja.parse({source_id:o,enabled:n})}))}}function Vh(t){const e="/external-clients",o=i=>`${e}/${encodeURIComponent(i)}`,n=i=>`${e}/sessions/${encodeURIComponent(i)}`;return{list:i=>t.json(e,i),create:(i,a)=>t.json(e,{...a,method:"POST",body:i}),update:(i,a,r)=>t.json(o(i),{...r,method:"PATCH",body:a}),revoke:(i,a)=>t.json(o(i),{...a,method:"DELETE"}),sessions:(i,a)=>t.json(`${o(i)}/sessions`,a),stdio:(i,a)=>t.json(`${o(i)}/stdio`,{...a,method:"POST",body:{}}),listener:i=>t.json(`${e}/listener`,i),configureListener:(i,a)=>t.json(`${e}/listener`,{...a,method:"PUT",body:i}),authorizations:i=>t.json(`${e}/authorizations`,i),respondAuthorization:(i,a,r)=>t.json(`${e}/authorizations/${encodeURIComponent(i)}/respond`,{...r,method:"POST",body:a}),saveText:(i,a,r)=>t.json(`${n(i)}/text`,{...r,method:"POST",body:a}),materials:(i,a)=>t.json(`${n(i)}/materials`,a),continue:(i,a,r)=>t.json(`${n(i)}/continue`,{...r,method:"POST",body:a??{}}),closeSession:(i,a)=>t.json(`${n(i)}/close`,{...a,method:"POST",body:{}}),stopSession:(i,a)=>t.json(`${n(i)}/stop`,{...a,method:"POST",body:{}})}}const Wh=c({preview_id:s().regex(/^[a-f0-9]{64}$/u),url:s().min(1),mime:s().min(1),size:l().int().nonnegative(),expires_at:l().int().positive()}).strict();function Hh(t){return{outputLayer:jh(t),externalClients:Vh(t),webAccess:$h(t),connections:Lh(t),threadBridges:Gh(t),usageExport:Fh(t),providerQuotas:Bh(t),healthz:async e=>{try{return(await t.json("/healthz",{baseUrl:e,timeoutMs:0,skipAuth:!0}))?.ok===!0}catch{return!1}},meta:()=>t.json("/meta"),renewLease:e=>t.json("/leases",{method:"POST",body:e,allowMissingRoute:!0}),usage:(e,o)=>t.json("/usage",{query:e,signal:o?.signal}),requestGovernance:()=>t.json("/usage/realtime"),agentActivity:()=>t.json("/usage/realtime/agents"),usageRescan:{status:()=>t.json("/usage/rescan"),start:()=>t.json("/usage/rescan",{method:"POST"})},usagePricing:{get:e=>t.json("/usage/pricing",{query:{model:e}}),set:e=>t.json("/usage/pricing",{method:"PUT",body:e})},shortcuts:{read:e=>t.json("/gui/shortcuts",{query:{platform:e}}),write:(e,o)=>t.json("/gui/shortcuts",{method:"PUT",query:{platform:e},body:{preferences:o}}),reset:(e,o={})=>t.json("/gui/shortcuts/reset",{method:"POST",query:{platform:e},body:o})},browser:{setupPresets:()=>t.json("/browser/setup"),setupStatus:e=>t.json(`/browser/setup/${encodeURIComponent(e)}`),prepare:(e,o)=>t.json(`/browser/setup/${encodeURIComponent(e)}:prepare`,{method:"POST",body:o}),connectPreset:(e,o={})=>t.json(`/browser/setup/${encodeURIComponent(e)}:connect`,{method:"POST",body:o}),openPreset:(e,o={})=>t.json(`/browser/setup/${encodeURIComponent(e)}:open`,{method:"POST",body:o}),updatePreset:(e,o={})=>t.json(`/browser/setup/${encodeURIComponent(e)}:update`,{method:"POST",body:o}),createShortcut:(e,o={})=>t.json(`/browser/setup/${encodeURIComponent(e)}:shortcut`,{method:"POST",body:o}),cancelSetup:e=>t.json(`/browser/setup/${encodeURIComponent(e)}:cancel`,{method:"POST",body:{}}),list:()=>t.json("/browser/connections"),saveSettings:e=>t.json("/config",{method:"POST",body:{browser_control:e}}),upsert:(e,o)=>t.json(`/browser/connections/${encodeURIComponent(e)}`,{method:"PUT",body:o}),remove:e=>t.json(`/browser/connections/${encodeURIComponent(e)}`,{method:"DELETE"}),setDefault:e=>t.json("/browser/default",{method:"PUT",body:{browser:e}}),status:e=>t.json(`/browser/connections/${encodeURIComponent(e)}:status`),tabs:e=>t.json(`/browser/connections/${encodeURIComponent(e)}:tabs`),catalog:(e,o)=>t.json(`/browser/connections/${encodeURIComponent(e)}:catalog`,{query:{includeSchema:o?.includeSchema}}),check:e=>t.json(`/browser/connections/${encodeURIComponent(e)}:check`,{method:"POST",body:{}}),connect:e=>t.json(`/browser/connections/${encodeURIComponent(e)}:connect`,{method:"POST",body:{}}),disconnect:e=>t.json(`/browser/connections/${encodeURIComponent(e)}:disconnect`,{method:"POST",body:{}})},ssh:{list:e=>t.json("/ssh/hosts",{query:{workspace_id:e}}),discover:()=>t.json("/ssh/hosts:discover"),upsert:(e,o,n)=>t.json(`/ssh/hosts/${encodeURIComponent(e)}`,{method:"PUT",body:o,query:{workspace_id:n}}),remove:(e,o)=>t.json(`/ssh/hosts/${encodeURIComponent(e)}`,{method:"DELETE",query:{workspace_id:o}}),configSync:()=>t.json("/ssh/config-sync"),setConfigSync:e=>t.json("/ssh/config-sync",{method:"PUT",body:{enabled:e}}),hostKeys:(e,o)=>t.json(`/ssh/hosts/${encodeURIComponent(e)}:host-keys`,{query:{workspace_id:o}}),connectionApproval:()=>t.json("/ssh/connection-approval"),setConnectionApproval:e=>t.json("/ssh/connection-approval",{method:"PUT",body:{enabled:e}}),writeBack:(e,o)=>t.json(`/ssh/hosts/${encodeURIComponent(e)}:write-back`,{method:"POST",body:{},query:{workspace_id:o}}),status:(e,o)=>t.json(`/ssh/hosts/${encodeURIComponent(e)}:status`,{query:{workspace_id:o}}),disconnect:(e,o)=>t.json(`/ssh/hosts/${encodeURIComponent(e)}:disconnect`,{method:"POST",body:{},query:{workspace_id:o}}),sessionHosts:e=>t.json(`/sessions/${encodeURIComponent(e)}/ssh/hosts`),addSessionHost:(e,o)=>t.json(`/sessions/${encodeURIComponent(e)}/ssh/hosts/${encodeURIComponent(o)}`,{method:"PUT",body:{}}),removeSessionHost:(e,o)=>t.json(`/sessions/${encodeURIComponent(e)}/ssh/hosts/${encodeURIComponent(o)}`,{method:"DELETE"}),submitApproval:(e,o,n)=>t.json(`/sessions/${encodeURIComponent(e)}/ssh/approvals/${encodeURIComponent(o)}`,{method:"POST",body:n}),copySharedCredentialsToIsolated:e=>t.json("/ssh/credentials:copy-to-isolated",{method:"POST",body:e})},worktrees:{list:e=>t.json("/worktrees",{query:e}),get:e=>t.json(`/worktrees/${encodeURIComponent(e)}`),inspect:e=>t.json(`/worktrees/${encodeURIComponent(e)}:inspect`,{method:"POST",body:{}}),remove:(e,o={})=>t.json(`/worktrees/${encodeURIComponent(e)}:remove`,{method:"POST",body:o}),gc:e=>t.json("/worktrees:gc",{method:"POST",body:{dryRun:e}})},sessions:{list:(e={},o)=>t.json("/sessions",{signal:o?.signal,timeoutMs:o?.timeoutMs,query:{page_size:e.page_size??50,before_id:e.before_id,after_id:e.after_id,busy:e.busy,include_archive:e.include_archive,include_ephemeral:e.include_ephemeral,archived_only:e.archived_only,q:e.q,exclude_empty:e.exclude_empty,workspace_id:e.workspace_id,persona:e.persona}}),listEphemeral:(e={})=>t.json("/sessions/ephemeral",{query:{...e,page_size:e.page_size??50}}),create:e=>t.json("/sessions",{method:"POST",body:e}),saveEphemeral:e=>t.json(`/sessions/${encodeURIComponent(e)}/ephemeral/save`,{method:"POST",body:{}}),endEphemeral:(e,o={})=>t.json(`/sessions/${encodeURIComponent(e)}/ephemeral/end`,{method:"POST",body:o}),compact:(e,o={})=>t.json(`/sessions/${encodeURIComponent(e)}:compact`,{method:"POST",body:o}),getAutoCompact:(e,o)=>t.json(`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(o)}/auto-compact`),setAutoCompact:(e,o,n)=>t.json(`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(o)}/auto-compact`,{method:"PATCH",body:n}),inspectHooks:(e,o)=>t.json(`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(o)}/hooks`),undo:(e,o={})=>t.json(`/sessions/${encodeURIComponent(e)}:undo`,{method:"POST",body:o}),updateProfile:(e,o)=>t.json(`/sessions/${encodeURIComponent(e)}/profile`,{method:"POST",body:o}),getPersonaSettings:e=>t.json(`/sessions/${encodeURIComponent(e)}/persona-settings`),applyPersonaSettings:(e,o={})=>t.json(`/sessions/${encodeURIComponent(e)}/persona-settings`,{method:"POST",body:o}),archive:(e,o={})=>t.json("/sessions/"+encodeURIComponent(e)+":archive",{method:"POST",body:o}),restore:e=>t.json("/sessions/"+encodeURIComponent(e)+":restore",{method:"POST",body:{}}),deleteArchived:async(e,o={})=>wo.parse(await t.json("/sessions/"+encodeURIComponent(e)+":delete-archived",{method:"POST",body:Ga.parse(o),timeoutMs:0})),deleteAllArchived:async()=>wo.parse(await t.json("/sessions:delete-archived",{method:"POST",body:{},timeoutMs:0})),goal:e=>t.json("/sessions/"+encodeURIComponent(e)+"/goal"),listMessages:(e,o={})=>t.json(`/sessions/${encodeURIComponent(e)}/messages`,{query:{before_id:o.before_id,page_size:o.page_size??50}}),listPrompts:(e,o={})=>t.json(`/sessions/${encodeURIComponent(e)}/prompts`,{query:{admission:o.admission,agent_id:o.agent_id,cursor:o.cursor}}),getPrompt:(e,o,n={})=>t.json(`/sessions/${encodeURIComponent(e)}/prompts/${encodeURIComponent(o)}`,{query:{admission:n.admission,agent_id:n.agent_id}}),resumePrompt:(e,o,n,i={})=>t.json(`/sessions/${encodeURIComponent(e)}/prompts/${encodeURIComponent(o)}:resume`,{method:"POST",body:n,query:{admission:"durable",agent_id:i.agent_id}}),listApprovals:async e=>(await t.json(`/sessions/${encodeURIComponent(e)}/approvals`,{query:{status:"pending"}})).items,listQuestions:async e=>(await t.json(`/sessions/${encodeURIComponent(e)}/questions`,{query:{status:"pending"}})).items,listTasks:(e,o)=>t.json(`/sessions/${encodeURIComponent(e)}/tasks`,{query:{status:o?.status,page_size:o?.page_size,offset:o?.offset}}),listAgentTasks:async(e,o={},n={})=>{const i=qa.parse(o);return $a.parse(await t.json(`/sessions/${encodeURIComponent(e)}/agent-tasks`,{...n,query:{page_size:i.page_size,page_token:i.page_token}}))},getTask:(e,o,n={})=>t.json(`/sessions/${encodeURIComponent(e)}/tasks/${encodeURIComponent(o)}`,{query:{with_output:n.with_output,output_bytes:n.output_bytes,agent_id:n.agent_id}}),listSkills:e=>t.json(`/sessions/${encodeURIComponent(e)}/skills`),activateSkill:(e,o,n={})=>t.json(`/sessions/${encodeURIComponent(e)}/skills/${encodeURIComponent(o)}:activate`,{method:"POST",body:n}),fsSearch:(e,o,n)=>t.json(`/sessions/${encodeURIComponent(e)}/fs:search`,{method:"POST",body:o,signal:n?.signal,timeoutMs:n?.timeoutMs}),media:async(e,o,n)=>pe(t,`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(o)}`,{signal:n?.signal,timeoutMs:n?.timeoutMs,headers:le(n)}),mediaPreview:async(e,o,n)=>pe(t,`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(o)}/preview`,{query:{media_type:n?.mediaType},signal:n?.signal,timeoutMs:n?.timeoutMs,headers:le(n)},xo),downloadMedia:(e,o,n,i)=>t.raw(`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(o)}`,{method:"GET",expectBinary:!0,signal:i?.signal,timeoutMs:i?.timeoutMs??0,headers:le(i)},a=>Lt(a,n,i?.signal)),openMediaPlayback:async(e,o,n)=>Wh.parse(await t.json(`/sessions/${encodeURIComponent(e)}/media-playback`,{method:"POST",body:{file_id:o},signal:n?.signal,timeoutMs:n?.timeoutMs??15e3})),closeMediaPlayback:async(e,o)=>{await t.json(`/sessions/media-playback/${encodeURIComponent(e)}`,{method:"DELETE",signal:o?.signal,timeoutMs:o?.timeoutMs??1e4})},export:e=>t.raw(`/sessions/${encodeURIComponent(e)}/export`,{method:"POST",body:{},timeoutMs:0,expectBinary:!0,jsonErrorOnSuccess:!0},async o=>{const n=o.headers.get("content-disposition")??"",i=/filename\*?=(?:UTF-8'')?"?([^";]+)"?/iu.exec(n);return{blob:await o.blob(),filename:i?.[1]??`kiki-session-${e}.zip`}})},bots:{list:()=>t.json("/bots"),enable:e=>t.json(`/bots/${encodeURIComponent(e)}/enable`,{method:"POST"}),ensureHomeSession:e=>t.json(`/bots/${encodeURIComponent(e)}/home`,{method:"POST"}),update:(e,o)=>t.json(`/bots/${encodeURIComponent(e)}`,{method:"PATCH",body:o})},rooms:{list:()=>t.json("/rooms"),listItems:()=>t.json("/rooms/items"),get:e=>t.json(`/rooms/${encodeURIComponent(e)}`),create:e=>t.json("/rooms",{method:"POST",body:e}),createFromThreads:e=>t.json("/rooms/from-threads",{method:"POST",body:e}),searchThreads:e=>t.json("/rooms/threads",{query:e}),addMember:(e,o)=>t.json(`/rooms/${encodeURIComponent(e)}/members`,{method:"POST",body:o}),removeMember:(e,o)=>t.json(`/rooms/${encodeURIComponent(e)}/members/${encodeURIComponent(o)}`,{method:"DELETE"}),update:(e,o)=>t.json(`/rooms/${encodeURIComponent(e)}`,{method:"PATCH",body:o}),delete:async e=>{await t.json(`/rooms/${encodeURIComponent(e)}`,{method:"DELETE"})},postUserMessage:(e,o)=>t.json(`/rooms/${encodeURIComponent(e)}/messages`,{method:"POST",body:o}),pause:e=>t.json(`/rooms/${encodeURIComponent(e)}/pause`,{method:"POST"}),continue:e=>t.json(`/rooms/${encodeURIComponent(e)}/continue`,{method:"POST"}),stop:e=>t.json(`/rooms/${encodeURIComponent(e)}/stop`,{method:"POST"}),log:(e,o)=>t.json(`/rooms/${encodeURIComponent(e)}/log`,{query:o}),usage:e=>t.json(`/rooms/${encodeURIComponent(e)}/usage`)},personas:{list:e=>t.json("/personas",{query:{includeArchived:e?.includeArchived}}),get:e=>t.json(`/personas/${encodeURIComponent(e)}`),ensureHome:e=>t.json(`/personas/${encodeURIComponent(e)}/home`,{method:"POST"}),setHome:(e,o)=>t.json(`/personas/${encodeURIComponent(e)}/home`,{method:"PUT",body:{sessionId:o}}),updateState:(e,o)=>t.json(`/personas/${encodeURIComponent(e)}/state`,{method:"PATCH",body:o}),put:e=>t.json(`/personas/${encodeURIComponent(e.definition.id)}`,{method:"PUT",body:e}),duplicate:(e,o)=>t.json(`/personas/${encodeURIComponent(e)}:duplicate`,{method:"POST",body:o??{}}),archive:(e,o=!0)=>t.json(`/personas/${encodeURIComponent(e)}:archive`,{method:"POST",body:{archived:o}}),delete:(e,o)=>t.json(`/personas/${encodeURIComponent(e)}`,{method:"DELETE",query:{expectedRevision:o?.expectedRevision}}),previewImport:e=>t.json("/personas/import/preview",{method:"POST",rawBody:cn(e)}),importCard:e=>t.json("/personas/import",{method:"POST",rawBody:cn(e)}),exportCard:(e,o,n)=>pe(t,`/personas/${encodeURIComponent(e)}/export`,{query:{format:o,includeMemory:n?.includeMemory},signal:n?.signal,timeoutMs:n?.timeoutMs}),getAvatar:(e,o)=>pe(t,`/personas/${encodeURIComponent(e)}/avatar`,{signal:o?.signal,timeoutMs:o?.timeoutMs}),putAvatar:(e,o,n,i)=>t.json(`/personas/${encodeURIComponent(e)}/avatar`,{method:"PUT",rawBody:Uh(o,n,i)}),deleteAvatar:e=>t.json(`/personas/${encodeURIComponent(e)}/avatar`,{method:"DELETE"}),avatar:({id:e,name:o,avatarMime:n,avatarShape:i})=>({id:e,name:o,avatarUrl:n===void 0?void 0:`/api/personas/${encodeURIComponent(e)}/avatar`,avatarShape:n===void 0?void 0:i})},skills:{list:e=>t.json("/skills",{query:{cwd:e}}),readBuiltinContent:(e,o)=>t.json(`/skills/${encodeURIComponent(e)}:content`,{signal:o?.signal,timeoutMs:o?.timeoutMs}),previewHostInstall:(e,o)=>t.json(`/skills/${encodeURIComponent(o)}:preview-install`,{method:"POST",body:{host:e}}),installHost:(e,o,n)=>t.json(`/skills/${encodeURIComponent(o)}:install`,{method:"POST",body:{host:e,revision:n,confirmed:!0}})},skins:{list:()=>t.json("/skins",{allowMissingRoute:!0}),get:e=>t.json(`/skins/${encodeURIComponent(e)}`)},workspaces:{list:()=>t.json("/workspaces"),listCatalog:()=>t.json("/workspaces",{query:{view:"catalog"}}),detail:e=>t.json(`/workspaces/${encodeURIComponent(e)}`),trust:e=>t.json(`/workspaces/${encodeURIComponent(e)}/trust`),setTrust:(e,o)=>t.json(`/workspaces/${encodeURIComponent(e)}/${o?"trust":"untrust"}`,{method:"POST"}),inspect:e=>t.json("/workspaces:inspect",{method:"POST",body:{root:e}}),rename:(e,o)=>t.json(`/workspaces/${encodeURIComponent(e)}`,{method:"PATCH",body:{name:o}}),setPinned:(e,o)=>t.json(`/workspaces/${encodeURIComponent(e)}`,{method:"PATCH",body:{pinned:o}}),updateCatalog:(e,o)=>t.json(`/workspaces/${encodeURIComponent(e)}`,{method:"PATCH",query:{view:"catalog"},body:o}),remove:e=>t.json(`/workspaces/${encodeURIComponent(e)}`,{method:"DELETE"}),listSkills:e=>t.json(`/workspaces/${encodeURIComponent(e)}/skills`),getTrust:e=>t.json(`/workspaces/${encodeURIComponent(e)}/trust`),untrust:e=>t.json(`/workspaces/${encodeURIComponent(e)}/untrust`,{method:"POST"})},homes:{presets:()=>t.json("/homes/presets"),list:()=>t.json("/homes"),detail:e=>t.json(`/homes/${encodeURIComponent(e)}/settings`),preview:(e,o)=>t.json(`/homes/${encodeURIComponent(e)}/settings/preview`,{method:"POST",body:o}),apply:(e,o)=>t.json(`/homes/${encodeURIComponent(e)}/settings/apply`,{method:"POST",body:o}),undo:(e,o)=>t.json(`/homes/${encodeURIComponent(e)}/settings/undo`,{method:"POST",body:{undo_id:o}}),importPreferences:(e,o)=>t.json(`/homes/${encodeURIComponent(e)}/settings/import-preferences`,{method:"POST",body:o}),create:e=>t.json("/homes",{method:"POST",body:e}),inspect:e=>t.json("/homes:inspect",{method:"POST",body:e}),attach:e=>t.json("/homes:attach",{method:"POST",body:e}),sshCopyCandidates:e=>t.json(`/homes/${encodeURIComponent(e)}/ssh-copy-candidates`),update:(e,o)=>t.json(`/homes/${encodeURIComponent(e)}`,{method:"PATCH",body:o}),remove:e=>t.json(`/homes/${encodeURIComponent(e)}`,{method:"DELETE"}),erase:(e,o)=>t.json(`/homes/${encodeURIComponent(e)}:delete`,{method:"POST",body:o})},config:{get:()=>t.json("/config"),patch:e=>t.json("/config",{method:"POST",body:e}),removeOverride:e=>t.json("/config/overrides:remove",{method:"POST",body:e}),previewModelGenerationMigration:()=>t.json("/config/model-generation-migration"),applyModelGenerationMigration:e=>t.json("/config/model-generation-migration/apply",{method:"POST",body:{revision:e,confirmed:!0}}),restoreModelGenerationMigration:(e,o)=>t.json("/config/model-generation-migration/restore",{method:"POST",body:{backup_key:e,revision:o,confirmed:!0}})},catalog:{list:e=>t.json("/catalog/providers",{signal:e?.signal,timeoutMs:e?.timeoutMs}),provider:e=>t.json(`/catalog/providers/${encodeURIComponent(e)}`),importProvider:(e,o)=>t.json("/providers:import_catalog",{method:"POST",body:e,signal:o?.signal,timeoutMs:o?.timeoutMs}),importRegistry:(e,o)=>t.json("/providers:import_registry",{method:"POST",body:e,signal:o?.signal,timeoutMs:o?.timeoutMs})},oauth:{usage:(e,o)=>t.json("/oauth/usage",{query:{provider:e},signal:o?.signal,timeoutMs:o?.timeoutMs})},providers:{probe:(e,o)=>t.json("/providers:probe",{method:"POST",body:e,signal:o?.signal,timeoutMs:o?.timeoutMs}),test:(e,o)=>t.json(`/providers/${encodeURIComponent(e)}:test`,{method:"POST",body:{},signal:o?.signal,timeoutMs:o?.timeoutMs}),health:()=>t.json("/providers:health")},nbSearch:{capabilities:()=>t.json("/nb-search/capabilities"),keyUsage:(e,o=!1,n)=>t.json("/nb-search/keys/usage",{method:"POST",body:{instance_id:e,refresh:o},signal:n?.signal,timeoutMs:n?.timeoutMs}),test:e=>t.json("/nb-search/test",{signal:e?.signal,timeoutMs:e?.timeoutMs}),readCredential:(e,o)=>t.json("/nb-search/credentials/read",{method:"POST",body:{instance_id:e,reveal:o}}),writeCredential:(e,o,n,i)=>t.json("/nb-search/credentials/write",{method:"POST",body:{instance_id:e,value:o,expected_version:n,expected_binding:i}})},requestIdentity:{get:()=>t.json("/request-identity"),preview:e=>t.json("/request-identity/preview",{method:"POST",body:e}),duplicateProfile:(e,o)=>t.json("/request-identity/profiles",{method:"POST",body:{from:e,label:o}}),updateProfile:(e,o)=>t.json(`/request-identity/profiles/${encodeURIComponent(e)}`,{method:"PUT",body:o}),deleteProfile:e=>t.json(`/request-identity/profiles/${encodeURIComponent(e)}`,{method:"DELETE"}),checkTrack:(e,o)=>t.json(`/request-identity/tracks/${e}/check`,{method:"POST",body:{source:o}}),applyTrack:(e,o)=>t.json(`/request-identity/tracks/${e}/apply`,{method:"POST",body:{version:o}}),trackAction:(e,o)=>t.json(`/request-identity/tracks/${e}/${o}`,{method:"POST",body:{}}),pinTrack:(e,o)=>t.json(`/request-identity/tracks/${e}/pin`,{method:"PUT",body:{pinned:o}}),setManifestUrl:e=>t.json("/request-identity/manifest",{method:"PUT",body:{url:e}})},notifications:{listCompletions:()=>t.json("/notifications/completions"),getSettings:()=>t.json("/notifications/settings"),updateSettings:e=>t.json("/notifications/settings",{method:"PUT",body:e}),listProviders:()=>t.json("/notifications/providers"),upsertInstance:(e,o,n)=>t.json(`/notifications/instances/${encodeURIComponent(e)}`,{method:"PUT",body:{instance:o,slots:n}}),deleteInstance:e=>t.json(`/notifications/instances/${encodeURIComponent(e)}`,{method:"DELETE"}),upsertChannel:(e,o)=>t.json(`/notifications/channels/${encodeURIComponent(e)}`,{method:"PUT",body:o}),deleteChannel:e=>t.json(`/notifications/channels/${encodeURIComponent(e)}`,{method:"DELETE"}),setCredential:(e,o)=>t.json(`/notifications/credentials/${encodeURIComponent(e)}`,{method:"PUT",body:{value:o}}),checkCredential:e=>t.json(`/notifications/instances/${encodeURIComponent(e)}:check`,{method:"POST",body:{}}),sendTest:e=>t.json(`/notifications/channels/${encodeURIComponent(e)}:test`,{method:"POST",body:{}}),listDeliveries:e=>t.json("/notifications/deliveries",{query:e===void 0?void 0:{channel_id:e}})},imSessions:{snapshot:()=>t.json("/im/sessions"),catalog:()=>t.json("/im/sessions/catalog"),setupCatalog:()=>t.json("/im/sessions/setup"),setup:e=>t.json("/im/sessions/setup",{method:"POST",body:e}),setPolicy:e=>t.json("/im/sessions/policy",{method:"PUT",body:e}),paste:(e,o)=>t.json("/im/sessions/paste",{method:"POST",body:{text:e,...o===void 0?{}:{instance_id:o}}}),check:e=>t.json(`/im/sessions/instances/${encodeURIComponent(e)}/check`,{method:"POST",body:{}}),listen:(e,o)=>t.json(`/im/sessions/instances/${encodeURIComponent(e)}/listen`,{method:"POST",body:{listening:o}}),confirm:(e,o)=>t.json(`/im/sessions/discoveries/${encodeURIComponent(e)}/confirm`,{method:"POST",body:o}),dismiss:e=>t.json(`/im/sessions/discoveries/${encodeURIComponent(e)}/dismiss`,{method:"POST",body:{}}),updateBinding:(e,o)=>t.json(`/im/sessions/bindings/${encodeURIComponent(e)}`,{method:"PATCH",body:o}),removeBinding:e=>t.json(`/im/sessions/bindings/${encodeURIComponent(e)}`,{method:"DELETE"}),testBinding:e=>t.json(`/im/sessions/bindings/${encodeURIComponent(e)}/test`,{method:"POST",body:{}}),channelViews:e=>t.json(`/im/sessions/targets/${encodeURIComponent(e)}/channels`),setNotificationChannel:(e,o,n)=>t.json(`/im/sessions/targets/${encodeURIComponent(e)}/notify/${encodeURIComponent(o)}`,{method:"PUT",body:{enabled:n}}),removeNotificationChannel:(e,o)=>t.json(`/im/sessions/targets/${encodeURIComponent(e)}/notify/${encodeURIComponent(o)}`,{method:"DELETE"}),setInternalChannel:(e,o)=>t.json(`/im/sessions/targets/${encodeURIComponent(e)}/internal`,{method:"PUT",body:{enabled:o}}),startWechatQr:()=>t.json("/im/sessions/wechat/qrcode",{method:"POST",body:{}}),pollWechatQr:(e,o)=>t.json(`/im/sessions/wechat/qrcode/${encodeURIComponent(e)}/poll`,{method:"POST",body:o===void 0?{}:{verify_code:o}}),cancelWechatQr:e=>t.json(`/im/sessions/wechat/qrcode/${encodeURIComponent(e)}/cancel`,{method:"POST",body:{}})},secrets:{reveal:e=>t.json("/secrets:reveal",{method:"POST",body:{ref:e}})},executors:{list:()=>t.json("/executors"),listInstallations:e=>t.json("/executors/installations",e),install:(e,o)=>t.json(`/executors/${encodeURIComponent(e)}/install`,{...o,method:"POST",body:{}}),rollback:(e,o)=>t.json(`/executors/${encodeURIComponent(e)}/rollback`,{...o,method:"POST",body:{}}),getModels:(e,o)=>t.json(`/executors/${encodeURIComponent(e)}/models`,o),refreshModels:(e,o)=>t.json(`/executors/${encodeURIComponent(e)}/models:refresh`,{...o,method:"POST",body:{}}),listLocalSessions:(e,o,n)=>t.json(`/executors/${encodeURIComponent(e)}/local-sessions`,{...n,query:o}),getLocalSession:(e,o,n)=>t.json(`/executors/${encodeURIComponent(e)}/local-sessions/${encodeURIComponent(o)}`,n),resumeLocalSession:(e,o,n,i)=>t.json(`/executors/${encodeURIComponent(e)}/local-sessions/${encodeURIComponent(o)}/resume`,{...i,method:"POST",body:n})},agents:{list:e=>t.json("/agents",{query:typeof e=="string"?{workspace_id:e}:e}),previewFile:(e,o)=>t.json("/agent-profiles/file-preview",{...o,method:"POST",body:e}),previewExecutorPrompt:(e,o={})=>t.json(`/agents/${encodeURIComponent(e)}/executor-prompt:preview`,{method:"POST",body:o}),previewModelMenu:(e,o,n)=>t.json(`/agents/${encodeURIComponent(e)}/model-menu:preview`,{...n,method:"POST",body:o}),create:e=>t.json("/agent-profiles",{method:"POST",body:e}),update:(e,o)=>t.json(`/agents/${encodeURIComponent(e)}`,{method:"PATCH",body:o}),shipped:{list:()=>t.json("/agents/shipped"),restore:e=>t.json(`/agents/shipped/${encodeURIComponent(e)}:restore`,{method:"POST",body:{}})}},filesystem:{openHtmlPreview:(e,o)=>t.json("/fs:html-preview",{...o,method:"POST",body:e}),closeHtmlPreview:async(e,o)=>{await t.json(`/fs:html-preview/${encodeURIComponent(e)}`,{...o,method:"DELETE"})},readHostFile:(e,o)=>t.raw("/fs:content",{method:"GET",query:{path:e},signal:o?.signal,timeoutMs:o?.timeoutMs},n=>n.text()),previewHostFile:(e,o,n)=>t.raw("/fs:content",{method:"GET",query:{path:e},headers:{range:`bytes=0-${o-1}`},signal:n?.signal,timeoutMs:n?.timeoutMs},async i=>({text:await i.text(),truncated:i.status===206&&Number(i.headers.get("content-range")?.split("/")[1])>o})),readHostFileBytes:(e,o)=>pe(t,"/fs:content",{query:{path:e},signal:o?.signal,timeoutMs:o?.timeoutMs,headers:le(o)}),readHostMediaPreview:(e,o)=>pe(t,"/fs:content",{query:{path:e,preview:"media"},signal:o?.signal,timeoutMs:o?.timeoutMs,headers:le(o)},xo),downloadHostFile:(e,o,n)=>t.raw("/fs:content",{method:"GET",expectBinary:!0,query:{path:e},signal:n?.signal,timeoutMs:n?.timeoutMs??0,headers:le(n)},i=>Lt(i,o,n?.signal)),workspaceFsSearch:(e,o,n)=>t.json("/workspace/fs:search",{method:"POST",body:{...o,workspace:e},signal:n?.signal,timeoutMs:n?.timeoutMs})},threads:{messages:(e,o)=>t.json("/threads/messages",{query:e,signal:o?.signal,timeoutMs:o?.timeoutMs})},search:{messages:(e,o)=>t.json("/search",{method:"POST",body:e,signal:o?.signal,timeoutMs:o?.timeoutMs}),retry:()=>t.json("/search/retry",{method:"POST"}),status:()=>t.json("/search/status",{method:"GET"})},cron:{get:(e,o={})=>t.json(`/cron/${encodeURIComponent(e)}`,{query:{session_id:o.session_id}}),create:e=>t.json("/cron",{method:"POST",body:e}),update:(e,o,n={})=>t.json(`/cron/${encodeURIComponent(e)}`,{method:"PATCH",body:o,query:{session_id:n.session_id}}),list:(e={})=>t.json("/cron",{query:{session_id:e.session_id,page_size:e.page_size,offset:e.offset}}),pause:(e,o={})=>t.json(`/cron/${encodeURIComponent(e)}:pause`,{method:"POST",body:{},query:{session_id:o.session_id}}),resume:(e,o={})=>t.json(`/cron/${encodeURIComponent(e)}:resume`,{method:"POST",body:{},query:{session_id:o.session_id}}),run:(e,o={})=>t.json(`/cron/${encodeURIComponent(e)}:run`,{method:"POST",body:{},query:{session_id:o.session_id}}),remove:(e,o={})=>t.json(`/cron/${encodeURIComponent(e)}`,{method:"DELETE",query:{session_id:o.session_id}})},runtime:{listTools:e=>t.json("/tools",{query:e===void 0?void 0:{session_id:e}}),listMcpServers:()=>t.json("/mcp/runtime/servers"),restartMcpServer:e=>t.json("/mcp/runtime/servers/"+encodeURIComponent(e)+":restart",{method:"POST",body:{}})},plugins:{navigation:()=>t.json("/plugins/navigation"),usage:e=>t.json("/plugins/usage",{query:e}),setUsage:e=>t.json("/plugins/usage",{method:"POST",body:e}),marketplace:()=>t.json("/plugins/marketplace"),preview:e=>t.json("/plugins:preview",{method:"POST",body:e,timeoutMs:0}),install:e=>t.json("/plugins",{method:"POST",body:typeof e=="string"?{source:e}:e,timeoutMs:0}),info:e=>t.json("/plugins/"+encodeURIComponent(e)),settings:e=>t.json(`/plugins/${encodeURIComponent(e)}/settings`),setSettings:(e,o)=>t.json(`/plugins/${encodeURIComponent(e)}/settings`,{method:"POST",body:o}),setEnabled:(e,o)=>t.json(`/plugins/${encodeURIComponent(e)}:${o?"enable":"disable"}`,{method:"POST",body:{}}),remove:(e,o)=>t.json(`/plugins/${encodeURIComponent(e)}:remove`,{method:"POST",body:o??{}}),rollback:e=>t.json(`/plugins/${encodeURIComponent(e)}:rollback`,{method:"POST",body:{}}),installPrerequisite:(e,o)=>t.json(`/plugins/${encodeURIComponent(e)}:install-prerequisite`,{method:"POST",body:o,timeoutMs:0}),panels:e=>t.json("/plugins/panels",{query:e}),panelDocument:(e,o,n)=>t.json(`/plugins/${encodeURIComponent(e)}/panels/${encodeURIComponent(o)}/document`,{query:n}),panelBridge:(e,o,n)=>t.json(`/plugins/${encodeURIComponent(e)}/panels/${encodeURIComponent(o)}/bridge`,{method:"POST",body:n}),commands:e=>t.json("/plugins/commands",{query:e}),recommend:e=>t.json("/plugins/recommendations/match",{method:"POST",body:e}),dismissRecommendation:e=>t.json(`/plugins/${encodeURIComponent(e)}:dismiss-recommendation`,{method:"POST",body:{}})},auth:{summary:()=>t.json("/auth")}}}function le(t){return{...t?.ifNoneMatch===void 0?{}:{"if-none-match":t.ifNoneMatch},...t?.range===void 0?{}:{range:t.range}}}function Zs(t){const e=t.headers.get("content-type")?.split(";",1)[0]?.trim()||"application/octet-stream";let n=/filename\*?=(?:UTF-8'')?"?([^";]+)"?/iu.exec(t.headers.get("content-disposition")??"")?.[1];if(n!==void 0)try{n=decodeURIComponent(n)}catch{}const i=t.headers.get("content-range")??void 0,a=i?.match(/\/(\d+)$/u)?.[1]??t.headers.get("content-length"),r=a==null?void 0:Number(a);return{mime:e,name:n,etag:t.headers.get("etag")??void 0,contentRange:i,totalBytes:r!==void 0&&Number.isSafeInteger(r)&&r>=0?r:void 0,notModified:t.status===304}}async function Lt(t,e,o,n=1/0){const i=Zs(t);let a=0;if(o?.throwIfAborted(),t.body===null)return{...i,bytes:a};const r=t.body.getReader(),u=()=>{r.cancel(o?.reason).catch(()=>{})};o?.addEventListener("abort",u,{once:!0});let m=!1;try{for(;;){o?.throwIfAborted();const p=await r.read();if(o?.throwIfAborted(),p.done){m=!0;break}for(let S=0;S<p.value.byteLength;S+=64*1024){o?.throwIfAborted();const f=p.value.subarray(S,Math.min(p.value.byteLength,S+64*1024));if(a+=f.byteLength,a>n)throw new Error("Media preview exceeds its byte budget");await e(f,{...i,bytes:a})}}return{...i,bytes:a}}finally{o?.removeEventListener("abort",u),m||await r.cancel().catch(()=>{}),r.releaseLock()}}async function pe(t,e,o,n){return t.raw(e,{...o,method:"GET",expectBinary:!0},async i=>{if(n===void 0)return{...Zs(i),bytes:new Uint8Array(await i.arrayBuffer())};const a=[],r=await Lt(i,p=>{a.push(p)},o?.signal,n),u=new Uint8Array(r.bytes);let m=0;for(const p of a)u.set(p,m),m+=p.byteLength;return{...r,bytes:u}})}function ei(t){let e=t.length;for(;e>0&&t[e-1]===void 0;)e-=1;return e===t.length?[...t]:t.slice(0,e)}function qt(t){return t.agentId!==void 0?"agent":t.sessionId!==void 0?"session":t.workspaceId!==void 0?"workspace":"core"}function zh(t,e,o){return{scope:qt(t),service:e,method:o,workspaceId:t.workspaceId,sessionId:t.sessionId,agentId:t.agentId}}function Kh(t){return JSON.stringify(t)}function Qh(t){try{const e=JSON.parse(t);if(e===null||typeof e!="object"||Array.isArray(e))return;const o=e;return typeof o.type!="string"?void 0:o}catch{return}}const Yh=3e4,Xh=500,Jh="kimi-code.bearer.",ti="transport.timeout";class Zh{endpoint;token;fetchImpl;defaultTimeoutMs;readingTimeoutMs;socket;activeCalls=new Set;rest;closed=!1;terminal={listTerminals:async e=>Va.parse(await this.viewRequest(this.terminalPath(e),{})),createTerminal:async(e,o={})=>Eo.parse(await this.viewRequest(this.terminalPath(e),{},{method:"POST",body:Ba.parse(o),okCodes:[0]})),getTerminal:async(e,o)=>Eo.parse(await this.viewRequest(this.terminalPath(e,o),{})),closeTerminal:async(e,o)=>Fa.parse(await this.viewRequest(`${this.terminalPath(e,o)}:close`,{},{method:"POST",body:{},okCodes:[0]})),terminalAttach:(e,o)=>this.socket.terminals.terminalAttach(e,o),terminalDetach:(e,o)=>this.socket.terminals.terminalDetach(e,o),terminalInput:(e,o,n)=>this.socket.terminals.terminalInput(e,o,n),terminalResize:(e,o,n,i)=>this.socket.terminals.terminalResize(e,o,n,i),onTerminalSignal:e=>this.socket.terminals.onTerminalSignal(e),onStatus:e=>this.socket.terminals.onStatus(e),nudge:()=>this.socket.terminals.nudge()};terminalPath(e,o){return`/api/sessions/${encodeURIComponent(e)}/terminals${o===void 0?"":`/${encodeURIComponent(o)}`}`}sessionView={snapshot:(e,o)=>this.viewRequest(`/api/klient/session-view/${encodeURIComponent(e)}/snapshot`,{},{signal:o?.signal,timeoutMs:o?.timeoutMs}),transcriptPage:(e,o,n)=>this.transcriptRequest("page",`/api/klient/session-view/${encodeURIComponent(e)}/transcript`,{agent_id:o.agentId,before_turn:o.beforeTurn,before_item:o.beforeItem,after_turn:o.afterTurn,after_item:o.afterItem,page_size:o.pageSize},n),transcriptCatchUp:(e,o,n)=>this.transcriptRequest("catchUp",`/api/klient/session-view/${encodeURIComponent(e)}/transcript/catch-up`,{agent_id:o.agentId,epoch:o.since.epoch,since_seq:o.since.seq,grade:o.grade??"delta"},n),transcriptDetail:(e,o,n)=>this.viewRequest(`/api/sessions/${encodeURIComponent(e)}/transcript/detail`,{agent_id:o.agentId,kind:o.kind,id:o.id},{signal:n?.signal,timeoutMs:n?.timeoutMs}),transcriptEntities:(e,o,n)=>this.viewRequest(`/api/sessions/${encodeURIComponent(e)}/transcript/details`,{agent_id:o.agentId,kind:o.kind,cursor:o.cursor,limit:o.limit},{signal:n?.signal,timeoutMs:n?.timeoutMs}),transcriptContent:(e,o,n)=>this.viewRequest(`/api/klient/session-view/${encodeURIComponent(e)}/transcript/content`,{},{method:"POST",body:o,signal:n?.signal,timeoutMs:n?.timeoutMs}),subscribe:(e,o,n)=>{if(this.closed)throw new Error("http closed");return this.socket.sessionViews.subscribe(e,o,n)}};sessionCommands={execute:async(e,o,n)=>{const i=us[o],a=n,r=i.suffix.replace("{target}",encodeURIComponent(a.target??"")),u=await this.viewRequest(`/api/sessions/${encodeURIComponent(e)}${r}`,{agent_id:a.query?.agent_id,receipt:o==="submit"?"true":void 0},{method:i.method,body:i.method==="GET"?void 0:a.body??{},okCodes:i.okCodes,timeoutMs:"timeoutMs"in i?i.timeoutMs:void 0});if(o==="submit"&&u!==null&&typeof u=="object"&&!("content"in u)){const{resolved_media:m,resolved_parts:p,...S}=Wa.parse(u),f=a.body.content,y=new Map,I=p??m?.map(({index:C,content:P})=>({index:C,content:[P]}))??[];for(const C of I){if(C.index>=f.length||f[C.index]?.type==="text"||y.has(C.index))throw new j(50001,"Invalid prompt receipt media projection");y.set(C.index,C.content)}const w=f.flatMap((C,P)=>y.get(P)??[C]);return{...S,content:w}}return u}};viewRequest(e,o,n){return this.requestJson(e,{...n,query:o})}async transcriptRequest(e,o,n,i){const a=await this.viewRequest(o,{...n,transcript_coverage_version:wn},{signal:i?.signal,timeoutMs:i?.timeoutMs});return Tn(a)?a:e==="page"?Ih(a):Th(a)}requestJson(e,o={}){const i=/\/klient\/session-view\//.test(e)||/\/transcript(?:\/(?:detail|details|ops))?$/.test(e)?{...o,timeoutMs:o.timeoutMs??this.readingTimeoutMs()}:o;return this.performFetch(e,i,async(a,r)=>{if(a.status===404&&o.allowMissingRoute===!0){await a.body?.cancel();return}const u=/\/klient\/session-view\//.test(e)||/\/transcript(?:\/(?:detail|details|ops))?$/.test(e),m=await this.readEnvelope(a,o.signal,u?Xs:4*1024*1024);r(m.request_id);const p=o.okCodes??[0];if(a.ok===!1||!p.includes(m.code))throw new j(p.includes(m.code)?a.status:m.code,m.msg,m.details,m.reason,m.request_id,m.data);return m.data})}requestRaw(e,o,n){const i=o??{};return this.performFetch(e,i,async(a,r)=>{const u=a.headers.get("content-type")??"";if((a.ok||a.status===304&&i.headers?.["if-none-match"]!==void 0)&&!(i.jsonErrorOnSuccess===!0&&u.includes("json")))return n(a);const m=await this.readEnvelope(a,i.signal);r(m.request_id);const p=i.okCodes??[0];throw new j(p.includes(m.code)?a.status:m.code,m.msg,m.details,m.reason,m.request_id,m.data)})}async performFetch(e,o,n){if(this.closed)throw new Error("http closed");const i=o.rawBody??(o.body===void 0?void 0:JSON.stringify(o.body)),a=typeof i=="string"?new TextEncoder().encode(i).byteLength:i instanceof Uint8Array?i.byteLength:void 0;if(a!==void 0&&a>Ph)throw new j(40001,"request body exceeds the allowed size limit");const r=new AbortController,u={controller:r};this.activeCalls.add(u);const m=o.timeoutMs??this.defaultTimeoutMs,p=performance.now();let S="headers",f;const y=m===0?void 0:setTimeout(()=>{r.signal.aborted||(f=S,r.abort())},m),I=o.signal,w=()=>{r.abort(I?.reason)};I?.aborted===!0?w():I?.addEventListener("abort",w,{once:!0});try{const P=(o.baseUrl??this.endpoint).replace(/\/+$/u,""),D=e.startsWith("/api/")?e:`/api${e}`,$=globalThis.location?.origin,H=P===""?new URL(D,$??"http://localhost"):new URL(`${P}${D}`);for(const[M,xe]of Object.entries(o.query??{}))if(Array.isArray(xe))for(const ui of xe)H.searchParams.append(M,ui);else xe!==void 0&&H.searchParams.set(M,String(xe));const ue=new Headers({accept:o.expectBinary===!0?"application/octet-stream":"application/json",...o.headers}),ut=ue.get("x-request-id");let lt=ut!==null&&Oo(ut)?ut:dc();ue.set("x-request-id",lt),this.token!==void 0&&o.skipAuth!==!0&&ue.set("authorization",`Bearer ${this.token}`),o.body!==void 0&&!ue.has("content-type")&&ue.set("content-type","application/json");const mo=M=>{typeof M=="string"&&Oo(M)&&(lt=M)},Me=()=>this.transportTimeoutError({method:o.method??"GET",path:H.pathname,phase:f??S,timeoutMs:m,elapsedMs:Math.round(performance.now()-p),request_id:lt});let pt;try{const M=e==="/api/klient/call"?H.toString():H;pt=await this.fetchImpl(M,{method:o.method??"GET",body:i,headers:Object.fromEntries(ue),signal:r.signal,redirect:"error"})}catch(M){throw f!==void 0?Me():this.closed&&r.signal.aborted?new Error("http closed",{cause:M}):M instanceof j?M:new j(-1,M instanceof Error?M.message:"Connection failed",void 0,"transport.network",void 0,void 0,"transport")}if(mo(pt.headers.get("x-request-id")),S="body",f!==void 0)throw Me();try{const M=await n(pt,mo);if(f!==void 0)throw Me();return M}catch(M){throw f!==void 0?Me():this.closed&&r.signal.aborted?new Error("http closed",{cause:M}):M instanceof TypeError&&!r.signal.aborted?new j(-1,M.message,void 0,"transport.network",void 0,void 0,"transport"):M}}finally{y!==void 0&&clearTimeout(y),I?.removeEventListener("abort",w),this.activeCalls.delete(u)}}transportTimeoutError(e){return new j(50001,`call timed out after ${e.timeoutMs}ms`,e,ti,e.request_id,void 0,"transport")}async readEnvelope(e,o,n=4*1024*1024){let i;try{i=await xh(e,n)}catch(a){throw og(a)||o?.aborted===!0||!(a instanceof SyntaxError)?a:new j(e.status,`HTTP ${e.status} — non-JSON response`)}if(i===null||typeof i.code!="number"||typeof i.msg!="string")throw new j(e.status,`HTTP ${e.status} — non-JSON response`);return i}constructor(e){const o=e.endpoint.replace(/\/$/u,"");this.endpoint=o,this.token=e.token;const n=e.fetch??globalThis.fetch;if(n===void 0)throw new Error("no fetch implementation available; pass fetch");this.fetchImpl=e.fetch??n.bind(globalThis),this.defaultTimeoutMs=e.timeoutMs??Yh,this.readingTimeoutMs=e.readingTimeoutMs??(()=>0),this.socket=new eg({endpoint:o,eventsUrl:e.eventsUrl,token:e.token,WebSocket:e.WebSocket,onDiagnostic:e.onSocketDiagnostic}),this.rest=Hh({json:(i,a)=>this.requestJson(i,a),raw:(i,a,r)=>this.requestRaw(i,a,r)})}call(e,o,n,i,a){return this.requestJson("/api/klient/call",{method:"POST",body:{procedure:zh(e,o,n),params:ei(i)},timeoutMs:a?.timeoutMs,signal:a?.signal})}stream(e,o,n,i){return this.closed?ng(new Error("http closed")):this.socket.stream(e,o,n,i)}listen(e,o,n,i,a){if(this.closed)throw new Error("http closed");return this.socket.listen(e,o,n,i,a)}close(){if(this.closed)return Promise.resolve();this.closed=!0;for(const e of this.activeCalls)e.controller.abort();return this.activeCalls.clear(),this.socket.close(),Promise.resolve()}}class eg{wsUrl;token;WebSocketCtor;listens=new Map;streams=new Map;ws;state="idle";closed=!1;reconnectAttempt=0;fatalRetriesLeft;reconnectTimer;establishmentTimer;lastInboundAt=0;openedAt=0;heartbeatMs;seq=0;onDiagnostic;terminals=new Rh({nextId:()=>this.nextId(),connect:()=>{this.requireWebSocket(),this.ensureConnected()},isOpen:()=>this.state==="open",send:e=>this.send(e),nudge:()=>this.nudge()});idPrefix=`h${Date.now().toString(36)}`;sessionViews=new Ch({nextId:()=>this.nextId(),connect:()=>{this.requireWebSocket(),this.ensureConnected()},isOpen:()=>this.state==="open",send:e=>{this.send(e)},restart:()=>{this.restart("view_restart")},nudge:()=>{this.nudge()}});restart(e="view_restart"){if(this.closed)return;this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;const o=this.ws;this.ws=void 0,this.state="idle",o!==void 0&&this.reportClose(e),o?.close(4e3,"session view restart");const n=new Error("http event socket restarted");for(const i of this.streams.values())i.error(n);this.streams.clear(),this.notifyDisconnect(n),this.sessionViews.connecting(),this.ensureConnected()}nudge(){if(!this.closed){if(this.state==="open"){this.heartbeatMs!==void 0&&Date.now()-this.lastInboundAt>Math.max(45e3,this.heartbeatMs*3)&&this.restart("stale_heartbeat");return}this.ws===void 0&&(this.fatalRetriesLeft=void 0,this.reconnectAttempt=0,this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.state="idle",this.ensureConnected())}}constructor(e){this.wsUrl=e.eventsUrl??tg(e.endpoint),this.token=e.token,this.WebSocketCtor=e.WebSocket??globalThis.WebSocket,this.onDiagnostic=e.onDiagnostic}diagnose(e){if(this.onDiagnostic!==void 0)try{this.onDiagnostic(e)}catch{}}reportClose(e,o){const n=Date.now();this.diagnose({kind:"close",cause:e,code:o?.code,reason:o?.reason===""?void 0:o?.reason,wasClean:o?.wasClean,openForMs:this.openedAt>0?n-this.openedAt:void 0,sinceInboundMs:this.lastInboundAt>0?n-this.lastInboundAt:void 0,heartbeatMs:this.heartbeatMs}),this.openedAt=0}listen(e,o,n,i,a){this.requireWebSocket();const r=this.nextId(),u={type:"subscribe",id:r,scope:qt(e),workspaceId:e.workspaceId,sessionId:e.sessionId,agentId:e.agentId},m=o.kind==="stream"?{...u,event:o.name}:{...u,service:o.service,event:o.event};return this.listens.set(r,{frame:m,handler:n,onError:i,onReady:a}),this.ensureConnected(),this.state==="open"&&this.send(m),{dispose:()=>{this.listens.delete(r)&&this.state==="open"&&this.send({type:"unsubscribe",id:r})}}}stream(e,o,n,i){return{[Symbol.asyncIterator]:()=>{const a=[],r=[];let u=!1,m;const p={frame:{type:"stream",scope:qt(e),service:o,method:n,arg:ei(i),workspaceId:e.workspaceId,sessionId:e.sessionId,agentId:e.agentId},sent:!1,push(y){if(u)return;const I={done:!1,value:y},w=r.shift();w===void 0?a.push(I):w.resolve(I)},end:()=>{if(u)return;u=!0,m!==void 0&&this.streams.delete(m);const y={done:!0,value:void 0},I=r.shift();I===void 0?a.push(y):I.resolve(y);for(const w of r)w.resolve({done:!0,value:void 0});r.length=0},error:y=>{if(u)return;u=!0,m!==void 0&&this.streams.delete(m);const I=r.shift();I===void 0?a.push(y):I.reject(y);for(const w of r)w.reject(y);r.length=0}};let S=!1;const f=()=>{if(!S){S=!0;try{this.requireWebSocket()}catch(y){p.error(y instanceof Error?y:new Error(String(y)));return}m=this.nextId(),p.frame={...p.frame,id:m},this.streams.set(m,p),this.ensureConnected(),this.state==="open"&&this.sendStream(p)}};return{next:()=>{f();const y=a.shift();return y instanceof Error?Promise.reject(y):y!==void 0?Promise.resolve(y):u?Promise.resolve({done:!0,value:void 0}):new Promise((I,w)=>{r.push({resolve:I,reject:w})})},return:()=>{if(!u){if(u=!0,m!==void 0){const y=this.streams.get(m);this.streams.delete(m),y?.sent===!0&&this.state==="open"&&this.send({type:"stream_cancel",id:m})}for(const y of r)y.resolve({done:!0,value:void 0});r.length=0}return Promise.resolve({done:!0,value:void 0})}}}}}close(){if(this.closed)return;this.closed=!0,this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.state="closed",this.ws?.close(1e3,"klient closed"),this.ws=void 0;const e=new Error("http event socket closed");this.notifyDisconnect(e);for(const o of this.streams.values())o.error(e);this.streams.clear(),this.listens.clear(),this.sessionViews.close(),this.terminals.close()}requireWebSocket(){const e=this.WebSocketCtor;if(e===void 0)throw new Error("no WebSocket implementation available; pass WebSocket");return e}ensureConnected(){!this.hasDemand()||this.closed||this.state==="open"||this.state==="connecting"||this.connect()}connect(){const e=this.requireWebSocket();this.state="connecting";const o=this.token!==void 0&&this.token.length>0?[`${Jh}${this.token}`]:void 0;let n;try{n=new e(this.wsUrl,o)}catch(i){this.notifyDisconnect(i instanceof Error?i:new Error(String(i))),this.scheduleReconnect();return}this.ws=n,this.heartbeatMs=void 0,this.lastInboundAt=0,this.openedAt=0,clearTimeout(this.establishmentTimer),this.establishmentTimer=setTimeout(()=>{this.ws!==n||this.closed||(this.ws=void 0,this.reportClose("establish_timeout"),n.close(4e3,"WebSocket establishment timed out"),this.onClose())},12e3),n.addEventListener("open",()=>{if(!(this.ws!==n||this.closed)){clearTimeout(this.establishmentTimer),this.diagnose({kind:"open",attempt:this.reconnectAttempt}),this.openedAt=Date.now(),this.reconnectAttempt=0,this.state="open";for(const i of this.listens.values())this.send(i.frame);for(const i of this.streams.values())this.sendStream(i);this.sessionViews.opened(),this.terminals.opened()}}),n.addEventListener("message",i=>{this.ws!==n||typeof i.data!="string"||(this.lastInboundAt=Date.now(),this.onFrame(Qh(i.data)))}),n.addEventListener("close",i=>{this.ws===n&&(this.ws=void 0,this.closed||this.reportClose("server",i),[4001,1008].includes(i.code)&&(this.fatalRetriesLeft=0),this.onClose())}),n.addEventListener("error",()=>{})}onFrame(e){if(e===void 0)return;if(e.type==="error"&&e.data?.fatal===!0){this.fatalRetriesLeft??=4;const n=this.ws;this.ws=void 0,this.state="closed",this.reportClose("fatal_frame",{reason:e.msg}),n?.close(4e3,"fatal protocol error"),this.onClose();return}if(e.type!=="error"&&(this.fatalRetriesLeft=void 0),this.sessionViews.receive(e)||this.terminals.receive(e))return;if(e.type==="ping"){const n=e.data;typeof n?.heartbeatMs=="number"&&n.heartbeatMs>0&&(this.heartbeatMs=n.heartbeatMs),this.send({type:"pong",data:{nonce:n?.nonce}});return}const o=typeof e.id=="string"?e.id:"";switch(e.type){case"subscribed":this.listens.get(o)?.onReady?.();return;case"event":this.listens.get(o)?.handler(e.data);return;case"error":{const n=this.listens.get(o);if(n===void 0)return;this.listens.delete(o),n.onError?.(dn(e));return}case"stream_data":this.streams.get(o)?.push(e.data);return;case"stream_end":this.streams.get(o)?.end();return;case"stream_error":this.streams.get(o)?.error(dn(e));return;default:return}}onClose(){if(this.closed)return;const e=new Error("http event socket disconnected");for(const o of this.streams.values())o.error(e);if(this.streams.clear(),this.notifyDisconnect(e),!this.hasDemand()){this.state="idle";return}this.scheduleReconnect()}notifyDisconnect(e){clearTimeout(this.establishmentTimer);for(const o of this.listens.values())o.onError?.(e);this.sessionViews.disconnected(e),this.terminals.disconnected(e)}hasDemand(){return this.listens.size>0||this.streams.size>0||this.sessionViews.hasDemand||this.terminals.hasDemand}scheduleReconnect(){if(this.closed||!this.hasDemand()){this.state=this.closed?"closed":"idle";return}if(this.fatalRetriesLeft!==void 0){if(this.fatalRetriesLeft<=0){this.state="closed";return}this.fatalRetriesLeft-=1}this.reconnectAttempt+=1,this.state="connecting",this.sessionViews.connecting(),this.terminals.connecting();const e=Math.min(Xh*2**(this.reconnectAttempt-1),1e4);this.diagnose({kind:"retry",attempt:this.reconnectAttempt,delayMs:e}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.state="idle",this.ensureConnected()},e)}sendStream(e){e.sent||(e.sent=!0,this.send(e.frame))}send(e){const o=this.ws;if(!(o===void 0||this.WebSocketCtor===void 0)&&o.readyState===this.WebSocketCtor.OPEN)try{o.send(Kh(e))}catch{}}nextId(){return this.seq+=1,`${this.idPrefix}_${this.seq}`}}function dn(t){return new j(typeof t.code=="number"?t.code:50001,t.msg??"error",t.details,t.reason)}function tg(t){const e=t===""?globalThis.location?.origin??"http://localhost":t,o=new URL(e);if(o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),o.protocol!=="ws:"&&o.protocol!=="wss:")throw new Error(`unsupported URL scheme for http transport: ${t}`);return o.pathname=`${o.pathname.replace(/\/$/u,"")}/api/klient/events`,o.search="",o.hash="",o.toString()}function og(t){return typeof t=="object"&&t!==null&&"name"in t&&t.name==="AbortError"}function ng(t){return{[Symbol.asyncIterator](){return{async next(){throw t}}}}}function sg(t){return bh(new Zh(t),t)}class N extends Error{code;requestId;data;details;source;reason;constructor(e){super(`${e.msg} (code ${e.code})`),this.name="ApiError",this.code=e.code,this.data=e.data,this.details=e.details,this.requestId=e.request_id,this.source=e.source??"server",this.reason=e.reason}}const V={INVALID_RESPONSE:-3,TIMEOUT:-2,REQUEST_INVALID:40001,UNAUTHORIZED:40101,SESSION_NOT_FOUND:40401,PROMPT_NOT_FOUND:40402,QUESTION_NOT_FOUND:40405,SKILL_NOT_FOUND:40415,SESSION_BUSY:40901,APPROVAL_ALREADY_RESOLVED:40902,COMPACTION_UNABLE:40910,SESSION_UNDO_UNAVAILABLE:40911,SKILL_NOT_ACTIVATABLE:40912,APPROVAL_EXPIRED:41001,QUESTION_EXPIRED:41002,TERMINAL_NOT_FOUND:40414,MESSAGE_ACTION_UNAVAILABLE:40936,SESSION_CURSOR_MISMATCH:40937,SESSION_INDEX_BUILDING:40939};function ig(t){return t instanceof N&&t.source==="transport"}const rg=/\s*\(code -?\d+\)$/;function ag(t){const e=t.replace(rg,"").trim();return!!(e==="session.not_found"||/^session not found$/i.test(e)||/^(?:temporary )?session \S+ does not exist$/i.test(e))}const cg={"*":"off",main:"delta"};function Lg(t){return t===void 0||t==="main"?cg:{"*":"off",main:"off",[t]:"delta"}}function dg(t){const e=async i=>{try{return await i()}catch(a){throw a instanceof j?new N({code:a.code,msg:a.message,data:a.data,details:a.details,request_id:a.requestId,source:a.source,reason:a.reason}):a}},o=i=>t.session(i).commands,n=(i,a)=>e(async()=>{if(!await t.session(i).resume())throw new j(40401,`session ${i} does not exist`);return a()});return{getSession:i=>e(()=>o(i).read()),submitPrompt:(i,a)=>e(()=>o(i).submit(a)),editMessage:(i,a,r)=>n(i,()=>o(i).edit(a,In.parse(r))),regenerateMessage:(i,a,r)=>n(i,()=>o(i).regenerate(a,_n.parse(r))),forkSession:(i,a)=>e(()=>o(i).fork(bn.parse(a))),abortPrompt:(i,a,r)=>e(()=>o(i).abort(a,r)),abortTurn:(i,a)=>e(()=>o(i).abortTurn(a)),movePrompt:(i,a,r)=>e(()=>o(i).move(a,r)),replacePrompt:(i,a,r)=>e(()=>o(i).replace(a,r)),timingPrompt:(i,a,r)=>e(()=>o(i).timing(a,r)),holdPrompt:(i,a,r)=>e(()=>o(i).hold(a,r)),steerPrompt:(i,a,r)=>n(i,()=>o(i).steer(a,r)),resolveApproval:(i,a,r)=>n(i,()=>o(i).approve(a,r)),resolveQuestion:(i,a,r)=>n(i,()=>o(i).answer(a,r)),dismissQuestion:(i,a)=>n(i,()=>o(i).dismiss(a)),cancelTask:(i,a,r)=>n(i,()=>o(i).cancelTask(a,r))}}const un=/^\/api\/sessions\/[^/]+\/document-preview\/assets\/[A-Za-z0-9_-]{16,128}$/;function ug(t){const e=t.trim();if(un.test(e))return e;const o=(()=>{try{return new URL(e,"http://example.test")}catch{return}})();if(o===void 0)throw new Error("Preview asset URL is not a readable document-preview asset path.");const n=o.pathname;if(o.origin!=="http://example.test"||!un.test(n))throw new Error("Preview asset URL does not belong to this connection.");return n}const x="main",he={roster:1,live:2,task:3};function $t(t,e){if(t===e)return 0;if(t===x)return-1;if(e===x)return 1;const o=/^agent-(\d+)$/.exec(t),n=/^agent-(\d+)$/.exec(e);return o&&n?Number(o[1])-Number(n[1]):o?-1:n?1:t<e?-1:1}function lg(t,e){if(t.agentId===x||e.agentId===x)return $t(t.agentId,e.agentId);const o=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),n=e.startedAt===void 0?Number.NaN:Date.parse(e.startedAt),i=Number.isFinite(o),a=Number.isFinite(n);return i&&a&&o!==n?n-o:i!==a?i?-1:1:$t(t.agentId,e.agentId)}function lo(){return Object.create(null)}function pg(){return{roots:Object.freeze([]),byId:Object.freeze(lo())}}function Ct(t,e){return t===e||t!==void 0&&e!==void 0&&t.inputOther===e.inputOther&&t.output===e.output&&t.inputCacheRead===e.inputCacheRead&&t.inputCacheCreation===e.inputCacheCreation}function mg(t,e){if(t===e)return!0;if(t===void 0||e===void 0||!Ct(t.currentTurn,e.currentTurn)||!Ct(t.total,e.total))return!1;const o=Object.keys(t.byModel??{}),n=Object.keys(e.byModel??{});return o.length===n.length&&o.every(i=>Ct(t.byModel?.[i],e.byModel?.[i]))}function hg(t,e){return t===e?!0:t.agentId===e.agentId&&t.createdAt===e.createdAt&&t.parentAgentId===e.parentAgentId&&t.parentToolCallId===e.parentToolCallId&&t.name===e.name&&t.label===e.label&&t.nameSource===e.nameSource&&t.statusSource===e.statusSource&&t.model===e.model&&t.thinkingEffort===e.thinkingEffort&&t.thinkingEffortExplicit===e.thinkingEffortExplicit&&t.executorId===e.executorId&&t.executorProtocol===e.executorProtocol&&t.contextTokens===e.contextTokens&&t.maxContextTokens===e.maxContextTokens&&mg(t.usage,e.usage)&&t.status===e.status&&t.refreshing===e.refreshing&&t.refreshingUntil===e.refreshingUntil&&t.busy===e.busy&&t.toolCallCount===e.toolCallCount&&t.toolCallCountKnown===e.toolCallCountKnown&&t.startedAt===e.startedAt&&t.endedAt===e.endedAt&&t.description===e.description&&t.summary===e.summary&&t.error===e.error&&t.turnOutcome?.turnId===e.turnOutcome?.turnId&&t.turnOutcome?.state===e.turnOutcome?.state&&t.turnOutcome?.error===e.turnOutcome?.error&&t.turnOutcome?.endedAt===e.turnOutcome?.endedAt&&t.turnOutcome?.lastRetry?.failedAttempt===e.turnOutcome?.lastRetry?.failedAttempt&&t.turnOutcome?.lastRetry?.maxAttempts===e.turnOutcome?.lastRetry?.maxAttempts&&t.turnOutcome?.lastRetry?.errorName===e.turnOutcome?.lastRetry?.errorName&&t.turnOutcome?.lastRetry?.errorMessage===e.turnOutcome?.lastRetry?.errorMessage&&t.childIds.length===e.childIds.length&&t.childIds.every((o,n)=>o===e.childIds[n])}function qg(t,e){if(t===void 0||t===e)return e;const o=lo(),n=new Set,i=S=>{const f=o[S];if(f!==void 0)return f;const y=e.byId[S];if(y===void 0)return;if(n.has(S))return o[S]=y,y;n.add(S);const I=t.byId[S];let w=I!==void 0;for(const P of y.childIds){const D=i(P);(D===void 0||D!==t.byId[P])&&(w=!1)}n.delete(S);const C=I!==void 0&&w&&hg(I,y)?I:y;return o[S]=C,C};for(const S of e.roots)i(S.agentId);for(const S of Object.keys(e.byId))i(S);const a=e.roots.map(S=>o[S.agentId]),r=Object.keys(t.byId),u=Object.keys(e.byId),m=r.length===u.length&&u.every(S=>o[S]===t.byId[S]),p=a.length===t.roots.length&&a.every((S,f)=>S===t.roots[f]);return m&&p?t:{roots:p?t.roots:a,byId:o}}function $g(t,e,o){const n=new Map;for(const p of bg(o??[])){const S=si(p),f=Ve(n,S);gg(f,p)}for(const p of e??[]){if(!re(p.agentId))continue;const S=Ve(n,p.agentId);vg(S,p)}for(const p of t){if(!re(p.subagentId))continue;const S=Ve(n,p.subagentId);Sg(S,p)}if(n.size===0)return pg();for(const p of n.values())(p.rosterParentAgentId??p.parentAgentId)===x&&!n.has(x)&&Ve(n,x);const i=new Map;for(const p of n.values())i.set(p.agentId,fg(p,n));yg(i);const a=new Map;for(const p of n.keys())a.set(p,[]);const r=[];for(const[p,S]of i){if(S===void 0){r.push(p);continue}a.get(S).push(p)}const u=(p,S)=>lg(n.get(p),n.get(S));for(const p of a.values())p.sort(u);if(r.sort(u),n.has(x)&&!i.get(x)){const p=n.get(x);if(p.status===void 0){const S=a.get(x)??[];p.status=S.some(f=>{const y=n.get(f);return y!==void 0&&te(y.status??"completed")})?"running":"completed"}}const m=lo();for(const p of n.values()){const S=i.get(p.agentId),f=re(p.name)?p.name:p.agentId,y=p.status??"unknown",I={agentId:p.agentId,createdAt:p.createdAt,parentAgentId:S,parentToolCallId:p.parentToolCallId,name:f,label:re(p.label)?p.label:f,model:p.model,thinkingEffort:p.thinkingEffort,thinkingEffortExplicit:p.thinkingEffortExplicit,executorId:p.executorId,executorProtocol:p.executorProtocol,contextTokens:p.contextTokens,maxContextTokens:p.maxContextTokens,usage:p.usage,status:y,refreshing:p.refreshing,refreshingUntil:p.refreshingUntil,busy:Tg(y,p.busy),toolCallCount:p.toolCallCount,toolCallCountKnown:p.toolCallCountKnown,startedAt:p.startedAt,endedAt:p.endedAt,description:p.description,summary:p.summary,error:p.error,childIds:a.get(p.agentId)??[]};m[p.agentId]=I}return{roots:r.map(p=>m[p]),byId:m}}function Gg(t,e){const o=t.byId[e];if(o===void 0)return[];const n=[],i=new Set;let a=o;for(;a!==void 0&&!i.has(a.agentId);){i.add(a.agentId),n.push(a);const r=a.parentAgentId;a=r===void 0?void 0:t.byId[r]}return n.reverse()}function Fg(t,e){const o=t.byId[e];return o===void 0?[]:o.childIds.flatMap(n=>{const i=t.byId[n];return i===void 0?[]:[i]})}function Ve(t,e){const o=t.get(e);if(o!==void 0)return o;const n={agentId:e,createdAt:void 0,parentAgentId:void 0,rosterParentAgentId:void 0,parentToolCallId:void 0,name:void 0,label:void 0,model:void 0,thinkingEffort:void 0,thinkingEffortExplicit:void 0,executorId:void 0,executorProtocol:void 0,contextTokens:void 0,maxContextTokens:void 0,usage:void 0,status:void 0,refreshing:void 0,refreshingUntil:void 0,statusAuthority:0,statusStartedAt:void 0,statusEndedAt:void 0,taskId:void 0,taskKind:void 0,disposedAt:void 0,busy:void 0,toolCallCount:0,toolCallCountKnown:!1,toolCallCountAuthoritative:!1,startedAt:void 0,endedAt:void 0,description:void 0,summary:void 0,error:void 0};return t.set(e,n),n}function oi(t,e,o,n){if(n===!0){t.toolCallCount=e??0,t.toolCallCountKnown=e!==void 0&&o!==!1,t.toolCallCountAuthoritative=!0;return}t.toolCallCountAuthoritative||e===void 0||(t.toolCallCount=Math.max(t.toolCallCount,e),o!==!1&&(t.toolCallCountKnown=!0))}function gg(t,e){const o=ge(e.status,e.detached===!0),n=T(e.startedAt,e.started_at),i=T(e.endedAt,e.completed_at);t.parentAgentId=t.parentAgentId??W(e.parentAgentId??e.parent_agent_id),t.parentToolCallId=t.parentToolCallId??W(e.parentToolCallId??e.parent_tool_call_id),t.name=t.name??T(e.name,e.description),t.description=T(e.description)??t.description,t.taskKind=e.kind??t.taskKind,(o===void 0?t.status===void 0&&t.disposedAt===void 0:po(t,o,he.task,n,i).accepted)&&(t.model=T(e.model)??t.model,t.thinkingEffort=T(e.thinkingEffort,e.thinking_effort)??t.thinkingEffort,t.thinkingEffortExplicit=e.thinkingEffortExplicit??e.thinking_effort_explicit??t.thinkingEffortExplicit,t.executorId=T(e.executorId,e.executor_id)??t.executorId,t.executorProtocol=T(e.executorProtocol,e.executor_protocol)??t.executorProtocol,t.startedAt??=n,t.endedAt??=i,t.summary=t.summary??T(e.summary,e.output_preview),t.error=t.error??T(e.error,e.stateReason,e.state_reason),o!==void 0&&o!=="unknown"&&(t.taskId=W(e.id)??t.taskId),e.detached===!0&&t.busy===void 0&&o==="background"&&(t.busy=!0))}function vg(t,e){t.createdAt??=T(e.createdAt);const o=W(e.parentAgentId);o!==void 0&&(t.rosterParentAgentId=o),t.parentAgentId=o??t.parentAgentId,t.parentToolCallId=T(e.parentToolCallId)??t.parentToolCallId,t.name=T(e.name,e.label)??t.name,t.label=T(e.label)??t.label,t.description=T(e.description)??t.description,oi(t,e.toolCallCount,e.toolCallCountKnown,e.toolCallCountAuthoritative);const n=q(e.disposedAt);n!==void 0&&(t.disposedAt===void 0||n>t.disposedAt)&&(t.disposedAt=n,ni(t,n,he.roster));const i=q(e.endedAt??e.startedAt),a=e.refreshing===!0&&e.disposedAt===void 0&&(q(e.refreshingUntil)??0)>Date.now()&&(i===void 0||(t.statusStartedAt===void 0||t.statusStartedAt<=i)&&(t.statusEndedAt===void 0||t.statusEndedAt<=i)),r=ge(e.status,e.detached===!0),u=e.statusSource===void 0?he.roster:4,m=e.statusSource==="metadata"&&r==="unknown",p=q(e.endedAt??e.startedAt),S=p!==void 0&&t.statusStartedAt!==void 0&&p<t.statusStartedAt,f=e.statusSource!==void 0&&!m&&!S&&(r==="idle"||r==="unknown"),y=f&&r==="idle"&&e.statusSource==="runtime"&&t.taskKind==="subagent",I=t.taskId!==void 0&&te(t.status??"unknown"),w=t.status==="completed"||t.status==="failed"||t.status==="cancelled",C=f&&(I||w)&&!y;f&&!C&&(t.status=r,t.statusAuthority=u,t.busy=!1);const P=!C&&(f||(r===void 0?t.status===void 0&&t.disposedAt===void 0:po(t,r,u,e.startedAt,e.endedAt).accepted));a&&(t.refreshing=!0,t.refreshingUntil=e.refreshingUntil),P&&(t.model=T(e.model)??t.model,t.thinkingEffort=T(e.thinkingEffort)??t.thinkingEffort,t.thinkingEffortExplicit=e.thinkingEffortExplicit??t.thinkingEffortExplicit,t.executorId=T(e.executorId)??t.executorId,t.executorProtocol=T(e.executorProtocol)??t.executorProtocol,t.contextTokens=e.contextTokens??t.contextTokens,t.maxContextTokens=e.maxContextTokens??t.maxContextTokens,t.usage=e.usage??t.usage,e.busy!==void 0&&(t.busy=e.busy),t.startedAt??=T(e.startedAt),t.endedAt??=T(e.endedAt),t.summary=T(e.summary)??t.summary,t.error=T(e.error)??t.error)}function ni(t,e,o){t.status===void 0||!te(t.status)||t.statusStartedAt!==void 0&&t.statusStartedAt>e||(t.status="unknown",t.statusAuthority=o,ii(t),t.busy=!1)}function Sg(t,e){if(t.createdAt??=T(e.createdAt),t.parentAgentId=t.parentAgentId??W(e.parentAgentId),t.parentToolCallId=T(e.parentToolCallId)??t.parentToolCallId,(e.name!==e.subagentId||t.name===void 0)&&(t.name=T(e.name)??t.name),t.label=T(e.label)??t.label,t.description=T(e.description)??t.description,oi(t,e.toolCallCount,e.toolCallCountKnown,e.toolCallCountAuthoritative),t.statusAuthority===4&&(t.status==="unknown"||t.status==="idle")&&te(ge(e.status)??"unknown"))return;const o=q(e.disposedAt);o!==void 0&&(t.disposedAt===void 0||o>t.disposedAt)&&(t.disposedAt=o,ni(t,o,he.live));const n=ge(e.status);(n===void 0?t.status===void 0&&t.disposedAt===void 0:po(t,n,he.live,e.startedAt,e.endedAt).accepted)&&(t.model=T(e.model)??t.model,t.thinkingEffort=T(e.thinkingEffort)??t.thinkingEffort,t.thinkingEffortExplicit=e.thinkingEffortExplicit??t.thinkingEffortExplicit,t.executorId=T(e.executorId)??t.executorId,t.executorProtocol=T(e.executorProtocol)??t.executorProtocol,t.contextTokens=e.contextTokens??t.contextTokens,t.maxContextTokens=e.maxContextTokens??t.maxContextTokens,t.usage=e.usage??t.usage,n!==void 0&&(t.busy=te(n)),t.startedAt??=T(e.startedAt),t.endedAt??=T(e.endedAt),t.summary=T(e.summary)??t.summary,t.error=T(e.error)??t.error)}function fg(t,e){const o=t.rosterParentAgentId??t.parentAgentId;if(!(o===void 0||o===t.agentId)&&e.has(o))return o}function yg(t){const e=new Set(t.keys());for(;e.size>0;){const o=e.values().next().value;if(o===void 0)break;const n=[],i=new Map;let a=o;for(;a!==void 0&&e.has(a);){const r=i.get(a);if(r!==void 0){const m=n.slice(r).reduce((p,S)=>$t(S,p)>0?S:p);t.set(m,void 0);break}i.set(a,n.length),n.push(a),a=t.get(a)}for(const r of n)e.delete(r)}}function si(t){return W(t.agentId)}function bg(t){const e=new Map;for(const o of t){const n=si(o);if(n===void 0)continue;const i=e.get(n);(i===void 0||_g(o,i))&&e.set(n,o)}return[...e.values()]}function _g(t,e){const o=q(T(t.startedAt,t.started_at)),n=q(T(e.startedAt,e.started_at)),i=q(T(t.endedAt,t.completed_at)),a=q(T(e.endedAt,e.completed_at)),r=W(t.id),u=W(e.id);if(r!==void 0&&u!==void 0&&r!==u){if(o!==void 0&&a!==void 0&&o>a)return!0;if(n!==void 0&&i!==void 0&&n>i)return!1}if(o!==n)return o===void 0?!1:n===void 0?!0:o>n;const p=ge(t.status,t.detached===!0),S=ge(e.status,e.detached===!0),f=p===void 0?-1:Pe(p),y=S===void 0?-1:Pe(S);return f!==y?f>y:i!==a?i===void 0?!1:a===void 0?!0:i>a:r!==u?r===void 0?!1:u===void 0?!0:r>u:ln(t)>ln(e)}function ln(t){return JSON.stringify([W(t.id)??"",t.kind??"",t.description??"",t.name??"",t.status??"",t.model??"",T(t.thinkingEffort,t.thinking_effort)??"",T(t.startedAt,t.started_at)??"",T(t.endedAt,t.completed_at)??"",T(t.summary,t.output_preview)??"",W(t.parentAgentId??t.parent_agent_id)??"",W(t.parentToolCallId??t.parent_tool_call_id)??"",t.detached===!0])}function q(t){if(t===void 0)return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0}function ge(t,e=!1){if(!re(t))return e?"background":void 0;switch(t){case"unknown":case"idle":case"lost":return t;case"running":case"queued":case"working":case"in_progress":return e?"background":"running";case"suspended":return"suspended";case"completed":return"completed";case"failed":case"timed_out":return"failed";case"cancelled":case"killed":return"cancelled";case"background":return"background";default:return e?"background":void 0}}function Pe(t){return t==="unknown"?0:t==="completed"||t==="failed"||t==="cancelled"||t==="lost"?2:1}function pn(t){return t==="suspended"?2:te(t)?1:0}function Ig(t,e,o){if(Pe(e)===2||t.disposedAt===void 0)return!1;const n=q(o);return n===void 0||n<=t.disposedAt}function ii(t){t.model=void 0,t.thinkingEffort=void 0,t.contextTokens=void 0,t.maxContextTokens=void 0,t.usage=void 0,t.busy=void 0,t.refreshing=void 0,t.refreshingUntil=void 0,t.startedAt=void 0,t.endedAt=void 0,t.summary=void 0,t.error=void 0}function po(t,e,o,n,i){const a=t.status===void 0?-1:Pe(t.status),r=Pe(e),u=q(n),m=q(i);if(Ig(t,e,n))return{accepted:!1,newGeneration:!1};const p=a>0&&r>0,S=q(t.startedAt),y=te(e)&&u!==void 0&&t.disposedAt!==void 0&&u>t.disposedAt&&(t.statusStartedAt===void 0||t.statusStartedAt<=t.disposedAt)||a<=0&&r===1&&u!==void 0&&S!==void 0&&u>S||p&&u!==void 0&&t.statusEndedAt!==void 0&&u>t.statusEndedAt;if(o<he.task&&r===2&&t.taskId!==void 0)return{accepted:!1,newGeneration:!1};const w=p&&t.statusStartedAt!==void 0&&m!==void 0&&t.statusStartedAt>=m;if(!y&&w)return{accepted:!1,newGeneration:!1};const C=t.status===void 0?-1:pn(t.status),P=pn(e),D=r===a&&(r===1?P<C||P===C&&o<t.statusAuthority:o<t.statusAuthority),$=r<a||D;return!y&&$?{accepted:!1,newGeneration:!1}:(y?(ii(t),t.taskId=void 0,t.statusStartedAt=u,t.statusEndedAt=m):r>0&&(t.statusStartedAt??=u,t.statusEndedAt=m??t.statusEndedAt),t.status=e,t.statusAuthority=o,{accepted:!0,newGeneration:y})}function te(t){return t==="running"||t==="suspended"||t==="background"}function Tg(t,e){return t==="completed"||t==="failed"||t==="cancelled"||t==="lost"||t==="idle"?!1:te(t)||e===!0}function re(t){return t!==void 0&&t!==""}function W(t){return re(t)?t:void 0}function T(...t){for(const e of t)if(re(e))return e}const mn=200,wg=5e3,hn=1e3,Ie=[],Gt=new Set;let ri=[];function oe(t,e=Date.now()){Ie.push({...t,at:e}),Ie.length>mn&&Ie.splice(0,Ie.length-mn),ri=Ie.slice();for(const o of Gt)o()}function Eg(){return ri}function Bg(t){return Gt.add(t),()=>{Gt.delete(t)}}function kg(t){return t.map(e=>{const{at:o,kind:n,...i}=e,a=Object.entries(i).filter(([,r])=>r!==void 0).map(([r,u])=>`${r}=${typeof u=="string"?JSON.stringify(u):String(u)}`);return[new Date(o).toISOString(),n,...a].join(" ")}).join(`
3
- `)}let We=0,Rt=null;function Vg(){if(typeof window>"u"||typeof document>"u")return()=>{};if(We+=1,We===1){const t=()=>{oe({kind:"visibility",state:document.visibilityState})},e=()=>{oe({kind:"focus",focused:!0})},o=()=>{oe({kind:"focus",focused:!1})},n=()=>{oe({kind:"online",online:!0})},i=()=>{oe({kind:"online",online:!1})};document.addEventListener("visibilitychange",t),window.addEventListener("focus",e),window.addEventListener("blur",o),window.addEventListener("online",n),window.addEventListener("offline",i);let a=Date.now();const r=window.setInterval(()=>{const m=Date.now(),p=m-a-hn;a=m,p>=wg&&oe({kind:"timer_gap",gapMs:p,visibility:document.visibilityState},m)},hn),u=window;u.__kikiConnectionLog=()=>kg(Eg()),Rt=()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("focus",e),window.removeEventListener("blur",o),window.removeEventListener("online",n),window.removeEventListener("offline",i),window.clearInterval(r),delete u.__kikiConnectionLog}}return()=>{We-=1,We===0&&(Rt?.(),Rt=null)}}function Cg(t){return t instanceof N&&t.code===V.SESSION_INDEX_BUILDING}function Rg(t){return ag(t)}function gn(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Te(t,e){if(t==null)return[];if(typeof t=="string")return[t];if(Array.isArray(t)&&t.every(o=>typeof o=="string"))return[...new Set(t)];throw new N({code:V.INVALID_RESPONSE,msg:`Invalid config response: ${e} must be a string or string array`,data:t})}function Ft(t){if(!gn(t))throw new N({code:V.INVALID_RESPONSE,msg:"Invalid config response: data must be a plain object",data:t});const e=t.tools;if(e!=null&&!gn(e))throw new N({code:V.INVALID_RESPONSE,msg:"Invalid config response: tools must be a plain object",data:e});const o=e??{};return{...t,extra_agent_dirs:Te(t.extra_agent_dirs,"extra_agent_dirs"),skip_builtin_profile_installation:Te(t.skip_builtin_profile_installation,"skip_builtin_profile_installation"),disabled_named_profiles:Te(t.disabled_named_profiles,"disabled_named_profiles"),tools:{...o,enabled:Te(o.enabled,"tools.enabled"),disabled:Te(o.disabled,"tools.disabled")}}}const Pg=["user","feedback","project","reference"],Og=40423,Ag=40944;function Mg(t){const e=t.endpoint===""?globalThis.location.origin:t.endpoint;return new di({baseUrl:e,token:t.token,timeoutMs:t.timeoutMs,onSessionMutation:t.onSessionMutation,transport:qh({...t,endpoint:e})})}class ai extends Error{constructor(){super("External agent messages support text only. Remove attachments and retry."),this.name="ExternalAgentAttachmentUnsupportedError"}}class dt extends Error{constructor(e){super("Native child prompt result unknown",{cause:e}),this.name="NativeChildPromptSendError"}}class ci extends dt{constructor(e){super(e),this.name="NativeChildPromptConflictError"}}function xg(t){const e=t instanceof dt?t.cause:t;return e instanceof N&&e.code===40001}class di{baseUrl;klient;sessions;token;transport;serverLeaseId;previewBytes=new Map;previewCacheBytes=0;previewFlights=new Map;onSessionMutation;constructor(e){this.onSessionMutation=e.onSessionMutation,this.transport=e.transport,this.baseUrl=e.baseUrl,this.token=e.token!==void 0&&e.token!==""?e.token:void 0,this.klient=sg({endpoint:this.baseUrl,token:this.token,timeoutMs:e.timeoutMs,readingTimeoutMs:()=>this.readingOptions().timeoutMs,onSocketDiagnostic:n=>{oe(n)},...e.transport});const o=dg(this.klient);this.sessions={...o,listDurableIngress:(n,i)=>this.run(()=>this.rest.sessions.listPrompts(n,{admission:"durable",agent_id:i?.agentId,cursor:i?.cursor})),getDurableIngress:(n,i,a)=>this.run(()=>this.rest.sessions.getPrompt(n,i,{admission:"durable",agent_id:a})),resumeDurableIngress:(n,i,a,r)=>this.runSessionMutation(n,()=>this.rest.sessions.resumePrompt(n,i,a,{agent_id:r})),submitPrompt:(...n)=>this.runSessionMutation(n[0],()=>o.submitPrompt(...n)),editMessage:(...n)=>this.runSessionMutation(n[0],()=>o.editMessage(...n)),regenerateMessage:(...n)=>this.runSessionMutation(n[0],()=>o.regenerateMessage(...n)),abortPrompt:(...n)=>this.runSessionMutation(n[0],()=>o.abortPrompt(...n)),abortTurn:(...n)=>this.runSessionMutation(n[0],()=>o.abortTurn(...n)),movePrompt:(...n)=>this.runSessionMutation(n[0],()=>o.movePrompt(...n)),replacePrompt:(...n)=>this.runSessionMutation(n[0],()=>o.replacePrompt(...n)),timingPrompt:(...n)=>this.runSessionMutation(n[0],()=>o.timingPrompt(...n)),steerPrompt:(...n)=>this.runSessionMutation(n[0],()=>o.steerPrompt(...n)),resolveApproval:(...n)=>this.runSessionMutation(n[0],()=>o.resolveApproval(...n)),resolveQuestion:(...n)=>this.runSessionMutation(n[0],()=>o.resolveQuestion(...n)),dismissQuestion:(...n)=>this.runSessionMutation(n[0],()=>o.dismissQuestion(...n)),cancelTask:(...n)=>this.runSessionMutation(n[0],()=>o.cancelTask(...n))}}async runSessionMutation(e,o){const n=await o();return this.onSessionMutation?.(e),n}readingOptions(){return{timeoutMs:typeof localStorage>"u"?0:Ha().readingTimeoutSeconds*1e3}}sessionView(e){const o=this.klient.session(e).view;return{snapshot:n=>this.run(()=>o.snapshot(n)),transcript:o.transcript,subscribe:(n,i)=>o.subscribe(n,i)}}get rest(){const e=this.klient.rest;if(e===void 0)throw new Error("KAP REST domains are unavailable on this transport");return e}async run(e){try{return await(typeof e=="function"?e():e)}catch(o){if(o instanceof j){const n=o.reason===ti;throw new N({code:n?V.TIMEOUT:o.code,msg:n?o.message.replace("call timed out",ko("en","common.requestTimedOut")):o.message,data:o.data??null,details:o.details,request_id:o.requestId,source:o.source,reason:o.reason})}throw o}}healthz(e){return this.rest.healthz(e)}meta(){return this.run(()=>this.rest.meta())}async renewLease(e){const o=await this.run(()=>this.rest.renewLease({lease_id:this.serverLeaseId}));o!==void 0&&(this.serverLeaseId=o.lease_id)}listSessions(e={},o){return this.run(()=>this.rest.sessions.list(e,o))}listEphemeralSessions(e){return this.run(()=>this.rest.sessions.listEphemeral(e))}createSession(e){return this.run(()=>this.rest.sessions.create(e))}saveEphemeralSession(e){return this.run(()=>this.rest.sessions.saveEphemeral(e))}endEphemeralSession(e,o){return this.run(()=>this.rest.sessions.endEphemeral(e,{worktree:o}))}getRequestGovernance(){return this.run(()=>this.rest.requestGovernance())}setRequestGovernanceRules(e){return this.patchConfig({request_governance:{rules:e.map(o=>{const n={...o},i=n.resource,a=i==="live_agent"?"agent_execution":i==="agent_execution"||i==="model_request"?i:void 0,r=(o.roles??[]).filter(u=>u==="main"||u==="subagent"||u==="independent");return{id:o.id,resource:a,scope:o.scope,models:o.models===void 0?void 0:[...o.models],providers:o.providers===void 0?void 0:[...o.providers],executors:o.executors===void 0?void 0:[...o.executors],profiles:o.profiles===void 0?void 0:[...o.profiles],roles:r.length===0?void 0:r,subagents_only:o.subagentsOnly??n.subagents_only===!0,max_concurrent:o.maxConcurrent??(typeof n.max_concurrent=="number"?n.max_concurrent:void 0),overflow:o.overflow,max_wait_ms:o.maxWaitMs??(typeof n.max_wait_ms=="number"?n.max_wait_ms:void 0),enabled:o.enabled}})}})}getAgentActivity(){return this.run(()=>this.rest.agentActivity())}getProviderQuotas(){return this.run(()=>this.rest.providerQuotas.snapshot())}refreshProviderQuota(e){return this.run(()=>this.rest.providerQuotas.refresh(e))}setProviderQuotaEnabled(e,o){return this.run(()=>this.rest.providerQuotas.setEnabled(e,o))}getUsageRescan(){return this.run(()=>this.rest.usageRescan.status())}startUsageRescan(){return this.run(()=>this.rest.usageRescan.start())}getUsage(e,o){return this.run(()=>this.rest.usage(e,o))}getUsagePricing(e){return this.run(()=>this.rest.usagePricing.get(e))}setUsagePricing(e){return this.run(()=>this.rest.usagePricing.set(e))}getSession(e){return this.sessions.getSession(e)}updateSessionProfile(e,o){return this.run(()=>this.rest.sessions.updateProfile(e,o))}getPersonaSettings(e){return this.run(()=>this.rest.sessions.getPersonaSettings(e))}applyPersonaSettings(e,o={}){return this.run(()=>this.rest.sessions.applyPersonaSettings(e,o))}archiveSession(e,o={}){return this.run(async()=>{const n=o.include_attached??!0,i=await this.rest.sessions.archive(e,{...o,include_attached:n});if(n&&i.outcomes===void 0)throw new Error("The connected server cannot confirm archiving attached conversations. Refresh the list and update the server before retrying.");if(!i.archived||i.outcomes?.some(a=>!a.ok)){const a=i.outcomes?.filter(r=>!r.ok).map(r=>`${r.id}: ${r.message}`).join("; ");throw new Error(`Some conversations could not be archived. Retry to finish archiving${a?`: ${a}`:"."}`)}return i})}restoreSession(e){return this.run(()=>this.rest.sessions.restore(e))}deleteArchivedSession(e,o={}){return this.run(()=>this.rest.sessions.deleteArchived(e,o))}deleteAllArchivedSessions(){return this.run(()=>this.rest.sessions.deleteAllArchived())}getSessionGoal(e){return this.run(()=>this.rest.sessions.goal(e))}createAgentGoal(e,o){return this.run(()=>this.klient.session(e).agent(x).createGoal(o))}updateAgentGoal(e,o){return this.run(()=>this.klient.session(e).agent(x).updateGoal(o))}pauseAgentGoal(e){return this.run(()=>this.klient.session(e).agent(x).pauseGoal())}resumeAgentGoal(e,o={}){return this.run(()=>this.klient.session(e).agent(x).resumeGoal(o))}cancelAgentGoal(e){return this.run(()=>this.klient.session(e).agent(x).cancelGoal())}resumeRecoveredQueue(e){return this.run(()=>this.klient.session(e).agent(x).resumeRecoveredPromptQueue())}listMessages(e,o={}){return this.run(()=>this.rest.sessions.listMessages(e,o))}listPrompts(e,o={}){return this.run(()=>this.rest.sessions.listPrompts(e,o))}submitPrompt(e,o){return this.sessions.submitPrompt(e,o)}replacePrompt(e,o,n){return this.sessions.replacePrompt(e,o,n)}movePrompt(e,o,n){return this.sessions.movePrompt(e,o,n)}abortPrompt(e,o){return this.sessions.abortPrompt(e,o)}abortTurn(e,o){return this.sessions.abortTurn(e,o)}steerPrompt(e,o){return this.sessions.steerPrompt(e,o)}timingPrompt(e,o,n){return this.sessions.timingPrompt(e,o,n)}listPendingApprovals(e){return this.run(()=>this.rest.sessions.listApprovals(e))}resolveApproval(e,o,n){return this.sessions.resolveApproval(e,o,n)}listPendingQuestions(e){return this.run(()=>this.rest.sessions.listQuestions(e))}resolveQuestion(e,o,n){return this.sessions.resolveQuestion(e,o,n)}dismissQuestion(e,o){return this.sessions.dismissQuestion(e,o)}listTasks(e,o){return this.run(()=>this.rest.sessions.listTasks(e,o))}getTask(e,o,n={}){return this.run(()=>this.rest.sessions.getTask(e,o,n))}cancelTask(e,o,n={}){return this.sessions.cancelTask(e,o,n)}stopAgentTask(e,o,n){return this.run(this.klient.session(e).agent(o).stopTask({taskId:n}))}startSideQuestion(e){return this.run(()=>this.klient.session(e).btw.start())}async isNativeAgent(e,o){return o===x?!0:(await this.run(()=>this.klient.session(e).getAgentExecutor(o))??"native")==="native"}async sendAgentMessage(e,o,n,i,a,r){const u=this.klient.session(e);if((await this.run(()=>u.getAgentExecutor(o))??"native")!=="native"){if(i?.some(f=>f.type!=="text"))throw new ai;return this.run(()=>u.sendUserAgentMessageReceipt({targetAgentId:o,content:n,idempotencyKey:a}))}const p=i===void 0?[{type:"text",text:n}]:[...i],S=o!==x&&p.every(f=>f.type==="text");try{await this.submitPrompt(e,{content:p,agent_id:o,after_model_switch:r,prompt_id:S?a:void 0})}catch(f){throw S&&f instanceof N&&f.code===40938?new ci(f):o!==x?new dt(f):f}return null}setAgentModel(e,o,n){return this.run(this.klient.session(e).agent(o).setModel(n))}setAgentEffort(e,o,n){return this.run(this.klient.session(e).agent(o).setEffort(n))}switchAgentModel(e,o,n){return this.run(this.klient.session(e).agent(o).switchModel(n))}async getAgentModelSwitch(e,o,n){return await this.run(this.klient.session(e).agent(o).getModelSwitch(n))??null}listAgentModelSwitches(e,o,n){return this.run(this.klient.session(e).agent(o).listModelSwitches({signal:n}))}updateAgentModelSwitch(e,o,n,i){return this.run(this.klient.session(e).agent(o).updateModelSwitch(n,i))}cancelAgentModelSwitch(e,o,n){return this.run(this.klient.session(e).agent(o).cancelModelSwitch(n))}recoverAgentModelSwitch(e,o,n,i,a){const r=this.klient.session(e).agent(o);return this.run(i==="retry"?r.recoverModelSwitch(n,i,a):r.recoverModelSwitch(n,i))}subscribeAgentModelSwitches(e,o,n){const i=this.klient.session(e).agent(o).events,a=i.on("prompt.model_switch_queued",u=>{n({kind:"queued",entry:u.entry,queueIndex:u.queueIndex})}),r=i.on("prompt.model_switch_status",u=>{n({kind:"status",operationId:u.operationId,receipt:u.receipt})});return{ready:Promise.all([a.ready,r.ready]).then(()=>{}),dispose:()=>{a.dispose(),r.dispose()}}}listTerminals(e){return this.klient.terminal.listTerminals(e)}createTerminal(e,o={}){return this.klient.terminal.createTerminal(e,o)}getTerminal(e,o){return this.klient.terminal.getTerminal(e,o)}closeTerminal(e,o){return this.klient.terminal.closeTerminal(e,o)}listModels(){return this.run(this.klient.global.kosong.listModels().then(e=>({items:[...e]})))}listSkins(){return this.run(()=>this.rest.skins.list())}getSkin(e){return this.run(()=>this.rest.skins.get(e))}async getConfig(){return Ft(await this.run(this.rest.config.get()))}previewModelGenerationMigration(){return this.run(this.rest.config.previewModelGenerationMigration())}applyModelGenerationMigration(e){return this.run(this.rest.config.applyModelGenerationMigration(e))}restoreModelGenerationMigration(e,o){return this.run(this.rest.config.restoreModelGenerationMigration(e,o))}async getNbSearchCapabilities(){return za.parse(await this.run(this.rest.nbSearch.capabilities()))}async testNbSearch(e){return Ka.parse(await this.run(this.rest.nbSearch.test({signal:e})))}async readNbSearchKeyUsage(e,o=!1,n){return Qa.parse(await this.run(this.rest.nbSearch.keyUsage(e,o,{signal:n})))}async readNbSearchCredential(e,o=!1){return Co.parse(await this.run(this.rest.nbSearch.readCredential(e,o)))}async revealSecret(e){return Ya.parse(await this.run(this.rest.secrets.reveal(e)))}async writeNbSearchCredential(e,o,n,i){return Co.parse(await this.run(this.rest.nbSearch.writeCredential(e,o,n,i)))}get requestIdentity(){const e=this.rest.requestIdentity,o=async n=>tc.parse(await this.run(n));return{get:()=>o(e.get()),preview:async n=>Xa.parse(await this.run(e.preview(n))),duplicateProfile:(n,i)=>o(e.duplicateProfile(n,i)),updateProfile:(n,i)=>o(e.updateProfile(n,i)),deleteProfile:n=>o(e.deleteProfile(n)),checkTrack:(n,i)=>o(e.checkTrack(n,i)),applyTrack:(n,i)=>o(e.applyTrack(n,i)),trackAction:(n,i)=>o(e.trackAction(n,i)),pinTrack:(n,i)=>o(e.pinTrack(n,i)),setManifestUrl:n=>o(e.setManifestUrl(n))}}get notifications(){const e=this.rest.notifications,o=n=>(...i)=>this.run(()=>n(...i));return{listCompletions:o(e.listCompletions.bind(e)),getSettings:o(e.getSettings.bind(e)),updateSettings:o(e.updateSettings.bind(e)),listProviders:o(e.listProviders.bind(e)),upsertInstance:o(e.upsertInstance.bind(e)),deleteInstance:o(e.deleteInstance.bind(e)),upsertChannel:o(e.upsertChannel.bind(e)),deleteChannel:o(e.deleteChannel.bind(e)),setCredential:o(e.setCredential.bind(e)),checkCredential:o(e.checkCredential.bind(e)),sendTest:o(e.sendTest.bind(e)),listDeliveries:o(e.listDeliveries.bind(e))}}get imSessions(){const e=this.rest.imSessions,o=n=>(...i)=>this.run(()=>n(...i));return{snapshot:o(e.snapshot.bind(e)),catalog:o(e.catalog.bind(e)),setupCatalog:o(e.setupCatalog.bind(e)),setup:o(e.setup.bind(e)),setPolicy:o(e.setPolicy.bind(e)),paste:o(e.paste.bind(e)),check:o(e.check.bind(e)),listen:o(e.listen.bind(e)),confirm:o(e.confirm.bind(e)),dismiss:o(e.dismiss.bind(e)),updateBinding:o(e.updateBinding.bind(e)),removeBinding:o(e.removeBinding.bind(e)),testBinding:o(e.testBinding.bind(e)),channelViews:o(e.channelViews.bind(e)),setInternalChannel:o(e.setInternalChannel.bind(e)),setNotificationChannel:o(e.setNotificationChannel.bind(e)),removeNotificationChannel:o(e.removeNotificationChannel.bind(e)),startWechatQr:o(e.startWechatQr.bind(e)),pollWechatQr:o(e.pollWechatQr.bind(e)),cancelWechatQr:o(e.cancelWechatQr.bind(e))}}listNamedAgentProfiles(e){return this.run(this.rest.agents.list(e))}getAgentCapabilities(e,o){return this.run(this.klient.global.agentPanel.read(e,{signal:o}))}listAgentTasks(e,o,n){return this.run(this.rest.sessions.listAgentTasks(e,o,n))}previewAgentProfileFile(e,o){return this.run(this.rest.agents.previewFile(e,o))}createAgentProfile(e){return this.run(this.rest.agents.create(e))}updateNamedAgentProfile(e,o){return this.run(this.rest.agents.update(e,o))}listShippedAgentProfiles(){return this.run(this.rest.agents.shipped.list())}restoreShippedAgentProfile(e){return this.run(this.rest.agents.shipped.restore(e))}async readHostFile(e,o){return this.run(this.rest.filesystem.readHostFile(e,{...this.readingOptions(),...o}))}async readBuiltinSkill(e,o){return(await this.run(this.rest.skills.readBuiltinContent(e,{...this.readingOptions(),...o}))).content}previewHostSkillInstall(e,o){return this.run(this.rest.skills.previewHostInstall(e,o))}installHostSkill(e,o,n){return this.run(this.rest.skills.installHost(e,o,n))}async previewHostFile(e,o=512001,n){return this.run(this.rest.filesystem.previewHostFile(e,o,{...this.readingOptions(),...n}))}async openHtmlPreview(e,o){return this.run(this.rest.filesystem.openHtmlPreview(e,o))}async closeHtmlPreview(e,o){return this.run(this.rest.filesystem.closeHtmlPreview(e,o))}async openHostMediaPreview(e,o){const n=await this.memoryRequest("POST","/fs:media-preview",{body:e,signal:o?.signal,timeoutMs:15e3});if(typeof n!="object"||n===null)throw new N({code:V.INVALID_RESPONSE,msg:"Media preview could not be opened",data:null});const i=n;if(typeof i.preview_id!="string"||typeof i.url!="string"||typeof i.mime!="string"||typeof i.size!="number"||typeof i.expires_at!="number")throw new N({code:V.INVALID_RESPONSE,msg:"Media preview could not be opened",data:null});return{preview_id:i.preview_id,url:Ug(this.baseUrl,i.url),mime:i.mime,size:i.size,expires_at:i.expires_at}}async closeHostMediaPreview(e){await this.memoryRequest("DELETE",`/fs:media-preview/${encodeURIComponent(e)}`,{timeoutMs:1e4})}cachedPreviewBytes(e,o,n){if(n?.aborted===!0)return Promise.reject(n.reason);let i=this.previewFlights.get(e);if(i===void 0){const r=new AbortController;i={controller:r,users:0,promise:this.readAndCachePreview(e,p=>o(p,r.signal))},this.previewFlights.set(e,i);const u=i,m=()=>{this.previewFlights.get(e)===u&&this.previewFlights.delete(e)};u.promise.then(m,m)}const a=i;return a.users+=1,new Promise((r,u)=>{let m=!1;const p=f=>{m||(m=!0,n?.removeEventListener("abort",S),a.users-=1,a.users===0&&this.previewFlights.get(e)===a&&(this.previewFlights.delete(e),a.controller.abort()),f())},S=()=>{p(()=>{u(n?.reason)})};n?.addEventListener("abort",S,{once:!0}),a.promise.then(f=>{p(()=>{r(f)})},f=>{p(()=>{u(f)})})})}async readAndCachePreview(e,o){const n=this.previewBytes.get(e),i=await this.run(o(n?.etag));if(i.notModified){if(n===void 0)throw new Error("Preview cache is missing a validated response");return n}if(n!==void 0&&(this.previewBytes.delete(e),this.previewCacheBytes-=n.bytes.byteLength),i.etag!==void 0&&i.bytes.byteLength<=32*1024*1024)for(this.previewBytes.set(e,{...i,etag:i.etag}),this.previewCacheBytes+=i.bytes.byteLength;this.previewBytes.size>8||this.previewCacheBytes>32*1024*1024;){const a=this.previewBytes.keys().next().value;this.previewCacheBytes-=this.previewBytes.get(a).bytes.byteLength,this.previewBytes.delete(a)}return i}readHostFileBytes(e,o){return this.run(this.rest.filesystem.readHostFileBytes(e,{...this.readingOptions(),...o}))}readHostMediaPreviewBytes(e,o){return this.cachedPreviewBytes(`host-preview:${e}:${o?.mediaType??""}`,(n,i)=>this.rest.filesystem.readHostMediaPreview(e,{...this.readingOptions(),...o,signal:i,ifNoneMatch:n}),o?.signal)}downloadHostFile(e,o,n){return this.run(this.rest.filesystem.downloadHostFile(e,o,{...this.readingOptions(),...n}))}readSessionMediaBytes(e,o,n){return this.run(this.rest.sessions.media(e,o,{...this.readingOptions(),...n}))}readSessionMediaPreviewBytes(e,o,n){return this.cachedPreviewBytes(`media-preview:${e}:${o}:${n?.mediaType??""}`,(i,a)=>this.rest.sessions.mediaPreview(e,o,{...this.readingOptions(),...n,signal:a,ifNoneMatch:i}),n?.signal)}downloadSessionMedia(e,o,n,i){return this.run(this.rest.sessions.downloadMedia(e,o,n,{...this.readingOptions(),...i}))}downloadTranscriptContent(e,o,n,i,a){const r=uc(o,n);return r===void 0?Promise.reject(new Error("This content has no original-file consumer")):this.downloadSessionMedia(e,r,i,a)}listWorkspaces(){return this.run(this.rest.workspaces.list())}listWorkspaceCatalog(){return this.run(this.rest.workspaces.listCatalog())}getWorkspaceDetails(e){return this.run(this.rest.workspaces.detail(e))}renameWorkspace(e,o){return this.run(this.rest.workspaces.rename(e,o))}setWorkspacePinned(e,o){return this.run(this.rest.workspaces.setPinned(e,o))}renameWorkspaceCatalog(e,o){return this.run(this.rest.workspaces.updateCatalog(e,{name:o}))}setWorkspacePinnedCatalog(e,o){return this.run(this.rest.workspaces.updateCatalog(e,{pinned:o}))}setWorkspaceTrust(e,o){return this.run(this.rest.workspaces.setTrust(e,o))}removeWorkspace(e){return this.run(this.rest.workspaces.remove(e))}getWorkspaceTrust(e){return this.run(this.rest.workspaces.getTrust(e))}trustWorkspace(e){return this.run(this.rest.workspaces.trust(e))}untrustWorkspace(e){return this.run(this.rest.workspaces.untrust(e))}getAuth(){return this.run(this.rest.auth.summary())}listProviders(){return this.run(this.klient.global.kosong.listProviders().then(e=>({items:[...e]})))}listCatalogProviders(){return this.run(()=>this.rest.catalog.list())}importCatalogProvider(e){return this.run(()=>this.rest.catalog.importProvider(e,{timeoutMs:9e4}))}getManagedUsage(e){return this.run(()=>this.rest.oauth.usage(e))}getCatalogProvider(e){return this.run(this.rest.catalog.provider(e))}refreshProvider(e,o){return this.run(this.klient.global.kosong.refreshProviders({providerId:e,apiKey:o}))}async probeProviderDraft(e){const o=n=>{const i=oc(e.type).defaultContextSize;return n.map(a=>({id:"",remoteId:a,maxContextSize:i,displayName:"",capabilities:[],supportEfforts:[],requestIdentityChoice:"inherit",requestIdentityOverridesJson:"",imageAcceptedTypes:null,imageConvertUnsupported:null}))};try{const n=await this.run(this.rest.providers.probe({type:e.type,base_url:e.baseUrl,api_key:e.apiKey}));if(!n.ok)throw new Error(n.error.message);return o(n.models)}catch(n){if(!(n instanceof N))throw n;return Ja(e)}}refreshAllProviders(){return this.run(this.klient.global.kosong.refreshProviders())}listDiscoveredModels(){return this.run(this.klient.global.kosong.listDiscoveredModels().then(e=>({items:[...e.items]})))}setDefaultModel(e){return this.run(this.klient.global.kosong.setDefaultModel(e))}getModel(e){return this.run(this.klient.global.kosong.readModel(e))}createModel(e){return this.run(this.klient.global.kosong.createModel(e))}updateModel(e,o){return this.run(this.klient.global.kosong.updateModel(e,o))}deleteModel(e,o){return this.run(this.klient.global.kosong.deleteModel(e,o))}listRecipes(){return this.run(this.klient.global.recipes.list())}getRecipe(e){return this.run(this.klient.global.recipes.get(e))}previewRecipe(e){return this.run(this.klient.global.recipes.preview(e))}installRecipe(e){return this.run(this.klient.global.recipes.install(e))}checkRecipeUpdates(){return this.run(this.klient.global.recipes.checkUpdates())}updateRecipe(e){return this.run(this.klient.global.recipes.update(e))}forkRecipe(e){return this.run(this.klient.global.recipes.fork(e))}saveLocalRecipe(e){return this.run(this.klient.global.recipes.saveLocal(e))}removeRecipe(e){return this.run(this.klient.global.recipes.remove(e))}listRecipeMarkets(){return this.run(this.klient.global.recipes.markets.list())}addRecipeMarket(e){return this.run(this.klient.global.recipes.markets.add(e))}updateRecipeMarket(e){return this.run(this.klient.global.recipes.markets.update(e))}removeRecipeMarket(e){return this.run(this.klient.global.recipes.markets.remove(e))}exportRecipe(e){return this.run(this.klient.global.recipes.export(e))}getProviderEntity(e){return this.run(this.klient.global.kosong.readProviderEntity(e))}createProvider(e){return this.run(this.klient.global.kosong.createProvider(e))}updateProvider(e,o){return this.run(this.klient.global.kosong.updateProvider(e,o))}deleteProviderEntity(e){return this.run(this.klient.global.kosong.deleteProviderEntity(e))}getOAuthStatus(e={}){return this.run(this.klient.global.auth.flow(e.provider)).then(o=>o??null)}startOAuthLogin(e={}){return this.run(this.klient.global.auth.startLogin(e.provider))}cancelOAuthLogin(e={}){return this.run(this.klient.global.auth.cancelLogin(e.provider))}readShortcuts(e){return this.run(()=>this.rest.shortcuts.read(e))}writeShortcuts(e,o){return this.run(()=>this.rest.shortcuts.write(e,o))}resetShortcuts(e,o){return this.run(()=>this.rest.shortcuts.reset(e,o))}listOAuthMethods(){return this.run(this.klient.global.auth.methods())}probeOriginalOAuth(e){return this.run(this.klient.global.auth.probeOriginal(e))}connectOriginalOAuth(e){return this.run(this.klient.global.auth.connectOriginal(e))}listProviderHealth(){return this.run(this.rest.providers.health())}testProviderConnection(e){return this.run(this.rest.providers.test(e,{timeoutMs:9e4}))}listExecutors(){return this.run(this.rest.executors.list())}listLocalSessions(e,o){return this.run(()=>this.rest.executors.listLocalSessions(e,{limit:o}))}getLocalSession(e,o){return this.run(()=>this.rest.executors.getLocalSession(e,o))}resumeLocalSession(e,o,n){return this.run(()=>this.rest.executors.resumeLocalSession(e,o,n))}listThreadMessages(e){return this.run(()=>this.rest.threads.messages(e))}getExecutor(e){return this.memoryRequest("GET",`/executors/${encodeURIComponent(e)}`)}checkExecutor(e){return this.memoryRequest("POST",`/executors/${encodeURIComponent(e)}/check`)}removeExecutorRegistration(e){return this.memoryRequest("POST",`/executors/${encodeURIComponent(e)}/registration:remove`,{body:{}})}setBrowserControlEnabled(e){return this.patchConfig({browser_control:{enabled:e}})}setComputerControlEnabled(e){return this.patchConfig({computer_control:{enabled:e}})}getAntigravityBinaries(){return this.memoryRequest("GET","/executors/antigravity-acp/binaries")}installAntigravityBinary(e){return this.memoryRequest("POST","/executors/antigravity-acp/binaries/install",{body:e===void 0?{}:{version:e},timeoutMs:11*6e4})}activateAntigravityBinary(e){return this.memoryRequest("POST","/executors/antigravity-acp/binaries/activate",{body:{version:e}})}startAntigravityLogin(e){return this.memoryRequest("POST","/executors/antigravity-acp/login/start",{body:{method_id:e}})}completeAntigravityLogin(e,o){return this.memoryRequest("POST","/executors/antigravity-acp/login/complete",{body:{handle:e,redirect_url:o}})}cancelAntigravityLogin(e){return this.memoryRequest("POST","/executors/antigravity-acp/login/cancel",{body:{handle:e}})}logoutAntigravity(){return this.memoryRequest("POST","/executors/antigravity-acp/logout",{body:{}})}previewExecutorPrompt(e,o,n){return this.memoryRequest("POST",`/agents/${encodeURIComponent(e)}/executor-prompt:preview`,{body:{workspace:o,executor:n}})}async setSubagentDefaultModel(e){const o=e.trim();await this.patchConfig({subagent:{default_model:o===""?null:o}})}async setFastModel(e){const o=e.trim();await this.patchConfig({fast_model:o===""?null:o})}logoutOAuth(e={}){return this.run(this.klient.global.auth.logout(e.provider))}listTools(e){return this.run(this.rest.runtime.listTools(e))}listMcpServers(){return this.run(this.rest.runtime.listMcpServers())}listPlugins(){return this.run(this.klient.global.plugins.list().then(e=>({plugins:[...e]})))}checkPluginUpdates(){return this.run(this.klient.global.plugins.checkUpdates())}listPluginMarketplace(){return this.run(this.rest.plugins.marketplace())}getPlugin(e){return this.run(this.rest.plugins.info(e))}getPluginSettings(e){return this.run(this.rest.plugins.settings(e))}setPluginSettings(e,o){return this.run(this.rest.plugins.setSettings(e,{values:{...o}}))}installPlugin(e){return this.run(this.rest.plugins.install(e))}listCapabilities(){return this.run(this.klient.global.capabilities.list())}getCapability(e){return this.run(this.klient.global.capabilities.get(e))}installCapability(e,o,n){return this.run(this.klient.global.capabilities.install(e,o,n))}cancelCapability(e){return this.run(this.klient.global.capabilities.cancel(e))}setPluginEnabled(e,o){return this.run(this.rest.plugins.setEnabled(e,o))}removePlugin(e,o){return this.run(this.rest.plugins.remove(e,o))}previewPlugin(e,o){return this.run(this.rest.plugins.preview({source:e,sha256:o}))}installPreviewedPlugin(e){return this.run(this.rest.plugins.install(e))}rollbackPlugin(e){return this.run(this.rest.plugins.rollback(e))}installPluginPrerequisite(e,o){return this.run(this.rest.plugins.installPrerequisite(e,{id:o,consent:!0}))}recommendPlugins(e){return this.run(this.rest.plugins.recommend(e))}dismissPluginRecommendation(e){return this.run(this.rest.plugins.dismissRecommendation(e))}listPluginPanels(e){return this.run(this.rest.plugins.panels(e))}getPluginPanelDocument(e,o,n){return this.run(this.rest.plugins.panelDocument(e,o,n))}listPluginCommands(e){return this.run(this.rest.plugins.commands(e))}getPluginUsage(e){return this.run(this.rest.plugins.usage(e))}pluginNavigation(){return this.run(this.rest.plugins.navigation())}setPluginUsage(e){return this.run(this.rest.plugins.setUsage(e))}callPluginPanelBridge(e,o,n){return this.run(this.rest.plugins.panelBridge(e,o,n))}restartMcpServer(e){return this.run(this.rest.runtime.restartMcpServer(e))}listDraftSkills(e){return this.run(this.rest.skills.list(e))}listWorkspaceSkills(e){return this.run(this.rest.workspaces.listSkills(e))}listSessionSkills(e){return this.run(this.rest.sessions.listSkills(e))}rebuildContext(e){return this.run(this.klient.session(e).agent("main").rebuildContext())}activateSkill(e,o,n={}){return this.run(this.rest.sessions.activateSkill(e,o,n))}async uploadFile(e){const o=new Uint8Array(await e.arrayBuffer());return this.run(this.klient.global.files.save({data:o,filename:e.name===""?"attachment":e.name,mimeType:e.type===""?void 0:e.type},{timeoutMs:0}))}fsSearch(e,o,n){return this.run(this.rest.sessions.fsSearch(e,o,{signal:n}))}workspaceFsSearch(e,o,n){return this.run(this.rest.filesystem.workspaceFsSearch(e,o,{signal:n}))}searchMessages(e,o){return this.run(this.rest.search.messages(e,{signal:o})).then(n=>({...n,items:[...n.items]}))}searchIndexStatus(){return this.run(this.rest.search.status())}retrySearchIndexer(){return this.run(this.rest.search.retry())}listCronTasks(e={}){return this.run(this.rest.cron.list(e))}getCronTask(e,o){return this.run(this.rest.cron.get(e,{session_id:o}))}createCronTask(e){return this.run(this.rest.cron.create(e))}updateCronTask(e,o,n){return this.run(this.rest.cron.update(e,o,{session_id:n}))}pauseCronTask(e,o){return this.run(this.rest.cron.pause(e,{session_id:o}))}resumeCronTask(e,o){return this.run(this.rest.cron.resume(e,{session_id:o}))}runCronTask(e,o){return this.run(this.rest.cron.run(e,{session_id:o}))}deleteCronTask(e,o){return this.run(this.rest.cron.remove(e,{session_id:o}))}getMemorySettings(){return this.memoryRequest("GET","/memory/settings")}patchMemorySettings(e){return this.memoryRequest("PATCH","/memory/settings",{body:e})}getWorkspaceMemorySettings(e){return this.memoryRequest("GET",`/memory/workspaces/${encodeURIComponent(e)}/settings`)}patchWorkspaceMemorySettings(e,o){return this.memoryRequest("PATCH",`/memory/workspaces/${encodeURIComponent(e)}/settings`,{body:{enabled:o}})}listMemory(e,o={},n){return this.memoryRequest("GET",`/memory/${e.scope}`,{target:e,signal:n,query:o.cursor!==void 0?{cursor:o.cursor}:{query:o.query!==void 0&&o.query.trim()!==""?o.query.trim():void 0,type:o.type,include_inactive:o.include_inactive===!0?"true":void 0,mode:o.mode,statuses:o.statuses?.join(","),page_size:o.page_size?.toString()}})}getMemory(e,o){return this.memoryRequest("GET",`/memory/${e.scope}/${encodeURIComponent(o)}`,{target:e})}putMemory(e,o,n){return this.memoryRequest("PUT",`/memory/${e.scope}/${encodeURIComponent(o)}`,{target:e,body:n})}deleteMemory(e,o,n){return this.memoryRequest("DELETE",`/memory/${e.scope}/${encodeURIComponent(o)}`,{target:e,query:{expected_revision:n}})}memoryJournal(e,o){return this.memoryRequest("GET",`/memory/${e.scope}/journal`,{target:e,query:{id:o}})}async memoryInbox(e,o={},n){const i=await this.memoryRequest("GET",`/memory/${e.scope}/inbox`,{target:e,signal:n,query:o.cursor!==void 0?{cursor:o.cursor}:{page_size:o.page_size?.toString()}});return Array.isArray(i)?{items:i}:i}undoMemory(e,o){return this.memoryRequest("POST",`/memory/${e.scope}/undo`,{target:e,body:{operation_id:o}})}async memoryRequest(e,o,n={}){const i=this.baseUrl.replace(/\/+$/u,""),a=i===""?new URL(`/api${o}`,globalThis.location?.origin??"http://localhost"):new URL(`${i}/api${o}`),r=n.target?.scope,u={...n.query,workspace_id:r==="workspace"||r==="persona_workspace"?n.target?.workspaceId:void 0,persona_id:r==="persona"||r==="persona_workspace"?n.target?.personaId:void 0};for(const[I,w]of Object.entries(u))w!==void 0&&a.searchParams.set(I,w);const m={accept:"application/json"};this.token!==void 0&&(m.authorization=`Bearer ${this.token}`),n.body!==void 0&&(m["content-type"]="application/json");const p=n.timeoutMs===0?void 0:AbortSignal.timeout(n.timeoutMs??3e4),S=n.signal===void 0?p:p===void 0?n.signal:AbortSignal.any([n.signal,p]);let f;try{f=await(this.transport?.fetch??fetch)(a,{method:e,headers:m,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:S})}catch(I){throw I instanceof DOMException&&I.name==="TimeoutError"?new N({code:V.TIMEOUT,msg:ko("en","common.requestTimedOut"),data:null}):I}let y;try{y=await f.json()}catch{y=null}if(y===null||typeof y!="object"||!("code"in y)||typeof y.code!="number"||!("msg"in y)||typeof y.msg!="string")throw new N({code:V.INVALID_RESPONSE,msg:`HTTP ${f.status} — non-JSON response`,data:null});if(y.code!==0)throw new N({code:y.code,msg:y.msg,data:"data"in y?y.data??null:null,details:"details"in y?y.details:void 0,request_id:"request_id"in y&&typeof y.request_id=="string"?y.request_id:void 0});return"data"in y?y.data:null}async readDocumentPreviewAsset(e,o){const n=ug(e),i=this.baseUrl.replace(/\/+$/u,""),a=i===""?new URL(n,globalThis.location?.origin??"http://localhost"):new URL(`${i}${n}`),r={accept:"*/*"};this.token!==void 0&&(r.authorization=`Bearer ${this.token}`);const u=await(this.transport?.fetch??fetch)(a,{headers:r,signal:o});if(!u.ok)throw new N({code:V.INVALID_RESPONSE,msg:`Preview asset could not be read (HTTP ${u.status})`,data:null});return{bytes:new Uint8Array(await u.arrayBuffer()),mime:u.headers.get("content-type")??"application/octet-stream"}}async listWorkPresets(){return Za.parse(await this.memoryRequest("GET","/work-presets"))}async enableWorkPreset(e,o){return wt.parse(await this.memoryRequest("POST",`/work-presets/${encodeURIComponent(e)}/enable`,{body:{consent:!0,install_prerequisites:o}}))}async updateWorkPreset(e,o){return wt.parse(await this.memoryRequest("PATCH",`/work-presets/${encodeURIComponent(e)}`,{body:o}))}async removeWorkPreset(e){return wt.parse(await this.memoryRequest("DELETE",`/work-presets/${encodeURIComponent(e)}`))}async documentPreview(e,o,n){return ec.parse(await this.memoryRequest("POST",`/sessions/${encodeURIComponent(e)}/document-preview`,{body:o,signal:n,...this.readingOptions()}))}forkSession(e,o={}){return this.sessions.forkSession(e,o)}editMessage(e,o,n){return this.sessions.editMessage(e,o,n)}regenerateMessage(e,o,n){return this.sessions.regenerateMessage(e,o,n)}compactSession(e,o={}){return this.run(this.rest.sessions.compact(e,o))}getAutoCompact(e,o){return this.run(this.rest.sessions.getAutoCompact(e,o))}getAgentHooksInspect(e,o){return this.run(this.rest.sessions.inspectHooks(e,o))}setAutoCompact(e,o,n){return this.run(this.rest.sessions.setAutoCompact(e,o,n))}getSessionOptionalCapabilities(e){return this.memoryRequest("GET",`/sessions/${encodeURIComponent(e)}/optional-capabilities`)}setSessionOptionalCapability(e,o){return this.memoryRequest("POST",`/sessions/${encodeURIComponent(e)}/optional-capabilities`,{body:o})}getContextStrategy(e,o){return this.memoryRequest("GET",`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(o)}/context-strategy`)}setContextStrategy(e,o,n){return this.memoryRequest("PATCH",`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(o)}/context-strategy`,{body:n})}undoSession(e,o={}){return this.run(this.rest.sessions.undo(e,o))}exportSession(e){return this.run(this.rest.sessions.export(e))}async patchConfig(e){return Ft(await this.run(this.rest.config.patch(e)))}listPersonas(e={}){return this.run(()=>this.rest.personas.list(e))}getPersona(e){return this.run(()=>this.rest.personas.get(e))}putPersona(e){return this.run(()=>this.rest.personas.put(e))}duplicatePersona(e,o={}){return this.run(()=>this.rest.personas.duplicate(e,o))}archivePersona(e,o){return this.run(()=>this.rest.personas.archive(e,o))}deletePersona(e,o){return this.run(()=>this.rest.personas.delete(e,{expectedRevision:o}))}async previewPersonaImport(e){const o=new Uint8Array(await e.arrayBuffer());return this.run(()=>this.rest.personas.previewImport({data:o,filename:e.name,format:Bt(e)}))}async importPersonaCard(e,o={}){const n=new Uint8Array(await e.arrayBuffer());return this.run(()=>this.rest.personas.importCard({data:n,filename:e.name,format:Bt(e),...o}))}async exportPersonaCard(e,o){const n=await this.run(()=>this.rest.personas.exportCard(e,o));return{blob:new Blob([n.bytes.slice().buffer],{type:n.mime}),filename:n.name??`${e}.${o}`}}async getPersonaAvatar(e,o){try{const n=await this.rest.personas.getAvatar(e,{signal:o});return new Blob([n.bytes.slice().buffer],{type:n.mime})}catch{return null}}async putPersonaAvatar(e,o,n){const i=new Uint8Array(await o.arrayBuffer());return this.run(()=>this.rest.personas.putAvatar(e,i,o.type,n))}deletePersonaAvatar(e){return this.run(()=>this.rest.personas.deleteAvatar(e))}async getStorageMigration(){return Ro.parse(await this.memoryRequest("GET","/storage"))}async postStorageMigrationAction(e){return Ro.parse(await this.memoryRequest("POST","/storage",{body:{action:e}}))}}function Ug(t,e){if(/^https?:\/\//iu.test(e))return e;const o=t.replace(/\/+$/u,""),n=o===""?globalThis.location?.origin??"http://localhost":o;return new URL(e,`${n}/`).toString()}const Dg=40945,Ng=40946;function Bt(t){const e=t.name.toLowerCase();return t.type==="image/png"||e.endsWith(".png")?"png":e.endsWith(".charx")?"charx":"json"}const Wg=Object.freeze(Object.defineProperty({__proto__:null,API_CODES:V,ApiError:N,ExternalAgentAttachmentUnsupportedError:ai,KikiClient:di,MEMORY_NOT_FOUND:Og,MEMORY_REVISION_CONFLICT:Ag,MEMORY_TYPES:Pg,NativeChildPromptConflictError:ci,NativeChildPromptSendError:dt,PERSONA_ALREADY_EXISTS:Dg,PERSONA_REVISION_CONFLICT:Ng,createRemoteSpaceClient:Mg,isDefinitivePromptRejection:xg,isSessionIndexBuildingError:Cg,isSessionNotFoundMessage:Rg,isUnconfirmedTransportError:ig,parseKikiConfigResponse:Ft,personaCardFormatOf:Bt},Symbol.toStringTag,{value:"Module"}));export{N as A,cg as D,ai as E,Ao as G,di as K,x as M,dt as N,Ng as P,j as R,V as a,$g as b,Mg as c,ig as d,Fg as e,uc as f,Mo as g,Ag as h,Rg as i,Gg as j,xg as k,Cg as l,Pg as m,Og as n,Dg as o,Bg as p,Eg as q,kg as r,qg as s,Lg as t,Wg as u,Vg as w};