kiki-agent-lite 0.3.1 → 0.3.2
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.
- package/README.md +13 -10
- package/dist/docs/en/configuration/config-files.md +63 -20
- package/dist/docs/en/configuration/data-locations.md +12 -4
- package/dist/docs/en/configuration/env-vars.md +4 -6
- package/dist/docs/en/configuration/overrides.md +13 -14
- package/dist/docs/en/configuration/providers.md +8 -6
- package/dist/docs/en/customization/agent-profiles.md +33 -38
- package/dist/docs/en/customization/agents.md +129 -107
- package/dist/docs/en/customization/hooks.md +41 -48
- package/dist/docs/en/customization/personas.md +19 -21
- package/dist/docs/en/customization/plugins.md +180 -156
- package/dist/docs/en/customization/prompt-fields.md +10 -6
- package/dist/docs/en/customization/skills.md +11 -13
- package/dist/docs/en/customization/skins.md +23 -27
- package/dist/docs/en/customization/themes.md +15 -15
- package/dist/docs/en/features/agents.md +85 -0
- package/dist/docs/en/features/daily.md +37 -7
- package/dist/docs/en/features/ecosystem.md +3 -1
- package/dist/docs/en/features/extend.md +7 -1
- package/dist/docs/en/features/freedom.md +4 -0
- package/dist/docs/en/features/index.md +6 -5
- package/dist/docs/en/features/long-work.md +23 -5
- package/dist/docs/en/features/look.md +1 -1
- package/dist/docs/en/features/people.md +10 -2
- package/dist/docs/en/features/spaces.md +16 -4
- package/dist/docs/en/features/workbench.md +11 -3
- package/dist/docs/en/getting-started/desktop-app.md +44 -29
- package/dist/docs/en/getting-started/first-launch.md +32 -21
- package/dist/docs/en/getting-started/installation.md +27 -12
- package/dist/docs/en/getting-started/use-cases.md +35 -35
- package/dist/docs/en/guides/goals.md +9 -7
- package/dist/docs/en/guides/interaction.md +26 -26
- package/dist/docs/en/guides/interface.md +18 -14
- package/dist/docs/en/guides/memory.md +43 -14
- package/dist/docs/en/guides/sessions.md +32 -26
- package/dist/docs/en/guides/settings.md +60 -29
- package/dist/docs/en/index.md +8 -2
- package/dist/docs/en/reference/command.md +8 -4
- package/dist/docs/en/reference/keyboard.md +18 -4
- package/dist/docs/en/reference/model-vocabulary.md +6 -8
- package/dist/docs/en/reference/slash-commands.md +4 -4
- package/dist/docs/en/reference/tools.md +92 -15
- package/dist/docs/en/release-notes/changelog.md +1 -9
- package/dist/docs/en/server/acp.md +1 -1
- package/dist/docs/en/server/ide.md +1 -1
- package/dist/docs/en/server/local-server.md +5 -5
- package/dist/docs/en/server/mcp.md +2 -2
- package/dist/docs/en/server/rest-api.md +79 -5
- package/dist/docs/en/server/sdk.md +2 -2
- package/dist/docs/zh/configuration/config-files.md +56 -15
- package/dist/docs/zh/configuration/data-locations.md +12 -4
- package/dist/docs/zh/configuration/env-vars.md +4 -6
- package/dist/docs/zh/configuration/overrides.md +13 -14
- package/dist/docs/zh/configuration/providers.md +7 -5
- package/dist/docs/zh/customization/agent-profiles.md +31 -36
- package/dist/docs/zh/customization/agents.md +120 -98
- package/dist/docs/zh/customization/hooks.md +35 -42
- package/dist/docs/zh/customization/personas.md +16 -18
- package/dist/docs/zh/customization/plugins.md +167 -142
- package/dist/docs/zh/customization/prompt-fields.md +9 -5
- package/dist/docs/zh/customization/skills.md +10 -12
- package/dist/docs/zh/customization/skins.md +19 -23
- package/dist/docs/zh/customization/themes.md +12 -12
- package/dist/docs/zh/features/agents.md +85 -0
- package/dist/docs/zh/features/daily.md +37 -7
- package/dist/docs/zh/features/ecosystem.md +3 -1
- package/dist/docs/zh/features/extend.md +7 -1
- package/dist/docs/zh/features/freedom.md +4 -0
- package/dist/docs/zh/features/index.md +6 -5
- package/dist/docs/zh/features/long-work.md +22 -4
- package/dist/docs/zh/features/look.md +1 -1
- package/dist/docs/zh/features/people.md +10 -2
- package/dist/docs/zh/features/spaces.md +15 -3
- package/dist/docs/zh/features/workbench.md +11 -3
- package/dist/docs/zh/getting-started/desktop-app.md +43 -28
- package/dist/docs/zh/getting-started/first-launch.md +32 -21
- package/dist/docs/zh/getting-started/installation.md +26 -11
- package/dist/docs/zh/getting-started/use-cases.md +35 -37
- package/dist/docs/zh/guides/goals.md +8 -8
- package/dist/docs/zh/guides/interaction.md +25 -25
- package/dist/docs/zh/guides/interface.md +18 -14
- package/dist/docs/zh/guides/memory.md +43 -14
- package/dist/docs/zh/guides/sessions.md +30 -24
- package/dist/docs/zh/guides/settings.md +54 -23
- package/dist/docs/zh/index.md +7 -1
- package/dist/docs/zh/reference/command.md +7 -3
- package/dist/docs/zh/reference/keyboard.md +18 -4
- package/dist/docs/zh/reference/model-vocabulary.md +6 -8
- package/dist/docs/zh/reference/slash-commands.md +3 -3
- package/dist/docs/zh/reference/tools.md +74 -9
- package/dist/docs/zh/release-notes/changelog.md +1 -9
- package/dist/docs/zh/server/acp.md +1 -1
- package/dist/docs/zh/server/ide.md +1 -1
- package/dist/docs/zh/server/local-server.md +5 -5
- package/dist/docs/zh/server/mcp.md +2 -2
- package/dist/docs/zh/server/rest-api.md +69 -1
- package/dist/docs/zh/server/sdk.md +2 -2
- package/dist/main.mjs +12545 -3456
- package/dist/web/assets/AppErrorBoundary-RFIAb-Uf.js +1 -0
- package/dist/web/assets/NavScopeBoundary-DY_ET7A-.js +1 -0
- package/dist/web/assets/{arc-y2SkSoyr.js → arc-CMgTB1m7.js} +1 -1
- package/dist/web/assets/{architectureDiagram-3BPJPVTR-uCwLz53m.js → architectureDiagram-3BPJPVTR-BU79ou2C.js} +1 -1
- package/dist/web/assets/{blockDiagram-GPEHLZMM-BZyWv36G.js → blockDiagram-GPEHLZMM-Bkuldod2.js} +1 -1
- package/dist/web/assets/{c4Diagram-AAUBKEIU-DKGx9i50.js → c4Diagram-AAUBKEIU-C3WMeqyu.js} +1 -1
- package/dist/web/assets/channel-DpDZUJRn.js +1 -0
- package/dist/web/assets/{chunk-2J33WTMH-CSkrhrsp.js → chunk-2J33WTMH-CesyWmwo.js} +1 -1
- package/dist/web/assets/{chunk-4BX2VUAB-CtxMoJ68.js → chunk-4BX2VUAB-C7rghYTf.js} +1 -1
- package/dist/web/assets/{chunk-55IACEB6-Dos3ftEy.js → chunk-55IACEB6-BqRHhwtz.js} +1 -1
- package/dist/web/assets/{chunk-727SXJPM-wbzEYK9z.js → chunk-727SXJPM-BhSqCRBc.js} +1 -1
- package/dist/web/assets/{chunk-AQP2D5EJ-B9GKvCD6.js → chunk-AQP2D5EJ-DdYE2ZVZ.js} +1 -1
- package/dist/web/assets/{chunk-FMBD7UC4-u5Y2P6IX.js → chunk-FMBD7UC4-BCRPUxDF.js} +1 -1
- package/dist/web/assets/{chunk-ND2GUHAM-B8rFKkTV.js → chunk-ND2GUHAM-CuvyDjTR.js} +1 -1
- package/dist/web/assets/{chunk-QZHKN3VN-EQsKtuD-.js → chunk-QZHKN3VN-BU5vAS78.js} +1 -1
- package/dist/web/assets/classDiagram-4FO5ZUOK-Bju1GfNu.js +1 -0
- package/dist/web/assets/classDiagram-v2-Q7XG4LA2-Bju1GfNu.js +1 -0
- package/dist/web/assets/client-C0oH7-8r.js +2 -0
- package/dist/web/assets/connection-BhO2nh7P.js +1 -0
- package/dist/web/assets/{cose-bilkent-S5V4N54A-D6dr5mIW.js → cose-bilkent-S5V4N54A-CXrvsA1a.js} +1 -1
- package/dist/web/assets/{dagre-BM42HDAG-Dnyhc4Hn.js → dagre-BM42HDAG-TaAea3Rt.js} +1 -1
- package/dist/web/assets/{diagram-2AECGRRQ-CYXkWdne.js → diagram-2AECGRRQ-CdEH4jGt.js} +1 -1
- package/dist/web/assets/{diagram-5GNKFQAL-DPwBf5Ag.js → diagram-5GNKFQAL-A0jZ_p-T.js} +1 -1
- package/dist/web/assets/{diagram-KO2AKTUF-DNeLYZ8X.js → diagram-KO2AKTUF-miHWORz3.js} +1 -1
- package/dist/web/assets/{diagram-LMA3HP47-zU8RsQTX.js → diagram-LMA3HP47-BlUIwEIg.js} +1 -1
- package/dist/web/assets/{diagram-OG6HWLK6-Cf9Mm94H.js → diagram-OG6HWLK6-DwDzMhEg.js} +1 -1
- package/dist/web/assets/{erDiagram-TEJ5UH35-Ch4CeiUI.js → erDiagram-TEJ5UH35-BJr5w62i.js} +1 -1
- package/dist/web/assets/export-BlxaZKEe.js +2 -0
- package/dist/web/assets/{flowDiagram-I6XJVG4X-Csn6WqEH.js → flowDiagram-I6XJVG4X-BP7KSFjx.js} +1 -1
- package/dist/web/assets/{ganttDiagram-6RSMTGT7-DsuBgEyu.js → ganttDiagram-6RSMTGT7-BstLBBof.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-PVQCEYII-CPA7jCxU.js → gitGraphDiagram-PVQCEYII-C57s7nZ-.js} +1 -1
- package/dist/web/assets/highlighted-body-OFNGDK62-BVb-7KsA.js +1 -0
- package/dist/web/assets/index-69qhvTvD.js +1 -0
- package/dist/web/assets/{index-BYUHmd8w.js → index-BDNM6yJI.js} +2 -2
- package/dist/web/assets/{index-BGgZxlEQ.js → index-BJF_gEDs.js} +2 -2
- package/dist/web/assets/index-BOwMP6BP.js +1 -0
- package/dist/web/assets/{index-C69a5Mcz.js → index-BZsyXCqm.js} +1 -1
- package/dist/web/assets/{index-C7EA7a_g.js → index-Bfl4JiNq.js} +2 -2
- package/dist/web/assets/index-BlD3AKX-.js +1 -0
- package/dist/web/assets/{index-CIymCfcP.js → index-BnvW0EvQ.js} +1 -1
- package/dist/web/assets/index-C4rmWyOm.js +1 -0
- package/dist/web/assets/index-CGLcb3HY.js +1 -0
- package/dist/web/assets/{index-kWBxPqIX.js → index-CPvOeQPX.js} +1 -1
- package/dist/web/assets/index-Cjbe0JKM.js +1 -0
- package/dist/web/assets/index-CmYoJWUm.js +1 -0
- package/dist/web/assets/index-CtUFrjKe.js +1 -0
- package/dist/web/assets/index-DDvDRMTK.js +1 -0
- package/dist/web/assets/index-DSpndwAR.css +1 -0
- package/dist/web/assets/index-D_JjTHxi.js +1 -0
- package/dist/web/assets/index-DbuwcnbT.js +1 -0
- package/dist/web/assets/index-DcXyS0nN.js +1 -0
- package/dist/web/assets/index-Dcl9ruKA.js +1 -0
- package/dist/web/assets/index-DgwALPNA.js +121 -0
- package/dist/web/assets/{index-DoN1FTEe.js → index-DkE8hRT1.js} +2 -2
- package/dist/web/assets/index-DsyRBZ4h.js +1 -0
- package/dist/web/assets/{index-29zav3JI.js → index-DuudNhLL.js} +4 -4
- package/dist/web/assets/index-Gc4F0b2f.js +1 -0
- package/dist/web/assets/index-HGqqwKoV.js +13 -0
- package/dist/web/assets/index-KchrJnno.js +3 -0
- package/dist/web/assets/{index-B0KNSyji.js → index-Tmi2BPYU.js} +1 -1
- package/dist/web/assets/index-Ya4GuDs0.js +1 -0
- package/dist/web/assets/index-_aDaKqLB.js +1 -0
- package/dist/web/assets/index-_qwOAotB.js +1 -0
- package/dist/web/assets/index-hnIkczza.js +7 -0
- package/dist/web/assets/{infoDiagram-5YYISTIA-D3Q__m62.js → infoDiagram-5YYISTIA-CifuVY6C.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-YF4QCWOH-CcvCBuZ5.js → ishikawaDiagram-YF4QCWOH-Cd60vQUi.js} +1 -1
- package/dist/web/assets/{journeyDiagram-JHISSGLW-COZU4LNt.js → journeyDiagram-JHISSGLW-Cb3Xl_wl.js} +1 -1
- package/dist/web/assets/{kanban-definition-UN3LZRKU-BrXjBoAU.js → kanban-definition-UN3LZRKU-Ei6ThuZt.js} +1 -1
- package/dist/web/assets/{linear-BgP1STFi.js → linear-CDZJx-o2.js} +1 -1
- package/dist/web/assets/mermaid-GHXKKRXX-DFxyxD7G.js +331 -0
- package/dist/web/assets/{mindmap-definition-RKZ34NQL-CgjSrE5r.js → mindmap-definition-RKZ34NQL-B0ygxzkx.js} +1 -1
- package/dist/web/assets/navViewState-Ck_HK-TK.js +1 -0
- package/dist/web/assets/{pieDiagram-4H26LBE5-DTfe1sKA.js → pieDiagram-4H26LBE5-B2FdrvDv.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-W4KKPZXB-D95hfh0q.js → quadrantDiagram-W4KKPZXB-CwpOTy3d.js} +1 -1
- package/dist/web/assets/{requirementDiagram-4Y6WPE33-DtSLi7Mh.js → requirementDiagram-4Y6WPE33-ExdZNzLQ.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-5OEKKPKP-gi_dJpcU.js → sankeyDiagram-5OEKKPKP-u0EZKD7D.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-3UESZ5HK-DKQ9a72t.js → sequenceDiagram-3UESZ5HK-BXHMy5DY.js} +1 -1
- package/dist/web/assets/{spaces-B2Ccyh_T.js → spaces-C8n7xQPx.js} +1 -1
- package/dist/web/assets/{stateDiagram-AJRCARHV-Bz7tmSqa.js → stateDiagram-AJRCARHV-DMXx7ell.js} +1 -1
- package/dist/web/assets/stateDiagram-v2-BHNVJYJU-Bydq1_By.js +1 -0
- package/dist/web/assets/theme-BBnHttAf.js +1 -0
- package/dist/web/assets/{timeline-definition-PNZ67QCA-BfMXPwhV.js → timeline-definition-PNZ67QCA-DtqVG_4u.js} +1 -1
- package/dist/web/assets/{vennDiagram-CIIHVFJN-WLxW2KT5.js → vennDiagram-CIIHVFJN-Dom0ex8r.js} +1 -1
- package/dist/web/assets/{wardley-L42UT6IY-DiiqwIdq.js → wardley-L42UT6IY-C-RstmuQ.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-YWT4CUSO-DmCukWuw.js → wardleyDiagram-YWT4CUSO-C8CzNfdf.js} +1 -1
- package/dist/web/assets/{xychartDiagram-2RQKCTM6-Cfq1W2tT.js → xychartDiagram-2RQKCTM6-1AxVTyB6.js} +1 -1
- package/dist/web/index.html +2 -2
- package/native/auth-native/prebuilds/linux-arm64/auth-native.node +0 -0
- package/native/auth-native/prebuilds/linux-x64/auth-native.node +0 -0
- package/native/auth-native/prebuilds/win32-arm64/auth-native.node +0 -0
- package/native/auth-native/prebuilds/win32-x64/auth-native.node +0 -0
- package/package.json +1 -1
- package/dist/web/assets/AppErrorBoundary-DWpgwxFV.js +0 -1
- package/dist/web/assets/NavScopeBoundary-D8Lf1G0U.js +0 -1
- package/dist/web/assets/channel-BGdXootG.js +0 -1
- package/dist/web/assets/classDiagram-4FO5ZUOK-CPcnLy_H.js +0 -1
- package/dist/web/assets/classDiagram-v2-Q7XG4LA2-CPcnLy_H.js +0 -1
- package/dist/web/assets/client-DSIbyfoz.js +0 -2
- package/dist/web/assets/connection-DYZn9oPZ.js +0 -1
- package/dist/web/assets/export-Bq8ZECqX.js +0 -2
- package/dist/web/assets/highlighted-body-OFNGDK62-CDPBxM_E.js +0 -1
- package/dist/web/assets/index-AksnytJj.js +0 -1
- package/dist/web/assets/index-B8xhhYDh.css +0 -1
- package/dist/web/assets/index-BUrlrKap.js +0 -1
- package/dist/web/assets/index-B_5-HLed.js +0 -62
- package/dist/web/assets/index-BfmoxdpP.js +0 -1
- package/dist/web/assets/index-Bo3e-ohM.js +0 -3
- package/dist/web/assets/index-BrYV9gV_.js +0 -1
- package/dist/web/assets/index-C8XUtAvK.js +0 -1
- package/dist/web/assets/index-C9uil5my.js +0 -13
- package/dist/web/assets/index-CKpWHSp9.js +0 -1
- package/dist/web/assets/index-CLKBgQxV.js +0 -1
- package/dist/web/assets/index-CTyyUNWj.js +0 -7
- package/dist/web/assets/index-D7cg9qYZ.js +0 -1
- package/dist/web/assets/index-D7dg8R_q.js +0 -1
- package/dist/web/assets/index-DCSpedV_.js +0 -1
- package/dist/web/assets/index-DLbD0Nx5.js +0 -1
- package/dist/web/assets/index-DaEzbvvu.js +0 -1
- package/dist/web/assets/index-DhbcjMZF.js +0 -1
- package/dist/web/assets/index-Dw2h88mF.js +0 -1
- package/dist/web/assets/index-FcMtfmKv.js +0 -1
- package/dist/web/assets/index-XFq9Kgg0.js +0 -1
- package/dist/web/assets/index-iI2mM43w.js +0 -1
- package/dist/web/assets/index-oXOF7lko.js +0 -1
- package/dist/web/assets/locale-CANfezJ4.js +0 -17
- package/dist/web/assets/mermaid-GHXKKRXX-_JLagMll.js +0 -321
- package/dist/web/assets/navViewState-DS5LnMYc.js +0 -1
- package/dist/web/assets/settings-CcwMWXbp.js +0 -42
- package/dist/web/assets/stateDiagram-v2-BHNVJYJU-D6-wdUbw.js +0 -1
- package/dist/web/assets/theme-DlDhDxeD.js +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{h as s,i as v,_ as h,j as H,k as M,l as y,n as l,m as S,o as c,u as $,t as d,q as us,v as ps,x as w,y as st,z as ne,E as ms,F as C,G as Ie,H as hs,I as gs,J as vs,K as Ss,L as Nt,M as fs,N as Lt,O as ys,P as bs,Q as _s,R as Is,T as Ts,U as ws,V as Es,W as We,X as Ke,Y as wo,Z as Eo,$ as ks,a0 as Cs,a1 as Rs,a2 as Ps,a3 as le,a4 as Os,a5 as As,a6 as Ms,a7 as Us,a8 as xs,a9 as Ds,aa as Ns,ab as Ls,ac as js,ad as qs,ae as Gs,af as jt,ag as $s,ah as Fs,ai as Le,aj as Bs,ak as Vs,al as qt,am as Hs,an as ze,ao as Ws,ap as Ks,aq as zs,ar as Qe,as as Qs,at as F,au as Ys,av as Xs,aw as Js,ax as Zs,ay as ei,az as ti,aA as oi,aB as ni,aC as V,aD as si,aE as ii,aF as ri,aG as ai,aH as ci,aI as Ye,aJ as di,aK as li,aL as ko,aM as Co,aN as Ro,aO as ui,aP as pi,aQ as Te,aR as Po,aS as Ge,aT as mi,aU as hi,aV as gi,aW as vi,aX as Si,aY as fi,aZ as yi,a_ as bi,a$ as _i,b0 as Ii,b1 as Ti,b2 as wi,b3 as Ei,b4 as ki,b5 as Ci,b6 as Ri,b7 as Pi,b8 as Gt,b9 as $t,ba as Oi,bb as Ai,bc as Mi,bd as Ui,be as xi,bf as Di,bg as Ni,bh as Li,bi as ji,bj as qi,bk as Oo,bl as Ao,bm as Mo,bn as Gi,bo as Uo,bp as xo,bq as $i,br as Xe,bs as Fi,bt as Ee,bu as Bi,bv as Vi,bw as ue,bx as Hi,by as Q,bz as Ft,bA as Wi,bB as Je,bC as Ki,bD as zi,bE as Qi,bF as Bt,bG as Yi,bH as Xi,bI as Ji,bJ as Zi,bK as er,bL as Vt,bM as tr,bN as or,bO as nr,bP as sr,bQ as ir}from"./settings-CcwMWXbp.js";import{t as Ht}from"./locale-CANfezJ4.js";const Wt={off:0,turn:1,block:2,delta:3};function Kt(o,e){return o?o[e]??o["*"]??"off":"off"}function rr(o,e){const t=e.path[0];if(e.path.length!==1||!(e.source.kind==="frame"&&(t==="input"||t==="output")||e.source.kind==="task"&&t==="outputTail"))return;const n=JSON.stringify([o,e.source.kind,e.source.id,e.source.turnId??"",e.source.stepId??"",t,e.revision]),r=new TextEncoder().encode(n);let a="";for(const i of r)a+=String.fromCharCode(i);return`raw:${btoa(a).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}`}const ar={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"],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}"],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"],usagePricing:["GET","/usage/pricing"],usageRescanStatus:["GET","/usage/rescan"],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"],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"]},cr=o=>!o||o==="."||o===".."||o.includes("/")||o.includes("\\");function dr(o,e){const t=Object.entries(ar).toSorted((n,r)=>(n[1][1].match(/\{/g)?.length??0)-(r[1][1].match(/\{/g)?.length??0));for(const[n,[r,a]]of t){if(r!==o)continue;const i=[],u=a.split(/(\{[A-Za-z]+\})/).map(f=>f.startsWith("{")?(i.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 g=!0;for(let f=0;f<i.length;f+=1){let b;try{b=decodeURIComponent(m[f+1])}catch{g=!1;break}if(cr(b)){g=!1;break}p[i[f]]=b}if(g)return{operation:n,params:p}}}function lr(o){if(o!==void 0)return o;const e=()=>{throw new Error("terminal capability is unsupported on this transport")},t=async()=>e();return{listTerminals:t,createTerminal:t,getTerminal:t,closeTerminal:t,terminalAttach:t,terminalDetach:e,terminalInput:e,terminalResize:e,onTerminalSignal:e,onStatus:e,nudge:e}}const O=s().min(1).max(512),yt=s().min(1).max(4096),je=v(O).max(256),qe=h(["active","in_progress","paused","done","cancelled","superseded"]),ye=H({root:yt,storageId:O,kind:h(["workspace","embedded"])}),ur=H({root:yt,storageId:O.optional(),kind:h(["workspace","embedded"])}),pr=H({mode:h(["auto","global","fixed"]),path:s().trim().max(4096).refine(o=>!/[\u0000-\u001F]/u.test(o),"Storage path contains control characters.").optional()}).refine(o=>o.mode!=="fixed"||!!o.path,{message:"Fixed storage requires a path.",path:["path"]}),mr=H({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:je.optional(),executionIds:je.optional(),status:qe.optional()}).refine(o=>Object.keys(o).length>0,"An update requires a changed field."),hr=M("action",[H({action:y("preview"),workspaceId:O.optional(),configuration:pr.optional()}),H({action:y("list"),workspaceId:O.optional(),storage:ye.optional(),sessionId:O.optional(),status:qe.optional(),archived:S().optional(),cursor:O.optional(),limit:l().int().min(1).max(100).optional()}),H({action:y("show"),workspaceId:O,storage:ye,id:O}),H({action:y("overview"),workspaceIds:v(O).min(1).max(32),status:qe.optional(),limit:l().int().min(1).max(100).optional()})]),gr=M("action",[H({action:y("create"),workspaceId:O.optional(),requestKey:O,target:ur.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:je.optional(),executionIds:je.optional()}),H({action:y("update"),workspaceId:O,storage:ye,id:O,expectedRevision:l().int().nonnegative().max(Number.MAX_SAFE_INTEGER),patch:mr})]),Do=c({id:O,workspaceId:O,storage:ye,title:s(),priority:s(),status:qe,revision:l().int().nonnegative(),createdAt:s(),updatedAt:s(),completedAt:s().nullable(),archived:S(),category:s(),sessionIds:v(s()),executionIds:v(s())}),No=Do.extend({description:s(),prd:s(),handoff:s().optional()}),Lo=c({code:s(),message:s()}),$e=o=>M("ok",[c({ok:y(!0),value:o}),c({ok:y(!1),error:Lo})]),jo=c({workspaceId:O,storage:ye.optional(),cards:v(Do),issues:v(Lo),nextCursor:s().optional()}),vr=c({mode:h(["auto","global","fixed"]),workspaceId:O,root:yt,tasksDirectory:s(),existing:S(),kind:h(["workspace","embedded"]),storageId:O.optional(),selectionOnly:y(!0)}),qo=c({workspaceId:O,result:$e(jo)}),Sr=$e($([No,jo,vr,v(qo)])),fr=$e(No),yr=$e(v(qo)),br={read:{input:d([hr]),output:Sr},write:{input:d([gr]),output:fr},overview:{input:d([]),output:yr}},_r={read:{input:d([us]),output:ps}},Ir=h(["running","streaming","tool_call","retrying"]),Tr=c({approvalId:s(),toolCallId:s().optional(),since:l()}),wr=c({toolCallId:s(),name:s(),since:l()}),Er=c({failedAttempt:l(),nextAttempt:l(),maxAttempts:l(),delayMs:l(),errorName:s().optional(),statusCode:l().optional()}),kr=c({turnId:l(),origin:w(),phase:Ir,stream:h(["assistant","thinking","tool_call"]).optional(),step:l(),ending:S(),endingReason:h(["aborted","max_steps","error"]).optional(),retry:Er.optional(),pendingApprovals:v(Tr),activeToolCalls:v(wr),since:l()}),Cr=h(["completed","cancelled","failed","blocked"]),Rr=c({turnId:l(),reason:Cr,durationMs:l().optional(),at:l()}),Pr=c({kind:s(),id:s(),since:l()}),Or=h(["ready","disposed"]),Ar=c({lifecycle:Or,turn:kr.optional(),lastTurn:Rr.optional(),background:v(Pr)}),Mr={state:{input:d([]),output:Ar}},Ur=o=>c({items:v(o),nextCursor:s().optional()}),A=o=>$([o,ne(),ms()]).transform(e=>e??void 0),_=$([st(),ne()]).transform(()=>{}),zt=c({added:v(s()),removed:v(s()),changed:v(s())}),bt=C(s(),s()),Qt=l().int().min(1).max(2147483647),_t={enabled:S().optional(),startupTimeoutMs:Qt.optional(),toolTimeoutMs:Qt.optional(),enabledTools:v(s()).optional(),disabledTools:v(s()).optional()},It=c({transport:y("stdio"),runtime_id:s().min(1).optional(),command:s().min(1),args:v(s()).optional(),env:bt.optional(),cwd:s().optional(),executor:h(["local","kaos"]).optional(),..._t}),Tt=c({transport:y("http"),url:s().url(),headers:bt.optional(),auth:y("oauth").optional(),bearerTokenEnvVar:s().min(1).optional(),..._t}),wt=c({transport:y("sse"),url:s().url(),headers:bt.optional(),auth:y("oauth").optional(),bearerTokenEnvVar:s().min(1).optional(),..._t}),Fe=M("transport",[It,Tt,wt]),Et=h(["direct","compact","fresh"]),it=c({operationId:s().min(1),model:s().min(1),mode:Et,thinking:s().optional(),selectedFromModel:s().optional()}),te=c({operationId:s(),agentId:s(),state:h(["pending","preparing","completed","failed","cancelled"]),fromModel:s(),toModel:s(),mode:Et,binding:c({model:s(),thinking:s()}).optional(),windowEpoch:l().int().nonnegative().optional(),summaryGenerated:S().optional(),error:c({code:s(),message:s()}).optional()}),Go=c({input:it,receipt:te,revision:l().int().nonnegative(),originalBinding:c({model:s(),thinking:s()}),queueIndex:l().int()}),xr=c({type:y("prompt.model_switch_queued"),time:l().optional(),entry:Go.omit({queueIndex:!0}),queueIndex:l().int().nonnegative()}),Dr=c({type:y("prompt.model_switch_status"),time:l().optional(),operationId:s(),receipt:te}),Nr=c({type:y("turn.step.started"),time:l().optional(),turnId:l(),step:l(),stepId:s().optional()}),Lr=c({type:y("turn.step.interrupted"),time:l().optional(),turnId:l(),step:l(),stepId:s().optional(),reason:s(),message:s().optional()}),jr=c({type:y("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()}),qr=c({type:y("hook.result"),time:l().optional(),turnId:l().optional(),hookEvent:s(),content:s(),blocked:S().optional()}),X=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:S(),turnBudgetReached:S(),wallClockBudgetReached:S(),overBudget:S()})}),Gr=c({type:y("goal.updated"),time:l().optional(),snapshot:X.nullable(),change:c({kind:h(["lifecycle","completion"]),status:X.shape.status.optional(),reason:s().optional(),actor:h(["user","model","runtime","system"]).optional(),stats:c({turnsUsed:l(),tokensUsed:l(),wallClockMs:l()}).optional()}).optional()}),$r=c({type:y("turn.started"),time:l().optional(),turnId:l(),origin:w(),prompt:s().optional(),promptId:s().optional()}),Fr=c({type:y("turn.ended"),time:l().optional(),turnId:l(),reason:h(["completed","cancelled","failed","blocked"]),error:w().optional(),durationMs:l().optional(),interruptReason:h(["user_cancelled","aborted","max_steps","error","filtered","blocked"]).optional()}),Br=c({type:y("assistant.delta"),time:l().optional(),turnId:l(),delta:s()}),Vr=c({type:y("thinking.delta"),time:l().optional(),turnId:l(),delta:s()}),Hr=c({type:y("tool.call.started"),time:l().optional(),turnId:l(),toolCallId:s(),name:s(),args:w(),description:s().optional(),display:w().optional()}),Wr=c({type:y("tool.call.delta"),time:l().optional(),turnId:l(),toolCallId:s(),name:s().optional(),argumentsPart:s().optional()}),Kr=c({type:y("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:w().optional(),replace:S().optional()})}),zr=c({type:y("tool.result"),time:l().optional(),turnId:l(),toolCallId:s(),output:w(),isError:S().optional(),synthetic:S().optional()}),Be=w(),kt=h(["agent_idle","subagents_done","tasks_done"]),Qr=c({type:y("prompt.submitted"),time:l().optional(),promptId:s(),userMessageId:s(),status:h(["running","queued","blocked"]),content:v(Be),createdAt:s(),appendTiming:kt.optional(),revision:l().int().nonnegative().optional()}),Yr=c({type:y("prompt.queued"),time:l().optional(),promptId:s(),content:v(Be),queueLength:l().int().nonnegative(),appendTiming:kt.optional(),revision:l().int().nonnegative().optional()}),Xr=c({type:y("prompt.started"),time:l().optional(),promptId:s()}),Jr=c({type:y("prompt.replaced"),time:l().optional(),promptId:s(),content:v(Be),replacedAt:s(),message:w().optional(),revision:l().int().nonnegative().optional()}),Zr=c({type:y("prompt.timing_changed"),time:l().optional(),promptId:s(),appendTiming:kt,revision:l().int().nonnegative(),changedAt:s()}),ea=c({type:y("prompt.steered"),time:l().optional(),activePromptId:s(),promptIds:v(s()),content:v(Be),steeredAt:s()}),ta=c({type:y("prompt.completed"),time:l().optional(),promptId:s(),finishedAt:s(),reason:h(["completed","failed","blocked"]).optional()}),oa=c({type:y("prompt.aborted"),time:l().optional(),promptId:s(),abortedAt:s(),beforeStart:S().optional()}),na=c({type:y("prompt.moved"),time:l().optional(),promptId:s(),targetIndex:l().int().nonnegative(),queuedPromptIds:v(s()),movedAt:s()}),sa=c({type:y("compaction.started"),time:l().optional(),trigger:h(["manual","auto"]),instruction:s().optional()}),ia=c({type:y("compaction.blocked"),time:l().optional(),turnId:l().optional()}),ra=c({type:y("compaction.cancelled"),time:l().optional()}),aa=c({type:y("compaction.completed"),time:l().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:v(s()).optional(),fallbackFrom:h(["relay","summarize"]).optional()})}),ca=Ie({time:l().optional(),turnId:l(),toolCallId:s(),toolName:s(),action:s()}),da=Ie({time:l().optional(),turnId:l(),toolCallId:s()}),la=Ie({time:l().optional(),message:s()}),ua=c({type:y("warning"),time:l().optional(),message:s(),code:s().optional()}),pa=Ie({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()}),ma={"prompt.model_switch_queued":{kind:"stream",name:"events",type:"prompt.model_switch_queued",schema:xr},"prompt.model_switch_status":{kind:"stream",name:"events",type:"prompt.model_switch_status",schema:Dr},"turn.step.started":{kind:"stream",name:"events",type:"turn.step.started",schema:Nr},"turn.step.interrupted":{kind:"stream",name:"events",type:"turn.step.interrupted",schema:Lr},"turn.step.retrying":{kind:"stream",name:"events",type:"turn.step.retrying",schema:jr},"hook.result":{kind:"stream",name:"events",type:"hook.result",schema:qr},"goal.updated":{kind:"stream",name:"events",type:"goal.updated",schema:Gr},"turn.started":{kind:"stream",name:"events",type:"turn.started",schema:$r},"turn.ended":{kind:"stream",name:"events",type:"turn.ended",schema:Fr},"assistant.delta":{kind:"stream",name:"events",type:"assistant.delta",schema:Br},"thinking.delta":{kind:"stream",name:"events",type:"thinking.delta",schema:Vr},"tool.call.started":{kind:"stream",name:"events",type:"tool.call.started",schema:Hr},"tool.call.delta":{kind:"stream",name:"events",type:"tool.call.delta",schema:Wr},"tool.progress":{kind:"stream",name:"events",type:"tool.progress",schema:Kr},"tool.result":{kind:"stream",name:"events",type:"tool.result",schema:zr},"prompt.submitted":{kind:"stream",name:"events",type:"prompt.submitted",schema:Qr},"prompt.queued":{kind:"stream",name:"events",type:"prompt.queued",schema:Yr},"prompt.started":{kind:"stream",name:"events",type:"prompt.started",schema:Xr},"prompt.replaced":{kind:"stream",name:"events",type:"prompt.replaced",schema:Jr},"prompt.moved":{kind:"stream",name:"events",type:"prompt.moved",schema:na},"prompt.timing_changed":{kind:"stream",name:"events",type:"prompt.timing_changed",schema:Zr},"prompt.steered":{kind:"stream",name:"events",type:"prompt.steered",schema:ea},"prompt.completed":{kind:"stream",name:"events",type:"prompt.completed",schema:ta},"prompt.aborted":{kind:"stream",name:"events",type:"prompt.aborted",schema:oa},"compaction.started":{kind:"stream",name:"events",type:"compaction.started",schema:sa},"compaction.blocked":{kind:"stream",name:"events",type:"compaction.blocked",schema:ia},"compaction.cancelled":{kind:"stream",name:"events",type:"compaction.cancelled",schema:ra},"compaction.completed":{kind:"stream",name:"events",type:"compaction.completed",schema:aa},"permission.approval.requested":{kind:"stream",name:"events",type:"permission.approval.requested",schema:ca},"permission.approval.resolved":{kind:"stream",name:"events",type:"permission.approval.resolved",schema:da},error:{kind:"stream",name:"events",type:"error",schema:la},warning:{kind:"stream",name:"events",type:"warning",schema:ua},"agent.status.updated":{kind:"stream",name:"events",type:"agent.status.updated",schema:pa}},ha=c({type:y("text"),text:s()}),ga=c({type:y("image_url"),imageUrl:c({url:s(),id:s().optional()})}),va=c({type:y("video_url"),videoUrl:c({url:s(),id:s().optional()})}),$o=M("type",[ha,ga,va]);c({});const Sa=c({afterModelSwitch:s().min(1).optional(),personaGreetingReply:S().optional(),profile:s().optional(),model:s().optional(),thinking:s().optional(),planMode:S().optional(),goalObjective:s().optional(),goalFollowUpTiming:h(["subagents_done","tasks_done"]).optional(),goalInitialStatus:h(["active","paused"]).optional(),goalControl:h(["pause","resume","cancel"]).optional()}),rt=c({input:v($o),execution:Sa.optional(),appendTiming:h(["agent_idle","subagents_done","tasks_done"]).optional(),disabledTools:v(s()).optional(),promptId:s().min(1).optional()}),fa=c({name:s(),args:s().optional()}),ya=rt.extend({skills:v(fa).min(1)}),ba=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()}),_a=c({input:v($o)}),Ia=c({name:s(),args:s().optional()}),at=c({turn_id:l()}),ct=c({code:s(),message:s(),name:s().optional(),details:C(s(),w()).optional(),retryable:S(),get cause(){return ct.optional()}}),Ta=c({promptId:s(),turnId:l().optional(),state:h(["completed","failed","cancelled","blocked"]),result:M("type",[c({type:y("completed"),steps:l(),truncated:S()}),c({type:y("failed"),steps:l(),error:ct}),c({type:y("cancelled"),steps:l(),reason:ct})]).optional()});c({turnId:l().optional()});const wa=c({command:s(),commandId:s().optional()}),Ea=c({stdout:s(),stderr:s(),isError:S().optional(),backgrounded:S().optional()});c({commandId:s()});c({model:s()});const ka=c({model:s(),providerName:s().optional()});c({effort:s().min(1)});const Ca=c({effort:s()}),Ra=c({rebuilt:v(h(["profile","prompt_fields","skills","instructions","plugins","injections"])),changed:S(),changes:c({profile:S(),promptFields:S(),skills:S(),instructions:S(),plugins:S(),injections:S()})}),Fo=h(["summarize","auto","fresh"]),Pa=c({strategy:Fo,source:h(["session","profile","global","default","subagent","executor"]),shadow:S()}),ke=c({workspaceId:s(),runtimeId:s()}),Oa=c({image_in:S(),video_in:S(),audio_in:S(),thinking:S(),tool_use:S(),max_context_tokens:l(),max_input_tokens:l().optional(),dynamically_loaded_tools:S().optional()}),xe=h(["manual","auto","review","yolo"]);c({mode:xe});const Aa=c({state:h(["idle","running"]),activeTurnId:l().optional(),pendingTurnIds:v(l()),hasPendingRequests:S(),activeTraceId:s().optional()}),De=c({inputOther:l(),output:l(),inputCacheRead:l(),inputCacheCreation:l()}),Ma=c({byModel:C(s(),De).optional(),currentTurn:De.optional(),total:De.optional()});c({history:v(w()),tokenCount:l()});const Ua=c({name:s(),description:s().optional(),source:s()});c({name:s(),args:s().optional()});const xa=$([ne(),c({id:s(),content:s(),path:s()})]);c({id:s().optional()});c({activeOnly:S().optional(),limit:l().optional()});const Da=h(["running","completed","failed","timed_out","killed","lost"]),Ce={taskId:s(),description:s(),status:Da,detached:S().optional(),startedAt:l(),endedAt:$([l(),ne()]),stopReason:s().optional(),terminalNotificationSuppressed:S().optional(),timeoutMs:l().optional(),receipt:hs.optional(),receiptVerification:h(["verified","legacy_unverified","invalid"]).optional()},Re=M("kind",[c({kind:y("process"),command:s(),pid:l(),exitCode:$([l(),ne()]),...Ce}),c({kind:y("agent"),agentId:s().optional(),profile:s().optional(),model:s().optional(),thinkingEffort:s().optional(),...Ce}),c({kind:y("question"),questionCount:l(),toolCallId:s().optional(),...Ce}),c({kind:y("media"),jobId:s(),...Ce})]);c({taskId:s(),reason:s().optional()});c({taskId:s(),tail:l().optional()});const Na={getGoal:{input:d([]),output:c({goal:X.nullable()})},createGoal:{input:d([c({objective:s(),completionCriterion:s().optional(),followUpTiming:h(["subagents_done","tasks_done"]).optional(),initialStatus:h(["active","paused"]).optional(),replace:S().optional()})]),output:X},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()})]),output:X},pauseGoal:{input:d([]),output:X},resumeGoal:{input:d([c({reason:s().optional(),continueIfPaused:S().optional(),continueIfBlocked:S().optional()}).optional()]),output:X},cancelGoal:{input:d([]),output:X}},La={switchModel:{input:d([it]),output:te},getModelSwitch:{input:d([s()]),output:A(te)},listModelSwitches:{input:d([]),output:v(Go)},updateModelSwitch:{input:d([it,l().int().nonnegative().optional()]),output:te},cancelModelSwitch:{input:d([s()]),output:te},recoverModelSwitch:{input:$([d([s(),y("retry"),Et.optional()]),d([s(),y("keep_original")])]),output:te},submit:{input:d([rt]),output:A(at)},submitAndWait:{input:d([rt]),output:Ta},submitSteer:{input:d([_a]),output:A(at)},resumeRecoveredQueue:{input:d([]),output:_}},ja={activate:{input:d([Ia]),output:at},promptWithSkills:{input:d([ya]),output:ba}},qa={reconcileWhenIdle:{input:d([s()]),output:_}},Ga={rebuild:{input:d([]),output:Ra}},$a={undo:{input:d([l().int().positive().max(Number.MAX_SAFE_INTEGER)]),output:l()}},Fa={activate:{input:d([c({pluginId:s(),commandName:s(),args:s().optional()})]),output:_}},Ba={refreshSessionStart:{input:d([]),output:_}},Va={cancelFromUser:{input:d([l().optional()]),output:_},status:{input:d([]),output:Aa}},Ha={mode:{input:d([]),output:xe},setMode:{input:d([xe]),output:_},setModeAndBroadcast:{input:d([xe]),output:_}},Wa={list:{input:d([]),output:v(Ua)},run:{input:d([s(),s().optional()]),output:_}},Ka={get:{input:d([]),output:ke},set:{input:d([ke]),output:ke},switch:{input:d([s()]),output:ke}},za={get:{input:d([]),output:v(w())},append:{input:d([w()]),output:_},clear:{input:d([]),output:_}},Qa={appendImported:{input:d([w()]),output:_}},Ya={statusSize:{input:d([]),output:l()}},Xa={run:{input:d([wa]),output:Ea},cancel:{input:d([s()]),output:_}},Ja={getModel:{input:d([]),output:s()},setModel:{input:d([s()]),output:ka},setEffort:{input:d([s()]),output:Ca},setThinking:{input:d([s()]),output:_},getEffectiveThinkingLevel:{input:d([]),output:s()},getModelCapabilities:{input:d([]),output:Oa},getAgentsMdWarning:{input:d([]),output:A(s())}},Za={status:{input:d([]),output:Ma}},ec={status:{input:d([]),output:xa},enter:{input:d([]),output:_},clear:{input:d([]),output:_},cancel:{input:d([s().optional()]),output:_}},tc=c({name:s(),transport:h(["stdio","http","sse"]),status:h(["pending","connected","failed","disabled","needs-auth","removed"]),toolCount:l(),error:s().optional()}),oc={list:{input:d([]),output:v(tc)},waitForInitialLoad:{input:d([]),output:_},initialLoadDurationMs:{input:d([]),output:l()},reconnect:{input:d([s()]),output:_},connect:{input:d([s(),Fe]),output:_}},nc=c({source:h(["manual","auto"]),instruction:s().optional()}),sc={begin:{input:d([nc]),output:S()},cancel:{input:d([]),output:_},isCompacting:{input:d([]),output:S()},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:Pa},setContextStrategyOverride:{input:d([Fo.nullable()]),output:_}},ic={list:{input:d([S().optional(),l().optional()]),output:v(Re)},stopByUser:{input:d([s()]),output:A(Re)},stop:{input:d([s(),s().optional()]),output:A(Re)},detach:{input:d([s()]),output:A(Re)},readOutput:{input:d([s(),l().optional()]),output:s()}},Bo=h(["pending","authenticated","denied","failed","expired","cancelled"]),rc=M("status",[c({flow_id:s(),provider:s(),status:y("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:y("authenticated")})]),ac=c({flow_id:s(),provider:s(),status:Bo,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()}),cc=c({cancelled:S(),status:Bo}),dc=c({logged_out:y(!0),provider:s()}),Vo=c({loggedIn:S(),provider:s().optional()}),lc=c({changed:v(c({provider_id:s(),provider_name:s(),added:l(),removed:l()})),unchanged:v(s()),failed:v(c({provider:s(),reason:s()}))}),uc=c({region:h(["mainland-cn","global"]).optional()}),pc=c({id:s(),label:s(),provider:s(),protocol:s(),signed_in:S(),auth_source:gs.optional(),connection_state:h(["ready","refresh_required","reconnect_required","signed_out"]).optional(),account:M("state",[c({state:y("known"),id:s()}),c({state:y("unknown")})]),quota:M("state",[c({state:y("known"),label:s(),remaining:l(),unit:h(["count","percent"]),reset_at:s().optional()}),c({state:y("unknown")})])}),mc={probeOriginal:{input:d([Ss]),output:Nt},connectOriginal:{input:d([vs]),output:Nt},listMethods:{input:d([]),output:v(pc)},startLogin:{input:d([s().optional(),uc.optional()]),output:rc},getFlow:{input:d([s().optional()]),output:A(ac)},cancelLogin:{input:d([s().optional()]),output:cc},logout:{input:d([s().optional()]),output:dc},status:{input:d([s().optional()]),output:Vo},refreshOAuthProviderModels:{input:d([]),output:lc}},hc={summarize:{input:d([]),output:v(Vo)},ensureReady:{input:d([s().optional()]),output:_}},gc=c({id:s(),state:h(["ok","missing","failed"]),reason:s().optional(),detail:s().optional(),optional:S().optional()}),vc=c({running:S(),step:s().optional(),percent:l().optional(),error:s().optional(),note:s().optional()}),Ze=c({id:h(["kimi-cu","kimi-webbridge","kiki-computer"]),pluginId:s().optional(),displayName:s(),description:s(),supported:S(),state:h(["not_installed","partial","ready","unsupported"]),version:s().optional(),steps:v(gc),plan:c({artifact:c({version:s(),url:s(),sha256:s(),metadataUrl:s(),maxBytes:l()}),destination:s(),browserExtensionUrl:s().optional(),note:s()}).optional(),install:vc}),Sc={listCapabilities:{input:d([]),output:v(Ze)},getCapability:{input:d([s()]),output:Ze},installCapability:{input:d([s(),s().optional()]),output:Ze}},Yt=new Map,fc=new Set;function T(o){for(const e of Object.values(o.codes)){const t=Yt.get(e);if(t!==void 0&&t!==o.codes)throw new Error(`error code '${e}' is registered by two different domains`);Yt.set(e,o.codes)}for(const e of o.retryable??[])fc.add(e);for(const[e,t]of Object.entries(o.info??{}));}const Ho={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."}}};T(Ho);const Wo={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."}}};T(Wo);const yc=/^(?:[a-z][a-z0-9_]{0,31}|custom:[a-z0-9][a-z0-9_-]{0,47})$/u,Ko=h(["codex_compatible","claude_code_compatible","grok_build_compatible","opencode_compatible","kimi_code","none"]),zo=s().regex(yc),Qo=M("mode",[c({mode:y("none")}).strict(),c({mode:y("codex_default")}).strict(),c({mode:y("custom"),value:s().min(1).refine(o=>!/[\u0000-\u001F\u007F]/u.test(o))}).strict()]),bc=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:Qo.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(Rt,{message:"request identity overrides must contain a leaf value"}),Ct=c({preset:Ko.optional(),profile:zo.optional(),overrides:bc.optional()}).strict().refine(Yo,{message:"request identity policy must contain preset, profile or overrides"}).refine(o=>o.preset===void 0||o.profile===void 0,{message:"request identity policy cannot set both preset and profile"}),_c=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:Qo.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(Rt,{message:"request identity overrides must contain a leaf value"});c({preset:Ko.optional(),profile:zo.optional(),overrides:_c.optional()}).strict().refine(Yo,{message:"request identity policy must contain preset, profile or overrides"}).refine(o=>o.preset===void 0||o.profile===void 0,{message:"request identity policy cannot set both preset and profile"});function Yo(o){return o.preset!==void 0||o.profile!==void 0||o.overrides!==void 0}function Rt(o){return o===void 0?!1:o===null||typeof o!="object"?!0:Object.values(o).some(Rt)}h(["connected","error","unconfigured"]);const Ic=c({systemPrompt:s(),messages:v(w()),tools:v(w()).optional(),responseFormat:w().optional()}),Tc=c({cacheKey:s().optional(),temperature:l().optional(),topP:l().optional(),thinkingEffort:s().optional(),maxCompletionTokens:l().optional()}).optional(),wc=c({type:s()}).passthrough(),Ec={listModels:{input:d([]),output:v(ys)},listProviders:{input:d([]),output:v(Lt)},getProvider:{input:d([s()]),output:Lt},setDefaultModel:{input:d([s()]),output:fs},generate:{input:d([s(),Ic,Tc]),chunk:wc,streaming:!0}},kc=c({scope:h(["all","oauth"]).optional(),providerId:s().optional(),apiKey:s().min(1).optional()}),Cc={listDiscoveredModels:{input:d([]),output:_s},refreshProviderModels:{input:d([kc.optional()]),output:bs}},Pt=h(["user","memory"]),Rc=c({value:w().optional(),defaultValue:w().optional(),userValue:w().optional(),memoryValue:w().optional()}),Pc=c({domain:s().optional(),severity:h(["warning","error"]),message:s()}),Oc=d([s(),w(),Pt.optional()]).superRefine(([o,e],t)=>{o==="requestIdentity"&&Ot(e,t,[1],!1)}),Ac=d([s(),w(),Pt.optional()]).superRefine(([o,e],t)=>{o==="requestIdentity"&&Ot(e,t,[1],!0)}),Mc=d([C(s(),w()),Pt.optional()]).superRefine(([o],e)=>{Object.hasOwn(o,"requestIdentity")&&Ot(o.requestIdentity,e,[0,"requestIdentity"],!0)});function Ot(o,e,t,n){if(n&&o==null)return;const r=Ct.safeParse(o);if(!r.success)for(const a of r.error.issues)e.addIssue({...a,path:[...t,...a.path]})}const Uc={get:{input:d([s()]),output:w()},inspect:{input:d([s()]),output:Rc},getAll:{input:d([]),output:C(s(),w())},set:{input:Oc,output:_},replace:{input:Ac,output:_},replaceSections:{input:Mc,output:_},reload:{input:d([]),output:_},diagnostics:{input:d([]),output:v(Pc)}},j={input:d([]),output:s()},xc={input:d([]),output:c({productName:s(),version:s(),platform:s(),userAgentSuffix:s().optional()})},Dc={platform:j,arch:j,cwd:j,osHomeDir:j,homeDir:j,configPath:j,clientVersion:j,clientIdentity:xc,sessionsDir:j,blobsDir:j,storeDir:j,cacheDir:j,logsDir:j},Xo=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()}),Nc=c({name:s().optional(),mimeType:s().optional(),expiresInSec:l().optional()}),Lc=c({meta:Xo,data:s()}),jc={save:{input:d([s(),s().min(1),Nc]),output:Xo},get:{input:d([s().min(1)]),output:Lc},delete:{input:d([s().min(1)]),output:_}},Xt=c({id:s(),title:s(),description:s(),surface:h(["core","tui","both"]),env:s(),defaultEnabled:S(),enabled:S(),source:h(["master-env","env","config","default"]),configValue:S().optional()}),qc={enabled:{input:d([s()]),output:S()},snapshot:{input:d([]),output:C(s(),S())},enabledIds:{input:d([]),output:v(s())},explain:{input:d([s()]),output:A(Xt)},explainAll:{input:d([]),output:v(Xt)}},Gc=c({name:s().min(1),path:s().min(1),is_dir:y(!0)}),$c=c({path:s().min(1),parent:s().min(1).nullable(),entries:v(Gc)}),Fc=c({home:s().min(1),recent_roots:v(s().min(1))}),Bc={browse:{input:d([s().optional()]),output:$c},home:{input:d([]),output:Fc}},Vc=h(["openai-codex","grok-build"]),Hc=h(["file","keyring","encrypted"]),Wc=c({kind:y("local_original"),provider:Vc,homeDir:s().min(1),storageBackend:Hc,authFile:s().min(1).optional(),accountId:s().min(1),userId:s().min(1).optional(),scope:s().min(1).optional()}).strict(),Jo=c({storage:h(["file","keyring"]),key:s().min(1),oauthHost:s().min(1).optional(),source:Wc.optional()}),Kc=h(["anthropic","openai","openai_responses","google-genai"]),Zo=c({providerId:s().optional(),baseUrl:s().optional(),apiKey:s().optional(),oauth:Jo.optional(),protocol:Kc.optional(),name:s().optional(),aliases:v(s()).optional(),provider:s().optional(),model:s().optional(),maxContextSize:l().int().min(1).optional(),maxOutputSize:l().int().min(1).optional(),capabilities:v(s()).optional(),displayName:s().optional(),reasoningKey:s().optional(),adaptiveThinking:S().optional(),betaApi:S().optional(),supportEfforts:v(s()).optional(),defaultEffort:s().optional(),requestIdentity:Ct.optional()}),zc=Zo.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=Zo.extend({overrides:zc.optional(),pricingModel:s().trim().min(1).optional()}).passthrough(),Qc={get:{input:d([s()]),output:A(et)},list:{input:d([]),output:C(s(),et)},set:{input:d([s(),et]),output:_},delete:{input:d([s()]),output:_}},Yc=c({baseRevision:s().min(1).optional()}),Xc={readModel:{input:d([s()]),output:Ke},createModel:{input:d([Es]),output:Ke},updateModel:{input:d([s(),ws]),output:Ke},deleteModel:{input:d([s(),Yc.optional()]),output:st()},readProvider:{input:d([s()]),output:We},createProvider:{input:d([Ts]),output:We},updateProvider:{input:d([s(),Is]),output:We},deleteProvider:{input:d([s()]),output:st()}},en=h(["global","plugin","caller"]),Jc=c({id:s(),name:s()}),K=c({cwd:s().min(1).optional()}),Zc=c({cwd:s().min(1).optional(),verify:S().optional()}),dt=M("transport",[It.extend({name:s().min(1)}),Tt.extend({name:s().min(1)}),wt.extend({name:s().min(1)})]),tn=M("transport",[It.extend({envKeys:v(s()).optional()}),Tt.extend({headerKeys:v(s()).optional()}),wt.extend({headerKeys:v(s()).optional()})]),pe=c({name:s(),config:tn,source:en,origin:s(),mutable:S(),plugin:Jc.optional()}),ed=c({name:s().min(1).optional(),server:dt.optional(),cwd:s().min(1).optional()}),td=c({success:S(),output:s()}),od=c({name:s().min(1),cwd:s().min(1).optional()}),nd=c({state:h(["idle","stopped","unconfirmed"]),output:s()}),Se=M("source",[c({source:y("global"),name:s().min(1)}),c({source:y("plugin"),pluginId:s().min(1),serverName:s().min(1)})]),on=h(["not-applicable","bearer-token","oauth-required","oauth-authorized","oauth-expired","unavailable"]),sd=c({serverId:s(),locator:Se,runtimeName:s(),canonicalUrl:s().optional(),origin:en,config:tn,enabled:S(),editable:S()}),id=sd.extend({authStatus:on,checkedAt:l().optional(),error:s().optional()}),rd=c({name:s(),authStatus:on}),lt=c({credentialId:s().regex(/^[a-f0-9]{64}$/)}),ad=lt.extend({serverName:s().min(1),displayUrl:s().min(1),origin:y("unknown")}),cd=c({canonicalUrl:wo()}),dd=M("status",[c({status:y("authorization-required"),flowId:s(),authorizationUrl:s()}),c({status:y("already-authorized")})]),ld=c({flowId:s().min(1),timeoutMs:l().int().min(1).max(2**31-1).optional()}),ud={listServers:{input:d([K.optional()]),output:v(pe)},getServer:{input:d([s().min(1),K.optional()]),output:pe},addServer:{input:d([dt,K.optional()]),output:v(pe)},updateServer:{input:d([dt,K.optional()]),output:v(pe)},removeServer:{input:d([s().min(1),K.optional()]),output:v(pe)},testServer:{input:d([ed]),output:td},stopServer:{input:d([od]),output:nd},listAuthStatuses:{input:d([Zc.optional()]),output:v(rd)},inspectServers:{input:d([v(Se).optional(),K.optional()]),output:v(id)},resolveServerByName:{input:d([s().min(1),K.optional()]),output:Se},beginServerAuth:{input:d([Se,K.optional()]),output:dd},completeServerAuth:{input:d([ld]),output:_},cancelServerAuth:{input:d([c({flowId:s().min(1)})]),output:_},resetServerAuth:{input:d([Se,K.optional(),wo().optional()]),output:_},listStoredOAuthCredentials:{input:d([]),output:v(ad)},revealStoredOAuthCredential:{input:d([lt]),output:cd},revokeStoredOAuthCredential:{input:d([lt]),output:_}},pd=c({severity:h(["error","warn","info"]),message:s()}),md=c({name:s().optional(),email:s().optional()}),hd=c({skill:s()}),gd=c({displayName:s().optional(),shortDescription:s().optional(),longDescription:s().optional(),developerName:s().optional(),websiteURL:s().optional()}),vd=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()}),Sd=c({path:s(),name:s()}),fd=h(["kimi-plugin-root","kimi-plugin-dir","claude-code"]),ut=h(["local-path","zip-url","github"]),yd=h(["ok","error"]),pt=c({kind:h(["branch","tag","sha"]),value:s()}),bd=c({name:s(),version:s().optional(),description:s().optional(),keywords:v(s()).optional(),author:md.optional(),homepage:s().optional(),license:s().optional(),icon:s().optional(),skills:v(s()).optional(),agents:v(s()).optional(),sessionStart:hd.optional(),mcpServers:C(s(),Fe).optional(),hooks:v(vd).optional(),commands:v(Sd).optional(),interface:gd.optional(),skillInstructions:s().optional(),systemPrompt:s().optional(),unsupportedComponents:v(s()).optional()}),_d=c({name:s(),runtimeName:s(),enabled:S(),transport:h(["stdio","http","sse"]),command:s().optional(),args:v(s()).optional(),cwd:s().optional(),url:s().optional(),envKeys:v(s()).optional(),headerKeys:v(s()).optional()}),Jt=c({owner:s(),repo:s(),ref:pt,installedSha:s().optional()}),Ne=c({id:s(),displayName:s(),version:s().optional(),icon:s().optional(),enabled:S(),state:yd,skillCount:l(),mcpServerCount:l(),enabledMcpServerCount:l(),hookCount:l(),commandCount:l(),hasErrors:S(),source:ut,originalSource:s().optional(),github:Jt.optional(),zipSha256:s().optional(),rollback:c({version:s().optional(),source:ut,originalSource:s().optional(),github:Jt.optional(),zipSha256:s().optional()}).optional()}),Id=Ne.extend({root:s(),installedAt:s(),updatedAt:s().optional(),manifestKind:fd.optional(),manifestPath:s().optional(),manifest:bd.optional(),mcpServers:v(_d),shadowedManifestPath:s().optional(),diagnostics:v(pd)}),Td=c({added:v(s()),removed:v(s()),errors:v(c({id:s(),message:s()}))}),wd=c({id:s(),source:ut,current:pt.optional(),latest:pt,displayVersion:s(),updateAvailable:S()}),Ed=c({pluginId:s(),name:s(),description:s(),body:s(),path:s()}),kd=Eo.extend({fingerprint:s().optional(),consent:S().optional()}),Cd=c({id:s(),enabled:S()}),Rd=c({id:s(),server:s(),enabled:S()}),Pd=c({id:s(),deleteData:S().optional()}),Od=c({id:s()}),Ad={listPlugins:{input:d([]),output:v(Ne)},previewPlugin:{input:d([Eo]),output:ks},installPlugin:{input:d([kd]),output:Ne},rollbackPlugin:{input:d([c({id:s()})]),output:Ne},setPluginEnabled:{input:d([Cd]),output:_},setPluginMcpServerEnabled:{input:d([Rd]),output:_},removePlugin:{input:d([Pd]),output:_},reloadPlugins:{input:d([]),output:Td},getPluginInfo:{input:d([Od]),output:Id},listPluginCommands:{input:d([]),output:v(Ed)},checkUpdates:{input:d([]),output:v(wd)}},Md={sources:{input:d([]),output:v(Ls)},discover:{input:d([Us]),output:Ns},preview:{input:d([Ms]),output:Ds},start:{input:d([As]),output:le},jobs:{input:d([Os.optional()]),output:c({items:v(le),cursor:s().nullable()})},job:{input:d([s()]),output:le},cancel:{input:d([s()]),output:le},resume:{input:d([s()]),output:le},archives:{input:d([Ps.optional()]),output:c({items:v(Rs),cursor:s().nullable()})},read:{input:d([Cs]),output:xs}},Ud={sources:{input:d([]),output:v(qt)},setSources:{input:d([Fs]),output:v(qt)},catalog:{input:d([c({id:s().min(1)}).strict()]),output:Vs},providers:{input:d([]),output:jt},capabilities:{input:d([$s]),output:$([Gs,c({providers:jt}).strict()])},voices:{input:d([qs]),output:Bs},jobs:{input:d([js.optional()]),output:v(Le)},job:{input:d([s().min(1)]),output:Le}},xd={cancel:{input:d([s().min(1)]),output:Le},resume:{input:d([s().min(1)]),output:Le}},Dd=c({definition:Hs.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:v(s()).optional(),roomGreeting:s().optional(),delivery:h(["reply","message"]).optional(),memory:c({shared:v(h(["global","workspace"]))}).optional(),skills:v(s()).optional(),tags:v(s()).optional(),notes:s().optional(),homeWorkspace:s().optional(),description:s().optional(),examples:s().optional(),extensions:w().optional(),expectedRevision:s().optional()}).strict(),Nd=c({memory:c({status:h(["committed","pending","failed"]),error:s().optional()}).strict()}).strict(),Ld={list:{input:d([Ws.optional()]),output:v(zs)},get:{input:d([s()]),output:A(ze)},put:{input:d([Dd]),output:ze},duplicate:{input:d([s(),c({id:s().optional(),name:s().optional()}).optional()]),output:ze},archive:{input:d([s(),S().optional()]),output:Ks},delete:{input:d([s(),s().optional()]),output:Nd}},jd={list:{input:d([]),output:v(Ye)},enable:{input:d([Qe]),output:Ye},ensureHomeSession:{input:d([Qe]),output:Ye},update:{input:d([Qe,Qs]),output:ci}},qd={list:{input:d([]),output:v(V)},listItems:{input:d([]),output:v(di)},get:{input:d([F]),output:A(V)},create:{input:d([ni]),output:V},createFromThreads:{input:d([oi]),output:V},searchThreads:{input:d([ti.optional()]),output:ai},addMember:{input:d([F,ei]),output:V},removeMember:{input:d([F,Zs]),output:V},update:{input:d([F,Js]),output:V},delete:{input:d([F]),output:_},postUserMessage:{input:d([F,Xs]),output:ri},pause:{input:d([F]),output:V},continue:{input:d([F]),output:V},stop:{input:d([F]),output:V},log:{input:d([F,Ys.optional()]),output:ii},usage:{input:d([F]),output:si}},Gd=s(),Zt=C(s(),s()),$d=h(["static","discover","oauth-catalog"]),Fd=Ct,Bd=c({modelSource:$d.optional(),baseUrl:s().optional(),customHeaders:Zt.optional(),defaultModel:s().optional(),requestIdentity:Fd.optional(),type:Gd.optional(),apiKey:s().optional(),oauth:Jo.optional(),env:Zt.optional(),source:C(s(),w()).optional()}),tt=li((o,e)=>{if(o!==null&&typeof o=="object")for(const t of["requestAttribution","requestOriginator"])t in o&&e.addIssue({code:"custom",message:`${t} was removed; use requestIdentity`,path:[t]});return o},Bd),Vd={get:{input:d([s()]),output:A(tt)},list:{input:d([]),output:C(s(),tt)},set:{input:d([s(),tt]),output:_},delete:{input:d([s()]),output:_}},nn=c({agentVersion:s().optional(),image:S().optional(),audio:S().optional(),fork:S().optional(),nativeSteering:S().optional(),questionForm:S().optional(),planApproval:S().optional(),models:v(s()).optional(),thinkingLevels:v(s()).optional(),authMethods:v(s()).optional(),resume:S().optional(),load:S().optional(),permissionModes:v(s()).optional()}),At=c({homedir:s().optional(),type:h(["main","sub","independent"]).optional(),parentAgentId:$([s(),ne()]).optional(),delegator:M("kind",[c({kind:y("agent"),agentId:s()}),c({kind:y("external"),delegationId:s()})]).optional(),forkedFrom:s().optional(),labels:C(s(),s()).optional(),displayName:s().optional(),userLabel:s().optional(),model:s().optional(),thinkingEffort:s().optional(),executor:s().optional(),executorProtocol:s().optional(),negotiated:nn.optional(),allowKikiSubagents:S().optional(),status:h(["completed","failed","cancelled"]).optional(),completedAt:l().optional(),resultSummary:s().optional(),error:s().optional(),usage:De.optional(),contextTokens:l().optional(),toolCallCount:l().int().nonnegative().optional()}),sn=c({worktreeId:s(),branch:s(),sourceRoot:s(),baseRef:s()}),Hd=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(),archived:S(),archivedAt:l().optional(),cwd:s().optional(),worktree:sn.optional(),forkedFrom:s().optional(),agents:C(s(),At).optional(),custom:C(s(),w()).optional(),sshHosts:C(s(),s()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),Wd=c({version:l().optional(),title:s().optional(),titleKind:h(["replaceable","generated","custom"]).optional(),lastPrompt:s().optional(),delivery:h(["reply","message"]).optional(),updatedAt:l().optional(),archived:S().optional(),archivedAt:l().optional(),cwd:s().optional(),worktree:sn.optional(),forkedFrom:s().optional(),agents:C(s(),At).optional(),custom:C(s(),w()).optional(),sshHosts:C(s(),s()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),Kd=h(["id","version","title","titleKind","lastPrompt","delivery","createdAt","updatedAt","archived","archivedAt","cwd","worktree","forkedFrom","agents","custom","sshHosts","lastTurnReason","usage"]),zd=c({changed:v(Kd)}),Qd={read:{input:d([]),output:Hd},update:{input:d([Wd]),output:_},setTitle:{input:d([s()]),output:_},setArchived:{input:d([S()]),output:_},registerAgent:{input:d([s(),At]),output:_}},eo=c({id:s(),workspaceId:s(),cwd:s().optional(),title:s().optional(),lastPrompt:s().optional(),delivery:h(["reply","message"]).optional(),createdAt:l(),updatedAt:l(),archived:S(),archivedAt:l().optional(),custom:C(s(),w()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional(),executorId:s().optional(),negotiated:nn.optional(),allowKikiSubagents:S().optional()}),Yd=c({workspaceIds:v(s()).optional(),sessionId:s().optional(),includeArchived:S().optional(),limit:l().optional(),childOf:s().optional(),before:s().optional(),after:s().optional()}),Xd=c({workspaceIds:v(s()).optional(),includeArchived:S().optional()}),Jd={listRecent:{input:d([Yd]),output:Ur(eo)},get:{input:d([s()]),output:A(eo)},count:{input:d([Xd]),output:l()}},Pe=c({id:s(),root:s(),name:s(),createdAt:l(),lastOpenedAt:l(),pinned:S()}),Zd=c({name:s().optional(),pinned:S().optional()}),el={list:{input:d([]),output:v(Pe)},get:{input:d([s()]),output:A(Pe)},createOrTouch:{input:d([s(),s().optional()]),output:Pe},update:{input:d([s(),Zd]),output:A(Pe)},delete:{input:d([s()]),output:_}},W=c({hostId:s().trim().min(1),workspaceId:s().trim().min(1),sessionId:s().trim().min(1),bridgeId:s().uuid().optional(),connectionId:s().uuid().optional()}),tl=c({ref:W,title:s().optional(),updatedAt:l().int().nonnegative(),createdAt:l().int().nonnegative(),state:h(["cold","idle","running"])}),ol=c({workspaceId:s().trim().min(1).optional(),cursor:s().min(1).optional(),limit:l().int().min(1).max(100).optional()}),nl=c({threads:v(tl),nextCursor:s().optional()}),sl=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"]),bridgedPeer:c({source:W,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:W,messageId:s().min(1)}).optional(),input:s(),output:s()}),il=c({thread:W,contentRef:ko.optional(),cursor:s().min(1).optional(),limit:l().int().min(1).max(100).optional()}),rl=o=>({...o,execution:o.execution===void 0?void 0:{...o.execution,losses:[...o.execution.losses]}}),al=Co.transform(o=>({...o,items:o.items.map(e=>e.kind==="turn"?rl(e):e)})),cl=c({thread:W,turns:v(sl),nextCursor:s().optional(),view:c({transcript:al.optional(),segment:Ro.optional()}).optional()}),dl=c({target:W,content:s().min(1).max(1e5),idempotencyKey:s().min(1).max(256)}).strict(),ll=c({messageId:s().min(1),targetSeq:l().int().nonnegative(),acceptedAt:l().int().nonnegative(),deduplicated:S(),delivery:h(["pending","delivered","undeliverable"])}),ul=c({ref:W,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()}),pl=c({thread:W,cursor:s().min(1).optional()}),ml=c({threads:v(pl).min(1).max(8),timeoutMs:l().int().min(0).max(6e4).optional()}).superRefine((o,e)=>{const t=new Set;o.threads.forEach((n,r)=>{const{hostId:a,workspaceId:i,sessionId:u}=n.thread,m=`${a}\0${i}\0${u}`;t.has(m)&&e.addIssue({code:"custom",path:["threads",r],message:"duplicate thread reference"}),t.add(m)})}),hl=c({thread:W,cursor:s().min(1),activities:v(ul)}),gl=c({threads:v(hl),timedOut:S()}),to=c({ref:W,title:s().optional(),deleted:S(),archived:S()}),vl=c({messageId:s().describe("Stable recipient main-agent prompt id and user-message id, including steered delivery and retries; navigate only delivered records."),source:M("kind",[c({kind:y("thread"),thread:to}),c({kind:y("room"),roomId:s()})]),target:to,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()}),Sl=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(o=>o.peerSessionId===void 0||o.sessionId!==void 0),fl=c({items:v(vl),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()}),yl={listMessages:{input:d([Sl.optional()]),output:fl},hostId:{input:d([]),output:s().min(1)},listThreads:{input:d([ol.optional()]),output:nl},readThread:{input:d([il]),output:cl},sendMessage:{input:d([dl]),output:ll},waitThreads:{input:d([ml]),output:gl},getWorkspaceOverride:{input:d([s().trim().min(1)]),output:A(S())},setWorkspaceOverride:{input:d([s().trim().min(1),S()]),output:_},clearWorkspaceOverride:{input:d([s().trim().min(1)]),output:_},isWorkspaceEnabled:{input:d([s().trim().min(1)]),output:S()}},bl=c({busy:S(),mainTurnActive:S(),pendingInteraction:h(["none","approval","question"]),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),_l={state:{input:d([]),output:bl}},Il={sendUserMessage:{input:d([c({targetAgentId:s().min(1),content:s().min(1).max(1e5),idempotencyKey:s().min(1).max(256)}).strict()]),output:c({message:c({messageId:s(),sessionId:s(),sourceAgentId:s(),sourceTaskName:s(),senderKind:y("user").optional(),targetAgentId:s(),targetTaskName:s(),content:s(),acceptedAt:l(),targetSeq:l()}),deduplicated:S(),delivery:h(["queued","delivered"]),payloadConflict:S(),resumed:S().optional()})}},Tl=c({id:s().optional(),sessionId:s().optional(),agentId:s().optional(),turnId:l().optional(),toolCallId:s().optional(),toolName:s(),action:s(),display:w(),approvalRule:s().optional()}),wl=c({decision:h(["approved","rejected","cancelled"]),scope:y("session").optional(),feedback:s().optional(),selectedLabel:s().optional(),selectedOptionId:s().optional()}),El={listPending:{input:d([]),output:v(Tl)},decide:{input:d([s(),wl]),output:_}},rn=h(["approval","question","user_tool"]),kl=c({agentId:s().optional(),turnId:l().optional()}),an=c({id:s(),kind:rn,payload:w(),origin:kl,createdAt:l()}),Cl=c({id:s(),response:w()}),Rl={listPending:{input:d([rn.optional()]),output:v(an)},respond:{input:d([s(),w()]),output:_},acquireConsumer:{input:d([s()]),output:_},releaseConsumer:{input:d([s()]),output:_},hasConsumer:{input:d([]),output:S()},isRecentlyResolved:{input:d([s()]),output:S()}},Pl=c({sessionId:s().optional(),localSession:c({localId:s(),executorId:s(),engine:h(["claude","codex"]),externalId:s(),home:s()}).optional(),workDir:s(),ephemeral:S().optional(),delivery:h(["reply","message"]).optional(),additionalDirs:v(s()).optional(),waitForSessionMs:l().nonnegative().finite().optional(),mainAgentBinding:c({persona:s().optional(),profile:s().optional(),model:s().optional(),thinking:s().optional()}).optional(),mcpServers:C(s(),Fe).optional()}),oo=c({additionalDirs:v(s()).optional(),waitForSessionMs:l().nonnegative().finite().optional(),mcpServers:C(s(),Fe).optional()}),cn=c({sourceSessionId:s(),newSessionId:s().optional(),title:s().optional(),metadata:C(s(),w()).optional(),turnIndex:l().optional()}),Ol=cn.omit({turnIndex:!0}),me=Ie({id:s(),kind:s()}),Al={countPendingBackgroundTasks:{input:d([]),output:l()},drainBackgroundTasks:{input:d([l().positive().finite()]),output:_}},Ml={create:{input:d([Pl]),output:me},resume:{input:d([s(),oo.optional()]),output:A(me)},close:{input:d([s()]),output:_},archive:{input:d([s()]),output:_},restore:{input:d([s(),oo.optional()]),output:A(me)},delete:{input:d([s()]),output:_},fork:{input:d([cn]),output:me},createChild:{input:d([Ol]),output:me}},Ul=c({label:s(),description:s().optional()}),xl=c({question:s(),header:s().optional(),body:s().optional(),options:v(Ul),multiSelect:S().optional(),otherLabel:s().optional(),otherDescription:s().optional()}),dn=C(s(),$([s(),y(!0)])),Dl=c({answers:dn,method:h(["enter","space","number_key"]).optional()}),Nl=$([ne(),dn,Dl]),Ll=c({id:s().optional(),turnId:l().optional(),toolCallId:s().optional(),questions:v(xl)}),jl={listPending:{input:d([]),output:v(Ll)},answer:{input:d([s(),Nl]),output:_},dismiss:{input:d([s()]),output:_}},ql=c({name:s(),description:s(),path:s(),source:h(["project","user","extra","builtin"]),type:s().optional(),disableModelInvocation:S().optional(),isSubSkill:S().optional()}),Gl={list:{input:d([]),output:v(ql)}},$l={generateTitle:{input:d([c({force:S().optional(),source:h(["user_prompts","first_turn","digest"]).optional()}).optional()]),output:A(s())}},Fl={start:{input:d([]),output:s()}},Bl=c({id:s(),cron:s(),prompt:s(),createdAt:l(),recurring:S().optional(),paused:S().optional(),lastFiredAt:l().optional(),tags:C(s(),s()).optional()}),Vl={list:{input:d([]),output:v(Bl)},getNextFireTime:{input:d([]),output:l().nullable()},getNextFireForTask:{input:d([s()]),output:l().nullable()}},Hl={generateAgentsMd:{input:d([]),output:_},cancelInit:{input:d([]),output:_}},Wl=c({title:s(),status:h(["pending","in_progress","done"])}),Kl={getTodos:{input:d([s().optional()]),output:v(Wl)}};function no(o){return"streaming"in o&&o.streaming===!0}const so={agentGoalService:Na,agentLifecycleService:Al,sessionCronService:Vl,sessionBtwService:Fl,sessionInitService:Hl,sessionTodoService:Kl,taskBoardService:br,agentPanelService:_r,sessionIndex:Jd,workspaceService:el,configService:Uc,providerService:Vd,modelService:Qc,modelResolver:Ec,modelCatalogMutation:Xc,providerDiscovery:Cc,oauthService:mc,authSummaryService:hc,flagService:qc,pluginService:Ad,pluginImportService:Md,pluginMediaService:Ud,agentPluginMediaService:xd,personaStore:Ld,botService:jd,roomService:qd,capabilityService:Sc,hostFolderBrowser:Bc,bootstrapService:Dc,threadCommunicationService:yl,fileService:jc,mcpManagementService:ud,sessionManager:Ml,sessionMetadata:Qd,agentCollaborationMessagingService:Il,sessionActivityView:_l,sessionInteractionService:Rl,sessionApprovalService:El,sessionQuestionService:jl,sessionSkillCatalog:Gl,sessionTitleService:$l,agentPromptService:La,agentSkillService:ja,agentLoopService:Va,agentContextInjectorService:qa,agentContextMemoryService:za,agentContextMutationService:Qa,agentContextRebuildService:Ga,agentConversationUndoService:$a,agentPluginCommandService:Fa,agentPluginService:Ba,agentPermissionModeService:Ha,agentCommandService:Wa,agentRuntimeBindingService:Ka,agentTokenCountingService:Ya,agentActivityView:Mr,agentShellCommandService:Xa,agentProfileService:Ja,agentUsageService:Za,agentPlanService:ec,agentTaskService:ic,agentMcpService:oc,agentFullCompactionService:sc},io=c({domain:s(),source:h(["load","reload","set"]),value:w(),previousValue:w()}),zl=c({added:v(s()),removed:v(s()),errors:v(c({id:s(),message:s()}))}),Ql=c({agentId:s(),sessionId:s(),title:s().optional(),patch:c({title:s().optional(),isCustomTitle:S().optional(),lastPrompt:s().optional()})}),Yl=c({changed:v(c({provider_id:s(),provider_name:s(),added:l(),removed:l()})),unchanged:v(s()),failed:v(c({provider:s(),reason:s()}))}),Xl=c({state:h(["building","ready","readonly","unavailable"]),indexed_sessions:l(),total_sessions:l(),documents:l(),stale:S().optional(),degraded:s().optional(),reason:h(["disabled","indexer_backoff","memory_budget","wal_stuck","disk_low","corrupt_rebuilding","sqlite_unavailable","runtime_disabled"]).optional()}),he={installId:s().min(1),version:s().min(1)},Jl=M("stage",[c({...he,stage:y("download"),receivedBytes:l().nonnegative(),totalBytes:l().positive().optional()}),c({...he,stage:y("extract")}),c({...he,stage:y("activate")}),c({...he,stage:y("done")}),c({...he,stage:y("failed"),error:s(),timedOut:S()})]),Zl={"room.changed":{kind:"emitter",service:"roomService",event:"onDidChange",schema:ui},"search.indexStateChanged":{kind:"bus",type:"event.search.index_state_changed",schema:Xl},"executors.antigravityInstallProgress":{kind:"bus",type:"event.executor.antigravity_install_progress",schema:Jl},"config.changed":{kind:"emitter",service:"configService",event:"onDidChangeConfiguration",schema:io},"config.sectionChanged":{kind:"emitter",service:"configService",event:"onDidSectionChange",schema:io},"kosong.providers.changed":{kind:"emitter",service:"providerService",event:"onDidChangeProviders",schema:zt},"kosong.models.changed":{kind:"emitter",service:"modelService",event:"onDidChangeModels",schema:zt},"plugins.reloaded":{kind:"emitter",service:"pluginService",event:"onDidReload",schema:zl},"session.archived":{kind:"bus",type:"event.session.archived",schema:c({sessionId:s()})},"session.metaUpdated":{kind:"bus",type:"session.meta.updated",schema:Ql},"kosong.changed":{kind:"bus",type:"event.model_catalog.changed",schema:Yl}},eu={"metadata.changed":{kind:"emitter",service:"sessionMetadata",event:"onDidChangeMetadata",schema:zd},"skills.changed":{kind:"emitter",service:"sessionSkillCatalog",event:"onDidChange",schema:s()},"interactions.changed":{kind:"stream",name:"interactions",schema:v(an)},"interactions.resolved":{kind:"stream",name:"interactions:resolved",schema:Cl}};class ce extends Error{constructor(e,t,n,r){super(`${e} validation failed for ${t}: ${n.map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}`),this.phase=e,this.procedure=t,this.issues=n,this.payload=r,this.name="KlientValidationError"}}function ro(o,e,t){const n=e.input.safeParse(t);if(!n.success)throw new ce("input",o,n.error.issues,t);return n.data}function tu(o,e,t){const n=e.output.safeParse(t);if(!n.success)throw new ce("output",o,n.error.issues,t);return n.data}function ou(o,e,t){const n=e.chunk.safeParse(t);if(!n.success)throw new ce("chunk",o,n.error.issues,t);return n.data}function nu(o,e,t){const n=e.safeParse(t);return n.success?{ok:!0,data:n.data}:{ok:!1,error:new ce("event",o,n.error.issues,t)}}function Oe(o){switch(o.kind){case"bus":return"bus";case"stream":return`stream:${o.name}`;case"emitter":return`emitter:${o.service}:${o.event}`}}function ao(o){if(typeof o!="object"||o===null)return;const e=o.type;return typeof e=="string"?e:void 0}class su{constructor(e,t,n,r){this.channel=e,this.validate=t,this.scope=n,this.registrations=r}listeners=new Map;subs=new Map;errorListeners=new Set;closed=!1;on(e,t){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 r=t;n.add(r);let a,i;const m={promise:new Promise((f,b)=>{a=f,i=b}),resolve:a,reject:i};m.promise.catch(()=>{});let p;try{p=this.acquire(e,m)}catch(f){throw n.delete(r),n.size===0&&this.listeners.delete(e),f}let g=!1;return{ready:m.promise,dispose:()=>{g||(g=!0,p.waiters.delete(m),m.reject(new Error("event subscription disposed before attachment")),n.delete(r),n.size===0&&this.listeners.delete(e),this.release(e))}}}observations=new Set;observe(e,t){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 b of e.events){const I=this.registrations[b];if(I===void 0)throw new Error(`unknown event: ${b}`);n.set(Oe(I),I)}const r=new Set,a=[];let i=!1,u=0,m=!1,p;const g={dispose:()=>{if(!i){i=!0,u+=1,p?.abort();for(const b of a)b.dispose();this.observations.delete(g)}}},f=()=>{u+=1,p?.abort(),!(i||m||r.size!==n.size)&&(m=!0,queueMicrotask(()=>{if(m=!1,i||r.size!==n.size)return;const b=u;p=new AbortController;const I=p.signal;Promise.resolve().then(()=>{if(!(i||b!==u))return e.read(I)}).then(k=>{if(!(i||b!==u))try{t(k)}catch(R){this.reportError(R instanceof Error?R:new Error(String(R)))}},k=>{i||b!==u||(g.dispose(),this.reportError(k instanceof Error?k:new Error(String(k))))})}))};this.observations.add(g);try{for(const[b,I]of n){const k=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,k,()=>{f()},R=>{i||(r.delete(b),f(),this.reportError(R))},()=>{i||(r.add(b),f())}))}}catch(b){throw g.dispose(),b}return g}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 t of e.waiters)t.reject(new Error("event hub closed before attachment"));e.waiters.clear(),e.disposable.dispose()}this.subs.clear(),this.listeners.clear()}acquire(e,t){const n=this.registrations[e],r=Oe(n);let a=this.subs.get(r);if(a===void 0){a={reg:n,disposable:{dispose(){}},refs:0,attached:!1,waiters:new Set([t])},this.subs.set(r,a);try{a.disposable=this.subscribe(r,a)}catch(i){throw this.subs.delete(r),i}}else a.attached?t.resolve():a.waiters.add(t);return a.refs+=1,a}release(e){const t=this.registrations[e];if(t===void 0)return;const n=Oe(t),r=this.subs.get(n);r!==void 0&&(r.refs-=1,r.refs<=0&&(r.disposable.dispose(),this.subs.delete(n)))}subscribe(e,t){const n=t.reg,r=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,r,a=>{this.deliver(e,a)},a=>{t.attached=!1;for(const i of t.waiters)i.reject(a);t.waiters.clear(),this.reportError(a)},()=>{t.attached=!0;for(const a of t.waiters)a.resolve();t.waiters.clear()})}deliver(e,t){for(const[n,r]of Object.entries(this.registrations))if(!(Oe(r)!==e||!this.listeners.has(n))){if(r.kind==="bus"){if(ao(t)!==r.type)continue;this.deliverValidated(n,r,t.payload);continue}if(r.kind==="stream"&&r.type!==void 0){if(ao(t)!==r.type)continue;this.deliverValidated(n,r,t);continue}this.deliverValidated(n,r,t)}}deliverValidated(e,t,n){let r=n;if(this.validate){const i=nu(e,t.schema,n);if(!i.ok){this.reportError(i.error);return}r=i.data}const a=this.listeners.get(e);if(a!==void 0)for(const i of a)try{i(r)}catch(u){this.reportError(u instanceof Error?u:new Error(String(u)))}}reportError(e){for(const t of this.errorListeners)try{t(e)}catch{}}}function iu(o){return{list:()=>o("botService","list",[]),enable:e=>o("botService","enable",[e]),ensureHomeSession:e=>o("botService","ensureHomeSession",[e]),update:(e,t)=>o("botService","update",[e,t])}}function ru(o){return{list:()=>o("roomService","list",[]),listItems:()=>o("roomService","listItems",[]),get:e=>o("roomService","get",[e]),create:e=>o("roomService","create",[e]),createFromThreads:e=>o("roomService","createFromThreads",[e]),searchThreads:e=>o("roomService","searchThreads",[e]),addMember:(e,t)=>o("roomService","addMember",[e,t]),removeMember:(e,t)=>o("roomService","removeMember",[e,t]),update:(e,t)=>o("roomService","update",[e,t]),delete:e=>o("roomService","delete",[e]),postUserMessage:(e,t)=>o("roomService","postUserMessage",[e,t]),pause:e=>o("roomService","pause",[e]),continue:e=>o("roomService","continue",[e]),stop:e=>o("roomService","stop",[e]),log:(e,t)=>o("roomService","log",t===void 0?[e]:[e,t]),usage:e=>o("roomService","usage",[e])}}function au(o){return{sources:()=>o("pluginImportService","sources",[]),discover:e=>o("pluginImportService","discover",[e]),preview:e=>o("pluginImportService","preview",[e]),start:e=>o("pluginImportService","start",[e]),jobs:e=>o("pluginImportService","jobs",[e]),job:e=>o("pluginImportService","job",[e]),cancel:e=>o("pluginImportService","cancel",[e]),resume:e=>o("pluginImportService","resume",[e]),archives:e=>o("pluginImportService","archives",[e]),read:e=>o("pluginImportService","read",[e])}}function cu(o){return{sources:()=>o("pluginMediaService","sources",[]),setSources:e=>o("pluginMediaService","setSources",[e]),catalog:e=>o("pluginMediaService","catalog",[e]),providers:()=>o("pluginMediaService","providers",[]),capabilities:e=>o("pluginMediaService","capabilities",[e]),voices:e=>o("pluginMediaService","voices",[e]),jobs:e=>o("pluginMediaService","jobs",[e]),job:e=>o("pluginMediaService","job",[e])}}function du(o){return{cancel:e=>o("agentPluginMediaService","cancel",[e]),resume:e=>o("agentPluginMediaService","resume",[e])}}const co=32768;function lu(o){let e="";for(let t=0;t<o.length;t+=co)e+=String.fromCodePoint(...o.subarray(t,t+co));return btoa(e)}function uu(o){const e=atob(o),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.codePointAt(n)??0;return t}function pu(o){return{id:o.id,name:o.name,avatarUrl:o.avatarMime===void 0?void 0:`/api/personas/${encodeURIComponent(o.id)}/avatar`,avatarShape:o.avatarMime===void 0?void 0:o.avatarShape}}const mu=7e4,lo=["platform","arch","cwd","osHomeDir","homeDir","configPath","sessionsDir","blobsDir","storeDir","cacheDir","logsDir"],hu=15*6e4,gu=3e4;function vu(o,e){const t=(i,u,m,p)=>o({},i,u,m,p),n=(i,u,m)=>e({},i,u,m);let r;const a=()=>(r??=Promise.all([...lo.map(i=>t("bootstrapService",i,[])),t("bootstrapService","clientIdentity",[])]).then(i=>{const u=Object.fromEntries(lo.map((p,g)=>[p,i[g]])),m=i[i.length-1];return{...u,clientVersion:m.version}}),r);return{board:{read:(i,u)=>t("taskBoardService","read",[i],u),write:i=>t("taskBoardService","write",[i]),overview:i=>t("taskBoardService","overview",[],i)},agentPanel:{read:(i,u)=>t("agentPanelService","read",[i],u)},sessions:{list:i=>t("sessionIndex","listRecent",[i]),get:i=>t("sessionIndex","get",[i]),countActive:i=>t("sessionIndex","count",[{workspaceIds:i}]),create:async({sessionId:i,workDir:u,ephemeral:m,additionalDirs:p,waitForSessionMs:g,title:f,persona:b,delivery:I,mcpServers:k,mainAgentBinding:R})=>{const D=b===void 0?R:{...R,persona:b},L={sessionId:(await o({},"sessionManager","create",[{sessionId:i,workDir:u,ephemeral:m,delivery:I,additionalDirs:p,waitForSessionMs:g,mcpServers:k,mainAgentBinding:D}])).id};return f!==void 0&&await o(L,"sessionMetadata","setTitle",[f]),o(L,"sessionMetadata","read",[])}},bots:iu(t),rooms:ru(t),personas:{list:i=>t("personaStore","list",i===void 0?[]:[i]),get:i=>t("personaStore","get",[i]),put:i=>t("personaStore","put",[{...i.definition,examples:i.examples,expectedRevision:i.revision}]),duplicate:(i,u)=>t("personaStore","duplicate",u===void 0?[i]:[i,u]),archive:(i,u)=>t("personaStore","archive",u===void 0?[i]:[i,u]),delete:async(i,u)=>{const m=await t("personaStore","delete",u?.expectedRevision===void 0?[i]:[i,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:pu},workspaces:{list:()=>t("workspaceService","list",[]),get:i=>t("workspaceService","get",[i]),createOrTouch:({root:i,name:u})=>t("workspaceService","createOrTouch",[i,u]),update:({id:i,patch:u})=>t("workspaceService","update",[i,u]),delete:i=>t("workspaceService","delete",[i])},config:{get:i=>t("configService","get",[i]),getAll:()=>t("configService","getAll",[]),inspect:i=>t("configService","inspect",[i]),set:({domain:i,patch:u,target:m})=>t("configService","set",[i,u,m]),replace:({domain:i,value:u,target:m})=>t("configService","replace",[i,u===void 0?null:u,m]),replaceSections:({sections:i,target:u})=>t("configService","replaceSections",[Object.fromEntries(Object.entries(i).map(([m,p])=>[m,p===void 0?null:p])),u]),reload:()=>t("configService","reload",[]),diagnostics:()=>t("configService","diagnostics",[])},kosong:{listProviders:()=>t("modelResolver","listProviders",[]),getProvider:i=>t("modelResolver","getProvider",[i]),addProvider:((i,u)=>{if(typeof i=="string"){const f=u;Su(f);const b={type:f.type,baseUrl:f.baseUrl,defaultModel:f.defaultModel,requestIdentity:f.requestIdentity,apiKey:f.auth.method==="api-key"?f.auth.apiKey:""};return t("providerService","set",[i,b])}const m=i,p=m.capabilities?Object.entries(m.capabilities).filter(([,f])=>f).map(([f])=>f):void 0,g={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 t("modelService","set",[m.id,g])}),removeProvider:async i=>await t("providerService","get",[i])!==void 0?t("providerService","delete",[i]):t("modelService","delete",[i]),refreshProviders:i=>t("providerDiscovery","refreshProviderModels",[i]),listDiscoveredModels:()=>t("providerDiscovery","listDiscoveredModels",[]),listModels:()=>t("modelResolver","listModels",[]),setDefaultModel:i=>t("modelResolver","setDefaultModel",[i]),readModel:i=>t("modelCatalogMutation","readModel",[i]),createModel:i=>t("modelCatalogMutation","createModel",[i]),updateModel:(i,u)=>t("modelCatalogMutation","updateModel",[i,u]),deleteModel:(i,u)=>t("modelCatalogMutation","deleteModel",[i,u]),readProviderEntity:i=>t("modelCatalogMutation","readProvider",[i]),createProvider:i=>t("modelCatalogMutation","createProvider",[i]),updateProvider:(i,u)=>t("modelCatalogMutation","updateProvider",[i,u]),deleteProviderEntity:i=>t("modelCatalogMutation","deleteProvider",[i]),generate:(i,u,m)=>n("modelResolver","generate",[i,u,m])},auth:{probeOriginal:i=>t("oauthService","probeOriginal",[i]),connectOriginal:i=>t("oauthService","connectOriginal",[i]),status:i=>t("oauthService","status",[i]),summarize:()=>t("authSummaryService","summarize",[]),ensureReady:i=>t("authSummaryService","ensureReady",[i]),startLogin:(i,u)=>t("oauthService","startLogin",[i,u]),flow:i=>t("oauthService","getFlow",[i]),cancelLogin:i=>t("oauthService","cancelLogin",[i]),logout:i=>t("oauthService","logout",[i]),methods:()=>t("oauthService","listMethods",[])},flags:{list:()=>t("flagService","explainAll",[]),enabled:i=>t("flagService","enabled",[i]),enabledIds:()=>t("flagService","enabledIds",[]),explain:i=>t("flagService","explain",[i]),snapshot:()=>t("flagService","snapshot",[])},imports:au(t),media:cu(t),plugins:{list:()=>t("pluginService","listPlugins",[]),info:i=>t("pluginService","getPluginInfo",[{id:i}]),preview:i=>t("pluginService","previewPlugin",[i]),install:async i=>{if(typeof i!="string")return t("pluginService","installPlugin",[i]);const u=await t("pluginService","previewPlugin",[{source:i}]);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 t("pluginService","installPlugin",[{source:i,fingerprint:u.fingerprint,consent:!1}])},setEnabled:i=>t("pluginService","setPluginEnabled",[i]),setMcpServerEnabled:i=>t("pluginService","setPluginMcpServerEnabled",[i]),remove:i=>t("pluginService","removePlugin",[{id:i}]),reload:()=>t("pluginService","reloadPlugins",[]),checkUpdates:()=>t("pluginService","checkUpdates",[]),listCommands:()=>t("pluginService","listPluginCommands",[])},capabilities:{list:()=>t("capabilityService","listCapabilities",[]),get:i=>t("capabilityService","getCapability",[i]),install:(i,u)=>t("capabilityService","installCapability",u===void 0?[i]:[i,u])},hostFs:{browse:i=>t("hostFolderBrowser","browse",[i]),home:()=>t("hostFolderBrowser","home",[])},threads:{messages:i=>t("threadCommunicationService","listMessages",[i]),hostId:()=>t("threadCommunicationService","hostId",[]),list:i=>t("threadCommunicationService","listThreads",[i]),read:i=>t("threadCommunicationService","readThread",[i]),send:i=>t("threadCommunicationService","sendMessage",[i]),wait:i=>t("threadCommunicationService","waitThreads",[i],{timeoutMs:mu}),getWorkspaceOverride:i=>t("threadCommunicationService","getWorkspaceOverride",[i]),setWorkspaceOverride:(i,u)=>t("threadCommunicationService","setWorkspaceOverride",[i,u]),clearWorkspaceOverride:i=>t("threadCommunicationService","clearWorkspaceOverride",[i]),isWorkspaceEnabled:i=>t("threadCommunicationService","isWorkspaceEnabled",[i])},files:{save:({data:i,filename:u,name:m,mimeType:p,expiresInSec:g},f)=>t("fileService","save",[lu(i),u,{name:m,mimeType:p,expiresInSec:g}],f),get:async i=>{const u=await t("fileService","get",[i]);return{meta:u.meta,data:uu(u.data)}},delete:i=>t("fileService","delete",[i])},mcp:{list:i=>t("mcpManagementService","listServers",[i===void 0?void 0:{cwd:i.cwd}]),get:({name:i,cwd:u})=>t("mcpManagementService","getServer",[i,u===void 0?void 0:{cwd:u}]),add:({server:i,cwd:u})=>t("mcpManagementService","addServer",[i,u===void 0?void 0:{cwd:u}]),update:({server:i,cwd:u})=>t("mcpManagementService","updateServer",[i,u===void 0?void 0:{cwd:u}]),remove:({name:i,cwd:u})=>t("mcpManagementService","removeServer",[i,u===void 0?void 0:{cwd:u}]),test:i=>t("mcpManagementService","testServer",[i]),stop:i=>t("mcpManagementService","stopServer",[i]),inspect:i=>t("mcpManagementService","inspectServers",[i?.targets,i===void 0?void 0:{cwd:i.cwd}]),authStatuses:i=>t("mcpManagementService","listAuthStatuses",[i===void 0?void 0:{cwd:i.cwd,verify:i.verify}]),resolveByName:({name:i,cwd:u})=>t("mcpManagementService","resolveServerByName",[i,{cwd:u}]),beginAuth:({locator:i,cwd:u})=>t("mcpManagementService","beginServerAuth",[i,{cwd:u}]),completeAuth:({flowId:i,timeoutMs:u},m)=>t("mcpManagementService","completeServerAuth",[{flowId:i,timeoutMs:u}],{signal:m?.signal,timeoutMs:Math.min((u??hu)+gu,2**31-1)}),cancelAuth:({flowId:i})=>t("mcpManagementService","cancelServerAuth",[{flowId:i}]),resetAuth:({locator:i,cwd:u,expectedCanonicalUrl:m})=>t("mcpManagementService","resetServerAuth",m===void 0?[i,{cwd:u}]:[i,{cwd:u},m]),listStoredOAuthCredentials:()=>t("mcpManagementService","listStoredOAuthCredentials",[]),revealStoredOAuthCredential:i=>t("mcpManagementService","revealStoredOAuthCredential",[i]),revokeStoredOAuthCredential:i=>t("mcpManagementService","revokeStoredOAuthCredential",[i])},env:a}}function Su(o){const e=o;for(const t of["requestAttribution","requestOriginator"])if(t in e)throw new TypeError(`${t} was removed; use requestIdentity`)}function fu(o,e){const t={sessionId:e},n=()=>o(t,"sessionMetadata","read",[]),r=async(a,i={})=>{const u=await o({},"sessionManager",a,[{...i,sourceSessionId:e}]);return o({sessionId:u.id},"sessionMetadata","read",[])};return{get:n,setTitle:a=>o(t,"sessionMetadata","setTitle",[a]),generateTitle:a=>o(t,"sessionTitleService","generateTitle",[a]),update:a=>o(t,"sessionMetadata","update",[a]),setArchived:a=>o(t,"sessionMetadata","setArchived",[a]),status:async()=>{const a=await o(t,"sessionActivityView","state",[]);return a.pendingInteraction==="approval"?"awaiting_approval":a.pendingInteraction==="question"?"awaiting_question":a.busy?"running":"idle"},close:()=>o({},"sessionManager","close",[e]),archive:()=>o({},"sessionManager","archive",[e]),resume:async a=>{const i=await o({},"sessionManager","resume",a===void 0?[e]:[e,a],{timeoutMs:0});return i!=null},restore:async a=>{const i=await o({},"sessionManager","restore",[e,a]);return i!=null},countPendingBackgroundTasks:()=>o(t,"agentLifecycleService","countPendingBackgroundTasks",[]),drainBackgroundTasks:a=>o(t,"agentLifecycleService","drainBackgroundTasks",[a],{timeoutMs:0}),nextCronFireAt:()=>o(t,"sessionCronService","getNextFireTime",[]),todos:{get:a=>o(t,"sessionTodoService","getTodos",a===void 0?[]:[a])},init:{generateAgentsMd:()=>o(t,"sessionInitService","generateAgentsMd",[]),cancelInit:()=>o(t,"sessionInitService","cancelInit",[])},btw:{start:()=>o(t,"sessionBtwService","start",[])},cron:{list:()=>o(t,"sessionCronService","list",[]),nextFireAt:a=>o(t,"sessionCronService","getNextFireForTask",[a])},delete:()=>o({},"sessionManager","delete",[e]),fork:a=>r("fork",a),createChild:a=>r("createChild",a),approvals:{list:()=>o(t,"sessionApprovalService","listPending",[]),decide:(a,i)=>o(t,"sessionApprovalService","decide",[a,i])},questions:{list:()=>o(t,"sessionQuestionService","listPending",[]),answer:(a,i)=>o(t,"sessionQuestionService","answer",[a,i]),dismiss:a=>o(t,"sessionQuestionService","dismiss",[a])},interactions:{list:a=>o(t,"sessionInteractionService","listPending",[a]),respond:(a,i)=>o(t,"sessionInteractionService","respond",[a,i]),acquireConsumer:a=>o(t,"sessionInteractionService","acquireConsumer",[a]),releaseConsumer:a=>o(t,"sessionInteractionService","releaseConsumer",[a])},skills:{list:()=>o(t,"sessionSkillCatalog","list",[])},agents:async()=>(await n()).agents??{},sendUserAgentMessage:a=>o(t,"agentCollaborationMessagingService","sendUserMessage",[a],{timeoutMs:0})}}c({});const yu=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(o=>[o.beforeTurn,o.beforeItem,o.afterTurn,o.afterItem].filter(e=>e!==void 0).length<=1,{message:"beforeTurn, beforeItem, afterTurn and afterItem are mutually exclusive"}).refine(o=>Ge(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),bu=c({agentId:s().min(1),since:Po,grade:h(["turn","block","delta"]).optional()}).refine(o=>Ge(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),_u=c({agentId:s().min(1),kind:h(["task","attachment","prompt"]),id:s().min(1)}).refine(o=>Ge(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),Iu=c({agentId:s().min(1),ref:ko}).refine(o=>Ge(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),Tu=Ro,wu=c({sessionCursor:Te,transcriptGrades:pi,transcriptSince:C(s(),Po).optional()}),se=l().int().nonnegative(),Eu=c({type:y("status"),status:h(["connecting","open","closed"]),generation:se,detail:s().optional()}),ku=c({type:y("ready"),currentSessionCursor:Te,reconnected:S(),generation:se}),Cu=c({type:y("sessionCursorAdvanced"),cursor:Te,generation:se,rosterAgentId:s().min(1).optional(),title:s().optional()}),Ru=c({type:y("historyRewritten"),reason:h(["edit_resend","regenerate"]),targetMessageId:s().min(1),cursor:Te,generation:se}),Pu=c({type:y("transcript"),event:mi,generation:se}),Ou=c({type:y("resyncRequired"),reason:hi,currentSessionCursor:Te,generation:se}),Au=c({type:y("protocolError"),detail:s(),recoverable:S(),generation:se}),Mu=M("type",[Au,Eu,ku,Cu,Ru,Pu,Ou]),Uu=Si,xu=Co,Du=vi,Nu=gi;function Lu(o,e,t){let n=0,r=0;const a=()=>{if(o===void 0)throw new Error("session view is unavailable on this transport");return o},i=(u,m,p,g)=>{const f=p.safeParse(g);if(!f.success)throw new ce(u,m,f.error.issues,g);return f.data};return{async snapshot(u){const m=await a().snapshot(e,u);return t?i("output","session.view.snapshot",Uu,m):m},transcript:{async page(u){const m=t?i("input","session.view.transcript.page",yu,u):u,p=await a().transcriptPage(e,m);return t?i("output","session.view.transcript.page",xu,p):p},async catchUp(u){const m=t?i("input","session.view.transcript.catchUp",bu,u):u,p=await a().transcriptCatchUp(e,m);return t?i("output","session.view.transcript.catchUp",Du,p):p},...o?.transcriptEntities===void 0?{}:{async entities(u,m){const p=i("input","session.view.transcript.entities",fi,{agent_id:u.agentId,kind:u.kind,cursor:u.cursor,limit:u.limit}),g=await a().transcriptEntities(e,{agentId:p.agent_id,kind:p.kind,cursor:p.cursor,limit:p.limit},m);return i("output","session.view.transcript.entities",yi,g)}},...o?.transcriptContent===void 0?{}:{async content(u,m){const p=i("input","session.view.transcript.content",Iu,u),g=await a().transcriptContent(e,p,m);return i("output","session.view.transcript.content",Tu,g)}},...o?.transcriptDetail===void 0?{}:{async detail(u,m){const p=t?i("input","session.view.transcript.detail",_u,u):u,g=await a().transcriptDetail(e,p,m);return t?i("output","session.view.transcript.detail",Nu,g):g}}},subscribe(u,m){const p=t?i("input","session.view.subscribe",wu,u):u;return a().subscribe(e,p,g=>{if(!t){m(g);return}const f=Mu.safeParse(g);if(!f.success){n+=1,m({type:"protocolError",generation:r,recoverable:n===1,detail:"Invalid session view signal; the transcript must be refreshed."});return}r=Math.max(r,f.data.generation),f.data.type==="transcript"&&f.data.event.type==="transcript.reset"&&(n=0),m(f.data)})}}}const Ve=s().min(1),uo=o=>c({body:o}),po=c({target:Ve}),Y=o=>c({target:Ve,body:o}),mo=c({target:Ve,query:c({agent_id:s().min(1).optional()}).optional()}),ln={read:{method:"GET",suffix:"",input:c({}),output:Gt,okCodes:[0]},submit:{method:"POST",suffix:"/prompts",input:uo(Gi),output:Oi,okCodes:[0],timeoutMs:0},edit:{method:"POST",suffix:"/messages/{target}:edit",input:Y(Mo),output:$t,okCodes:[0]},regenerate:{method:"POST",suffix:"/messages/{target}:regenerate",input:Y(Ao),output:$t,okCodes:[0]},fork:{method:"POST",suffix:":fork",input:uo(Oo),output:Gt,okCodes:[0]},abort:{method:"POST",suffix:"/prompts/{target}:abort",input:mo,output:Pi,okCodes:[0,40903]},abortTurn:{method:"POST",suffix:"/turns/{target}:abort",input:po,output:Ri,okCodes:[0]},move:{method:"POST",suffix:"/prompts/{target}:move",input:Y(qi),output:Ci,okCodes:[0]},replace:{method:"POST",suffix:"/prompts/{target}:replace",input:Y(ji),output:ki,okCodes:[0]},timing:{method:"POST",suffix:"/prompts/{target}:timing",input:Y(Li),output:Ei,okCodes:[0]},hold:{method:"POST",suffix:"/prompts/{target}:hold",input:Y(Ni),output:wi,okCodes:[0]},steer:{method:"POST",suffix:"/prompts/{target}:steer",input:mo,output:Ti,okCodes:[0]},approve:{method:"POST",suffix:"/approvals/{target}",input:Y(Di),output:Ii,okCodes:[0]},answer:{method:"POST",suffix:"/questions/{target}",input:Y(xi),output:_i,okCodes:[0]},dismiss:{method:"POST",suffix:"/questions/{target}:dismiss",input:po,output:bi,okCodes:[0,40909]},cancelTask:{method:"POST",suffix:"/tasks/{target}:cancel",input:c({target:Ve,query:Ui.optional()}),output:$([Ai,Mi]),okCodes:[0,40904]}};function ho(o,e){return e===void 0||e==="main"?{target:o}:{target:o,query:{agent_id:e}}}function ju(o,e,t){const n=(a,i,u,m)=>{const p=u.safeParse(m);if(!p.success)throw new ce(a,i,p.error.issues,m);return p.data},r=async(a,i)=>{if(o===void 0)throw new Error("session commands are unavailable on this transport");const u=ln[a],m=`session.commands.${a}`,p=t?n("input",m,u.input,i):i,g=await o.execute(e,a,p);return t?n("output",m,u.output,g):g};return{read:()=>r("read",{}),submit:a=>r("submit",{body:a}),edit:(a,i)=>r("edit",{target:a,body:i}),regenerate:(a,i)=>r("regenerate",{target:a,body:i}),fork:(a={})=>r("fork",{body:a}),abort:(a,i)=>r("abort",ho(a,i)),abortTurn:a=>r("abortTurn",{target:String(a)}),move:(a,i)=>r("move",{target:a,body:i}),replace:(a,i)=>r("replace",{target:a,body:i}),timing:(a,i)=>r("timing",{target:a,body:i}),hold:(a,i)=>r("hold",{target:a,body:i}),steer:(a,i)=>r("steer",ho(a,i)),approve:(a,i)=>r("approve",{target:a,body:i}),answer:(a,i)=>r("answer",{target:a,body:i}),dismiss:a=>r("dismiss",{target:a}),cancelTask:(a,i={})=>r("cancelTask",{target:a,query:i})}}function qu(o,e){function t(n,r){return o(e,"agentPromptService",r?.waitFor==="terminal"?"submitAndWait":"submit",[n],r===void 0?void 0:{timeoutMs:0,signal:r.signal})}return{media:du((n,r,a,i)=>o(e,n,r,a,i)),switchModel:n=>o(e,"agentPromptService","switchModel",[n]),getModelSwitch:n=>o(e,"agentPromptService","getModelSwitch",[n]),listModelSwitches:()=>o(e,"agentPromptService","listModelSwitches",[]),updateModelSwitch:(n,r)=>o(e,"agentPromptService","updateModelSwitch",r===void 0?[n]:[n,r]),cancelModelSwitch:n=>o(e,"agentPromptService","cancelModelSwitch",[n]),recoverModelSwitch:(n,r,a)=>o(e,"agentPromptService","recoverModelSwitch",a===void 0?[n,r]:[n,r,a]),prompt:t,promptWithSkills:n=>o(e,"agentSkillService","promptWithSkills",[n]),steer:n=>o(e,"agentPromptService","submitSteer",[n]),resumeRecoveredPromptQueue:()=>o(e,"agentPromptService","resumeRecoveredQueue",[]),activateSkill:n=>o(e,"agentSkillService","activate",[n]),activatePluginCommand:n=>o(e,"agentPluginCommandService","activate",[n]),refreshPluginSessionStart:()=>o(e,"agentPluginService","refreshSessionStart",[]),cancel:n=>o(e,"agentLoopService","cancelFromUser",n?.turnId===void 0?[]:[n.turnId]),getLoopStatus:()=>o(e,"agentLoopService","status",[]),runShellCommand:n=>o(e,"agentShellCommandService","run",[n]),cancelShellCommand:n=>o(e,"agentShellCommandService","cancel",[n.commandId]),getModel:()=>o(e,"agentProfileService","getModel",[]),setModel:n=>o(e,"agentProfileService","setModel",[n]),setEffort:n=>o(e,"agentProfileService","setEffort",[n]),getThinking:()=>o(e,"agentProfileService","getEffectiveThinkingLevel",[]),setThinking:n=>o(e,"agentProfileService","setThinking",[n]),getModelCapabilities:()=>o(e,"agentProfileService","getModelCapabilities",[]),getAgentsMdWarning:()=>o(e,"agentProfileService","getAgentsMdWarning",[]),getPermission:()=>o(e,"agentPermissionModeService","mode",[]),setPermission:(n,r)=>o(e,"agentPermissionModeService",r?.broadcast===!1?"setMode":"setModeAndBroadcast",[n]),getGoal:()=>o(e,"agentGoalService","getGoal",[]),createGoal:n=>o(e,"agentGoalService","createGoal",[n]),updateGoal:n=>o(e,"agentGoalService","updateGoal",[n]),pauseGoal:()=>o(e,"agentGoalService","pauseGoal",[]),resumeGoal:n=>o(e,"agentGoalService","resumeGoal",n===void 0?[]:[n]),cancelGoal:()=>o(e,"agentGoalService","cancelGoal",[]),getUsage:()=>o(e,"agentUsageService","status",[]),getContext:async()=>{const[n,r]=await Promise.all([o(e,"agentContextMemoryService","get",[]),o(e,"agentTokenCountingService","statusSize",[])]);return{history:n,tokenCount:r}},appendContext:n=>o(e,"agentContextMemoryService","append",[n]),appendImportedContext:n=>o(e,"agentContextMutationService","appendImported",[n]),clearContext:()=>o(e,"agentContextMemoryService","clear",[]),rebuildContext:()=>o(e,"agentContextRebuildService","rebuild",[]),undo:n=>o(e,"agentConversationUndoService","undo",[n]),listCommands:()=>o(e,"agentCommandService","list",[]),runCommand:n=>o(e,"agentCommandService","run",n.args===void 0?[n.name]:[n.name,n.args]),getRuntime:()=>o(e,"agentRuntimeBindingService","get",[]),switchRuntime:n=>o(e,"agentRuntimeBindingService","switch",[n]),getPlan:()=>o(e,"agentPlanService","status",[]),enterPlan:()=>o(e,"agentPlanService","enter",[]),clearPlan:()=>o(e,"agentPlanService","clear",[]),cancelPlan:n=>o(e,"agentPlanService","cancel",[n?.id]),reconcileContextWhenIdle:n=>o(e,"agentContextInjectorService","reconcileWhenIdle",[n]),getTasks:n=>o(e,"agentTaskService","list",[n?.activeOnly??!1,n?.limit]),stopTask:async n=>{if(n.reason===void 0){await o(e,"agentTaskService","stopByUser",[n.taskId]);return}await o(e,"agentTaskService","stop",[n.taskId,n.reason])},stopTaskWithReason:n=>o(e,"agentTaskService","stop",n.reason===void 0?[n.taskId]:[n.taskId,n.reason]).then(()=>{}),detachTask:n=>o(e,"agentTaskService","detach",[n]),getTaskOutput:n=>o(e,"agentTaskService","readOutput",[n.taskId,n.tail]),getMcpServers:()=>o(e,"agentMcpService","list",[]),waitForMcpInitialLoad:()=>o(e,"agentMcpService","waitForInitialLoad",[]),getMcpStartupDuration:()=>o(e,"agentMcpService","initialLoadDurationMs",[]),reconnectMcpServer:n=>o(e,"agentMcpService","reconnect",[n]),connectMcpServer:n=>o(e,"agentMcpService","connect",[n.name,n.config]),compact:n=>o(e,"agentFullCompactionService","begin",[{source:"manual",instruction:n?.instruction}]),cancelCompaction:()=>o(e,"agentFullCompactionService","cancel",[]),isCompacting:()=>o(e,"agentFullCompactionService","isCompacting",[]),getAutoCompact:()=>o(e,"agentFullCompactionService","getAutoCompact",[]),getDefaultAutoCompact:()=>o(e,"agentFullCompactionService","getDefaultAutoCompact",[]),setAutoCompactOverride:n=>o(e,"agentFullCompactionService","setAutoCompactOverride",[n]),getContextStrategy:()=>o(e,"agentFullCompactionService","getContextStrategy",[]),setContextStrategyOverride:n=>o(e,"agentFullCompactionService","setContextStrategyOverride",[n])}}function Gu(o,e={}){const t=e.validate??!0,n=async(u,m,p,g,f)=>{const b=so[m]?.[p];if(b===void 0)throw new Error(`no contract registered for ${m}.${p}`);if(no(b))throw new Error(`${m}.${p} is a streaming procedure — use callStream instead`);const I=`${m}.${p}`,k=t?ro(I,b,g):g,R=await o.call(u,m,p,k,f);return t?tu(I,b,R):R},r=(u,m,p,g)=>{const f=so[m]?.[p];if(f===void 0)throw new Error(`no contract registered for ${m}.${p}`);if(!no(f))throw new Error(`${m}.${p} is not a streaming procedure — use call instead`);const b=`${m}.${p}`,I=t?ro(b,f,g):g,k=o.stream(u,m,p,I);if(!t)return k;const R=f;return{[Symbol.asyncIterator](){const D=k[Symbol.asyncIterator]();return{async next(){const U=await D.next();return U.done?{done:!0,value:void 0}:{done:!1,value:ou(b,R,U.value)}},async return(U){return await D.return?.(U),{done:!0,value:void 0}}}}}},a=new Set,i=(u,m)=>{const p=new su(o,t,u,m);return a.add(p),p};return{rest:o.rest,terminal:lr(o.terminal),global:vu(n,r),events:i({},Zl),session(u){const m={sessionId:u};return{...fu(n,u),events:i(m,eu),view:Lu(o.sessionView,u,t),commands:ju(o.sessionCommands,u,t),agent(p){const g={sessionId:u,agentId:p};return{...qu(n,g),events:i(g,ma)}}}},close:()=>{for(const u of a)u.close();return a.clear(),o.close()}}}const Mt={kind:"unknown",hasMoreOlder:!0};function $u(o){if(o===null||typeof o!="object")return o;const e=o;if(e.type!=="transcript")return o;const t=e.event;if(t===null||typeof t!="object")return o;const n=t.type;if(n==="transcript.reset")return{...o,event:{...t,coverage:Mt,snapshot:pn(t.snapshot)}};if(n==="transcript.ops"){const r=t.ops;return Array.isArray(r)?{...o,event:{...t,ops:r.map(un)}}:o}return o}function Fu(o){return o===null||typeof o!="object"?o:{...o,coverage:Mt,tool_call_count:void 0}}function Bu(o){if(o===null||typeof o!="object")return o;const e=o.batches;return Array.isArray(e)?{...o,batches:e.map(Vu)}:o}function Vu(o){if(o===null||typeof o!="object")return o;const e=o.ops;return Array.isArray(e)?{...o,ops:e.map(un)}:o}function un(o){if(o===null||typeof o!="object")return o;const e=o;return e.op==="reset"?{...e,coverage:Mt,snapshot:pn(e.snapshot)}:e.op==="tool.count.set"?{...e,count:void 0}:o}function pn(o){return o===null||typeof o!="object"?o:{...o,toolCallCount:void 0,toolCallCountKnown:!1}}class Hu{constructor(e){this.host=e}views=new Map;generation=0;get hasDemand(){return this.views.size>0}subscribe(e,t,n){const r=this.host.nextId(),a={id:r,sessionId:e,input:t,handler:n,attachCount:0};this.views.set(r,a);try{n({type:"status",status:"connecting",generation:this.generation}),this.host.connect(),this.host.isOpen()&&this.attach(a)}catch(i){throw this.views.delete(r),i}return{updateSessionCursor:i=>{a.input={...a.input,sessionCursor:i}},setTranscriptGrades:i=>{if(!this.views.has(r))return;const u=a.input.transcriptSince===void 0?void 0:Object.fromEntries(Object.entries(a.input.transcriptSince).filter(([m])=>Wt[Kt(i,m)]<=Wt[Kt(a.input.transcriptGrades,m)]));a.input={...a.input,transcriptGrades:i,transcriptSince:u},this.host.isOpen()&&this.attach(a)},updateTranscriptCursor:(i,u)=>{a.input={...a.input,transcriptSince:{...a.input.transcriptSince,[i]:u}}},restart:()=>{this.views.has(r)&&this.host.restart()},nudge:()=>{this.views.has(r)&&this.host.nudge()},close:()=>{this.views.delete(r)&&(this.host.isOpen()&&this.host.send({type:"view_detach",id:r}),n({type:"status",status:"closed",generation:this.generation}))}}}opened(){this.generation+=1;for(const e of this.views.values())e.handler({type:"status",status:"open",generation:this.generation}),this.attach(e)}disconnected(e){for(const t of this.views.values())t.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(){this.views.clear()}receive(e){if(e.type!=="view_signal"&&e.type!=="view_error")return!1;const t=typeof e.id=="string"?this.views.get(e.id):void 0;if(t===void 0)return!0;if(e.type==="view_error")this.views.delete(t.id),t.handler({type:"protocolError",generation:this.generation,recoverable:!1,detail:(e.msg??"Session view subscription failed").slice(0,512)});else{const n=e.data,r=n!==null&&typeof n=="object"?n.generation:void 0;if(typeof r=="number"&&r!==this.generation)return!0;const a=Uo(n)?n:$u(n);t.handler(a)}return!0}attach(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:xo}}),e.attachCount+=1}}const Ae=(o,e)=>JSON.stringify([o,e]);class Wu{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,t)=>{if(this.closed)return Promise.reject(new Error("http closed"));const n=Ae(e,t);let r=this.tracked.get(n);return r===void 0&&(r={sessionId:e,terminalId:t,lastSeq:0},this.tracked.set(n,r)),this.socket.connect(),this.socket.isOpen()?this.attach(r):Promise.reject(new Error("socket is not connected"))};terminalDetach=(e,t)=>{this.tracked.delete(Ae(e,t));for(const[n,r]of this.pending)r.sessionId!==e||r.terminalId!==t||(this.pending.delete(n),clearTimeout(r.timer),r.reject(new Error("terminal detached before the attach ack arrived")));this.send("terminal_detach",{session_id:e,terminal_id:t})};terminalInput=(e,t,n)=>{this.send("terminal_input",{session_id:e,terminal_id:t,data:n})};terminalResize=(e,t,n,r)=>{this.send("terminal_resize",{session_id:e,terminal_id:t,cols:n,rows:r})};send(e,t){!this.closed&&this.socket.isOpen()&&this.socket.send({type:e,id:this.socket.nextId(),data:t})}attach(e){const t=this.socket.nextId();return new Promise((n,r)=>{const a=setTimeout(()=>{this.pending.delete(t),r(new Error("terminal attach timed out — the server does not answer terminal frames"))},8e3);this.pending.set(t,{...e,resolve:n,reject:r,timer:a}),this.socket.send({type:"terminal_attach",id:t,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(Ae(e.sessionId,e.terminalId))||this.emit({kind:"unavailable",sessionId:e.sessionId,terminalId:e.terminalId})})}connecting(){this.setStatus("connecting")}disconnected(e){for(const t of this.pending.values())clearTimeout(t.timer),t.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 t of this.statuses)t(e)}emit(e){for(const t of this.listeners)try{t(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 t=e.data;if(typeof t?.session_id!="string"||typeof t.terminal_id!="string")return!0;const n=t.session_id,r=t.terminal_id,a=Ae(n,r),i=this.tracked.get(a);return i===void 0||(e.type==="terminal_output"&&typeof t.seq=="number"&&Number.isSafeInteger(t.seq)&&t.seq>i.lastSeq?(i.lastSeq=t.seq,this.emit({kind:"output",sessionId:n,terminalId:r,seq:t.seq,data:typeof t.payload?.data=="string"?t.payload.data:""})):e.type==="terminal_exit"&&(this.tracked.delete(a),this.emit({kind:"exit",sessionId:n,terminalId:r,exitCode:typeof t.payload?.exit_code=="number"?t.payload.exit_code:null}))),!0}}const Ku=Math.ceil((8<<20)*4/3)+65536,mn={codes:{REQUEST_LIMIT_REJECTED:"request.limit_rejected",REQUEST_QUEUE_TIMEOUT:"request.queue_timeout",REQUEST_QUEUE_FULL:"request.queue_full"},info:{"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."}}};T(mn);const hn={codes:{DISPATCH_LIMIT_EXCEEDED:"dispatch.limit_exceeded"}};T(hn);const gn={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"}};T(gn);const vn={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."}}};T(vn);const Sn={codes:{TASK_ID_EMPTY:"task.task_id_empty",TASK_LIMIT_EXCEEDED:"task.limit_exceeded"},retryable:["task.limit_exceeded"]};T(Sn);const fn={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"},retryable:["thread.delivery_failed","mailbox.legacy_writer_active"]};T(fn);const zu="config.invalid",Qu="provider.api_error",Yu="provider.filtered",Xu="provider.rate_limit",Ju="provider.auth_error",Zu="provider.connection_error",ep="provider.overloaded",tp="context.overflow",yn={codes:{PROVIDER_API_ERROR:Qu,PROVIDER_FILTERED:Yu,PROVIDER_RATE_LIMIT:Xu,PROVIDER_AUTH_ERROR:Ju,PROVIDER_CONNECTION_ERROR:Zu,PROVIDER_OVERLOADED:ep,CONTEXT_OVERFLOW:tp},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."}}};T(yn);const bn={codes:{CONFIG_INVALID:zu,CONFIG_PERSIST_BLOCKED:"config.persist_blocked"}};T(bn);const _n={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"},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}}};T(_n);const In={codes:{CAPABILITY_NOT_FOUND:"capability.not_found",CAPABILITY_UNSUPPORTED:"capability.unsupported",CAPABILITY_INSTALL_IN_PROGRESS:"capability.install_in_progress"}};T(In);const Tn={codes:{CRON_EXPRESSION_INVALID:"cron.expression_invalid"}};T(Tn);const wn={codes:{DEBUG_SCOPE_NOT_FOUND:"debug.scope_not_found",DEBUG_TOKEN_NOT_FOUND:"debug.token_not_found"}};T(wn);const En={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."}}};T(En);const kn={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."}}};T(kn);var J;(o=>{o.serviceIds=new Map,o.DI_TARGET="$di$target",o.DI_DEPENDENCIES="$di$dependencies";function e(n){return n[o.DI_DEPENDENCIES]||[]}o.getServiceDependencies=e;function t(n){return e(n).filter(r=>r.kind==="instance")}o.getInstanceDependencies=t})(J||(J={}));function op(o,e,t,n="instance"){const r=e;r[J.DI_TARGET]===e?r[J.DI_DEPENDENCIES].push({id:o,index:t,kind:n}):(r[J.DI_DEPENDENCIES]=[{id:o,index:t,kind:n}],r[J.DI_TARGET]=e)}function He(o){const e=J.serviceIds.get(o);if(e)return e;const t=function(r,a,i){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");op(t,r,i)};return Object.defineProperty(t,"toString",{value:function(){return o},enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(t,np,{value:!0,enumerable:!1}),J.serviceIds.set(o,t),t}const np=Symbol("serviceIdentifier");He("instantiationService");const sp=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}(?::?\d{2})?)$/,go=s().refine(o=>sp.test(o),{message:"must be an ISO 8601 datetime string"}).transform((o,e)=>{const t=Date.parse(o);return Number.isNaN(t)?(e.addIssue({code:"custom",message:"invalid ISO 8601 datetime"}),$i):new Date(t).toISOString()});c({id:s().min(1),name:s().min(1),media_type:s().min(1),size:l().int().nonnegative(),created_at:go,expires_at:go.optional()});He("fileService");const Cn={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."}}};T(Cn);const Rn={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"}};T(Rn);const Pn={codes:{COMPACTION_FAILED:"compaction.failed",COMPACTION_UNABLE:"compaction.unable"}};T(Pn);const On={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."}}};T(On);const An={codes:{LOOP_MAX_STEPS_EXCEEDED:"loop.max_steps_exceeded",TURN_AGENT_BUSY:"turn.agent_busy"},retryable:["turn.agent_busy"],info:{"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".'}}};T(An);const Mn={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"}};T(Mn);const Un={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."}}};T(Un);const xn={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}}};T(xn);He("hostProcessService");const fe={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."}}};T(fe);fe.codes.OS_PROCESS_SPAWN_FAILED,fe.codes.OS_PROCESS_KILL_FAILED,fe.codes.SHELL_GIT_BASH_NOT_FOUND;const Dn={codes:{PLUGIN_NOT_FOUND:"plugin.not_found",PLUGIN_LOAD_FAILED:"plugin.load_failed",PLUGIN_READ_ONLY:"plugin.read_only"}};T(Dn);const Nn={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"}};T(Nn);const Ln={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"}};T(Ln);const jn={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."}}};T(jn);const qn={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"}};T(qn);const Gn={codes:{SESSION_INDEX_BUILDING:"session.index_building"},retryable:["session.index_building"]};T(Gn);const $n={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"]};T($n);const Fn={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"}};T(Fn);const Bn={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."}}};T(Bn);const Vn={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."}}};T(Vn);He("fileSystemStorageService");const Hn={codes:{TERMINAL_NOT_FOUND:"terminal.not_found"}};T(Hn);const Wn={codes:{TURN_ID_CONFLICT:"usage.turn_id_conflict"}};T(Wn);const Kn={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}}};T(Kn);const zn={codes:{WORKSPACE_NOT_FOUND:"workspace.not_found"}};T(zn);const Qn={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"}};T(Qn);const Yn={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"}};T(Yn);({...mn.codes,...Ho.codes,...hn.codes,...gn.codes,...vn.codes,...Sn.codes,...fn.codes,...yn.codes,...bn.codes,..._n.codes,...In.codes,...Tn.codes,...wn.codes,...kn.codes,...Cn.codes,...Rn.codes,...Pn.codes,...On.codes,...An.codes,...Mn.codes,...Un.codes,...Wo.codes,...xn.codes,...fe.codes,...Dn.codes,...Nn.codes,...Ln.codes,...jn.codes,...qn.codes,...Gn.codes,...$n.codes,...Fn.codes,...Vn.codes,...Hn.codes,...Wn.codes,...Kn.codes,...zn.codes,...Qn.codes,...Yn.codes,...En.codes,...Bn.codes});class N extends Error{constructor(e,t,n,r,a,i){super(t),this.code=e,this.details=n,this.reason=r,this.requestId=a,this.data=i,this.name="RPCError"}}const Xn=96*1024;async function ip(o,e=Xn){if(o.body===null)throw new SyntaxError("Empty response body");const t=o.body.getReader(),n=[];let r=0;try{for(;;){const u=await t.read();if(u.done)break;if(r+=u.value.byteLength,r>e)throw await t.cancel("decoded response budget exceeded"),new N(50001,`Session response exceeded ${e} decoded bytes`);n.push(u.value)}const a=new Uint8Array(r);let i=0;for(const u of n)a.set(u,i),i+=u.byteLength;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}finally{t.releaseLock()}}function vo(o){const e=o.format??ap(o.filename),t=o.filename??`persona.${e}`,n=new FormData;return n.append("file",new Blob([Jn(o.data)],{type:cp(e)}),t),e!==void 0&&n.append("format",e),"id"in o&&o.id!==void 0&&n.append("id",o.id),"name"in o&&o.name!==void 0&&n.append("name",o.name),n}function rp(o,e,t){const n=e??"application/octet-stream",r=n==="image/jpeg"?"jpg":n==="image/webp"?"webp":"png",a=new FormData;return t!==void 0&&a.append("shape",t),a.append("file",new Blob([Jn(o)],{type:n}),`avatar.${r}`),a}function Jn(o){return o.slice().buffer}function ap(o){const e=o?.toLowerCase();if(e?.endsWith(".png"))return"png";if(e?.endsWith(".charx"))return"charx";if(e?.endsWith(".json"))return"json"}function cp(o){return o==="png"?"image/png":o==="charx"?"application/zip":"application/json"}function dp(o){const e="/remote-connections",t=encodeURIComponent;return{list:()=>o.json(e),inbound:()=>o.json(e+"/inbound"),setInbound:n=>o.json(e+"/inbound",{method:"PUT",body:{enabled:n}}),invite:n=>o.json(e+"/inbound/invitations",{method:"POST",body:n}),revoke:n=>o.json(e+"/inbound/grants/"+t(n)+"/revoke",{method:"POST",body:{}}),add:n=>o.json(e,{method:"POST",body:n}),remove:n=>o.json(e+"/"+t(n),{method:"DELETE"}),setEnabled:(n,r)=>o.json(e+"/"+t(n)+"/enabled",{method:"PUT",body:{enabled:r}}),retry:n=>o.json(e+"/"+t(n)+"/retry",{method:"POST",body:{}}),summary:(n,r)=>o.json(e+"/"+t(n)+"/call",{...r,method:"POST",body:{operation:"spaceSummary"}}),handshake:()=>o.json(e+"/handshake"),sshPlan:(n,r)=>o.json(e+"/ssh/plan",{...r,method:"POST",body:n}),sshExecute:(n,r,a)=>o.json(e+"/ssh/plans/"+t(n)+"/execute",{...a,method:"POST",body:r}),sshRegister:(n,r)=>o.json(e+"/ssh/register",{...r,method:"POST",body:n}),sshStatus:()=>o.json(e+"/ssh/status")}}function lp(o){if(!/^[0-9a-f-]{36}$/.test(o.connectionId))throw new Error("Invalid connectionId");const t=o.endpoint.replace(/\/+$/,"")+"/api/remote-connections/"+encodeURIComponent(o.connectionId),n=o.fetch??globalThis.fetch,r=async(i,u={})=>{const m=new URL(i instanceof Request?i.url:String(i)),p=u.method??(i instanceof Request?i.method:"GET"),g=dr(p,m.pathname);if(g===void 0)throw new N(40301,"Operation is not available to a remote space");const f={};for(const[U,L]of m.searchParams){const Z=f[U];f[U]=Z===void 0?L:Array.isArray(Z)?[...Z,L]:[Z,L]}const b=["media","mediaPreview","file","appearanceAsset","personaAvatar"].includes(g.operation),I=new Headers(u.headers??(i instanceof Request?i.headers:void 0));if(g.operation==="fileUpload")return I.delete("authorization"),o.token!==void 0&&I.set("authorization",`Bearer ${o.token}`),n(t+"/upload",{...u,headers:I,method:"POST",redirect:"error"});const k=typeof u.body=="string"?JSON.parse(u.body):void 0,R={operation:g.operation,params:g.params,query:f,body:k,headers:{ifNoneMatch:I.get("if-none-match")??void 0,range:I.get("range")??void 0}},D=new Headers({"content-type":"application/json"});return o.token!==void 0&&D.set("authorization",`Bearer ${o.token}`),n(t+(b?"/download":"/call"),{method:"POST",headers:D,body:JSON.stringify(R),signal:u.signal,redirect:"error",credentials:"same-origin"})},a=new URL(t+"/events");return a.protocol=a.protocol==="https:"?"wss:":"ws:",{fetch:r,eventsUrl:a.toString()}}function up(o){const e="/web-access";return{status:async()=>Ee.parse(await o.json(e)),enable:async t=>Ee.parse(await o.json(e,{method:"PUT",body:Vi.parse(t)})),disable:async()=>Ee.parse(await o.json(e,{method:"DELETE"})),issueLink:async()=>Bi.parse(await o.json(e+"/links",{method:"POST",body:{}})),revoke:async t=>Ee.parse(await o.json(e+"/revoke",{method:"POST",body:{sessionId:t}})),current:async()=>Xe.parse(await o.json(e+"/session",{skipAuth:!0})),exchange:async t=>Xe.parse(await o.json(e+"/exchange",{method:"POST",body:Fi.parse(t),skipAuth:!0})),logout:async()=>Xe.parse(await o.json(e+"/logout",{method:"POST",body:{},skipAuth:!0}))}}function pp(o){const e="/thread-bridges",t=(n,r)=>e+"/"+n+"/"+encodeURIComponent(r);return{status:n=>o.json(e,n),approve:(n,r)=>o.json(e+"/inbound",{...r,method:"POST",body:n}),registerTarget:(n,r)=>o.json(e+"/targets",{...r,method:"POST",body:n}),provisionLocal:(n,r)=>o.json(e+"/local",{...r,method:"POST",body:n}),install:(n,r)=>o.json(e+"/outbound",{...r,method:"POST",body:n}),setEnabled:(n,r,a,i)=>o.json(t(n,r)+"/enabled",{...i,method:"PUT",body:{enabled:a}}),revoke:(n,r,a)=>o.json(t(n,r)+"/revoke",{...a,method:"POST",body:{}}),receipts:(n,r)=>o.json(e+"/receipts",{...r,query:n}),retry:n=>o.json(e+"/retry",{...n,method:"POST",body:{}})}}function mp(o){const e="/usage-export",t=(n,r)=>`${e}/destinations/${encodeURIComponent(n)}/${r}`;return{status:async()=>Q.parse(await o.json(e)),saveDraft:async n=>Je.parse(await o.json(e+"/destinations",{method:"POST",body:zi.parse(n)})),preview:async n=>Ft.parse(await o.json(t(n,"preview"))),testProtocol:n=>o.json(t(n,"test"),{method:"POST",body:{}}),enable:async(n,r)=>Je.parse(await o.json(t(n,"enable"),{method:"POST",body:Ki.parse(r)})),disable:async n=>Je.parse(await o.json(t(n,"disable"),{method:"POST",body:{}})),remove:(n,r)=>o.json(t(n,"remove"),{method:"POST",body:{discard_pending:r}}),syncNow:async n=>Q.parse(await o.json(t(n,"sync"),{method:"POST",body:{}})),backfill:async(n,r)=>Ft.parse(await o.json(t(n,"backfill"),{method:"POST",body:Wi.parse(r)})),diagnostics:async()=>Q.parse(await o.json(e+"/diagnostics")),exportLocal:n=>o.json(t(n,"export")),rebuild:async n=>Q.parse(await o.json(e+"/rebuild",{method:"POST",body:{force:n}})),retry:async n=>Q.parse(await o.json(t(n,"retry"),{method:"POST",body:{}})),setQueueCapacity:async n=>Q.parse(await o.json(e+"/queue-capacity",{method:"PUT",body:{bytes:n}})),clearQueue:async(n,r)=>Q.parse(await o.json(t(n,"clear-queue"),{method:"POST",body:{acknowledge:r}})),withdraw:async(n,r)=>Q.parse(await o.json(t(n,"withdraw"),{method:"POST",body:{acknowledge:r}})),handoff:async n=>ue.nullable().parse(await o.json(t(n,"handoff"))),planHandoff:async(n,r)=>ue.parse(await o.json(t(n,"handoff/plan"),{method:"POST",body:{cutoff_at:r}})),armHandoff:async(n,r)=>ue.parse(await o.json(t(n,"handoff/arm"),{method:"POST",body:Hi.parse(r)})),refreshHandoff:async n=>ue.nullable().parse(await o.json(t(n,"handoff/refresh"),{method:"POST",body:{}})),rollbackHandoff:async(n,r,a)=>ue.parse(await o.json(t(n,"handoff/rollback"),{method:"POST",body:{cutoff_at:r,acknowledge:a}}))}}function hp(o){return{webAccess:up(o),connections:dp(o),threadBridges:pp(o),usageExport:mp(o),healthz:async e=>{try{return(await o.json("/healthz",{baseUrl:e,timeoutMs:0,skipAuth:!0}))?.ok===!0}catch{return!1}},meta:()=>o.json("/meta"),renewLease:e=>o.json("/leases",{method:"POST",body:e,allowMissingRoute:!0}),usage:e=>o.json("/usage",{query:e}),requestGovernance:()=>o.json("/usage/realtime"),usageRescan:{status:()=>o.json("/usage/rescan"),start:()=>o.json("/usage/rescan",{method:"POST"})},usagePricing:{get:e=>o.json("/usage/pricing",{query:{model:e}}),set:e=>o.json("/usage/pricing",{method:"PUT",body:e})},shortcuts:{read:e=>o.json("/gui/shortcuts",{query:{platform:e}}),write:(e,t)=>o.json("/gui/shortcuts",{method:"PUT",query:{platform:e},body:{preferences:t}}),reset:(e,t={})=>o.json("/gui/shortcuts/reset",{method:"POST",query:{platform:e},body:t})},browser:{list:()=>o.json("/browser/connections"),upsert:(e,t)=>o.json(`/browser/connections/${encodeURIComponent(e)}`,{method:"PUT",body:t}),remove:e=>o.json(`/browser/connections/${encodeURIComponent(e)}`,{method:"DELETE"}),setDefault:e=>o.json("/browser/default",{method:"PUT",body:{browser:e}}),status:e=>o.json(`/browser/connections/${encodeURIComponent(e)}:status`),tabs:e=>o.json(`/browser/connections/${encodeURIComponent(e)}:tabs`),catalog:(e,t)=>o.json(`/browser/connections/${encodeURIComponent(e)}:catalog`,{query:{includeSchema:t?.includeSchema}}),check:e=>o.json(`/browser/connections/${encodeURIComponent(e)}:check`,{method:"POST",body:{}}),connect:e=>o.json(`/browser/connections/${encodeURIComponent(e)}:connect`,{method:"POST",body:{}}),disconnect:e=>o.json(`/browser/connections/${encodeURIComponent(e)}:disconnect`,{method:"POST",body:{}})},ssh:{list:e=>o.json("/ssh/hosts",{query:{workspace_id:e}}),discover:()=>o.json("/ssh/hosts:discover"),upsert:(e,t,n)=>o.json(`/ssh/hosts/${encodeURIComponent(e)}`,{method:"PUT",body:t,query:{workspace_id:n}}),remove:(e,t)=>o.json(`/ssh/hosts/${encodeURIComponent(e)}`,{method:"DELETE",query:{workspace_id:t}}),configSync:()=>o.json("/ssh/config-sync"),setConfigSync:e=>o.json("/ssh/config-sync",{method:"PUT",body:{enabled:e}}),hostKeys:(e,t)=>o.json(`/ssh/hosts/${encodeURIComponent(e)}:host-keys`,{query:{workspace_id:t}}),connectionApproval:()=>o.json("/ssh/connection-approval"),setConnectionApproval:e=>o.json("/ssh/connection-approval",{method:"PUT",body:{enabled:e}}),writeBack:(e,t)=>o.json(`/ssh/hosts/${encodeURIComponent(e)}:write-back`,{method:"POST",body:{},query:{workspace_id:t}}),status:(e,t)=>o.json(`/ssh/hosts/${encodeURIComponent(e)}:status`,{query:{workspace_id:t}}),disconnect:(e,t)=>o.json(`/ssh/hosts/${encodeURIComponent(e)}:disconnect`,{method:"POST",body:{},query:{workspace_id:t}}),sessionHosts:e=>o.json(`/sessions/${encodeURIComponent(e)}/ssh/hosts`),addSessionHost:(e,t)=>o.json(`/sessions/${encodeURIComponent(e)}/ssh/hosts/${encodeURIComponent(t)}`,{method:"PUT",body:{}}),removeSessionHost:(e,t)=>o.json(`/sessions/${encodeURIComponent(e)}/ssh/hosts/${encodeURIComponent(t)}`,{method:"DELETE"}),submitApproval:(e,t,n)=>o.json(`/sessions/${encodeURIComponent(e)}/ssh/approvals/${encodeURIComponent(t)}`,{method:"POST",body:n}),copySharedCredentialsToIsolated:e=>o.json("/ssh/credentials:copy-to-isolated",{method:"POST",body:e})},worktrees:{list:e=>o.json("/worktrees",{query:e}),get:e=>o.json(`/worktrees/${encodeURIComponent(e)}`),inspect:e=>o.json(`/worktrees/${encodeURIComponent(e)}:inspect`,{method:"POST",body:{}}),remove:(e,t={})=>o.json(`/worktrees/${encodeURIComponent(e)}:remove`,{method:"POST",body:t}),gc:e=>o.json("/worktrees:gc",{method:"POST",body:{dryRun:e}})},sessions:{list:(e={})=>o.json("/sessions",{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,exclude_empty:e.exclude_empty,workspace_id:e.workspace_id,persona:e.persona}}),listEphemeral:(e={})=>o.json("/sessions/ephemeral",{query:{...e,page_size:e.page_size??50}}),create:e=>o.json("/sessions",{method:"POST",body:e}),saveEphemeral:e=>o.json(`/sessions/${encodeURIComponent(e)}/ephemeral/save`,{method:"POST",body:{}}),endEphemeral:(e,t={})=>o.json(`/sessions/${encodeURIComponent(e)}/ephemeral/end`,{method:"POST",body:t}),compact:(e,t={})=>o.json(`/sessions/${encodeURIComponent(e)}:compact`,{method:"POST",body:t}),getAutoCompact:(e,t)=>o.json(`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/auto-compact`),setAutoCompact:(e,t,n)=>o.json(`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/auto-compact`,{method:"PATCH",body:n}),inspectHooks:(e,t)=>o.json(`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/hooks`),undo:(e,t={})=>o.json(`/sessions/${encodeURIComponent(e)}:undo`,{method:"POST",body:t}),updateProfile:(e,t)=>o.json(`/sessions/${encodeURIComponent(e)}/profile`,{method:"POST",body:t}),getPersonaSettings:e=>o.json(`/sessions/${encodeURIComponent(e)}/persona-settings`),applyPersonaSettings:(e,t={})=>o.json(`/sessions/${encodeURIComponent(e)}/persona-settings`,{method:"POST",body:t}),archive:e=>o.json("/sessions/"+encodeURIComponent(e)+":archive",{method:"POST",body:{}}),restore:e=>o.json("/sessions/"+encodeURIComponent(e)+":restore",{method:"POST",body:{}}),goal:e=>o.json("/sessions/"+encodeURIComponent(e)+"/goal"),listMessages:(e,t={})=>o.json(`/sessions/${encodeURIComponent(e)}/messages`,{query:{before_id:t.before_id,page_size:t.page_size??50}}),listPrompts:e=>o.json(`/sessions/${encodeURIComponent(e)}/prompts`),listApprovals:async e=>(await o.json(`/sessions/${encodeURIComponent(e)}/approvals`,{query:{status:"pending"}})).items,listQuestions:async e=>(await o.json(`/sessions/${encodeURIComponent(e)}/questions`,{query:{status:"pending"}})).items,listTasks:(e,t)=>o.json(`/sessions/${encodeURIComponent(e)}/tasks`,{query:{status:t?.status,page_size:t?.page_size,offset:t?.offset}}),getTask:(e,t,n={})=>o.json(`/sessions/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}`,{query:{with_output:n.with_output,output_bytes:n.output_bytes,agent_id:n.agent_id}}),listSkills:e=>o.json(`/sessions/${encodeURIComponent(e)}/skills`),activateSkill:(e,t,n={})=>o.json(`/sessions/${encodeURIComponent(e)}/skills/${encodeURIComponent(t)}:activate`,{method:"POST",body:n}),fsSearch:(e,t,n)=>o.json(`/sessions/${encodeURIComponent(e)}/fs:search`,{method:"POST",body:t,signal:n?.signal,timeoutMs:n?.timeoutMs}),media:async(e,t,n)=>re(o,`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(t)}`,{signal:n?.signal,timeoutMs:n?.timeoutMs,headers:ie(n)}),mediaPreview:async(e,t,n)=>re(o,`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(t)}/preview`,{query:{media_type:n?.mediaType},signal:n?.signal,timeoutMs:n?.timeoutMs,headers:ie(n)},64*1024),downloadMedia:(e,t,n,r)=>o.raw(`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(t)}`,{method:"GET",expectBinary:!0,signal:r?.signal,timeoutMs:r?.timeoutMs??0,headers:ie(r)},a=>mt(a,n,r?.signal)),export:e=>o.raw(`/sessions/${encodeURIComponent(e)}/export`,{method:"POST",body:{},timeoutMs:0,expectBinary:!0,jsonErrorOnSuccess:!0},async t=>{const n=t.headers.get("content-disposition")??"",r=/filename\*?=(?:UTF-8'')?"?([^";]+)"?/iu.exec(n);return{blob:await t.blob(),filename:r?.[1]??`kiki-session-${e}.zip`}})},bots:{list:()=>o.json("/bots"),enable:e=>o.json(`/bots/${encodeURIComponent(e)}/enable`,{method:"POST"}),ensureHomeSession:e=>o.json(`/bots/${encodeURIComponent(e)}/home`,{method:"POST"}),update:(e,t)=>o.json(`/bots/${encodeURIComponent(e)}`,{method:"PATCH",body:t})},rooms:{list:()=>o.json("/rooms"),listItems:()=>o.json("/rooms/items"),get:e=>o.json(`/rooms/${encodeURIComponent(e)}`),create:e=>o.json("/rooms",{method:"POST",body:e}),createFromThreads:e=>o.json("/rooms/from-threads",{method:"POST",body:e}),searchThreads:e=>o.json("/rooms/threads",{query:e}),addMember:(e,t)=>o.json(`/rooms/${encodeURIComponent(e)}/members`,{method:"POST",body:t}),removeMember:(e,t)=>o.json(`/rooms/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:"DELETE"}),update:(e,t)=>o.json(`/rooms/${encodeURIComponent(e)}`,{method:"PATCH",body:t}),delete:async e=>{await o.json(`/rooms/${encodeURIComponent(e)}`,{method:"DELETE"})},postUserMessage:(e,t)=>o.json(`/rooms/${encodeURIComponent(e)}/messages`,{method:"POST",body:t}),pause:e=>o.json(`/rooms/${encodeURIComponent(e)}/pause`,{method:"POST"}),continue:e=>o.json(`/rooms/${encodeURIComponent(e)}/continue`,{method:"POST"}),stop:e=>o.json(`/rooms/${encodeURIComponent(e)}/stop`,{method:"POST"}),log:(e,t)=>o.json(`/rooms/${encodeURIComponent(e)}/log`,{query:t}),usage:e=>o.json(`/rooms/${encodeURIComponent(e)}/usage`)},personas:{list:e=>o.json("/personas",{query:{includeArchived:e?.includeArchived}}),get:e=>o.json(`/personas/${encodeURIComponent(e)}`),ensureHome:e=>o.json(`/personas/${encodeURIComponent(e)}/home`,{method:"POST"}),setHome:(e,t)=>o.json(`/personas/${encodeURIComponent(e)}/home`,{method:"PUT",body:{sessionId:t}}),updateState:(e,t)=>o.json(`/personas/${encodeURIComponent(e)}/state`,{method:"PATCH",body:t}),put:e=>o.json(`/personas/${encodeURIComponent(e.definition.id)}`,{method:"PUT",body:e}),duplicate:(e,t)=>o.json(`/personas/${encodeURIComponent(e)}:duplicate`,{method:"POST",body:t??{}}),archive:(e,t=!0)=>o.json(`/personas/${encodeURIComponent(e)}:archive`,{method:"POST",body:{archived:t}}),delete:(e,t)=>o.json(`/personas/${encodeURIComponent(e)}`,{method:"DELETE",query:{expectedRevision:t?.expectedRevision}}),previewImport:e=>o.json("/personas/import/preview",{method:"POST",rawBody:vo(e)}),importCard:e=>o.json("/personas/import",{method:"POST",rawBody:vo(e)}),exportCard:(e,t,n)=>re(o,`/personas/${encodeURIComponent(e)}/export`,{query:{format:t,includeMemory:n?.includeMemory},signal:n?.signal,timeoutMs:n?.timeoutMs}),getAvatar:(e,t)=>re(o,`/personas/${encodeURIComponent(e)}/avatar`,{signal:t?.signal,timeoutMs:t?.timeoutMs}),putAvatar:(e,t,n,r)=>o.json(`/personas/${encodeURIComponent(e)}/avatar`,{method:"PUT",rawBody:rp(t,n,r)}),deleteAvatar:e=>o.json(`/personas/${encodeURIComponent(e)}/avatar`,{method:"DELETE"}),avatar:({id:e,name:t,avatarMime:n,avatarShape:r})=>({id:e,name:t,avatarUrl:n===void 0?void 0:`/api/personas/${encodeURIComponent(e)}/avatar`,avatarShape:n===void 0?void 0:r})},skills:{readBuiltinContent:e=>o.json(`/skills/${encodeURIComponent(e)}:content`),previewHostInstall:e=>o.json("/skills/kiki-as-subagent:preview-install",{method:"POST",body:{host:e}}),installHost:(e,t)=>o.json("/skills/kiki-as-subagent:install",{method:"POST",body:{host:e,revision:t,confirmed:!0}})},skins:{list:()=>o.json("/skins",{allowMissingRoute:!0}),get:e=>o.json(`/skins/${encodeURIComponent(e)}`)},workspaces:{list:()=>o.json("/workspaces"),inspect:e=>o.json("/workspaces:inspect",{method:"POST",body:{root:e}}),rename:(e,t)=>o.json(`/workspaces/${encodeURIComponent(e)}`,{method:"PATCH",body:{name:t}}),setPinned:(e,t)=>o.json(`/workspaces/${encodeURIComponent(e)}`,{method:"PATCH",body:{pinned:t}}),remove:e=>o.json(`/workspaces/${encodeURIComponent(e)}`,{method:"DELETE"}),listSkills:e=>o.json(`/workspaces/${encodeURIComponent(e)}/skills`)},homes:{presets:()=>o.json("/homes/presets"),list:()=>o.json("/homes"),detail:e=>o.json(`/homes/${encodeURIComponent(e)}/settings`),preview:(e,t)=>o.json(`/homes/${encodeURIComponent(e)}/settings/preview`,{method:"POST",body:t}),apply:(e,t)=>o.json(`/homes/${encodeURIComponent(e)}/settings/apply`,{method:"POST",body:t}),undo:(e,t)=>o.json(`/homes/${encodeURIComponent(e)}/settings/undo`,{method:"POST",body:{undo_id:t}}),importPreferences:(e,t)=>o.json(`/homes/${encodeURIComponent(e)}/settings/import-preferences`,{method:"POST",body:t}),create:e=>o.json("/homes",{method:"POST",body:e}),attach:e=>o.json("/homes:attach",{method:"POST",body:e}),sshCopyCandidates:e=>o.json(`/homes/${encodeURIComponent(e)}/ssh-copy-candidates`),update:(e,t)=>o.json(`/homes/${encodeURIComponent(e)}`,{method:"PATCH",body:t}),remove:e=>o.json(`/homes/${encodeURIComponent(e)}`,{method:"DELETE"}),erase:(e,t)=>o.json(`/homes/${encodeURIComponent(e)}:delete`,{method:"POST",body:t})},config:{get:()=>o.json("/config"),patch:e=>o.json("/config",{method:"POST",body:e}),removeOverride:e=>o.json("/config/overrides:remove",{method:"POST",body:e}),previewModelGenerationMigration:()=>o.json("/config/model-generation-migration"),applyModelGenerationMigration:e=>o.json("/config/model-generation-migration/apply",{method:"POST",body:{revision:e,confirmed:!0}}),restoreModelGenerationMigration:(e,t)=>o.json("/config/model-generation-migration/restore",{method:"POST",body:{backup_key:e,revision:t,confirmed:!0}})},catalog:{list:e=>o.json("/catalog/providers",{signal:e?.signal,timeoutMs:e?.timeoutMs}),provider:e=>o.json(`/catalog/providers/${encodeURIComponent(e)}`),importProvider:(e,t)=>o.json("/providers:import_catalog",{method:"POST",body:e,signal:t?.signal,timeoutMs:t?.timeoutMs}),importRegistry:(e,t)=>o.json("/providers:import_registry",{method:"POST",body:e,signal:t?.signal,timeoutMs:t?.timeoutMs})},oauth:{usage:(e,t)=>o.json("/oauth/usage",{query:{provider:e},signal:t?.signal,timeoutMs:t?.timeoutMs})},providers:{probe:(e,t)=>o.json("/providers:probe",{method:"POST",body:e,signal:t?.signal,timeoutMs:t?.timeoutMs}),test:(e,t)=>o.json(`/providers/${encodeURIComponent(e)}:test`,{method:"POST",body:{},signal:t?.signal,timeoutMs:t?.timeoutMs}),health:()=>o.json("/providers:health")},nbSearch:{capabilities:()=>o.json("/nb-search/capabilities"),keyUsage:(e,t=!1,n)=>o.json("/nb-search/keys/usage",{method:"POST",body:{instance_id:e,refresh:t},signal:n?.signal,timeoutMs:n?.timeoutMs}),test:e=>o.json("/nb-search/test",{signal:e?.signal,timeoutMs:e?.timeoutMs}),readCredential:(e,t)=>o.json("/nb-search/credentials/read",{method:"POST",body:{instance_id:e,reveal:t}}),writeCredential:(e,t,n,r)=>o.json("/nb-search/credentials/write",{method:"POST",body:{instance_id:e,value:t,expected_version:n,expected_binding:r}})},requestIdentity:{get:()=>o.json("/request-identity"),preview:e=>o.json("/request-identity/preview",{method:"POST",body:e}),duplicateProfile:(e,t)=>o.json("/request-identity/profiles",{method:"POST",body:{from:e,label:t}}),updateProfile:(e,t)=>o.json(`/request-identity/profiles/${encodeURIComponent(e)}`,{method:"PUT",body:t}),deleteProfile:e=>o.json(`/request-identity/profiles/${encodeURIComponent(e)}`,{method:"DELETE"}),checkTrack:(e,t)=>o.json(`/request-identity/tracks/${e}/check`,{method:"POST",body:{source:t}}),applyTrack:(e,t)=>o.json(`/request-identity/tracks/${e}/apply`,{method:"POST",body:{version:t}}),trackAction:(e,t)=>o.json(`/request-identity/tracks/${e}/${t}`,{method:"POST",body:{}}),pinTrack:(e,t)=>o.json(`/request-identity/tracks/${e}/pin`,{method:"PUT",body:{pinned:t}}),setManifestUrl:e=>o.json("/request-identity/manifest",{method:"PUT",body:{url:e}})},notifications:{getSettings:()=>o.json("/notifications/settings"),updateSettings:e=>o.json("/notifications/settings",{method:"PUT",body:e}),listProviders:()=>o.json("/notifications/providers"),upsertInstance:(e,t,n)=>o.json(`/notifications/instances/${encodeURIComponent(e)}`,{method:"PUT",body:{instance:t,slots:n}}),deleteInstance:e=>o.json(`/notifications/instances/${encodeURIComponent(e)}`,{method:"DELETE"}),upsertChannel:(e,t)=>o.json(`/notifications/channels/${encodeURIComponent(e)}`,{method:"PUT",body:t}),deleteChannel:e=>o.json(`/notifications/channels/${encodeURIComponent(e)}`,{method:"DELETE"}),setCredential:(e,t)=>o.json(`/notifications/credentials/${encodeURIComponent(e)}`,{method:"PUT",body:{value:t}}),checkCredential:e=>o.json(`/notifications/instances/${encodeURIComponent(e)}:check`,{method:"POST",body:{}}),sendTest:e=>o.json(`/notifications/channels/${encodeURIComponent(e)}:test`,{method:"POST",body:{}}),listDeliveries:e=>o.json("/notifications/deliveries",{query:e===void 0?void 0:{channel_id:e}})},secrets:{reveal:e=>o.json("/secrets:reveal",{method:"POST",body:{ref:e}})},executors:{list:()=>o.json("/executors"),listLocalSessions:(e,t,n)=>o.json(`/executors/${encodeURIComponent(e)}/local-sessions`,{...n,query:t}),getLocalSession:(e,t,n)=>o.json(`/executors/${encodeURIComponent(e)}/local-sessions/${encodeURIComponent(t)}`,n),resumeLocalSession:(e,t,n,r)=>o.json(`/executors/${encodeURIComponent(e)}/local-sessions/${encodeURIComponent(t)}/resume`,{...r,method:"POST",body:n})},agents:{list:e=>o.json("/agents",{query:typeof e=="string"?{workspace_id:e}:e}),previewExecutorPrompt:(e,t={})=>o.json(`/agents/${encodeURIComponent(e)}/executor-prompt:preview`,{method:"POST",body:t}),previewModelMenu:(e,t,n)=>o.json(`/agents/${encodeURIComponent(e)}/model-menu:preview`,{...n,method:"POST",body:t}),create:e=>o.json("/agent-profiles",{method:"POST",body:e}),update:(e,t)=>o.json(`/agents/${encodeURIComponent(e)}`,{method:"PATCH",body:t}),shipped:{list:()=>o.json("/agents/shipped"),restore:e=>o.json(`/agents/shipped/${encodeURIComponent(e)}:restore`,{method:"POST",body:{}})}},filesystem:{readHostFile:e=>o.raw("/fs:content",{method:"GET",query:{path:e}},t=>t.text()),previewHostFile:(e,t)=>o.raw("/fs:content",{method:"GET",query:{path:e},headers:{range:`bytes=0-${t-1}`}},async n=>({text:await n.text(),truncated:n.status===206&&Number(n.headers.get("content-range")?.split("/")[1])>t})),readHostFileBytes:(e,t)=>re(o,"/fs:content",{query:{path:e},signal:t?.signal,timeoutMs:t?.timeoutMs,headers:ie(t)}),readHostMediaPreview:(e,t)=>re(o,"/fs:content",{query:{path:e,preview:"media"},signal:t?.signal,timeoutMs:t?.timeoutMs,headers:ie(t)},64*1024),downloadHostFile:(e,t,n)=>o.raw("/fs:content",{method:"GET",expectBinary:!0,query:{path:e},signal:n?.signal,timeoutMs:n?.timeoutMs??0,headers:ie(n)},r=>mt(r,t,n?.signal)),workspaceFsSearch:(e,t,n)=>o.json("/workspace/fs:search",{method:"POST",body:{...t,workspace:e},signal:n?.signal,timeoutMs:n?.timeoutMs})},threads:{messages:(e,t)=>o.json("/threads/messages",{query:e,signal:t?.signal,timeoutMs:t?.timeoutMs})},search:{messages:(e,t)=>o.json("/search",{method:"POST",body:e,signal:t?.signal,timeoutMs:t?.timeoutMs}),retry:()=>o.json("/search/retry",{method:"POST"}),status:()=>o.json("/search/status",{method:"GET"})},cron:{list:(e={})=>o.json("/cron",{query:{session_id:e.session_id,page_size:e.page_size,offset:e.offset}}),pause:(e,t={})=>o.json(`/cron/${encodeURIComponent(e)}:pause`,{method:"POST",body:{},query:{session_id:t.session_id}}),resume:(e,t={})=>o.json(`/cron/${encodeURIComponent(e)}:resume`,{method:"POST",body:{},query:{session_id:t.session_id}}),run:(e,t={})=>o.json(`/cron/${encodeURIComponent(e)}:run`,{method:"POST",body:{},query:{session_id:t.session_id}}),remove:(e,t={})=>o.json(`/cron/${encodeURIComponent(e)}`,{method:"DELETE",query:{session_id:t.session_id}})},runtime:{listTools:e=>o.json("/tools",{query:e===void 0?void 0:{session_id:e}}),listMcpServers:()=>o.json("/mcp/runtime/servers"),restartMcpServer:e=>o.json("/mcp/runtime/servers/"+encodeURIComponent(e)+":restart",{method:"POST",body:{}})},plugins:{marketplace:()=>o.json("/plugins/marketplace"),preview:e=>o.json("/plugins:preview",{method:"POST",body:e,timeoutMs:0}),install:e=>o.json("/plugins",{method:"POST",body:typeof e=="string"?{source:e}:e,timeoutMs:0}),info:e=>o.json("/plugins/"+encodeURIComponent(e)),settings:e=>o.json(`/plugins/${encodeURIComponent(e)}/settings`),setSettings:(e,t)=>o.json(`/plugins/${encodeURIComponent(e)}/settings`,{method:"POST",body:t}),setEnabled:(e,t)=>o.json(`/plugins/${encodeURIComponent(e)}:${t?"enable":"disable"}`,{method:"POST",body:{}}),remove:(e,t)=>o.json(`/plugins/${encodeURIComponent(e)}:remove`,{method:"POST",body:t??{}}),rollback:e=>o.json(`/plugins/${encodeURIComponent(e)}:rollback`,{method:"POST",body:{}}),installPrerequisite:(e,t)=>o.json(`/plugins/${encodeURIComponent(e)}:install-prerequisite`,{method:"POST",body:t,timeoutMs:0}),panels:()=>o.json("/plugins/panels"),panelDocument:(e,t)=>o.json(`/plugins/${encodeURIComponent(e)}/panels/${encodeURIComponent(t)}/document`),panelBridge:(e,t,n)=>o.json(`/plugins/${encodeURIComponent(e)}/panels/${encodeURIComponent(t)}/bridge`,{method:"POST",body:n}),commands:()=>o.json("/plugins/commands"),recommend:e=>o.json("/plugins/recommendations/match",{method:"POST",body:e}),dismissRecommendation:e=>o.json(`/plugins/${encodeURIComponent(e)}:dismiss-recommendation`,{method:"POST",body:{}})},auth:{summary:()=>o.json("/auth")}}}function ie(o){return{...o?.ifNoneMatch===void 0?{}:{"if-none-match":o.ifNoneMatch},...o?.range===void 0?{}:{range:o.range}}}function Zn(o){const e=o.headers.get("content-type")?.split(";",1)[0]?.trim()||"application/octet-stream";let n=/filename\*?=(?:UTF-8'')?"?([^";]+)"?/iu.exec(o.headers.get("content-disposition")??"")?.[1];if(n!==void 0)try{n=decodeURIComponent(n)}catch{}const r=o.headers.get("content-range")??void 0,a=r?.match(/\/(\d+)$/u)?.[1]??o.headers.get("content-length"),i=a==null?void 0:Number(a);return{mime:e,name:n,etag:o.headers.get("etag")??void 0,contentRange:r,totalBytes:i!==void 0&&Number.isSafeInteger(i)&&i>=0?i:void 0,notModified:o.status===304}}async function mt(o,e,t,n=1/0){const r=Zn(o);let a=0;if(t?.throwIfAborted(),o.body===null)return{...r,bytes:a};const i=o.body.getReader(),u=()=>{i.cancel(t?.reason).catch(()=>{})};t?.addEventListener("abort",u,{once:!0});let m=!1;try{for(;;){t?.throwIfAborted();const p=await i.read();if(t?.throwIfAborted(),p.done){m=!0;break}for(let g=0;g<p.value.byteLength;g+=64*1024){t?.throwIfAborted();const f=p.value.subarray(g,Math.min(p.value.byteLength,g+64*1024));if(a+=f.byteLength,a>n)throw new Error("Media preview exceeds its byte budget");await e(f,{...r,bytes:a})}}return{...r,bytes:a}}finally{t?.removeEventListener("abort",u),m||await i.cancel().catch(()=>{}),i.releaseLock()}}async function re(o,e,t,n){return o.raw(e,{...t,method:"GET",expectBinary:!0},async r=>{if(n===void 0)return{...Zn(r),bytes:new Uint8Array(await r.arrayBuffer())};const a=[],i=await mt(r,p=>{a.push(p)},t?.signal,n),u=new Uint8Array(i.bytes);let m=0;for(const p of a)u.set(p,m),m+=p.byteLength;return{...i,bytes:u}})}function es(o){let e=o.length;for(;e>0&&o[e-1]===void 0;)e-=1;return e===o.length?[...o]:o.slice(0,e)}function ht(o){return o.agentId!==void 0?"agent":o.sessionId!==void 0?"session":o.workspaceId!==void 0?"workspace":"core"}function gp(o,e,t){return{scope:ht(o),service:e,method:t,workspaceId:o.workspaceId,sessionId:o.sessionId,agentId:o.agentId}}function vp(o){return JSON.stringify(o)}function Sp(o){try{const e=JSON.parse(o);if(e===null||typeof e!="object"||Array.isArray(e))return;const t=e;return typeof t.type!="string"?void 0:t}catch{return}}const fp=3e4,yp=500,bp="kimi-code.bearer.",ts="transport.timeout";class _p{endpoint;token;fetchImpl;defaultTimeoutMs;socket;activeCalls=new Set;rest;closed=!1;terminal={listTerminals:async e=>Xi.parse(await this.viewRequest(this.terminalPath(e),{})),createTerminal:async(e,t={})=>Bt.parse(await this.viewRequest(this.terminalPath(e),{},{method:"POST",body:Yi.parse(t),okCodes:[0]})),getTerminal:async(e,t)=>Bt.parse(await this.viewRequest(this.terminalPath(e,t),{})),closeTerminal:async(e,t)=>Qi.parse(await this.viewRequest(`${this.terminalPath(e,t)}:close`,{},{method:"POST",body:{},okCodes:[0]})),terminalAttach:(e,t)=>this.socket.terminals.terminalAttach(e,t),terminalDetach:(e,t)=>this.socket.terminals.terminalDetach(e,t),terminalInput:(e,t,n)=>this.socket.terminals.terminalInput(e,t,n),terminalResize:(e,t,n,r)=>this.socket.terminals.terminalResize(e,t,n,r),onTerminalSignal:e=>this.socket.terminals.onTerminalSignal(e),onStatus:e=>this.socket.terminals.onStatus(e),nudge:()=>this.socket.terminals.nudge()};terminalPath(e,t){return`/api/sessions/${encodeURIComponent(e)}/terminals${t===void 0?"":`/${encodeURIComponent(t)}`}`}sessionView={snapshot:(e,t)=>this.viewRequest(`/api/klient/session-view/${encodeURIComponent(e)}/snapshot`,{},{signal:t?.signal,timeoutMs:t?.timeoutMs}),transcriptPage:(e,t)=>this.transcriptRequest("page",`/api/klient/session-view/${encodeURIComponent(e)}/transcript`,{agent_id:t.agentId,before_turn:t.beforeTurn,before_item:t.beforeItem,after_turn:t.afterTurn,after_item:t.afterItem,page_size:t.pageSize}),transcriptCatchUp:(e,t)=>this.transcriptRequest("catchUp",`/api/klient/session-view/${encodeURIComponent(e)}/transcript/catch-up`,{agent_id:t.agentId,epoch:t.since.epoch,since_seq:t.since.seq,grade:t.grade??"delta"}),transcriptDetail:(e,t,n)=>this.viewRequest(`/api/sessions/${encodeURIComponent(e)}/transcript/detail`,{agent_id:t.agentId,kind:t.kind,id:t.id},{signal:n?.signal,timeoutMs:n?.timeoutMs}),transcriptEntities:(e,t,n)=>this.viewRequest(`/api/sessions/${encodeURIComponent(e)}/transcript/details`,{agent_id:t.agentId,kind:t.kind,cursor:t.cursor,limit:t.limit},{signal:n?.signal,timeoutMs:n?.timeoutMs}),transcriptContent:(e,t,n)=>this.viewRequest(`/api/klient/session-view/${encodeURIComponent(e)}/transcript/content`,{},{method:"POST",body:t,signal:n?.signal,timeoutMs:n?.timeoutMs}),subscribe:(e,t,n)=>{if(this.closed)throw new Error("http closed");return this.socket.sessionViews.subscribe(e,t,n)}};sessionCommands={execute:(e,t,n)=>{const r=ln[t],a=n,i=r.suffix.replace("{target}",encodeURIComponent(a.target??""));return this.viewRequest(`/api/sessions/${encodeURIComponent(e)}${i}`,{agent_id:a.query?.agent_id},{method:r.method,body:r.method==="GET"?void 0:a.body??{},okCodes:r.okCodes,timeoutMs:"timeoutMs"in r?r.timeoutMs:void 0})}};viewRequest(e,t,n){return this.requestJson(e,{...n,query:t})}async transcriptRequest(e,t,n){const r=await this.viewRequest(t,{...n,transcript_coverage_version:xo});return Uo(r)?r:e==="page"?Fu(r):Bu(r)}requestJson(e,t={}){return this.performFetch(e,t,async n=>{if(n.status===404&&t.allowMissingRoute===!0){await n.body?.cancel();return}const r=/\/klient\/session-view\//.test(e)||/\/transcript(?:\/(?:detail|details|ops))?$/.test(e),a=await this.readEnvelope(n,t.signal,r?Xn:4*1024*1024),i=t.okCodes??[0];if(n.ok===!1||!i.includes(a.code))throw new N(i.includes(a.code)?n.status:a.code,a.msg,a.details,a.reason,a.request_id,a.data);return a.data})}requestRaw(e,t,n){const r=t??{};return this.performFetch(e,r,async a=>{const i=a.headers.get("content-type")??"";if((a.ok||a.status===304&&r.headers?.["if-none-match"]!==void 0)&&!(r.jsonErrorOnSuccess===!0&&i.includes("json")))return n(a);const u=await this.readEnvelope(a,r.signal),m=r.okCodes??[0];throw new N(m.includes(u.code)?a.status:u.code,u.msg,u.details,u.reason,u.request_id,u.data)})}async performFetch(e,t,n){if(this.closed)throw new Error("http closed");const r=t.rawBody??(t.body===void 0?void 0:JSON.stringify(t.body)),a=typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:void 0;if(a!==void 0&&a>Ku)throw new N(40001,"request body exceeds the allowed size limit");const i=new AbortController,u={controller:i};this.activeCalls.add(u);const m=t.timeoutMs??this.defaultTimeoutMs;let p=!1;const g=m===0?void 0:setTimeout(()=>{p=!0,i.abort()},m),f=t.signal,b=()=>{i.abort(f?.reason)};f?.aborted===!0?b():f?.addEventListener("abort",b,{once:!0});try{const k=(t.baseUrl??this.endpoint).replace(/\/+$/u,""),R=e.startsWith("/api/")?e:`/api${e}`,D=globalThis.location?.origin,U=k===""?new URL(R,D??"http://localhost"):new URL(`${k}${R}`);for(const[x,we]of Object.entries(t.query??{}))if(Array.isArray(we))for(const ls of we)U.searchParams.append(x,ls);else we!==void 0&&U.searchParams.set(x,String(we));const L={accept:t.expectBinary===!0?"application/octet-stream":"application/json",...t.headers};this.token!==void 0&&t.skipAuth!==!0&&(L.authorization=`Bearer ${this.token}`),t.body!==void 0&&L["content-type"]===void 0&&(L["content-type"]="application/json");let Z;try{const x=e==="/api/klient/call"?U.toString():U;Z=await this.fetchImpl(x,{method:t.method??"GET",body:r,headers:L,signal:i.signal,redirect:"error"})}catch(x){throw p?this.transportTimeoutError(m):this.closed&&i.signal.aborted?new Error("http closed",{cause:x}):x instanceof N?x:new N(-1,x instanceof Error?x.message:"Connection failed")}if(p)throw this.transportTimeoutError(m);try{const x=await n(Z);if(p)throw this.transportTimeoutError(m);return x}catch(x){throw p?this.transportTimeoutError(m):this.closed&&i.signal.aborted?new Error("http closed",{cause:x}):x instanceof TypeError&&!i.signal.aborted?new N(-1,x.message):x}}finally{g!==void 0&&clearTimeout(g),f?.removeEventListener("abort",b),this.activeCalls.delete(u)}}transportTimeoutError(e){return new N(50001,`call timed out after ${e}ms`,void 0,ts)}async readEnvelope(e,t,n=4*1024*1024){let r;try{r=await ip(e,n)}catch(a){throw wp(a)||t?.aborted===!0||!(a instanceof SyntaxError)?a:new N(e.status,`HTTP ${e.status} — non-JSON response`)}if(r===null||typeof r.code!="number"||typeof r.msg!="string")throw new N(e.status,`HTTP ${e.status} — non-JSON response`);return r}constructor(e){const t=e.endpoint.replace(/\/$/u,"");this.endpoint=t,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??fp,this.socket=new Ip({endpoint:t,eventsUrl:e.eventsUrl,token:e.token,WebSocket:e.WebSocket,onDiagnostic:e.onSocketDiagnostic}),this.rest=hp({json:(r,a)=>this.requestJson(r,a),raw:(r,a,i)=>this.requestRaw(r,a,i)})}call(e,t,n,r,a){return this.requestJson("/api/klient/call",{method:"POST",body:{procedure:gp(e,t,n),params:es(r)},timeoutMs:a?.timeoutMs,signal:a?.signal})}stream(e,t,n,r){return this.closed?Ep(new Error("http closed")):this.socket.stream(e,t,n,r)}listen(e,t,n,r,a){if(this.closed)throw new Error("http closed");return this.socket.listen(e,t,n,r,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 Ip{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 Wu({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 Hu({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 t=this.ws;this.ws=void 0,this.state="idle",t!==void 0&&this.reportClose(e),t?.close(4e3,"session view restart");const n=new Error("http event socket restarted");for(const r of this.streams.values())r.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??Tp(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,t){const n=Date.now();this.diagnose({kind:"close",cause:e,code:t?.code,reason:t?.reason===""?void 0:t?.reason,wasClean:t?.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,t,n,r,a){this.requireWebSocket();const i=this.nextId(),u={type:"subscribe",id:i,scope:ht(e),workspaceId:e.workspaceId,sessionId:e.sessionId,agentId:e.agentId},m=t.kind==="stream"?{...u,event:t.name}:{...u,service:t.service,event:t.event};return this.listens.set(i,{frame:m,handler:n,onError:r,onReady:a}),this.ensureConnected(),this.state==="open"&&this.send(m),{dispose:()=>{this.listens.delete(i)&&this.state==="open"&&this.send({type:"unsubscribe",id:i})}}}stream(e,t,n,r){return{[Symbol.asyncIterator]:()=>{const a=[],i=[];let u=!1,m;const p={frame:{type:"stream",scope:ht(e),service:t,method:n,arg:es(r),workspaceId:e.workspaceId,sessionId:e.sessionId,agentId:e.agentId},sent:!1,push(b){if(u)return;const I={done:!1,value:b},k=i.shift();k===void 0?a.push(I):k.resolve(I)},end:()=>{if(u)return;u=!0,m!==void 0&&this.streams.delete(m);const b={done:!0,value:void 0},I=i.shift();I===void 0?a.push(b):I.resolve(b);for(const k of i)k.resolve({done:!0,value:void 0});i.length=0},error:b=>{if(u)return;u=!0,m!==void 0&&this.streams.delete(m);const I=i.shift();I===void 0?a.push(b):I.reject(b);for(const k of i)k.reject(b);i.length=0}};let g=!1;const f=()=>{if(!g){g=!0;try{this.requireWebSocket()}catch(b){p.error(b instanceof Error?b:new Error(String(b)));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 b=a.shift();return b instanceof Error?Promise.reject(b):b!==void 0?Promise.resolve(b):u?Promise.resolve({done:!0,value:void 0}):new Promise((I,k)=>{i.push({resolve:I,reject:k})})},return:()=>{if(!u){if(u=!0,m!==void 0){const b=this.streams.get(m);this.streams.delete(m),b?.sent===!0&&this.state==="open"&&this.send({type:"stream_cancel",id:m})}for(const b of i)b.resolve({done:!0,value:void 0});i.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 t of this.streams.values())t.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 t=this.token!==void 0&&this.token.length>0?[`${bp}${this.token}`]:void 0;let n;try{n=new e(this.wsUrl,t)}catch(r){this.notifyDisconnect(r instanceof Error?r:new Error(String(r))),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 r of this.listens.values())this.send(r.frame);for(const r of this.streams.values())this.sendStream(r);this.sessionViews.opened(),this.terminals.opened()}}),n.addEventListener("message",r=>{this.ws!==n||typeof r.data!="string"||(this.lastInboundAt=Date.now(),this.onFrame(Sp(r.data)))}),n.addEventListener("close",r=>{this.ws===n&&(this.ws=void 0,this.closed||this.reportClose("server",r),[4001,1008].includes(r.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 t=typeof e.id=="string"?e.id:"";switch(e.type){case"subscribed":this.listens.get(t)?.onReady?.();return;case"event":this.listens.get(t)?.handler(e.data);return;case"error":{const n=this.listens.get(t);if(n===void 0)return;this.listens.delete(t),n.onError?.(So(e));return}case"stream_data":this.streams.get(t)?.push(e.data);return;case"stream_end":this.streams.get(t)?.end();return;case"stream_error":this.streams.get(t)?.error(So(e));return;default:return}}onClose(){if(this.closed)return;const e=new Error("http event socket disconnected");for(const t of this.streams.values())t.error(e);if(this.streams.clear(),this.notifyDisconnect(e),!this.hasDemand()){this.state="idle";return}this.scheduleReconnect()}notifyDisconnect(e){clearTimeout(this.establishmentTimer);for(const t of this.listens.values())t.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(yp*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 t=this.ws;if(!(t===void 0||this.WebSocketCtor===void 0)&&t.readyState===this.WebSocketCtor.OPEN)try{t.send(vp(e))}catch{}}nextId(){return this.seq+=1,`${this.idPrefix}_${this.seq}`}}function So(o){return new N(typeof o.code=="number"?o.code:50001,o.msg??"error",o.details,o.reason)}function Tp(o){const e=o===""?globalThis.location?.origin??"http://localhost":o,t=new URL(e);if(t.protocol==="http:"?t.protocol="ws:":t.protocol==="https:"&&(t.protocol="wss:"),t.protocol!=="ws:"&&t.protocol!=="wss:")throw new Error(`unsupported URL scheme for http transport: ${o}`);return t.pathname=`${t.pathname.replace(/\/$/u,"")}/api/klient/events`,t.search="",t.hash="",t.toString()}function wp(o){return typeof o=="object"&&o!==null&&"name"in o&&o.name==="AbortError"}function Ep(o){return{[Symbol.asyncIterator](){return{async next(){throw o}}}}}function fo(o){return Gu(new _p(o),o)}class q extends Error{code;requestId;data;details;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}}const z={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},kp={"*":"turn",main:"delta"};function em(o){return o===void 0||o==="main"?kp:{"*":"turn",main:"off",[o]:"delta"}}function Cp(o){const e=async r=>{try{return await r()}catch(a){throw a instanceof N?new q({code:a.code,msg:a.message,data:a.data,request_id:a.requestId}):a}},t=r=>o.session(r).commands,n=(r,a)=>e(async()=>{if(!await o.session(r).resume())throw new N(40401,`session ${r} does not exist`);return a()});return{getSession:r=>e(()=>t(r).read()),submitPrompt:(r,a)=>n(r,()=>t(r).submit(a)),editMessage:(r,a,i)=>n(r,()=>t(r).edit(a,Mo.parse(i))),regenerateMessage:(r,a,i)=>n(r,()=>t(r).regenerate(a,Ao.parse(i))),forkSession:(r,a)=>e(()=>t(r).fork(Oo.parse(a))),abortPrompt:(r,a,i)=>e(()=>t(r).abort(a,i)),abortTurn:(r,a)=>e(()=>t(r).abortTurn(a)),movePrompt:(r,a,i)=>e(()=>t(r).move(a,i)),replacePrompt:(r,a,i)=>e(()=>t(r).replace(a,i)),timingPrompt:(r,a,i)=>e(()=>t(r).timing(a,i)),holdPrompt:(r,a,i)=>e(()=>t(r).hold(a,i)),steerPrompt:(r,a,i)=>n(r,()=>t(r).steer(a,i)),resolveApproval:(r,a,i)=>n(r,()=>t(r).approve(a,i)),resolveQuestion:(r,a,i)=>n(r,()=>t(r).answer(a,i)),dismissQuestion:(r,a)=>n(r,()=>t(r).dismiss(a)),cancelTask:(r,a,i)=>n(r,()=>t(r).cancelTask(a,i))}}const P="main",ae={roster:1,live:2,task:3};function gt(o,e){if(o===e)return 0;if(o===P)return-1;if(e===P)return 1;const t=/^agent-(\d+)$/.exec(o),n=/^agent-(\d+)$/.exec(e);return t&&n?Number(t[1])-Number(n[1]):t?-1:n?1:o<e?-1:1}function Rp(o,e){if(o.agentId===P||e.agentId===P)return gt(o.agentId,e.agentId);const t=o.startedAt===void 0?Number.NaN:Date.parse(o.startedAt),n=e.startedAt===void 0?Number.NaN:Date.parse(e.startedAt),r=Number.isFinite(t),a=Number.isFinite(n);return r&&a&&t!==n?n-t:r!==a?r?-1:1:gt(o.agentId,e.agentId)}function Ut(){return Object.create(null)}function Pp(){return{roots:Object.freeze([]),byId:Object.freeze(Ut())}}function ot(o,e){return o===e||o!==void 0&&e!==void 0&&o.inputOther===e.inputOther&&o.output===e.output&&o.inputCacheRead===e.inputCacheRead&&o.inputCacheCreation===e.inputCacheCreation}function Op(o,e){if(o===e)return!0;if(o===void 0||e===void 0||!ot(o.currentTurn,e.currentTurn)||!ot(o.total,e.total))return!1;const t=Object.keys(o.byModel??{}),n=Object.keys(e.byModel??{});return t.length===n.length&&t.every(r=>ot(o.byModel?.[r],e.byModel?.[r]))}function Ap(o,e){return o===e?!0:o.agentId===e.agentId&&o.parentAgentId===e.parentAgentId&&o.parentToolCallId===e.parentToolCallId&&o.name===e.name&&o.label===e.label&&o.model===e.model&&o.thinkingEffort===e.thinkingEffort&&o.contextTokens===e.contextTokens&&o.maxContextTokens===e.maxContextTokens&&Op(o.usage,e.usage)&&o.status===e.status&&o.refreshing===e.refreshing&&o.refreshingUntil===e.refreshingUntil&&o.busy===e.busy&&o.toolCallCount===e.toolCallCount&&o.toolCallCountKnown===e.toolCallCountKnown&&o.startedAt===e.startedAt&&o.endedAt===e.endedAt&&o.description===e.description&&o.summary===e.summary&&o.error===e.error&&o.turnOutcome?.turnId===e.turnOutcome?.turnId&&o.turnOutcome?.state===e.turnOutcome?.state&&o.turnOutcome?.error===e.turnOutcome?.error&&o.turnOutcome?.endedAt===e.turnOutcome?.endedAt&&o.turnOutcome?.lastRetry?.failedAttempt===e.turnOutcome?.lastRetry?.failedAttempt&&o.turnOutcome?.lastRetry?.maxAttempts===e.turnOutcome?.lastRetry?.maxAttempts&&o.turnOutcome?.lastRetry?.errorName===e.turnOutcome?.lastRetry?.errorName&&o.turnOutcome?.lastRetry?.errorMessage===e.turnOutcome?.lastRetry?.errorMessage&&o.childIds.length===e.childIds.length&&o.childIds.every((t,n)=>t===e.childIds[n])}function tm(o,e){if(o===void 0||o===e)return e;const t=Ut(),n=new Set,r=g=>{const f=t[g];if(f!==void 0)return f;const b=e.byId[g];if(b===void 0)return;if(n.has(g))return t[g]=b,b;n.add(g);const I=o.byId[g];let k=I!==void 0;for(const D of b.childIds){const U=r(D);(U===void 0||U!==o.byId[D])&&(k=!1)}n.delete(g);const R=I!==void 0&&k&&Ap(I,b)?I:b;return t[g]=R,R};for(const g of e.roots)r(g.agentId);for(const g of Object.keys(e.byId))r(g);const a=e.roots.map(g=>t[g.agentId]),i=Object.keys(o.byId),u=Object.keys(e.byId),m=i.length===u.length&&u.every(g=>t[g]===o.byId[g]),p=a.length===o.roots.length&&a.every((g,f)=>g===o.roots[f]);return m&&p?o:{roots:p?o.roots:a,byId:t}}function om(o,e,t){const n=new Map;for(const p of Lp(t??[])){const g=ss(p),f=Me(n,g);Mp(f,p)}for(const p of e??[]){if(!oe(p.agentId))continue;const g=Me(n,p.agentId);Up(g,p)}for(const p of o){if(!oe(p.subagentId))continue;const g=Me(n,p.subagentId);xp(g,p)}if(n.size===0)return Pp();for(const p of n.values())(p.rosterParentAgentId??p.parentAgentId)===P&&!n.has(P)&&Me(n,P);const r=new Map;for(const p of n.values())r.set(p.agentId,Dp(p,n));Np(r);const a=new Map;for(const p of n.keys())a.set(p,[]);const i=[];for(const[p,g]of r){if(g===void 0){i.push(p);continue}a.get(g).push(p)}const u=(p,g)=>Rp(n.get(p),n.get(g));for(const p of a.values())p.sort(u);if(i.sort(u),n.has(P)&&!r.get(P)){const p=n.get(P);if(p.status===void 0){const g=a.get(P)??[];p.status=g.some(f=>{const b=n.get(f);return b!==void 0&&de(b.status??"completed")})?"running":"completed"}}const m=Ut();for(const p of n.values()){const g=r.get(p.agentId),f=oe(p.name)?p.name:p.agentId,b=p.status??"unknown",I={agentId:p.agentId,parentAgentId:g,parentToolCallId:p.parentToolCallId,name:f,label:oe(p.label)?p.label:f,model:p.model,thinkingEffort:p.thinkingEffort,contextTokens:p.contextTokens,maxContextTokens:p.maxContextTokens,usage:p.usage,status:b,refreshing:p.refreshing,refreshingUntil:p.refreshingUntil,busy:Gp(b,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:i.map(p=>m[p]),byId:m}}function nm(o,e){const t=o.byId[e];if(t===void 0)return[];const n=[],r=new Set;let a=t;for(;a!==void 0&&!r.has(a.agentId);){r.add(a.agentId),n.push(a);const i=a.parentAgentId;a=i===void 0?void 0:o.byId[i]}return n.reverse()}function sm(o,e){const t=o.byId[e];return t===void 0?[]:t.childIds.flatMap(n=>{const r=o.byId[n];return r===void 0?[]:[r]})}function Me(o,e){const t=o.get(e);if(t!==void 0)return t;const n={agentId:e,parentAgentId:void 0,rosterParentAgentId:void 0,parentToolCallId:void 0,name:void 0,label:void 0,model:void 0,thinkingEffort: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,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 o.set(e,n),n}function os(o,e,t,n){if(n===!0){o.toolCallCount=e??0,o.toolCallCountKnown=e!==void 0&&t!==!1,o.toolCallCountAuthoritative=!0;return}o.toolCallCountAuthoritative||e===void 0||(o.toolCallCount=Math.max(o.toolCallCount,e),t!==!1&&(o.toolCallCountKnown=!0))}function Mp(o,e){const t=be(e.status,e.detached===!0),n=E(e.startedAt,e.started_at),r=E(e.endedAt,e.completed_at);o.parentAgentId=o.parentAgentId??B(e.parentAgentId??e.parent_agent_id),o.parentToolCallId=o.parentToolCallId??B(e.parentToolCallId??e.parent_tool_call_id),o.name=o.name??E(e.name,e.description),o.description=E(e.description)??o.description,(t===void 0?o.status===void 0&&o.disposedAt===void 0:xt(o,t,ae.task,n,r).accepted)&&(o.model=E(e.model)??o.model,o.thinkingEffort=E(e.thinkingEffort,e.thinking_effort)??o.thinkingEffort,o.startedAt??=n,o.endedAt??=r,o.summary=o.summary??E(e.summary,e.output_preview),o.error=o.error??E(e.error,e.stateReason,e.state_reason),t!==void 0&&t!=="unknown"&&(o.taskId=B(e.id)??o.taskId),e.detached===!0&&o.busy===void 0&&t==="background"&&(o.busy=!0))}function Up(o,e){const t=B(e.parentAgentId);t!==void 0&&(o.rosterParentAgentId=t),o.parentAgentId=t??o.parentAgentId,o.parentToolCallId=E(e.parentToolCallId)??o.parentToolCallId,o.name=E(e.name,e.label)??o.name,o.label=E(e.label)??o.label,o.description=E(e.description)??o.description,os(o,e.toolCallCount,e.toolCallCountKnown,e.toolCallCountAuthoritative);const n=G(e.disposedAt);n!==void 0&&(o.disposedAt===void 0||n>o.disposedAt)&&(o.disposedAt=n,ns(o,n,ae.roster));const r=G(e.endedAt??e.startedAt),a=e.refreshing===!0&&e.disposedAt===void 0&&(G(e.refreshingUntil)??0)>Date.now()&&(r===void 0||(o.statusStartedAt===void 0||o.statusStartedAt<=r)&&(o.statusEndedAt===void 0||o.statusEndedAt<=r)),i=be(e.status),u=i===void 0?o.status===void 0&&o.disposedAt===void 0:xt(o,i,ae.roster,e.startedAt,e.endedAt).accepted;a&&(o.refreshing=!0,o.refreshingUntil=e.refreshingUntil),u&&(o.model=E(e.model)??o.model,o.thinkingEffort=E(e.thinkingEffort)??o.thinkingEffort,o.contextTokens=e.contextTokens??o.contextTokens,o.maxContextTokens=e.maxContextTokens??o.maxContextTokens,o.usage=e.usage??o.usage,e.busy!==void 0&&(o.busy=e.busy),o.startedAt??=E(e.startedAt),o.endedAt??=E(e.endedAt),o.summary=E(e.summary)??o.summary,o.error=E(e.error)??o.error)}function ns(o,e,t){o.status===void 0||!de(o.status)||o.statusStartedAt!==void 0&&o.statusStartedAt>e||(o.status="unknown",o.statusAuthority=t,is(o),o.busy=!1)}function xp(o,e){o.parentAgentId=o.parentAgentId??B(e.parentAgentId),o.parentToolCallId=E(e.parentToolCallId)??o.parentToolCallId,o.name=E(e.name)??o.name,o.label=E(e.label)??o.label,o.description=E(e.description)??o.description,os(o,e.toolCallCount,e.toolCallCountKnown,e.toolCallCountAuthoritative);const t=G(e.disposedAt);t!==void 0&&(o.disposedAt===void 0||t>o.disposedAt)&&(o.disposedAt=t,ns(o,t,ae.live));const n=be(e.status);(n===void 0?o.status===void 0&&o.disposedAt===void 0:xt(o,n,ae.live,e.startedAt,e.endedAt).accepted)&&(o.model=E(e.model)??o.model,o.thinkingEffort=E(e.thinkingEffort)??o.thinkingEffort,o.contextTokens=e.contextTokens??o.contextTokens,o.maxContextTokens=e.maxContextTokens??o.maxContextTokens,o.usage=e.usage??o.usage,n!==void 0&&(o.busy=de(n)),o.startedAt??=E(e.startedAt),o.endedAt??=E(e.endedAt),o.summary=E(e.summary)??o.summary,o.error=E(e.error)??o.error)}function Dp(o,e){const t=o.rosterParentAgentId??o.parentAgentId;if(!(t===void 0||t===o.agentId)&&e.has(t))return t}function Np(o){const e=new Set(o.keys());for(;e.size>0;){const t=e.values().next().value;if(t===void 0)break;const n=[],r=new Map;let a=t;for(;a!==void 0&&e.has(a);){const i=r.get(a);if(i!==void 0){const m=n.slice(i).reduce((p,g)=>gt(g,p)>0?g:p);o.set(m,void 0);break}r.set(a,n.length),n.push(a),a=o.get(a)}for(const i of n)e.delete(i)}}function ss(o){return B(o.agentId)}function Lp(o){const e=new Map;for(const t of o){const n=ss(t);if(n===void 0)continue;const r=e.get(n);(r===void 0||jp(t,r))&&e.set(n,t)}return[...e.values()]}function jp(o,e){const t=G(E(o.startedAt,o.started_at)),n=G(E(e.startedAt,e.started_at)),r=G(E(o.endedAt,o.completed_at)),a=G(E(e.endedAt,e.completed_at)),i=B(o.id),u=B(e.id);if(i!==void 0&&u!==void 0&&i!==u){if(t!==void 0&&a!==void 0&&t>a)return!0;if(n!==void 0&&r!==void 0&&n>r)return!1}if(t!==n)return t===void 0?!1:n===void 0?!0:t>n;const p=be(o.status,o.detached===!0),g=be(e.status,e.detached===!0),f=p===void 0?-1:_e(p),b=g===void 0?-1:_e(g);return f!==b?f>b:r!==a?r===void 0?!1:a===void 0?!0:r>a:i!==u?i===void 0?!1:u===void 0?!0:i>u:yo(o)>yo(e)}function yo(o){return JSON.stringify([B(o.id)??"",o.kind??"",o.description??"",o.name??"",o.status??"",o.model??"",E(o.thinkingEffort,o.thinking_effort)??"",E(o.startedAt,o.started_at)??"",E(o.endedAt,o.completed_at)??"",E(o.summary,o.output_preview)??"",B(o.parentAgentId??o.parent_agent_id)??"",B(o.parentToolCallId??o.parent_tool_call_id)??"",o.detached===!0])}function G(o){if(o===void 0)return;const e=Date.parse(o);return Number.isFinite(e)?e:void 0}function be(o,e=!1){if(!oe(o))return e?"background":void 0;switch(o){case"unknown":return"unknown";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":case"lost":return"failed";case"cancelled":case"killed":return"cancelled";case"background":return"background";default:return e?"background":void 0}}function _e(o){return o==="unknown"?0:o==="completed"||o==="failed"||o==="cancelled"?2:1}function bo(o){return o==="suspended"?2:de(o)?1:0}function qp(o,e,t){if(_e(e)===2||o.disposedAt===void 0)return!1;const n=G(t);return n===void 0||n<=o.disposedAt}function is(o){o.model=void 0,o.thinkingEffort=void 0,o.contextTokens=void 0,o.maxContextTokens=void 0,o.usage=void 0,o.busy=void 0,o.refreshing=void 0,o.refreshingUntil=void 0,o.startedAt=void 0,o.endedAt=void 0,o.summary=void 0,o.error=void 0}function xt(o,e,t,n,r){const a=o.status===void 0?-1:_e(o.status),i=_e(e),u=G(n),m=G(r);if(qp(o,e,n))return{accepted:!1,newGeneration:!1};const p=a>0&&i>0,g=G(o.startedAt),b=de(e)&&u!==void 0&&o.disposedAt!==void 0&&u>o.disposedAt&&(o.statusStartedAt===void 0||o.statusStartedAt<=o.disposedAt)||a<=0&&i===1&&u!==void 0&&g!==void 0&&u>g||p&&u!==void 0&&o.statusEndedAt!==void 0&&u>o.statusEndedAt;if(t<ae.task&&i===2&&o.taskId!==void 0)return{accepted:!1,newGeneration:!1};const k=p&&o.statusStartedAt!==void 0&&m!==void 0&&o.statusStartedAt>=m;if(!b&&k)return{accepted:!1,newGeneration:!1};const R=o.status===void 0?-1:bo(o.status),D=bo(e),U=i===a&&(i===1?D<R||D===R&&t<o.statusAuthority:t<o.statusAuthority),L=i<a||U;return!b&&L?{accepted:!1,newGeneration:!1}:(b?(is(o),o.taskId=void 0,o.statusStartedAt=u,o.statusEndedAt=m):i>0&&(o.statusStartedAt??=u,o.statusEndedAt=m??o.statusEndedAt),o.status=e,o.statusAuthority=t,{accepted:!0,newGeneration:b})}function de(o){return o==="running"||o==="suspended"||o==="background"}function Gp(o,e){return o==="completed"||o==="failed"||o==="cancelled"?!1:e??de(o)}function oe(o){return o!==void 0&&o!==""}function B(o){return oe(o)?o:void 0}function E(...o){for(const e of o)if(oe(e))return e}const _o=200,$p=5e3,Io=1e3,ge=[],vt=new Set;let rs=[];function ee(o,e=Date.now()){ge.push({...o,at:e}),ge.length>_o&&ge.splice(0,ge.length-_o),rs=ge.slice();for(const t of vt)t()}function Fp(){return rs}function im(o){return vt.add(o),()=>{vt.delete(o)}}function Bp(o){return o.map(e=>{const{at:t,kind:n,...r}=e,a=Object.entries(r).filter(([,i])=>i!==void 0).map(([i,u])=>`${i}=${typeof u=="string"?JSON.stringify(u):String(u)}`);return[new Date(t).toISOString(),n,...a].join(" ")}).join(`
|
|
2
|
-
`)}let Ue=0,nt=null;function rm(){if(typeof window>"u"||typeof document>"u")return()=>{};if(Ue+=1,Ue===1){const o=()=>{ee({kind:"visibility",state:document.visibilityState})},e=()=>{ee({kind:"focus",focused:!0})},t=()=>{ee({kind:"focus",focused:!1})},n=()=>{ee({kind:"online",online:!0})},r=()=>{ee({kind:"online",online:!1})};document.addEventListener("visibilitychange",o),window.addEventListener("focus",e),window.addEventListener("blur",t),window.addEventListener("online",n),window.addEventListener("offline",r);let a=Date.now();const i=window.setInterval(()=>{const m=Date.now(),p=m-a-Io;a=m,p>=$p&&ee({kind:"timer_gap",gapMs:p,visibility:document.visibilityState},m)},Io),u=window;u.__kikiConnectionLog=()=>Bp(Fp()),nt=()=>{document.removeEventListener("visibilitychange",o),window.removeEventListener("focus",e),window.removeEventListener("blur",t),window.removeEventListener("online",n),window.removeEventListener("offline",r),window.clearInterval(i),delete u.__kikiConnectionLog}}return()=>{Ue-=1,Ue===0&&(nt?.(),nt=null)}}function Vp(o){return o instanceof q&&o.code===z.SESSION_INDEX_BUILDING}function Hp(o){return o.includes("session.not_found")||o.includes(`code ${z.SESSION_NOT_FOUND}`)}function To(o){if(typeof o!="object"||o===null||Array.isArray(o))return!1;const e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function ve(o,e){if(o==null)return[];if(typeof o=="string")return[o];if(Array.isArray(o)&&o.every(t=>typeof t=="string"))return[...new Set(o)];throw new q({code:z.INVALID_RESPONSE,msg:`Invalid config response: ${e} must be a string or string array`,data:o})}function St(o){if(!To(o))throw new q({code:z.INVALID_RESPONSE,msg:"Invalid config response: data must be a plain object",data:o});const e=o.tools;if(e!=null&&!To(e))throw new q({code:z.INVALID_RESPONSE,msg:"Invalid config response: tools must be a plain object",data:e});const t=e??{};return{...o,extra_agent_dirs:ve(o.extra_agent_dirs,"extra_agent_dirs"),skip_builtin_profile_installation:ve(o.skip_builtin_profile_installation,"skip_builtin_profile_installation"),disabled_named_profiles:ve(o.disabled_named_profiles,"disabled_named_profiles"),tools:{...t,enabled:ve(t.enabled,"tools.enabled"),disabled:ve(t.disabled,"tools.disabled")}}}const Wp=["user","feedback","project","reference"],Kp=40423,zp=40944;function Qp(o){const e=o.endpoint===""?globalThis.location.origin:o.endpoint;return new ds({baseUrl:e,token:o.token,timeoutMs:o.timeoutMs,onSessionMutation:o.onSessionMutation,transport:lp({...o,endpoint:e})})}class as 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 cs extends Dt{constructor(e){super(e),this.name="NativeChildPromptConflictError"}}class ds{baseUrl;klient;sessions;token;transport;serverLeaseId;previewBytes=new Map;previewCacheBytes=0;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=fo({endpoint:this.baseUrl,token:this.token,timeoutMs:e.timeoutMs,onSocketDiagnostic:n=>{ee(n)},...e.transport});const t=Cp(this.klient);this.sessions={...t,submitPrompt:(...n)=>this.runSessionMutation(n[0],()=>t.submitPrompt(...n)),editMessage:(...n)=>this.runSessionMutation(n[0],()=>t.editMessage(...n)),regenerateMessage:(...n)=>this.runSessionMutation(n[0],()=>t.regenerateMessage(...n)),abortPrompt:(...n)=>this.runSessionMutation(n[0],()=>t.abortPrompt(...n)),abortTurn:(...n)=>this.runSessionMutation(n[0],()=>t.abortTurn(...n)),movePrompt:(...n)=>this.runSessionMutation(n[0],()=>t.movePrompt(...n)),replacePrompt:(...n)=>this.runSessionMutation(n[0],()=>t.replacePrompt(...n)),timingPrompt:(...n)=>this.runSessionMutation(n[0],()=>t.timingPrompt(...n)),steerPrompt:(...n)=>this.runSessionMutation(n[0],()=>t.steerPrompt(...n)),resolveApproval:(...n)=>this.runSessionMutation(n[0],()=>t.resolveApproval(...n)),resolveQuestion:(...n)=>this.runSessionMutation(n[0],()=>t.resolveQuestion(...n)),dismissQuestion:(...n)=>this.runSessionMutation(n[0],()=>t.dismissQuestion(...n)),cancelTask:(...n)=>this.runSessionMutation(n[0],()=>t.cancelTask(...n))}}async runSessionMutation(e,t){const n=await t();return this.onSessionMutation?.(e),n}sessionView(e){const t=this.klient.session(e).view;return{snapshot:async n=>{const r=fo({endpoint:this.baseUrl,token:this.token,timeoutMs:0,...this.transport});try{return await this.run(()=>r.session(e).view.snapshot(n))}finally{await r.close()}},transcript:t.transcript,subscribe:(n,r)=>t.subscribe(n,r)}}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(t){if(t instanceof N){const n=t.reason===ts;throw new q({code:n?z.TIMEOUT:t.code,msg:n?t.message.replace("call timed out",Ht("en","common.requestTimedOut")):t.message,data:t.data??null,details:t.details,request_id:t.requestId})}throw t}}healthz(e){return this.rest.healthz(e)}meta(){return this.run(()=>this.rest.meta())}async renewLease(e){const t=await this.run(()=>this.rest.renewLease({lease_id:this.serverLeaseId}));t!==void 0&&(this.serverLeaseId=t.lease_id)}listSessions(e={}){return this.run(()=>this.rest.sessions.list(e))}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,t){return this.run(()=>this.rest.sessions.endEphemeral(e,{worktree:t}))}getRequestGovernance(){return this.run(()=>this.rest.requestGovernance())}setRequestGovernanceRules(e){return this.patchConfig({request_governance:{rules:e.map(t=>({id:t.id,scope:t.scope,...t.models!==void 0?{models:[...t.models]}:{},...t.providers!==void 0?{providers:[...t.providers]}:{},subagents_only:t.subagentsOnly,...t.maxConcurrent!==void 0?{max_concurrent:t.maxConcurrent}:{},overflow:t.overflow,...t.maxWaitMs!==void 0?{max_wait_ms:t.maxWaitMs}:{},enabled:t.enabled}))}})}getUsageRescan(){return this.run(()=>this.rest.usageRescan.status())}startUsageRescan(){return this.run(()=>this.rest.usageRescan.start())}getUsage(e){return this.run(()=>this.rest.usage(e))}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,t){return this.run(()=>this.rest.sessions.updateProfile(e,t))}getPersonaSettings(e){return this.run(()=>this.rest.sessions.getPersonaSettings(e))}applyPersonaSettings(e,t={}){return this.run(()=>this.rest.sessions.applyPersonaSettings(e,t))}archiveSession(e){return this.run(()=>this.rest.sessions.archive(e))}restoreSession(e){return this.run(()=>this.rest.sessions.restore(e))}getSessionGoal(e){return this.run(()=>this.rest.sessions.goal(e))}createAgentGoal(e,t){return this.run(()=>this.klient.session(e).agent(P).createGoal(t))}updateAgentGoal(e,t){return this.run(()=>this.klient.session(e).agent(P).updateGoal(t))}pauseAgentGoal(e){return this.run(()=>this.klient.session(e).agent(P).pauseGoal())}resumeAgentGoal(e,t={}){return this.run(()=>this.klient.session(e).agent(P).resumeGoal(t))}cancelAgentGoal(e){return this.run(()=>this.klient.session(e).agent(P).cancelGoal())}resumeRecoveredQueue(e){return this.run(()=>this.klient.session(e).agent(P).resumeRecoveredPromptQueue())}listMessages(e,t={}){return this.run(()=>this.rest.sessions.listMessages(e,t))}listPrompts(e){return this.run(()=>this.rest.sessions.listPrompts(e))}submitPrompt(e,t){return this.sessions.submitPrompt(e,t)}replacePrompt(e,t,n){return this.sessions.replacePrompt(e,t,n)}movePrompt(e,t,n){return this.sessions.movePrompt(e,t,n)}abortPrompt(e,t){return this.sessions.abortPrompt(e,t)}abortTurn(e,t){return this.sessions.abortTurn(e,t)}steerPrompt(e,t){return this.sessions.steerPrompt(e,t)}timingPrompt(e,t,n){return this.sessions.timingPrompt(e,t,n)}listPendingApprovals(e){return this.run(()=>this.rest.sessions.listApprovals(e))}resolveApproval(e,t,n){return this.sessions.resolveApproval(e,t,n)}listPendingQuestions(e){return this.run(()=>this.rest.sessions.listQuestions(e))}resolveQuestion(e,t,n){return this.sessions.resolveQuestion(e,t,n)}dismissQuestion(e,t){return this.sessions.dismissQuestion(e,t)}listTasks(e,t){return this.run(()=>this.rest.sessions.listTasks(e,t))}getTask(e,t,n={}){return this.run(()=>this.rest.sessions.getTask(e,t,n))}cancelTask(e,t,n={}){return this.sessions.cancelTask(e,t,n)}stopAgentTask(e,t,n){return this.run(this.klient.session(e).agent(t).stopTask({taskId:n}))}startSideQuestion(e){return this.run(()=>this.klient.session(e).btw.start())}async isNativeAgent(e,t){return t===P?!0:((await this.run(()=>this.klient.session(e).agents()))[t]?.executor??"native")==="native"}async sendAgentMessage(e,t,n,r,a,i){const u=this.klient.session(e),m=await this.run(()=>u.agents());if(m[t]!==void 0&&(m[t].executor??"native")!=="native"){if(r?.some(f=>f.type!=="text"))throw new as;return this.run(()=>u.sendUserAgentMessage({targetAgentId:t,content:n,idempotencyKey:a}))}const p=r===void 0?[{type:"text",text:n}]:[...r],g=t!==P&&p.every(f=>f.type==="text");try{await this.submitPrompt(e,{content:p,agent_id:t,after_model_switch:i,prompt_id:g?a:void 0})}catch(f){throw g&&f instanceof q&&f.code===40938?new cs(f):t!==P?new Dt(f):f}return null}setAgentModel(e,t,n){return this.run(this.klient.session(e).agent(t).setModel(n))}setAgentEffort(e,t,n){return this.run(this.klient.session(e).agent(t).setEffort(n))}switchAgentModel(e,t,n){return this.run(this.klient.session(e).agent(t).switchModel(n))}async getAgentModelSwitch(e,t,n){return await this.run(this.klient.session(e).agent(t).getModelSwitch(n))??null}listAgentModelSwitches(e,t){return this.run(this.klient.session(e).agent(t).listModelSwitches())}updateAgentModelSwitch(e,t,n,r){return this.run(this.klient.session(e).agent(t).updateModelSwitch(n,r))}cancelAgentModelSwitch(e,t,n){return this.run(this.klient.session(e).agent(t).cancelModelSwitch(n))}recoverAgentModelSwitch(e,t,n,r,a){const i=this.klient.session(e).agent(t);return this.run(r==="retry"?i.recoverModelSwitch(n,r,a):i.recoverModelSwitch(n,r))}subscribeAgentModelSwitches(e,t,n){const r=this.klient.session(e).agent(t).events,a=r.on("prompt.model_switch_queued",u=>{n({kind:"queued",entry:u.entry,queueIndex:u.queueIndex})}),i=r.on("prompt.model_switch_status",u=>{n({kind:"status",operationId:u.operationId,receipt:u.receipt})});return{ready:Promise.all([a.ready,i.ready]).then(()=>{}),dispose:()=>{a.dispose(),i.dispose()}}}listTerminals(e){return this.klient.terminal.listTerminals(e)}createTerminal(e,t={}){return this.klient.terminal.createTerminal(e,t)}getTerminal(e,t){return this.klient.terminal.getTerminal(e,t)}closeTerminal(e,t){return this.klient.terminal.closeTerminal(e,t)}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 St(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,t){return this.run(this.rest.config.restoreModelGenerationMigration(e,t))}async getNbSearchCapabilities(){return Ji.parse(await this.run(this.rest.nbSearch.capabilities()))}async testNbSearch(e){return Zi.parse(await this.run(this.rest.nbSearch.test({signal:e})))}async readNbSearchKeyUsage(e,t=!1,n){return er.parse(await this.run(this.rest.nbSearch.keyUsage(e,t,{signal:n})))}async readNbSearchCredential(e,t=!1){return Vt.parse(await this.run(this.rest.nbSearch.readCredential(e,t)))}async revealSecret(e){return tr.parse(await this.run(this.rest.secrets.reveal(e)))}async writeNbSearchCredential(e,t,n,r){return Vt.parse(await this.run(this.rest.nbSearch.writeCredential(e,t,n,r)))}get requestIdentity(){const e=this.rest.requestIdentity,t=async n=>sr.parse(await this.run(n));return{get:()=>t(e.get()),preview:async n=>or.parse(await this.run(e.preview(n))),duplicateProfile:(n,r)=>t(e.duplicateProfile(n,r)),updateProfile:(n,r)=>t(e.updateProfile(n,r)),deleteProfile:n=>t(e.deleteProfile(n)),checkTrack:(n,r)=>t(e.checkTrack(n,r)),applyTrack:(n,r)=>t(e.applyTrack(n,r)),trackAction:(n,r)=>t(e.trackAction(n,r)),pinTrack:(n,r)=>t(e.pinTrack(n,r)),setManifestUrl:n=>t(e.setManifestUrl(n))}}get notifications(){const e=this.rest.notifications,t=n=>(...r)=>this.run(()=>n(...r));return{getSettings:t(e.getSettings.bind(e)),updateSettings:t(e.updateSettings.bind(e)),listProviders:t(e.listProviders.bind(e)),upsertInstance:t(e.upsertInstance.bind(e)),deleteInstance:t(e.deleteInstance.bind(e)),upsertChannel:t(e.upsertChannel.bind(e)),deleteChannel:t(e.deleteChannel.bind(e)),setCredential:t(e.setCredential.bind(e)),checkCredential:t(e.checkCredential.bind(e)),sendTest:t(e.sendTest.bind(e)),listDeliveries:t(e.listDeliveries.bind(e))}}listNamedAgentProfiles(e){return this.run(this.rest.agents.list(e))}getAgentCapabilities(e,t){return this.run(this.klient.global.agentPanel.read(e,{signal:t}))}createAgentProfile(e){return this.run(this.rest.agents.create(e))}updateNamedAgentProfile(e,t){return this.run(this.rest.agents.update(e,t))}listShippedAgentProfiles(){return this.run(this.rest.agents.shipped.list())}restoreShippedAgentProfile(e){return this.run(this.rest.agents.shipped.restore(e))}async readHostFile(e){return this.run(this.rest.filesystem.readHostFile(e))}async readBuiltinSkill(e){return(await this.run(this.rest.skills.readBuiltinContent(e))).content}previewHostSkillInstall(e){return this.run(this.rest.skills.previewHostInstall(e))}installHostSkill(e,t){return this.run(this.rest.skills.installHost(e,t))}async previewHostFile(e,t=512001){return this.run(this.rest.filesystem.previewHostFile(e,t))}async cachedPreviewBytes(e,t){const n=this.previewBytes.get(e),r=await this.run(t(n?.etag));if(r.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),r.etag!==void 0&&r.bytes.byteLength<=32*1024*1024)for(this.previewBytes.set(e,{...r,etag:r.etag}),this.previewCacheBytes+=r.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 r}readHostFileBytes(e,t){return this.run(this.rest.filesystem.readHostFileBytes(e,t))}readHostMediaPreviewBytes(e,t){return this.cachedPreviewBytes(`host-preview:${e}`,n=>this.rest.filesystem.readHostMediaPreview(e,{...t,ifNoneMatch:n}))}downloadHostFile(e,t,n){return this.run(this.rest.filesystem.downloadHostFile(e,t,n))}readSessionMediaBytes(e,t,n){return this.run(this.rest.sessions.media(e,t,n))}readSessionMediaPreviewBytes(e,t,n){return this.cachedPreviewBytes(`media-preview:${e}:${t}:${n?.mediaType??""}`,r=>this.rest.sessions.mediaPreview(e,t,{...n,ifNoneMatch:r}))}downloadSessionMedia(e,t,n,r){return this.run(this.rest.sessions.downloadMedia(e,t,n,r))}downloadTranscriptContent(e,t,n,r,a){const i=rr(t,n);return i===void 0?Promise.reject(new Error("This content has no original-file consumer")):this.downloadSessionMedia(e,i,r,a)}listWorkspaces(){return this.run(this.rest.workspaces.list())}renameWorkspace(e,t){return this.run(this.rest.workspaces.rename(e,t))}setWorkspacePinned(e,t){return this.run(this.rest.workspaces.setPinned(e,t))}removeWorkspace(e){return this.run(this.rest.workspaces.remove(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,t){return this.run(this.klient.global.kosong.refreshProviders({providerId:e,apiKey:t}))}async probeProviderDraft(e){const t=n=>{const r=ir(e.type).defaultContextSize;return n.map(a=>({id:"",remoteId:a,maxContextSize:r,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 t(n.models)}catch(n){if(!(n instanceof q))throw n;return nr(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,t){return this.run(this.klient.global.kosong.updateModel(e,t))}deleteModel(e,t){return this.run(this.klient.global.kosong.deleteModel(e,t))}getProviderEntity(e){return this.run(this.klient.global.kosong.readProviderEntity(e))}createProvider(e){return this.run(this.klient.global.kosong.createProvider(e))}updateProvider(e,t){return this.run(this.klient.global.kosong.updateProvider(e,t))}deleteProviderEntity(e){return this.run(this.klient.global.kosong.deleteProviderEntity(e))}getOAuthStatus(e={}){return this.run(this.klient.global.auth.flow(e.provider)).then(t=>t??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,t){return this.run(()=>this.rest.shortcuts.write(e,t))}resetShortcuts(e,t){return this.run(()=>this.rest.shortcuts.reset(e,t))}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,t){return this.run(()=>this.rest.executors.listLocalSessions(e,{limit:t}))}getLocalSession(e,t){return this.run(()=>this.rest.executors.getLocalSession(e,t))}resumeLocalSession(e,t,n){return this.run(()=>this.rest.executors.resumeLocalSession(e,t,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`)}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,t){return this.memoryRequest("POST","/executors/antigravity-acp/login/complete",{body:{handle:e,redirect_url:t}})}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,t,n){return this.memoryRequest("POST",`/agents/${encodeURIComponent(e)}/executor-prompt:preview`,{body:{workspace:t,executor:n}})}async setSubagentDefaultModel(e){const t=e.trim();await this.patchConfig({subagent:{default_model:t===""?null:t}})}async setFastModel(e){const t=e.trim();await this.patchConfig({fast_model:t===""?null:t})}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,t){return this.run(this.rest.plugins.setSettings(e,{values:{...t}}))}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,t){return this.run(this.klient.global.capabilities.install(e,t))}setPluginEnabled(e,t){return this.run(this.rest.plugins.setEnabled(e,t))}removePlugin(e,t){return this.run(this.rest.plugins.remove(e,t))}previewPlugin(e,t){return this.run(this.rest.plugins.preview({source:e,sha256:t}))}installPreviewedPlugin(e){return this.run(this.rest.plugins.install(e))}rollbackPlugin(e){return this.run(this.rest.plugins.rollback(e))}installPluginPrerequisite(e,t){return this.run(this.rest.plugins.installPrerequisite(e,{id:t,consent:!0}))}recommendPlugins(e){return this.run(this.rest.plugins.recommend(e))}dismissPluginRecommendation(e){return this.run(this.rest.plugins.dismissRecommendation(e))}listPluginPanels(){return this.run(this.rest.plugins.panels())}getPluginPanelDocument(e,t){return this.run(this.rest.plugins.panelDocument(e,t))}callPluginPanelBridge(e,t,n){return this.run(this.rest.plugins.panelBridge(e,t,n))}restartMcpServer(e){return this.run(this.rest.runtime.restartMcpServer(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,t,n={}){return this.run(this.rest.sessions.activateSkill(e,t,n))}async uploadFile(e){const t=new Uint8Array(await e.arrayBuffer());return this.run(this.klient.global.files.save({data:t,filename:e.name===""?"attachment":e.name,mimeType:e.type===""?void 0:e.type},{timeoutMs:0}))}fsSearch(e,t,n){return this.run(this.rest.sessions.fsSearch(e,t,{signal:n}))}workspaceFsSearch(e,t,n){return this.run(this.rest.filesystem.workspaceFsSearch(e,t,{signal:n}))}searchMessages(e,t){return this.run(this.rest.search.messages(e,{signal:t})).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))}pauseCronTask(e,t){return this.run(this.rest.cron.pause(e,{session_id:t}))}resumeCronTask(e,t){return this.run(this.rest.cron.resume(e,{session_id:t}))}runCronTask(e,t){return this.run(this.rest.cron.run(e,{session_id:t}))}deleteCronTask(e,t){return this.run(this.rest.cron.remove(e,{session_id:t}))}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,t){return this.memoryRequest("PATCH",`/memory/workspaces/${encodeURIComponent(e)}/settings`,{body:{enabled:t}})}listMemory(e,t={}){return this.memoryRequest("GET",`/memory/${e.scope}`,{target:e,query:{query:t.query!==void 0&&t.query.trim()!==""?t.query.trim():void 0,type:t.type,include_inactive:t.include_inactive===!0?"true":void 0}})}getMemory(e,t){return this.memoryRequest("GET",`/memory/${e.scope}/${encodeURIComponent(t)}`,{target:e})}putMemory(e,t,n){return this.memoryRequest("PUT",`/memory/${e.scope}/${encodeURIComponent(t)}`,{target:e,body:n})}deleteMemory(e,t,n){return this.memoryRequest("DELETE",`/memory/${e.scope}/${encodeURIComponent(t)}`,{target:e,query:{expected_revision:n}})}memoryJournal(e,t){return this.memoryRequest("GET",`/memory/${e.scope}/journal`,{target:e,query:{id:t}})}memoryInbox(e){return this.memoryRequest("GET",`/memory/${e.scope}/inbox`,{target:e})}undoMemory(e,t){return this.memoryRequest("POST",`/memory/${e.scope}/undo`,{target:e,body:{operation_id:t}})}async memoryRequest(e,t,n={}){const r=this.baseUrl.replace(/\/+$/u,""),a=r===""?new URL(`/api${t}`,globalThis.location?.origin??"http://localhost"):new URL(`${r}/api${t}`),i=n.target?.scope,u={...n.query,workspace_id:i==="workspace"||i==="persona_workspace"?n.target?.workspaceId:void 0,persona_id:i==="persona"||i==="persona_workspace"?n.target?.personaId:void 0};for(const[f,b]of Object.entries(u))b!==void 0&&a.searchParams.set(f,b);const m={accept:"application/json"};this.token!==void 0&&(m.authorization=`Bearer ${this.token}`),n.body!==void 0&&(m["content-type"]="application/json");let p;try{p=await(this.transport?.fetch??fetch)(a,{method:e,headers:m,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:AbortSignal.timeout(n.timeoutMs??3e4)})}catch(f){throw f instanceof DOMException&&f.name==="TimeoutError"?new q({code:z.TIMEOUT,msg:Ht("en","common.requestTimedOut"),data:null}):f}let g;try{g=await p.json()}catch{g=null}if(g===null||typeof g!="object"||!("code"in g)||typeof g.code!="number"||!("msg"in g)||typeof g.msg!="string")throw new q({code:z.INVALID_RESPONSE,msg:`HTTP ${p.status} — non-JSON response`,data:null});if(g.code!==0)throw new q({code:g.code,msg:g.msg,data:"data"in g?g.data??null:null,details:"details"in g?g.details:void 0,request_id:"request_id"in g&&typeof g.request_id=="string"?g.request_id:void 0});return"data"in g?g.data:null}forkSession(e,t={}){return this.sessions.forkSession(e,t)}editMessage(e,t,n){return this.sessions.editMessage(e,t,n)}regenerateMessage(e,t,n){return this.sessions.regenerateMessage(e,t,n)}compactSession(e,t={}){return this.run(this.rest.sessions.compact(e,t))}getAutoCompact(e,t){return this.run(this.rest.sessions.getAutoCompact(e,t))}getAgentHooksInspect(e,t){return this.run(this.rest.sessions.inspectHooks(e,t))}setAutoCompact(e,t,n){return this.run(this.rest.sessions.setAutoCompact(e,t,n))}getContextStrategy(e,t){return this.memoryRequest("GET",`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/context-strategy`)}setContextStrategy(e,t,n){return this.memoryRequest("PATCH",`/sessions/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/context-strategy`,{body:n})}undoSession(e,t={}){return this.run(this.rest.sessions.undo(e,t))}exportSession(e){return this.run(this.rest.sessions.export(e))}async patchConfig(e){return St(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,t={}){return this.run(()=>this.rest.personas.duplicate(e,t))}archivePersona(e,t){return this.run(()=>this.rest.personas.archive(e,t))}deletePersona(e,t){return this.run(()=>this.rest.personas.delete(e,{expectedRevision:t}))}async previewPersonaImport(e){const t=new Uint8Array(await e.arrayBuffer());return this.run(()=>this.rest.personas.previewImport({data:t,filename:e.name,format:ft(e)}))}async importPersonaCard(e,t={}){const n=new Uint8Array(await e.arrayBuffer());return this.run(()=>this.rest.personas.importCard({data:n,filename:e.name,format:ft(e),...t}))}async exportPersonaCard(e,t){const n=await this.run(()=>this.rest.personas.exportCard(e,t));return{blob:new Blob([n.bytes.slice().buffer],{type:n.mime}),filename:n.name??`${e}.${t}`}}async getPersonaAvatar(e,t){try{const n=await this.rest.personas.getAvatar(e,{signal:t});return new Blob([n.bytes.slice().buffer],{type:n.mime})}catch{return null}}async putPersonaAvatar(e,t,n){const r=new Uint8Array(await t.arrayBuffer());return this.run(()=>this.rest.personas.putAvatar(e,r,t.type,n))}deletePersonaAvatar(e){return this.run(()=>this.rest.personas.deleteAvatar(e))}}const Yp=40945,Xp=40946;function ft(o){const e=o.name.toLowerCase();return o.type==="image/png"||e.endsWith(".png")?"png":e.endsWith(".charx")?"charx":"json"}const am=Object.freeze(Object.defineProperty({__proto__:null,API_CODES:z,ApiError:q,ExternalAgentAttachmentUnsupportedError:as,KikiClient:ds,MEMORY_NOT_FOUND:Kp,MEMORY_REVISION_CONFLICT:zp,MEMORY_TYPES:Wp,NativeChildPromptConflictError:cs,NativeChildPromptSendError:Dt,PERSONA_ALREADY_EXISTS:Yp,PERSONA_REVISION_CONFLICT:Xp,createRemoteSpaceClient:Qp,isSessionIndexBuildingError:Vp,isSessionNotFoundMessage:Hp,parseKikiConfigResponse:St,personaCardFormatOf:ft},Symbol.toStringTag,{value:"Module"}));export{q as A,kp as D,as as E,Wt as G,ds as K,P as M,Dt as N,Xp as P,N as R,z as a,om as b,Qp as c,sm as d,rr as e,zp as f,Kt as g,nm as h,Wp as i,Kp as j,Hp as k,Yp as l,im as m,Fp as n,Bp as o,Vp as p,am as q,tm as s,em as t,rm as w};
|