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
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{as as s,at as v,au as h,av as H,aw as M,ax as y,ay as u,az as S,aA as c,aB as $,aC as d,aD as hs,aE as gs,aF as w,aG as it,aH as se,aI as vs,aJ as C,aK as Ie,aL as Ss,aM as fs,aN as ys,aO as bs,aP as _s,aQ as Is,aR as jt,aS as Ts,aT as Lt,aU as ws,aV as Es,aW as ks,aX as Cs,aY as Rs,aZ as Ps,a_ as Os,a$ as ze,b0 as Ke,b1 as Eo,b2 as ko,b3 as As,b4 as Ms,b5 as Us,b6 as xs,b7 as Ds,b8 as Ns,b9 as js,ba as Ls,bb as ue,bc as qs,bd as Gs,be as $s,bf as Fs,bg as Bs,bh as Vs,bi as Hs,bj as qt,bk as Ws,bl as zs,bm as Le,bn as Ks,bo as Qs,bp as Gt,bq as Ys,br as Qe,bs as Xs,bt as Js,bu as Zs,bv as Ye,bw as ei,bx as F,by as ti,bz as oi,bA as ni,bB as si,bC as ii,bD as ri,bE as ai,bF as ci,bG as V,bH as di,bI as li,bJ as ui,bK as pi,bL as mi,bM as Xe,bN as hi,bO as gi,bP as Co,bQ as Ro,bR as Po,bS as vi,bT as Si,bU as Te,bV as Oo,bW as fi,bX as yi,bY as $e,bZ as bi,b_ as _i,b$ as Ii,c0 as Ti,c1 as wi,c2 as Ei,c3 as ki,c4 as Ci,c5 as Ri,c6 as Pi,c7 as Oi,c8 as Ai,c9 as Mi,ca as Ui,cb as xi,cc as $t,cd as Ft,ce as Di,cf as Ni,cg as ji,ch as Li,ci as qi,cj as Gi,ck as $i,cl as Fi,cm as Bi,cn as Vi,co as Ao,cp as Mo,cq as Uo,cr as Hi,cs as xo,ct as Do,cu as Wi,cv as Je,cw as zi,cx as Ee,cy as Ki,cz as Qi,cA as pe,cB as Yi,cC as Q,cD as Bt,cE as Xi,cF as Ze,cG as Ji,cH as et,cI as Zi,cJ as er,cK as tr,cL as or,cM as nr,cN as Vt,cO as sr,cP as ir,a as rr,B as Ht,cQ as ar,cR as cr,cS as dr,cT as Wt,cU as lr,cV as ur,cW as pr,cX as mr,cY as hr}from"./index-DgwALPNA.js";const zt={off:0,turn:1,block:2,delta:3};function Kt(o,e){return o?o[e]??o["*"]??"off":"off"}function gr(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]),i=new TextEncoder().encode(n);let a="";for(const r of i)a+=String.fromCharCode(r);return`raw:${btoa(a).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}`}const Qt=512*1024,vr={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}"],agentTaskList:["GET","/sessions/{sessionId}/agent-tasks"],userMessages:["GET","/sessions/{sessionId}/user-messages"],skills:["GET","/sessions/{sessionId}/skills"],skillActivate:["POST","/sessions/{sessionId}/skills/{skillName}:activate"],context:["GET","/sessions/{sessionId}/context"],metrics:["GET","/sessions/{sessionId}/metrics"],media:["GET","/sessions/{sessionId}/media/{fileId}"],mediaPreview:["GET","/sessions/{sessionId}/media/{fileId}/preview"],fileUpload:["POST","/files"],file:["GET","/files/{fileId}"],tools:["GET","/tools"],models:["GET","/models"],providers:["GET","/providers"],auth:["GET","/auth"],configRead:["GET","/config"],usage:["GET","/usage"],requestGovernance:["GET","/usage/realtime"],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"]},Sr=o=>!o||o==="."||o===".."||o.includes("/")||o.includes("\\");function fr(o,e){const t=Object.entries(vr).toSorted((n,i)=>(n[1][1].match(/\{/g)?.length??0)-(i[1][1].match(/\{/g)?.length??0));for(const[n,[i,a]]of t){if(i!==o)continue;const r=[],l=a.split(/(\{[A-Za-z]+\})/).map(f=>f.startsWith("{")?(r.push(f.slice(1,-1)),"([^/]+)"):f.replaceAll(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(""),m=new RegExp("^/api"+l+"$").exec(e.startsWith("/api/")?e:"/api"+e);if(m===null)continue;const p={};let g=!0;for(let f=0;f<r.length;f+=1){let b;try{b=decodeURIComponent(m[f+1])}catch{g=!1;break}if(Sr(b)){g=!1;break}p[r[f]]=b}if(g)return{operation:n,params:p}}}function yr(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),bt=s().min(1).max(4096),qe=v(O).max(256),Ge=h(["active","in_progress","paused","done","cancelled","superseded"]),be=H({root:bt,storageId:O,kind:h(["workspace","embedded"])}),br=H({root:bt,storageId:O.optional(),kind:h(["workspace","embedded"])}),_r=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"]}),Ir=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:qe.optional(),executionIds:qe.optional(),status:Ge.optional()}).refine(o=>Object.keys(o).length>0,"An update requires a changed field."),Tr=M("action",[H({action:y("preview"),workspaceId:O.optional(),configuration:_r.optional()}),H({action:y("list"),workspaceId:O.optional(),storage:be.optional(),sessionId:O.optional(),status:Ge.optional(),archived:S().optional(),cursor:O.optional(),limit:u().int().min(1).max(100).optional()}),H({action:y("show"),workspaceId:O,storage:be,id:O}),H({action:y("overview"),workspaceIds:v(O).min(1).max(32),status:Ge.optional(),limit:u().int().min(1).max(100).optional()})]),wr=M("action",[H({action:y("create"),workspaceId:O.optional(),requestKey:O,target:br.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:qe.optional(),executionIds:qe.optional()}),H({action:y("update"),workspaceId:O,storage:be,id:O,expectedRevision:u().int().nonnegative().max(Number.MAX_SAFE_INTEGER),patch:Ir})]),No=c({id:O,workspaceId:O,storage:be,title:s(),priority:s(),status:Ge,revision:u().int().nonnegative(),createdAt:s(),updatedAt:s(),completedAt:s().nullable(),archived:S(),category:s(),sessionIds:v(s()),executionIds:v(s())}),jo=No.extend({description:s(),prd:s(),handoff:s().optional()}),Lo=c({code:s(),message:s()}),Fe=o=>M("ok",[c({ok:y(!0),value:o}),c({ok:y(!1),error:Lo})]),qo=c({workspaceId:O,storage:be.optional(),cards:v(No),issues:v(Lo),nextCursor:s().optional()}),Er=c({mode:h(["auto","global","fixed"]),workspaceId:O,root:bt,tasksDirectory:s(),existing:S(),kind:h(["workspace","embedded"]),storageId:O.optional(),selectionOnly:y(!0)}),Go=c({workspaceId:O,result:Fe(qo)}),kr=Fe($([jo,qo,Er,v(Go)])),Cr=Fe(jo),Rr=Fe(v(Go)),Pr={read:{input:d([Tr]),output:kr},write:{input:d([wr]),output:Cr},overview:{input:d([]),output:Rr}},Or={read:{input:d([hs]),output:gs}},Ar=h(["running","streaming","tool_call","retrying"]),Mr=c({approvalId:s(),toolCallId:s().optional(),since:u()}),Ur=c({toolCallId:s(),name:s(),since:u()}),xr=c({failedAttempt:u(),nextAttempt:u(),maxAttempts:u(),delayMs:u(),errorName:s().optional(),statusCode:u().optional()}),Dr=c({turnId:u(),origin:w(),phase:Ar,stream:h(["assistant","thinking","tool_call"]).optional(),step:u(),ending:S(),endingReason:h(["aborted","max_steps","error"]).optional(),retry:xr.optional(),pendingApprovals:v(Mr),activeToolCalls:v(Ur),since:u()}),Nr=h(["completed","cancelled","failed","blocked"]),jr=c({turnId:u(),reason:Nr,durationMs:u().optional(),at:u()}),Lr=c({kind:s(),id:s(),since:u()}),qr=h(["ready","disposed"]),Gr=c({lifecycle:qr,turn:Dr.optional(),lastTurn:jr.optional(),background:v(Lr)}),$r={state:{input:d([]),output:Gr}},Fr=o=>c({items:v(o),nextCursor:s().optional()}),A=o=>$([o,se(),vs()]).transform(e=>e??void 0),_=$([it(),se()]).transform(()=>{}),Yt=c({added:v(s()),removed:v(s()),changed:v(s())}),_t=C(s(),s()),Xt=u().int().min(1).max(2147483647),It={enabled:S().optional(),startupTimeoutMs:Xt.optional(),toolTimeoutMs:Xt.optional(),enabledTools:v(s()).optional(),disabledTools:v(s()).optional()},Tt=c({transport:y("stdio"),runtime_id:s().min(1).optional(),command:s().min(1),args:v(s()).optional(),env:_t.optional(),cwd:s().optional(),executor:h(["local","kaos"]).optional(),...It}),wt=c({transport:y("http"),url:s().url(),headers:_t.optional(),auth:y("oauth").optional(),bearerTokenEnvVar:s().min(1).optional(),...It}),Et=c({transport:y("sse"),url:s().url(),headers:_t.optional(),auth:y("oauth").optional(),bearerTokenEnvVar:s().min(1).optional(),...It}),Be=M("transport",[Tt,wt,Et]),kt=h(["direct","compact","fresh"]),rt=c({operationId:s().min(1),model:s().min(1),mode:kt,thinking:s().optional(),selectedFromModel:s().optional()}),te=c({operationId:s(),agentId:s(),state:h(["pending","preparing","completed","failed","cancelled"]),fromModel:s(),toModel:s(),mode:kt,binding:c({model:s(),thinking:s()}).optional(),windowEpoch:u().int().nonnegative().optional(),summaryGenerated:S().optional(),error:c({code:s(),message:s()}).optional()}),$o=c({input:rt,receipt:te,revision:u().int().nonnegative(),originalBinding:c({model:s(),thinking:s()}),queueIndex:u().int()}),Br=c({type:y("prompt.model_switch_queued"),time:u().optional(),entry:$o.omit({queueIndex:!0}),queueIndex:u().int().nonnegative()}),Vr=c({type:y("prompt.model_switch_status"),time:u().optional(),operationId:s(),receipt:te}),Hr=c({type:y("turn.step.started"),time:u().optional(),turnId:u(),step:u(),stepId:s().optional()}),Wr=c({type:y("turn.step.interrupted"),time:u().optional(),turnId:u(),step:u(),stepId:s().optional(),reason:s(),message:s().optional()}),zr=c({type:y("turn.step.retrying"),time:u().optional(),turnId:u(),step:u(),stepId:s().optional(),failedAttempt:u(),nextAttempt:u(),maxAttempts:u(),delayMs:u(),errorName:s(),errorMessage:s(),statusCode:u().optional()}),Kr=c({type:y("hook.result"),time:u().optional(),turnId:u().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:u().int().nonnegative().optional(),turnsUsed:u(),tokensUsed:u(),wallClockMs:u(),terminalReason:s().optional(),budget:c({tokenBudget:u().nullable(),turnBudget:u().nullable(),wallClockBudgetMs:u().nullable(),remainingTokens:u().nullable(),remainingTurns:u().nullable(),remainingWallClockMs:u().nullable(),tokenBudgetReached:S(),turnBudgetReached:S(),wallClockBudgetReached:S(),overBudget:S()})}),Qr=c({type:y("goal.updated"),time:u().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:u(),tokensUsed:u(),wallClockMs:u()}).optional()}).optional()}),Yr=c({type:y("turn.started"),time:u().optional(),turnId:u(),origin:w(),prompt:s().optional(),promptId:s().optional()}),Xr=c({type:y("turn.ended"),time:u().optional(),turnId:u(),reason:h(["completed","cancelled","failed","blocked"]),error:w().optional(),durationMs:u().optional(),interruptReason:h(["user_cancelled","aborted","max_steps","error","filtered","blocked"]).optional()}),Jr=c({type:y("assistant.delta"),time:u().optional(),turnId:u(),delta:s()}),Zr=c({type:y("thinking.delta"),time:u().optional(),turnId:u(),delta:s()}),ea=c({type:y("tool.call.started"),time:u().optional(),turnId:u(),toolCallId:s(),name:s(),args:w(),description:s().optional(),display:w().optional()}),ta=c({type:y("tool.call.delta"),time:u().optional(),turnId:u(),toolCallId:s(),name:s().optional(),argumentsPart:s().optional()}),oa=c({type:y("tool.progress"),time:u().optional(),turnId:u(),toolCallId:s(),update:c({kind:h(["stdout","stderr","progress","status","custom"]),text:s().optional(),percent:u().optional(),customKind:s().optional(),customData:w().optional(),replace:S().optional()})}),na=c({type:y("tool.result"),time:u().optional(),turnId:u(),toolCallId:s(),output:w(),isError:S().optional(),synthetic:S().optional()}),Ve=w(),Ct=h(["agent_idle","subagents_done","tasks_done"]),sa=c({type:y("prompt.submitted"),time:u().optional(),promptId:s(),userMessageId:s(),status:h(["running","queued","blocked"]),content:v(Ve),createdAt:s(),appendTiming:Ct.optional(),revision:u().int().nonnegative().optional()}),ia=c({type:y("prompt.queued"),time:u().optional(),promptId:s(),content:v(Ve),queueLength:u().int().nonnegative(),appendTiming:Ct.optional(),revision:u().int().nonnegative().optional()}),ra=c({type:y("prompt.started"),time:u().optional(),promptId:s()}),aa=c({type:y("prompt.replaced"),time:u().optional(),promptId:s(),content:v(Ve),replacedAt:s(),message:w().optional(),revision:u().int().nonnegative().optional()}),ca=c({type:y("prompt.timing_changed"),time:u().optional(),promptId:s(),appendTiming:Ct,revision:u().int().nonnegative(),changedAt:s()}),da=c({type:y("prompt.steered"),time:u().optional(),activePromptId:s(),promptIds:v(s()),content:v(Ve),steeredAt:s()}),la=c({type:y("prompt.completed"),time:u().optional(),promptId:s(),finishedAt:s(),reason:h(["completed","failed","blocked"]).optional()}),ua=c({type:y("prompt.aborted"),time:u().optional(),promptId:s(),abortedAt:s(),beforeStart:S().optional()}),pa=c({type:y("prompt.moved"),time:u().optional(),promptId:s(),targetIndex:u().int().nonnegative(),queuedPromptIds:v(s()),movedAt:s()}),ma=c({type:y("compaction.started"),time:u().optional(),trigger:h(["manual","auto"]),instruction:s().optional(),phase:h(["queued","running"]).optional()}),ha=c({type:y("compaction.blocked"),time:u().optional(),turnId:u().optional()}),ga=c({type:y("compaction.cancelled"),time:u().optional(),trigger:h(["manual","auto"]).optional(),reason:s().optional()}),va=c({type:y("compaction.completed"),time:u().optional(),trigger:h(["manual","auto"]).optional(),result:c({summary:s(),compactedCount:u(),tokensBefore:u(),tokensAfter:u(),keptUserMessageCount:u().optional(),keptHeadUserMessageCount:u().optional(),droppedCount:u().optional(),strategy:h(["summarize","relay"]).optional(),shapeVersion:u().int().positive().optional(),reasonCodes:v(s()).optional(),fallbackFrom:h(["relay","summarize"]).optional()})}),Sa=Ie({time:u().optional(),turnId:u(),toolCallId:s(),toolName:s(),action:s()}),fa=Ie({time:u().optional(),turnId:u(),toolCallId:s()}),ya=Ie({time:u().optional(),message:s()}),ba=c({type:y("warning"),time:u().optional(),message:s(),code:s().optional()}),_a=Ie({time:u().optional(),phase:s().optional(),autoCompactTokens:u().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:u().optional(),reservedContextTokens:u().optional()}),Ia={"prompt.model_switch_queued":{kind:"stream",name:"events",type:"prompt.model_switch_queued",schema:Br},"prompt.model_switch_status":{kind:"stream",name:"events",type:"prompt.model_switch_status",schema:Vr},"turn.step.started":{kind:"stream",name:"events",type:"turn.step.started",schema:Hr},"turn.step.interrupted":{kind:"stream",name:"events",type:"turn.step.interrupted",schema:Wr},"turn.step.retrying":{kind:"stream",name:"events",type:"turn.step.retrying",schema:zr},"hook.result":{kind:"stream",name:"events",type:"hook.result",schema:Kr},"goal.updated":{kind:"stream",name:"events",type:"goal.updated",schema:Qr},"turn.started":{kind:"stream",name:"events",type:"turn.started",schema:Yr},"turn.ended":{kind:"stream",name:"events",type:"turn.ended",schema:Xr},"assistant.delta":{kind:"stream",name:"events",type:"assistant.delta",schema:Jr},"thinking.delta":{kind:"stream",name:"events",type:"thinking.delta",schema:Zr},"tool.call.started":{kind:"stream",name:"events",type:"tool.call.started",schema:ea},"tool.call.delta":{kind:"stream",name:"events",type:"tool.call.delta",schema:ta},"tool.progress":{kind:"stream",name:"events",type:"tool.progress",schema:oa},"tool.result":{kind:"stream",name:"events",type:"tool.result",schema:na},"prompt.submitted":{kind:"stream",name:"events",type:"prompt.submitted",schema:sa},"prompt.queued":{kind:"stream",name:"events",type:"prompt.queued",schema:ia},"prompt.started":{kind:"stream",name:"events",type:"prompt.started",schema:ra},"prompt.replaced":{kind:"stream",name:"events",type:"prompt.replaced",schema:aa},"prompt.moved":{kind:"stream",name:"events",type:"prompt.moved",schema:pa},"prompt.timing_changed":{kind:"stream",name:"events",type:"prompt.timing_changed",schema:ca},"prompt.steered":{kind:"stream",name:"events",type:"prompt.steered",schema:da},"prompt.completed":{kind:"stream",name:"events",type:"prompt.completed",schema:la},"prompt.aborted":{kind:"stream",name:"events",type:"prompt.aborted",schema:ua},"compaction.started":{kind:"stream",name:"events",type:"compaction.started",schema:ma},"compaction.blocked":{kind:"stream",name:"events",type:"compaction.blocked",schema:ha},"compaction.cancelled":{kind:"stream",name:"events",type:"compaction.cancelled",schema:ga},"compaction.completed":{kind:"stream",name:"events",type:"compaction.completed",schema:va},"permission.approval.requested":{kind:"stream",name:"events",type:"permission.approval.requested",schema:Sa},"permission.approval.resolved":{kind:"stream",name:"events",type:"permission.approval.resolved",schema:fa},error:{kind:"stream",name:"events",type:"error",schema:ya},warning:{kind:"stream",name:"events",type:"warning",schema:ba},"agent.status.updated":{kind:"stream",name:"events",type:"agent.status.updated",schema:_a}};function Fo(o){const e=o.overrides;return{...o,overrides:e===void 0?void 0:{...e,kiki_context:e.kiki_context===null||e.kiki_context===void 0?e.kiki_context:[...e.kiki_context]}}}const Bo=Ss.transform(Fo),Ta=fs.transform(o=>({...o,selection:Fo(o.selection),effective:{...o.effective,kiki_context:[...o.effective.kiki_context]}})),wa=c({type:y("text"),text:s()}),Ea=c({type:y("image_url"),imageUrl:c({url:s(),id:s().optional()})}),ka=c({type:y("video_url"),videoUrl:c({url:s(),id:s().optional()})}),Vo=M("type",[wa,Ea,ka]);c({});const Ca=c({execution:Bo.optional(),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()}),at=c({input:v(Vo),execution:Ca.optional(),appendTiming:h(["agent_idle","subagents_done","tasks_done"]).optional(),disabledTools:v(s()).optional(),promptId:s().min(1).optional()}),Ra=c({name:s(),args:s().optional()}),Pa=at.extend({skills:v(Ra).min(1)}),Oa=c({turn_id:u().optional(),prompt_id:s(),created_at:s(),state:h(["running","queued","blocked"]),append_timing:h(["agent_idle","subagents_done","tasks_done"]),revision:u().int().nonnegative()}),Aa=c({input:v(Vo)}),Ma=c({name:s(),args:s().optional()}),ct=c({turn_id:u()}),dt=c({code:s(),message:s(),name:s().optional(),details:C(s(),w()).optional(),retryable:S(),get cause(){return dt.optional()}}),Ua=c({promptId:s(),turnId:u().optional(),state:h(["completed","failed","cancelled","blocked"]),result:M("type",[c({type:y("completed"),steps:u(),truncated:S()}),c({type:y("failed"),steps:u(),error:dt}),c({type:y("cancelled"),steps:u(),reason:dt})]).optional()});c({turnId:u().optional()});const xa=c({command:s(),commandId:s().optional()}),Da=c({stdout:s(),stderr:s(),isError:S().optional(),backgrounded:S().optional()});c({commandId:s()});c({model:s()});const Na=c({model:s(),providerName:s().optional()});c({effort:s().min(1)});const ja=c({effort:s()}),La=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()})}),Ho=h(["summarize","auto","fresh"]),qa=c({strategy:Ho,source:h(["session","profile","global","default","subagent","executor"]),shadow:S()}),ke=c({workspaceId:s(),runtimeId:s()}),Ga=c({image_in:S(),video_in:S(),audio_in:S(),thinking:S(),tool_use:S(),max_context_tokens:u(),max_input_tokens:u().optional(),dynamically_loaded_tools:S().optional()}),De=h(["manual","auto","review","yolo"]);c({mode:De});const $a=c({state:h(["idle","running"]),activeTurnId:u().optional(),pendingTurnIds:v(u()),hasPendingRequests:S(),activeTraceId:s().optional()}),Ne=c({inputOther:u(),output:u(),inputCacheRead:u(),inputCacheCreation:u()}),Fa=c({byModel:C(s(),Ne).optional(),currentTurn:Ne.optional(),total:Ne.optional()});c({history:v(w()),tokenCount:u()});const Ba=c({name:s(),description:s().optional(),source:s()});c({name:s(),args:s().optional()});const Va=$([se(),c({id:s(),content:s(),path:s()})]);c({id:s().optional()});c({activeOnly:S().optional(),limit:u().optional()});const Ha=h(["running","completed","failed","timed_out","killed","lost"]),Ce={taskId:s(),description:s(),status:Ha,detached:S().optional(),startedAt:u(),endedAt:$([u(),se()]),stopReason:s().optional(),terminalNotificationSuppressed:S().optional(),timeoutMs:u().optional(),receipt:ys.optional(),receiptVerification:h(["verified","legacy_unverified","invalid"]).optional()},Re=M("kind",[c({kind:y("process"),command:s(),pid:u(),exitCode:$([u(),se()]),...Ce}),c({kind:y("agent"),agentId:s().optional(),profile:s().optional(),model:s().optional(),thinkingEffort:s().optional(),...Ce}),c({kind:y("question"),questionCount:u(),toolCallId:s().optional(),...Ce}),c({kind:y("media"),jobId:s(),...Ce})]);c({taskId:s(),reason:s().optional()});c({taskId:s(),tail:u().optional()});const Wa={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:u().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}},za={switchModel:{input:d([rt]),output:te},getModelSwitch:{input:d([s()]),output:A(te)},listModelSwitches:{input:d([]),output:v($o)},updateModelSwitch:{input:d([rt,u().int().nonnegative().optional()]),output:te},cancelModelSwitch:{input:d([s()]),output:te},recoverModelSwitch:{input:$([d([s(),y("retry"),kt.optional()]),d([s(),y("keep_original")])]),output:te},submit:{input:d([at]),output:A(ct)},submitAndWait:{input:d([at]),output:Ua},submitSteer:{input:d([Aa]),output:A(ct)},resumeRecoveredQueue:{input:d([]),output:_}},Ka={activate:{input:d([Ma]),output:ct},promptWithSkills:{input:d([Pa]),output:Oa}},Qa={reconcileWhenIdle:{input:d([s()]),output:_}},Ya={rebuild:{input:d([]),output:La}},Xa={undo:{input:d([u().int().positive().max(Number.MAX_SAFE_INTEGER)]),output:u()}},Ja={activate:{input:d([c({pluginId:s(),commandName:s(),args:s().optional()})]),output:_}},Za={refreshSessionStart:{input:d([]),output:_}},ec={cancelFromUser:{input:d([u().optional()]),output:_},status:{input:d([]),output:$a}},tc={mode:{input:d([]),output:De},setMode:{input:d([De]),output:_},setModeAndBroadcast:{input:d([De]),output:_}},oc={list:{input:d([]),output:v(Ba)},run:{input:d([s(),s().optional()]),output:_}},nc={get:{input:d([]),output:ke},set:{input:d([ke]),output:ke},switch:{input:d([s()]),output:ke}},sc={get:{input:d([]),output:v(w())},append:{input:d([w()]),output:_},clear:{input:d([]),output:_}},ic={appendImported:{input:d([w()]),output:_}},rc={statusSize:{input:d([]),output:u()}},ac={run:{input:d([xa]),output:Da},cancel:{input:d([s()]),output:_}},cc={getModel:{input:d([]),output:s()},setModel:{input:d([s()]),output:Na},setEffort:{input:d([s()]),output:ja},setThinking:{input:d([s()]),output:_},getEffectiveThinkingLevel:{input:d([]),output:s()},getModelCapabilities:{input:d([]),output:Ga},getAgentsMdWarning:{input:d([]),output:A(s())}},dc={status:{input:d([]),output:Fa}},lc={status:{input:d([]),output:Va},enter:{input:d([]),output:_},clear:{input:d([]),output:_},cancel:{input:d([s().optional()]),output:_}},uc=c({name:s(),transport:h(["stdio","http","sse"]),status:h(["pending","connected","failed","disabled","needs-auth","removed"]),toolCount:u(),error:s().optional()}),pc={list:{input:d([]),output:v(uc)},waitForInitialLoad:{input:d([]),output:_},initialLoadDurationMs:{input:d([]),output:u()},reconnect:{input:d([s()]),output:_},connect:{input:d([s(),Be]),output:_}},mc=c({source:h(["manual","auto"]),instruction:s().optional()}),hc={begin:{input:d([mc]),output:S()},cancel:{input:d([]),output:_},isCompacting:{input:d([]),output:S()},getAutoCompact:{input:d([]),output:c({tokens:u(),source:h(["session","profile","model","global","legacy"]),effectiveMaxContextTokens:u(),reservedContextTokens:u()})},getDefaultAutoCompact:{input:d([]),output:c({tokens:u(),source:h(["session","profile","model","global","legacy"]),effectiveMaxContextTokens:u(),reservedContextTokens:u()})},setAutoCompactOverride:{input:d([u().int().positive().safe().nullable()]),output:_},getContextStrategy:{input:d([]),output:qa},setContextStrategyOverride:{input:d([Ho.nullable()]),output:_}},gc={list:{input:d([S().optional(),u().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(),u().optional()]),output:s()}},Wo=h(["pending","authenticated","denied","failed","expired","cancelled"]),vc=M("status",[c({flow_id:s(),provider:s(),status:y("pending"),verification_uri:s(),verification_uri_complete:s(),user_code:s(),expires_in:u(),interval:u(),expires_at:s()}),c({flow_id:s(),provider:s(),status:y("authenticated")})]),Sc=c({flow_id:s(),provider:s(),status:Wo,verification_uri:s(),verification_uri_complete:s(),user_code:s(),expires_in:u(),expires_at:s(),interval:u(),resolved_at:s().optional(),error_message:s().optional()}),fc=c({cancelled:S(),status:Wo}),yc=c({logged_out:y(!0),provider:s()}),zo=c({loggedIn:S(),provider:s().optional()}),bc=c({changed:v(c({provider_id:s(),provider_name:s(),added:u(),removed:u()})),unchanged:v(s()),failed:v(c({provider:s(),reason:s()}))}),_c=c({region:h(["mainland-cn","global"]).optional()}),Ic=c({id:s(),label:s(),provider:s(),protocol:s(),signed_in:S(),auth_source:bs.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:u(),unit:h(["count","percent"]),reset_at:s().optional()}),c({state:y("unknown")})])}),Tc={probeOriginal:{input:d([Is]),output:jt},connectOriginal:{input:d([_s]),output:jt},listMethods:{input:d([]),output:v(Ic)},startLogin:{input:d([s().optional(),_c.optional()]),output:vc},getFlow:{input:d([s().optional()]),output:A(Sc)},cancelLogin:{input:d([s().optional()]),output:fc},logout:{input:d([s().optional()]),output:yc},status:{input:d([s().optional()]),output:zo},refreshOAuthProviderModels:{input:d([]),output:bc}},wc={summarize:{input:d([]),output:v(zo)},ensureReady:{input:d([s().optional()]),output:_}},Ec=c({id:s(),state:h(["ok","missing","failed"]),reason:s().optional(),detail:s().optional(),optional:S().optional()}),kc=c({running:S(),step:s().optional(),percent:u().optional(),error:s().optional(),note:s().optional()}),Pe=c({id:h(["kimi-cu","kimi-webbridge","kiki-computer","kiki-browser"]),pluginId:s().optional(),displayName:s(),description:s(),supported:S(),state:h(["not_installed","partial","ready","unsupported"]),version:s().optional(),steps:v(Ec),plan:c({artifact:c({version:s(),url:s(),sha256:s(),metadataUrl:s(),maxBytes:u()}),destination:s(),browserExtensionUrl:s().optional(),note:s()}).optional(),install:kc}),Cc={listCapabilities:{input:d([]),output:v(Pe)},getCapability:{input:d([s()]),output:Pe},installCapability:{input:d([s(),s().optional(),h(["driver-only","managed-browser"]).optional()]),output:Pe},cancelCapability:{input:d([s()]),output:Pe}},Jt=new Map,Rc=new Set;function T(o){for(const e of Object.values(o.codes)){const t=Jt.get(e);if(t!==void 0&&t!==o.codes)throw new Error(`error code '${e}' is registered by two different domains`);Jt.set(e,o.codes)}for(const e of o.retryable??[])Rc.add(e);for(const[e,t]of Object.entries(o.info??{}));}const Ko={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(Ko);const Qo={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(Qo);const Pc=/^(?:[a-z][a-z0-9_]{0,31}|custom:[a-z0-9][a-z0-9_-]{0,47})$/u,Yo=h(["codex_compatible","claude_code_compatible","grok_build_compatible","opencode_compatible","kimi_code","none"]),Xo=s().regex(Pc),Jo=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()]),Oc=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:Jo.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(Pt,{message:"request identity overrides must contain a leaf value"}),Rt=c({preset:Yo.optional(),profile:Xo.optional(),overrides:Oc.optional()}).strict().refine(Zo,{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"}),Ac=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:Jo.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(Pt,{message:"request identity overrides must contain a leaf value"});c({preset:Yo.optional(),profile:Xo.optional(),overrides:Ac.optional()}).strict().refine(Zo,{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 Zo(o){return o.preset!==void 0||o.profile!==void 0||o.overrides!==void 0}function Pt(o){return o===void 0?!1:o===null||typeof o!="object"?!0:Object.values(o).some(Pt)}h(["connected","error","unconfigured"]);const Mc=c({systemPrompt:s(),messages:v(w()),tools:v(w()).optional(),responseFormat:w().optional()}),Uc=c({cacheKey:s().optional(),temperature:u().optional(),topP:u().optional(),thinkingEffort:s().optional(),maxCompletionTokens:u().optional()}).optional(),xc=c({type:s()}).passthrough(),Dc={listModels:{input:d([]),output:v(ws)},listProviders:{input:d([]),output:v(Lt)},getProvider:{input:d([s()]),output:Lt},setDefaultModel:{input:d([s()]),output:Ts},generate:{input:d([s(),Mc,Uc]),chunk:xc,streaming:!0}},Nc=c({scope:h(["all","oauth"]).optional(),providerId:s().optional(),apiKey:s().min(1).optional()}),jc={listDiscoveredModels:{input:d([]),output:ks},refreshProviderModels:{input:d([Nc.optional()]),output:Es}},Ot=h(["user","memory"]),Lc=c({value:w().optional(),defaultValue:w().optional(),userValue:w().optional(),memoryValue:w().optional()}),qc=c({domain:s().optional(),severity:h(["warning","error"]),message:s()}),Gc=d([s(),w(),Ot.optional()]).superRefine(([o,e],t)=>{o==="requestIdentity"&&At(e,t,[1],!1)}),$c=d([s(),w(),Ot.optional()]).superRefine(([o,e],t)=>{o==="requestIdentity"&&At(e,t,[1],!0)}),Fc=d([C(s(),w()),Ot.optional()]).superRefine(([o],e)=>{Object.hasOwn(o,"requestIdentity")&&At(o.requestIdentity,e,[0,"requestIdentity"],!0)});function At(o,e,t,n){if(n&&o==null)return;const i=Rt.safeParse(o);if(!i.success)for(const a of i.error.issues)e.addIssue({...a,path:[...t,...a.path]})}const Bc={get:{input:d([s()]),output:w()},inspect:{input:d([s()]),output:Lc},getAll:{input:d([]),output:C(s(),w())},set:{input:Gc,output:_},replace:{input:$c,output:_},replaceSections:{input:Fc,output:_},reload:{input:d([]),output:_},diagnostics:{input:d([]),output:v(qc)}},q={input:d([]),output:s()},Vc={input:d([]),output:c({productName:s(),version:s(),platform:s(),userAgentSuffix:s().optional()})},Hc={platform:q,arch:q,cwd:q,osHomeDir:q,homeDir:q,configPath:q,clientVersion:q,clientIdentity:Vc,sessionsDir:q,blobsDir:q,storeDir:q,cacheDir:q,logsDir:q},en=c({id:s().min(1),name:s().min(1),media_type:s().min(1),size:u().int().nonnegative(),created_at:s(),expires_at:s().optional()}),Wc=c({name:s().optional(),mimeType:s().optional(),expiresInSec:u().optional()}),zc=c({meta:en,data:s()}),Kc={save:{input:d([s(),s().min(1),Wc]),output:en},get:{input:d([s().min(1)]),output:zc},delete:{input:d([s().min(1)]),output:_}},Zt=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(Zt)},explainAll:{input:d([]),output:v(Zt)}},Yc=c({name:s().min(1),path:s().min(1),is_dir:y(!0)}),Xc=c({path:s().min(1),parent:s().min(1).nullable(),entries:v(Yc)}),Jc=c({home:s().min(1),recent_roots:v(s().min(1))}),Zc={browse:{input:d([s().optional()]),output:Xc},home:{input:d([]),output:Jc}},ed=h(["openai-codex","grok-build"]),td=h(["file","keyring","encrypted"]),od=c({kind:y("local_original"),provider:ed,homeDir:s().min(1),storageBackend:td,authFile:s().min(1).optional(),accountId:s().min(1),userId:s().min(1).optional(),scope:s().min(1).optional()}).strict(),tn=c({storage:h(["file","keyring"]),key:s().min(1),oauthHost:s().min(1).optional(),source:od.optional()}),nd=h(["anthropic","openai","openai_responses","google-genai"]),on=c({providerId:s().optional(),baseUrl:s().optional(),apiKey:s().optional(),oauth:tn.optional(),protocol:nd.optional(),name:s().optional(),aliases:v(s()).optional(),provider:s().optional(),model:s().optional(),maxContextSize:u().int().min(1).optional(),maxOutputSize:u().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:Rt.optional()}),sd=on.omit({providerId:!0,baseUrl:!0,apiKey:!0,oauth:!0,protocol:!0,name:!0,aliases:!0,provider:!0,model:!0,betaApi:!0,requestIdentity:!0}).partial(),tt=on.extend({overrides:sd.optional(),pricingModel:s().trim().min(1).optional()}).passthrough(),id={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:_}},rd=c({baseRevision:s().min(1).optional()}),ad={readModel:{input:d([s()]),output:Ke},createModel:{input:d([Os]),output:Ke},updateModel:{input:d([s(),Ps]),output:Ke},deleteModel:{input:d([s(),rd.optional()]),output:it()},readProvider:{input:d([s()]),output:ze},createProvider:{input:d([Rs]),output:ze},updateProvider:{input:d([s(),Cs]),output:ze},deleteProvider:{input:d([s()]),output:it()}},nn=h(["global","plugin","caller"]),cd=c({id:s(),name:s()}),z=c({cwd:s().min(1).optional()}),dd=c({cwd:s().min(1).optional(),verify:S().optional()}),lt=M("transport",[Tt.extend({name:s().min(1)}),wt.extend({name:s().min(1)}),Et.extend({name:s().min(1)})]),sn=M("transport",[Tt.extend({envKeys:v(s()).optional()}),wt.extend({headerKeys:v(s()).optional()}),Et.extend({headerKeys:v(s()).optional()})]),me=c({name:s(),config:sn,source:nn,origin:s(),mutable:S(),plugin:cd.optional()}),ld=c({name:s().min(1).optional(),server:lt.optional(),cwd:s().min(1).optional()}),ud=c({success:S(),output:s()}),pd=c({name:s().min(1),cwd:s().min(1).optional()}),md=c({state:h(["idle","stopped","unconfirmed"]),output:s()}),fe=M("source",[c({source:y("global"),name:s().min(1)}),c({source:y("plugin"),pluginId:s().min(1),serverName:s().min(1)})]),rn=h(["not-applicable","bearer-token","oauth-required","oauth-authorized","oauth-expired","unavailable"]),hd=c({serverId:s(),locator:fe,runtimeName:s(),canonicalUrl:s().optional(),origin:nn,config:sn,enabled:S(),editable:S()}),gd=hd.extend({authStatus:rn,checkedAt:u().optional(),error:s().optional()}),vd=c({name:s(),authStatus:rn}),ut=c({credentialId:s().regex(/^[a-f0-9]{64}$/)}),Sd=ut.extend({serverName:s().min(1),displayUrl:s().min(1),origin:y("unknown")}),fd=c({canonicalUrl:Eo()}),yd=M("status",[c({status:y("authorization-required"),flowId:s(),authorizationUrl:s()}),c({status:y("already-authorized")})]),bd=c({flowId:s().min(1),timeoutMs:u().int().min(1).max(2**31-1).optional()}),_d={listServers:{input:d([z.optional()]),output:v(me)},getServer:{input:d([s().min(1),z.optional()]),output:me},addServer:{input:d([lt,z.optional()]),output:v(me)},updateServer:{input:d([lt,z.optional()]),output:v(me)},removeServer:{input:d([s().min(1),z.optional()]),output:v(me)},testServer:{input:d([ld]),output:ud},stopServer:{input:d([pd]),output:md},listAuthStatuses:{input:d([dd.optional()]),output:v(vd)},inspectServers:{input:d([v(fe).optional(),z.optional()]),output:v(gd)},resolveServerByName:{input:d([s().min(1),z.optional()]),output:fe},beginServerAuth:{input:d([fe,z.optional()]),output:yd},completeServerAuth:{input:d([bd]),output:_},cancelServerAuth:{input:d([c({flowId:s().min(1)})]),output:_},resetServerAuth:{input:d([fe,z.optional(),Eo().optional()]),output:_},listStoredOAuthCredentials:{input:d([]),output:v(Sd)},revealStoredOAuthCredential:{input:d([ut]),output:fd},revokeStoredOAuthCredential:{input:d([ut]),output:_}},Id=c({severity:h(["error","warn","info"]),message:s()}),Td=c({name:s().optional(),email:s().optional()}),wd=c({skill:s()}),Ed=c({displayName:s().optional(),shortDescription:s().optional(),longDescription:s().optional(),developerName:s().optional(),websiteURL:s().optional()}),kd=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:u().int().min(1).max(600).optional()}),Cd=c({path:s(),name:s()}),Rd=h(["kimi-plugin-root","kimi-plugin-dir","claude-code"]),pt=h(["local-path","zip-url","github"]),Pd=h(["ok","error"]),mt=c({kind:h(["branch","tag","sha"]),value:s()}),Od=c({name:s(),version:s().optional(),description:s().optional(),keywords:v(s()).optional(),author:Td.optional(),homepage:s().optional(),license:s().optional(),icon:s().optional(),skills:v(s()).optional(),agents:v(s()).optional(),sessionStart:wd.optional(),mcpServers:C(s(),Be).optional(),hooks:v(kd).optional(),commands:v(Cd).optional(),interface:Ed.optional(),skillInstructions:s().optional(),systemPrompt:s().optional(),unsupportedComponents:v(s()).optional()}),Ad=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()}),eo=c({owner:s(),repo:s(),ref:mt,installedSha:s().optional()}),je=c({id:s(),displayName:s(),version:s().optional(),icon:s().optional(),enabled:S(),state:Pd,skillCount:u(),mcpServerCount:u(),enabledMcpServerCount:u(),hookCount:u(),commandCount:u(),hasErrors:S(),source:pt,originalSource:s().optional(),github:eo.optional(),zipSha256:s().optional(),rollback:c({version:s().optional(),source:pt,originalSource:s().optional(),github:eo.optional(),zipSha256:s().optional()}).optional()}),Md=je.extend({root:s(),installedAt:s(),updatedAt:s().optional(),manifestKind:Rd.optional(),manifestPath:s().optional(),manifest:Od.optional(),mcpServers:v(Ad),shadowedManifestPath:s().optional(),diagnostics:v(Id)}),Ud=c({added:v(s()),removed:v(s()),errors:v(c({id:s(),message:s()}))}),xd=c({id:s(),source:pt,current:mt.optional(),latest:mt,displayVersion:s(),updateAvailable:S()}),Dd=c({pluginId:s(),name:s(),description:s(),body:s(),path:s()}),Nd=ko.extend({fingerprint:s().optional(),consent:S().optional()}),jd=c({id:s(),enabled:S()}),Ld=c({id:s(),server:s(),enabled:S()}),qd=c({id:s(),deleteData:S().optional()}),Gd=c({id:s()}),$d={listPlugins:{input:d([]),output:v(je)},previewPlugin:{input:d([ko]),output:As},installPlugin:{input:d([Nd]),output:je},rollbackPlugin:{input:d([c({id:s()})]),output:je},setPluginEnabled:{input:d([jd]),output:_},setPluginMcpServerEnabled:{input:d([Ld]),output:_},removePlugin:{input:d([qd]),output:_},reloadPlugins:{input:d([]),output:Ud},getPluginInfo:{input:d([Gd]),output:Md},listPluginCommands:{input:d([]),output:v(Dd)},checkUpdates:{input:d([]),output:v(xd)}},Fd={sources:{input:d([]),output:v(Fs)},discover:{input:d([js]),output:Gs},preview:{input:d([Ns]),output:qs},start:{input:d([Ds]),output:ue},jobs:{input:d([xs.optional()]),output:c({items:v(ue),cursor:s().nullable()})},job:{input:d([s()]),output:ue},cancel:{input:d([s()]),output:ue},resume:{input:d([s()]),output:ue},archives:{input:d([Us.optional()]),output:c({items:v($s),cursor:s().nullable()})},read:{input:d([Ms]),output:Ls}},Bd={sources:{input:d([]),output:v(Gt)},setSources:{input:d([zs]),output:v(Gt)},catalog:{input:d([c({id:s().min(1)}).strict()]),output:Qs},providers:{input:d([]),output:qt},capabilities:{input:d([Ws]),output:$([Hs,c({providers:qt}).strict()])},voices:{input:d([Vs]),output:Ks},jobs:{input:d([Bs.optional()]),output:v(Le)},job:{input:d([s().min(1)]),output:Le}},Vd={cancel:{input:d([s().min(1)]),output:Le},resume:{input:d([s().min(1)]),output:Le}},Hd=c({definition:Ys.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(),Wd=c({memory:c({status:h(["committed","pending","failed"]),error:s().optional()}).strict()}).strict(),zd={list:{input:d([Xs.optional()]),output:v(Zs)},get:{input:d([s()]),output:A(Qe)},put:{input:d([Hd]),output:Qe},duplicate:{input:d([s(),c({id:s().optional(),name:s().optional()}).optional()]),output:Qe},archive:{input:d([s(),S().optional()]),output:Js},delete:{input:d([s(),s().optional()]),output:Wd}},Kd={list:{input:d([]),output:v(Xe)},enable:{input:d([Ye]),output:Xe},ensureHomeSession:{input:d([Ye]),output:Xe},update:{input:d([Ye,ei]),output:mi}},Qd={list:{input:d([]),output:v(V)},listItems:{input:d([]),output:v(hi)},get:{input:d([F]),output:A(V)},create:{input:d([ci]),output:V},createFromThreads:{input:d([ai]),output:V},searchThreads:{input:d([ri.optional()]),output:pi},addMember:{input:d([F,ii]),output:V},removeMember:{input:d([F,si]),output:V},update:{input:d([F,ni]),output:V},delete:{input:d([F]),output:_},postUserMessage:{input:d([F,oi]),output:ui},pause:{input:d([F]),output:V},continue:{input:d([F]),output:V},stop:{input:d([F]),output:V},log:{input:d([F,ti.optional()]),output:li},usage:{input:d([F]),output:di}},Yd=s(),to=C(s(),s()),Xd=h(["static","discover","oauth-catalog"]),Jd=Rt,Zd=c({modelSource:Xd.optional(),baseUrl:s().optional(),customHeaders:to.optional(),defaultModel:s().optional(),requestIdentity:Jd.optional(),type:Yd.optional(),apiKey:s().optional(),oauth:tn.optional(),env:to.optional(),source:C(s(),w()).optional()}),ot=gi((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},Zd),el={get:{input:d([s()]),output:A(ot)},list:{input:d([]),output:C(s(),ot)},set:{input:d([s(),ot]),output:_},delete:{input:d([s()]),output:_}},an=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()}),Mt=c({execution:Ta.optional(),homedir:s().optional(),type:h(["main","sub","independent"]).optional(),parentAgentId:$([s(),se()]).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:an.optional(),allowKikiSubagents:S().optional(),status:h(["completed","failed","cancelled"]).optional(),completedAt:u().optional(),resultSummary:s().optional(),error:s().optional(),usage:Ne.optional(),contextTokens:u().optional(),toolCallCount:u().int().nonnegative().optional()}),cn=c({worktreeId:s(),branch:s(),sourceRoot:s(),baseRef:s()}),tl=c({id:s(),version:u().optional(),title:s().optional(),titleKind:h(["replaceable","generated","custom"]).optional(),lastPrompt:s().optional(),delivery:h(["reply","message"]).optional(),createdAt:u(),updatedAt:u(),activityUpdatedAt:u().optional(),archived:S(),archivedAt:u().optional(),cwd:s().optional(),worktree:cn.optional(),forkedFrom:s().optional(),agents:C(s(),Mt).optional(),custom:C(s(),w()).optional(),sshHosts:C(s(),s()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),ol=c({version:u().optional(),title:s().optional(),titleKind:h(["replaceable","generated","custom"]).optional(),lastPrompt:s().optional(),delivery:h(["reply","message"]).optional(),updatedAt:u().optional(),activityUpdatedAt:u().optional(),archived:S().optional(),archivedAt:u().optional(),cwd:s().optional(),worktree:cn.optional(),forkedFrom:s().optional(),agents:C(s(),Mt).optional(),custom:C(s(),w()).optional(),sshHosts:C(s(),s()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),nl=h(["id","version","title","titleKind","lastPrompt","delivery","createdAt","updatedAt","activityUpdatedAt","archived","archivedAt","cwd","worktree","forkedFrom","agents","custom","sshHosts","lastTurnReason","usage"]),sl=c({changed:v(nl)}),il={read:{input:d([]),output:tl},update:{input:d([ol]),output:_},setTitle:{input:d([s()]),output:_},setArchived:{input:d([S()]),output:_},registerAgent:{input:d([s(),Mt]),output:_}},oo=c({id:s(),workspaceId:s(),cwd:s().optional(),title:s().optional(),lastPrompt:s().optional(),delivery:h(["reply","message"]).optional(),createdAt:u(),updatedAt:u(),archived:S(),archivedAt:u().optional(),custom:C(s(),w()).optional(),lastTurnReason:h(["completed","cancelled","failed"]).optional(),executorId:s().optional(),negotiated:an.optional(),allowKikiSubagents:S().optional()}),rl=c({workspaceIds:v(s()).optional(),sessionId:s().optional(),includeArchived:S().optional(),limit:u().optional(),childOf:s().optional(),before:s().optional(),after:s().optional()}),al=c({workspaceIds:v(s()).optional(),includeArchived:S().optional()}),cl={listRecent:{input:d([rl]),output:Fr(oo)},get:{input:d([s()]),output:A(oo)},count:{input:d([al]),output:u()}},Oe=c({id:s(),root:s(),name:s(),createdAt:u(),lastOpenedAt:u(),pinned:S()}),dl=c({name:s().optional(),pinned:S().optional()}),ll={list:{input:d([]),output:v(Oe)},get:{input:d([s()]),output:A(Oe)},createOrTouch:{input:d([s(),s().optional()]),output:Oe},update:{input:d([s(),dl]),output:A(Oe)},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()}),ul=c({ref:W,title:s().optional(),updatedAt:u().int().nonnegative(),createdAt:u().int().nonnegative(),state:h(["cold","idle","running"])}),pl=c({workspaceId:s().trim().min(1).optional(),cursor:s().min(1).optional(),limit:u().int().min(1).max(100).optional()}),ml=c({threads:v(ul),nextCursor:s().optional()}),hl=c({turnId:u().int().nonnegative(),startedAt:u().int().nonnegative().optional(),endedAt:u().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:u().int().positive(),location:h(["local","network"]),createdAt:u(),expiresAt:u(),sourceSeq:u(),causeId:s(),hop:u(),messageId:s()}).optional(),peer:c({source:W,messageId:s().min(1)}).optional(),input:s(),output:s()}),gl=c({thread:W,contentRef:Co.optional(),cursor:s().min(1).optional(),limit:u().int().min(1).max(100).optional()}),vl=o=>({...o,execution:o.execution===void 0?void 0:{...o.execution,losses:[...o.execution.losses]}}),Sl=Ro.transform(o=>({...o,items:o.items.map(e=>e.kind==="turn"?vl(e):e)})),fl=c({thread:W,turns:v(hl),nextCursor:s().optional(),view:c({transcript:Sl.optional(),segment:Po.optional()}).optional()}),yl=c({target:W,content:s().min(1).max(1e5),idempotencyKey:s().min(1).max(256)}).strict(),bl=c({messageId:s().min(1),targetSeq:u().int().nonnegative(),acceptedAt:u().int().nonnegative(),deduplicated:S(),delivery:h(["pending","delivered","undeliverable"])}),_l=c({ref:W,seq:u().int().nonnegative(),kind:h(["terminal","attention","lifecycle","message_undeliverable"]),at:u().int().nonnegative(),reason:s(),turnId:u().int().nonnegative().optional(),messageId:s().min(1).optional()}),Il=c({thread:W,cursor:s().min(1).optional()}),Tl=c({threads:v(Il).min(1).max(8),timeoutMs:u().int().min(0).max(6e4).optional()}).superRefine((o,e)=>{const t=new Set;o.threads.forEach((n,i)=>{const{hostId:a,workspaceId:r,sessionId:l}=n.thread,m=`${a}\0${r}\0${l}`;t.has(m)&&e.addIssue({code:"custom",path:["threads",i],message:"duplicate thread reference"}),t.add(m)})}),wl=c({thread:W,cursor:s().min(1),activities:v(_l)}),El=c({threads:v(wl),timedOut:S()}),no=c({ref:W,title:s().optional(),deleted:S(),archived:S()}),kl=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:no}),c({kind:y("room"),roomId:s()})]),target:no,content:s(),acceptedAt:u(),targetSeq:u(),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()}),Cl=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:u().int().min(1).max(100).optional()}).strict().refine(o=>o.peerSessionId===void 0||o.sessionId!==void 0),Rl=c({items:v(kl),nextCursor:s().optional(),incomplete:h(["scan_budget","history_preparing"]).optional(),history:c({generation:s(),state:h(["complete","preparing","error"]),processedMessages:u().int().nonnegative(),completedShards:u().int().nonnegative(),totalShards:u().int().positive(),pending:h(["room","all"]).optional(),error:s().optional()}).optional()}),Pl={listMessages:{input:d([Cl.optional()]),output:Rl},hostId:{input:d([]),output:s().min(1)},listThreads:{input:d([pl.optional()]),output:ml},readThread:{input:d([gl]),output:fl},sendMessage:{input:d([yl]),output:bl},waitThreads:{input:d([Tl]),output:El},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()}},Ol=c({busy:S(),mainTurnActive:S(),pendingInteraction:h(["none","approval","question"]),lastTurnReason:h(["completed","cancelled","failed"]).optional()}),Al={state:{input:d([]),output:Ol}},Ml={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:u(),targetSeq:u()}),deduplicated:S(),delivery:h(["queued","delivered"]),payloadConflict:S(),resumed:S().optional()})}},Ul=c({id:s().optional(),sessionId:s().optional(),agentId:s().optional(),turnId:u().optional(),toolCallId:s().optional(),toolName:s(),action:s(),display:w(),approvalRule:s().optional()}),xl=c({decision:h(["approved","rejected","cancelled"]),scope:y("session").optional(),feedback:s().optional(),selectedLabel:s().optional(),selectedOptionId:s().optional()}),Dl={listPending:{input:d([]),output:v(Ul)},decide:{input:d([s(),xl]),output:_}},dn=h(["approval","question","user_tool"]),Nl=c({agentId:s().optional(),turnId:u().optional()}),ln=c({id:s(),kind:dn,payload:w(),origin:Nl,createdAt:u()}),jl=c({id:s(),response:w()}),Ll={listPending:{input:d([dn.optional()]),output:v(ln)},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()}},ql=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:u().nonnegative().finite().optional(),mainAgentBinding:c({execution:Bo.optional(),persona:s().optional(),profile:s().optional(),model:s().optional(),thinking:s().optional()}).optional(),mcpServers:C(s(),Be).optional()}),so=c({additionalDirs:v(s()).optional(),waitForSessionMs:u().nonnegative().finite().optional(),mcpServers:C(s(),Be).optional()}),un=c({sourceSessionId:s(),newSessionId:s().optional(),title:s().optional(),metadata:C(s(),w()).optional(),turnIndex:u().optional()}),Gl=un.omit({turnIndex:!0}),he=Ie({id:s(),kind:s()}),$l={countPendingBackgroundTasks:{input:d([]),output:u()},drainBackgroundTasks:{input:d([u().positive().finite()]),output:_}},Fl={create:{input:d([ql]),output:he},resume:{input:d([s(),so.optional()]),output:A(he)},close:{input:d([s()]),output:_},archive:{input:d([s()]),output:_},restore:{input:d([s(),so.optional()]),output:A(he)},delete:{input:d([s()]),output:_},fork:{input:d([un]),output:he},createChild:{input:d([Gl]),output:he}},Bl=c({label:s(),description:s().optional()}),Vl=c({question:s(),header:s().optional(),body:s().optional(),options:v(Bl),multiSelect:S().optional(),otherLabel:s().optional(),otherDescription:s().optional()}),pn=C(s(),$([s(),y(!0)])),Hl=c({answers:pn,method:h(["enter","space","number_key"]).optional()}),Wl=$([se(),pn,Hl]),zl=c({id:s().optional(),turnId:u().optional(),toolCallId:s().optional(),questions:v(Vl)}),Kl={listPending:{input:d([]),output:v(zl)},answer:{input:d([s(),Wl]),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()}),Yl={list:{input:d([]),output:v(Ql)}},Xl={generateTitle:{input:d([c({force:S().optional(),source:h(["user_prompts","first_turn","digest"]).optional()}).optional()]),output:A(s())}},Jl={start:{input:d([]),output:s()}},Zl=c({id:s(),cron:s(),prompt:s(),createdAt:u(),recurring:S().optional(),paused:S().optional(),lastFiredAt:u().optional(),tags:C(s(),s()).optional()}),eu={list:{input:d([]),output:v(Zl)},getNextFireTime:{input:d([]),output:u().nullable()},getNextFireForTask:{input:d([s()]),output:u().nullable()}},tu={generateAgentsMd:{input:d([]),output:_},cancelInit:{input:d([]),output:_}},ou=c({title:s(),status:h(["pending","in_progress","done"])}),nu={getTodos:{input:d([s().optional()]),output:v(ou)}};function io(o){return"streaming"in o&&o.streaming===!0}const ro={agentGoalService:Wa,agentLifecycleService:$l,sessionCronService:eu,sessionBtwService:Jl,sessionInitService:tu,sessionTodoService:nu,taskBoardService:Pr,agentPanelService:Or,sessionIndex:cl,workspaceService:ll,configService:Bc,providerService:el,modelService:id,modelResolver:Dc,modelCatalogMutation:ad,providerDiscovery:jc,oauthService:Tc,authSummaryService:wc,flagService:Qc,pluginService:$d,pluginImportService:Fd,pluginMediaService:Bd,agentPluginMediaService:Vd,personaStore:zd,botService:Kd,roomService:Qd,capabilityService:Cc,hostFolderBrowser:Zc,bootstrapService:Hc,threadCommunicationService:Pl,fileService:Kc,mcpManagementService:_d,sessionManager:Fl,sessionMetadata:il,agentCollaborationMessagingService:Ml,sessionActivityView:Al,sessionInteractionService:Ll,sessionApprovalService:Dl,sessionQuestionService:Kl,sessionSkillCatalog:Yl,sessionTitleService:Xl,agentPromptService:za,agentSkillService:Ka,agentLoopService:ec,agentContextInjectorService:Qa,agentContextMemoryService:sc,agentContextMutationService:ic,agentContextRebuildService:Ya,agentConversationUndoService:Xa,agentPluginCommandService:Ja,agentPluginService:Za,agentPermissionModeService:tc,agentCommandService:oc,agentRuntimeBindingService:nc,agentTokenCountingService:rc,agentActivityView:$r,agentShellCommandService:ac,agentProfileService:cc,agentUsageService:dc,agentPlanService:lc,agentTaskService:gc,agentMcpService:pc,agentFullCompactionService:hc},ao=c({domain:s(),source:h(["load","reload","set"]),value:w(),previousValue:w()}),su=c({added:v(s()),removed:v(s()),errors:v(c({id:s(),message:s()}))}),iu=c({agentId:s(),sessionId:s(),title:s().optional(),patch:c({title:s().optional(),isCustomTitle:S().optional(),lastPrompt:s().optional()})}),ru=c({changed:v(c({provider_id:s(),provider_name:s(),added:u(),removed:u()})),unchanged:v(s()),failed:v(c({provider:s(),reason:s()}))}),au=c({state:h(["building","ready","readonly","unavailable"]),indexed_sessions:u(),total_sessions:u(),documents:u(),stale:S().optional(),degraded:s().optional(),reason:h(["disabled","indexer_backoff","memory_budget","wal_stuck","disk_low","corrupt_rebuilding","sqlite_unavailable","runtime_disabled"]).optional()}),ge={installId:s().min(1),version:s().min(1)},cu=M("stage",[c({...ge,stage:y("download"),receivedBytes:u().nonnegative(),totalBytes:u().positive().optional()}),c({...ge,stage:y("extract")}),c({...ge,stage:y("activate")}),c({...ge,stage:y("done")}),c({...ge,stage:y("failed"),error:s(),timedOut:S()})]),du={"usage.settled":{kind:"bus",type:"event.usage.settled",schema:c({sessionId:s().optional(),agentId:s().optional()})},"room.changed":{kind:"emitter",service:"roomService",event:"onDidChange",schema:vi},"search.indexStateChanged":{kind:"bus",type:"event.search.index_state_changed",schema:au},"executors.antigravityInstallProgress":{kind:"bus",type:"event.executor.antigravity_install_progress",schema:cu},"config.changed":{kind:"emitter",service:"configService",event:"onDidChangeConfiguration",schema:ao},"config.sectionChanged":{kind:"emitter",service:"configService",event:"onDidSectionChange",schema:ao},"kosong.providers.changed":{kind:"emitter",service:"providerService",event:"onDidChangeProviders",schema:Yt},"kosong.models.changed":{kind:"emitter",service:"modelService",event:"onDidChangeModels",schema:Yt},"plugins.reloaded":{kind:"emitter",service:"pluginService",event:"onDidReload",schema:su},"session.archived":{kind:"bus",type:"event.session.archived",schema:c({sessionId:s()})},"session.metaUpdated":{kind:"bus",type:"session.meta.updated",schema:iu},"kosong.changed":{kind:"bus",type:"event.model_catalog.changed",schema:ru}},lu={"metadata.changed":{kind:"emitter",service:"sessionMetadata",event:"onDidChangeMetadata",schema:sl},"skills.changed":{kind:"emitter",service:"sessionSkillCatalog",event:"onDidChange",schema:s()},"interactions.changed":{kind:"stream",name:"interactions",schema:v(ln)},"interactions.resolved":{kind:"stream",name:"interactions:resolved",schema:jl}};class le extends Error{constructor(e,t,n,i){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=i,this.name="KlientValidationError"}}function co(o,e,t){const n=e.input.safeParse(t);if(!n.success)throw new le("input",o,n.error.issues,t);return n.data}function uu(o,e,t){const n=e.output.safeParse(t);if(!n.success)throw new le("output",o,n.error.issues,t);return n.data}function pu(o,e,t){const n=e.chunk.safeParse(t);if(!n.success)throw new le("chunk",o,n.error.issues,t);return n.data}function mu(o,e,t){const n=e.safeParse(t);return n.success?{ok:!0,data:n.data}:{ok:!1,error:new le("event",o,n.error.issues,t)}}function Ae(o){switch(o.kind){case"bus":return"bus";case"stream":return`stream:${o.name}`;case"emitter":return`emitter:${o.service}:${o.event}`}}function lo(o){if(typeof o!="object"||o===null)return;const e=o.type;return typeof e=="string"?e:void 0}class hu{constructor(e,t,n,i){this.channel=e,this.validate=t,this.scope=n,this.registrations=i}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 i=t;n.add(i);let a,r;const m={promise:new Promise((f,b)=>{a=f,r=b}),resolve:a,reject:r};m.promise.catch(()=>{});let p;try{p=this.acquire(e,m)}catch(f){throw n.delete(i),n.size===0&&this.listeners.delete(e),f}let 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(i),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(Ae(I),I)}const i=new Set,a=[];let r=!1,l=0,m=!1,p;const g={dispose:()=>{if(!r){r=!0,l+=1,p?.abort();for(const b of a)b.dispose();this.observations.delete(g)}}},f=()=>{l+=1,p?.abort(),!(r||m||i.size!==n.size)&&(m=!0,queueMicrotask(()=>{if(m=!1,r||i.size!==n.size)return;const b=l;p=new AbortController;const I=p.signal;Promise.resolve().then(()=>{if(!(r||b!==l))return e.read(I)}).then(k=>{if(!(r||b!==l))try{t(k)}catch(R){this.reportError(R instanceof Error?R:new Error(String(R)))}},k=>{r||b!==l||(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=>{r||(i.delete(b),f(),this.reportError(R))},()=>{r||(i.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],i=Ae(n);let a=this.subs.get(i);if(a===void 0){a={reg:n,disposable:{dispose(){}},refs:0,attached:!1,waiters:new Set([t])},this.subs.set(i,a);try{a.disposable=this.subscribe(i,a)}catch(r){throw this.subs.delete(i),r}}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=Ae(t),i=this.subs.get(n);i!==void 0&&(i.refs-=1,i.refs<=0&&(i.disposable.dispose(),this.subs.delete(n)))}subscribe(e,t){const n=t.reg,i=n.kind==="emitter"?{kind:"emitter",service:n.service,event:n.event}:{kind:"stream",name:n.kind==="bus"?"events":n.name};return this.channel.listen(this.scope,i,a=>{this.deliver(e,a)},a=>{t.attached=!1;for(const r of t.waiters)r.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,i]of Object.entries(this.registrations))if(!(Ae(i)!==e||!this.listeners.has(n))){if(i.kind==="bus"){if(lo(t)!==i.type)continue;this.deliverValidated(n,i,t.payload);continue}if(i.kind==="stream"&&i.type!==void 0){if(lo(t)!==i.type)continue;this.deliverValidated(n,i,t);continue}this.deliverValidated(n,i,t)}}deliverValidated(e,t,n){let i=n;if(this.validate){const r=mu(e,t.schema,n);if(!r.ok){this.reportError(r.error);return}i=r.data}const a=this.listeners.get(e);if(a!==void 0)for(const r of a)try{r(i)}catch(l){this.reportError(l instanceof Error?l:new Error(String(l)))}}reportError(e){for(const t of this.errorListeners)try{t(e)}catch{}}}function gu(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 vu(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 Su(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 fu(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 yu(o){return{cancel:e=>o("agentPluginMediaService","cancel",[e]),resume:e=>o("agentPluginMediaService","resume",[e])}}const uo=32768;function bu(o){let e="";for(let t=0;t<o.length;t+=uo)e+=String.fromCodePoint(...o.subarray(t,t+uo));return btoa(e)}function _u(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 Iu(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 Tu=7e4,po=["platform","arch","cwd","osHomeDir","homeDir","configPath","sessionsDir","blobsDir","storeDir","cacheDir","logsDir"],wu=15*6e4,Eu=3e4;function ku(o,e){const t=(r,l,m,p)=>o({},r,l,m,p),n=(r,l,m)=>e({},r,l,m);let i;const a=()=>(i??=Promise.all([...po.map(r=>t("bootstrapService",r,[])),t("bootstrapService","clientIdentity",[])]).then(r=>{const l=Object.fromEntries(po.map((p,g)=>[p,r[g]])),m=r[r.length-1];return{...l,clientVersion:m.version}}),i);return{board:{read:(r,l)=>t("taskBoardService","read",[r],l),write:r=>t("taskBoardService","write",[r]),overview:r=>t("taskBoardService","overview",[],r)},agentPanel:{read:(r,l)=>t("agentPanelService","read",[r],l)},sessions:{list:r=>t("sessionIndex","listRecent",[r]),get:r=>t("sessionIndex","get",[r]),countActive:r=>t("sessionIndex","count",[{workspaceIds:r}]),create:async({sessionId:r,workDir:l,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},j={sessionId:(await o({},"sessionManager","create",[{sessionId:r,workDir:l,ephemeral:m,delivery:I,additionalDirs:p,waitForSessionMs:g,mcpServers:k,mainAgentBinding:D}])).id};return f!==void 0&&await o(j,"sessionMetadata","setTitle",[f]),o(j,"sessionMetadata","read",[])}},bots:gu(t),rooms:vu(t),personas:{list:r=>t("personaStore","list",r===void 0?[]:[r]),get:r=>t("personaStore","get",[r]),put:r=>t("personaStore","put",[{...r.definition,examples:r.examples,expectedRevision:r.revision}]),duplicate:(r,l)=>t("personaStore","duplicate",l===void 0?[r]:[r,l]),archive:(r,l)=>t("personaStore","archive",l===void 0?[r]:[r,l]),delete:async(r,l)=>{const m=await t("personaStore","delete",l?.expectedRevision===void 0?[r]:[r,l.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:Iu},workspaces:{list:()=>t("workspaceService","list",[]),get:r=>t("workspaceService","get",[r]),createOrTouch:({root:r,name:l})=>t("workspaceService","createOrTouch",[r,l]),update:({id:r,patch:l})=>t("workspaceService","update",[r,l]),delete:r=>t("workspaceService","delete",[r])},config:{get:r=>t("configService","get",[r]),getAll:()=>t("configService","getAll",[]),inspect:r=>t("configService","inspect",[r]),set:({domain:r,patch:l,target:m})=>t("configService","set",[r,l,m]),replace:({domain:r,value:l,target:m})=>t("configService","replace",[r,l===void 0?null:l,m]),replaceSections:({sections:r,target:l})=>t("configService","replaceSections",[Object.fromEntries(Object.entries(r).map(([m,p])=>[m,p===void 0?null:p])),l]),reload:()=>t("configService","reload",[]),diagnostics:()=>t("configService","diagnostics",[])},kosong:{listProviders:()=>t("modelResolver","listProviders",[]),getProvider:r=>t("modelResolver","getProvider",[r]),addProvider:((r,l)=>{if(typeof r=="string"){const f=l;Cu(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",[r,b])}const m=r,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 r=>await t("providerService","get",[r])!==void 0?t("providerService","delete",[r]):t("modelService","delete",[r]),refreshProviders:r=>t("providerDiscovery","refreshProviderModels",[r]),listDiscoveredModels:()=>t("providerDiscovery","listDiscoveredModels",[]),listModels:()=>t("modelResolver","listModels",[]),setDefaultModel:r=>t("modelResolver","setDefaultModel",[r]),readModel:r=>t("modelCatalogMutation","readModel",[r]),createModel:r=>t("modelCatalogMutation","createModel",[r]),updateModel:(r,l)=>t("modelCatalogMutation","updateModel",[r,l]),deleteModel:(r,l)=>t("modelCatalogMutation","deleteModel",[r,l]),readProviderEntity:r=>t("modelCatalogMutation","readProvider",[r]),createProvider:r=>t("modelCatalogMutation","createProvider",[r]),updateProvider:(r,l)=>t("modelCatalogMutation","updateProvider",[r,l]),deleteProviderEntity:r=>t("modelCatalogMutation","deleteProvider",[r]),generate:(r,l,m)=>n("modelResolver","generate",[r,l,m])},auth:{probeOriginal:r=>t("oauthService","probeOriginal",[r]),connectOriginal:r=>t("oauthService","connectOriginal",[r]),status:r=>t("oauthService","status",[r]),summarize:()=>t("authSummaryService","summarize",[]),ensureReady:r=>t("authSummaryService","ensureReady",[r]),startLogin:(r,l)=>t("oauthService","startLogin",[r,l]),flow:r=>t("oauthService","getFlow",[r]),cancelLogin:r=>t("oauthService","cancelLogin",[r]),logout:r=>t("oauthService","logout",[r]),methods:()=>t("oauthService","listMethods",[])},flags:{list:()=>t("flagService","explainAll",[]),enabled:r=>t("flagService","enabled",[r]),enabledIds:()=>t("flagService","enabledIds",[]),explain:r=>t("flagService","explain",[r]),snapshot:()=>t("flagService","snapshot",[])},imports:Su(t),media:fu(t),plugins:{list:()=>t("pluginService","listPlugins",[]),info:r=>t("pluginService","getPluginInfo",[{id:r}]),preview:r=>t("pluginService","previewPlugin",[r]),install:async r=>{if(typeof r!="string")return t("pluginService","installPlugin",[r]);const l=await t("pluginService","previewPlugin",[{source:r}]);if(l.consentRequired)throw new Error(`Plugin ${l.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:r,fingerprint:l.fingerprint,consent:!1}])},setEnabled:r=>t("pluginService","setPluginEnabled",[r]),setMcpServerEnabled:r=>t("pluginService","setPluginMcpServerEnabled",[r]),remove:r=>t("pluginService","removePlugin",[{id:r}]),reload:()=>t("pluginService","reloadPlugins",[]),checkUpdates:()=>t("pluginService","checkUpdates",[]),listCommands:()=>t("pluginService","listPluginCommands",[])},capabilities:{list:()=>t("capabilityService","listCapabilities",[]),get:r=>t("capabilityService","getCapability",[r]),install:(r,l,m)=>t("capabilityService","installCapability",m!==void 0?[r,l,m]:l===void 0?[r]:[r,l]),cancel:r=>t("capabilityService","cancelCapability",[r])},hostFs:{browse:r=>t("hostFolderBrowser","browse",[r]),home:()=>t("hostFolderBrowser","home",[])},threads:{messages:r=>t("threadCommunicationService","listMessages",[r]),hostId:()=>t("threadCommunicationService","hostId",[]),list:r=>t("threadCommunicationService","listThreads",[r]),read:r=>t("threadCommunicationService","readThread",[r]),send:r=>t("threadCommunicationService","sendMessage",[r]),wait:r=>t("threadCommunicationService","waitThreads",[r],{timeoutMs:Tu}),getWorkspaceOverride:r=>t("threadCommunicationService","getWorkspaceOverride",[r]),setWorkspaceOverride:(r,l)=>t("threadCommunicationService","setWorkspaceOverride",[r,l]),clearWorkspaceOverride:r=>t("threadCommunicationService","clearWorkspaceOverride",[r]),isWorkspaceEnabled:r=>t("threadCommunicationService","isWorkspaceEnabled",[r])},files:{save:({data:r,filename:l,name:m,mimeType:p,expiresInSec:g},f)=>t("fileService","save",[bu(r),l,{name:m,mimeType:p,expiresInSec:g}],f),get:async r=>{const l=await t("fileService","get",[r]);return{meta:l.meta,data:_u(l.data)}},delete:r=>t("fileService","delete",[r])},mcp:{list:r=>t("mcpManagementService","listServers",[r===void 0?void 0:{cwd:r.cwd}]),get:({name:r,cwd:l})=>t("mcpManagementService","getServer",[r,l===void 0?void 0:{cwd:l}]),add:({server:r,cwd:l})=>t("mcpManagementService","addServer",[r,l===void 0?void 0:{cwd:l}]),update:({server:r,cwd:l})=>t("mcpManagementService","updateServer",[r,l===void 0?void 0:{cwd:l}]),remove:({name:r,cwd:l})=>t("mcpManagementService","removeServer",[r,l===void 0?void 0:{cwd:l}]),test:r=>t("mcpManagementService","testServer",[r]),stop:r=>t("mcpManagementService","stopServer",[r]),inspect:r=>t("mcpManagementService","inspectServers",[r?.targets,r===void 0?void 0:{cwd:r.cwd}]),authStatuses:r=>t("mcpManagementService","listAuthStatuses",[r===void 0?void 0:{cwd:r.cwd,verify:r.verify}]),resolveByName:({name:r,cwd:l})=>t("mcpManagementService","resolveServerByName",[r,{cwd:l}]),beginAuth:({locator:r,cwd:l})=>t("mcpManagementService","beginServerAuth",[r,{cwd:l}]),completeAuth:({flowId:r,timeoutMs:l},m)=>t("mcpManagementService","completeServerAuth",[{flowId:r,timeoutMs:l}],{signal:m?.signal,timeoutMs:Math.min((l??wu)+Eu,2**31-1)}),cancelAuth:({flowId:r})=>t("mcpManagementService","cancelServerAuth",[{flowId:r}]),resetAuth:({locator:r,cwd:l,expectedCanonicalUrl:m})=>t("mcpManagementService","resetServerAuth",m===void 0?[r,{cwd:l}]:[r,{cwd:l},m]),listStoredOAuthCredentials:()=>t("mcpManagementService","listStoredOAuthCredentials",[]),revealStoredOAuthCredential:r=>t("mcpManagementService","revealStoredOAuthCredential",[r]),revokeStoredOAuthCredential:r=>t("mcpManagementService","revokeStoredOAuthCredential",[r])},env:a}}function Cu(o){const e=o;for(const t of["requestAttribution","requestOriginator"])if(t in e)throw new TypeError(`${t} was removed; use requestIdentity`)}function Ru(o,e){const t={sessionId:e},n=()=>o(t,"sessionMetadata","read",[]),i=async(a,r={})=>{const l=await o({},"sessionManager",a,[{...r,sourceSessionId:e}]);return o({sessionId:l.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 r=await o({},"sessionManager","resume",a===void 0?[e]:[e,a],{timeoutMs:0});return r!=null},restore:async a=>{const r=await o({},"sessionManager","restore",[e,a]);return r!=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=>i("fork",a),createChild:a=>i("createChild",a),approvals:{list:()=>o(t,"sessionApprovalService","listPending",[]),decide:(a,r)=>o(t,"sessionApprovalService","decide",[a,r])},questions:{list:()=>o(t,"sessionQuestionService","listPending",[]),answer:(a,r)=>o(t,"sessionQuestionService","answer",[a,r]),dismiss:a=>o(t,"sessionQuestionService","dismiss",[a])},interactions:{list:a=>o(t,"sessionInteractionService","listPending",[a]),respond:(a,r)=>o(t,"sessionInteractionService","respond",[a,r]),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 Pu=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:u().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=>$e(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),Ou=c({agentId:s().min(1),since:Oo,grade:h(["turn","block","delta"]).optional()}).refine(o=>$e(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),Au=c({agentId:s().min(1),kind:h(["task","attachment","prompt","tool"]),id:s().min(1)}).refine(o=>$e(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),Mu=c({agentId:s().min(1),ref:Co,range:S().optional()}).refine(o=>$e(o.agentId),{message:"agentId must be a plain agent id",path:["agentId"]}),Uu=Po,xu=c({sessionCursor:Te,transcriptGrades:Si,transcriptSince:C(s(),Oo).optional()}),ie=u().int().nonnegative(),Du=c({type:y("status"),status:h(["connecting","open","closed"]),generation:ie,detail:s().optional()}),Nu=c({type:y("ready"),currentSessionCursor:Te,reconnected:S(),generation:ie}),ju=c({type:y("sessionCursorAdvanced"),cursor:Te,generation:ie,rosterAgentId:s().min(1).optional(),title:s().optional()}),Lu=c({type:y("historyRewritten"),reason:h(["edit_resend","regenerate"]),targetMessageId:s().min(1),cursor:Te,generation:ie}),qu=c({type:y("transcript"),event:fi,generation:ie}),Gu=c({type:y("resyncRequired"),reason:yi,currentSessionCursor:Te,generation:ie}),$u=c({type:y("protocolError"),detail:s(),recoverable:S(),generation:ie}),Fu=M("type",[$u,Du,Nu,ju,Lu,qu,Gu]),Bu=Ii,Vu=Ro,Hu=_i,Wu=bi;function zu(o,e,t){let n=0,i=0;const a=()=>{if(o===void 0)throw new Error("session view is unavailable on this transport");return o},r=(l,m,p,g)=>{const f=p.safeParse(g);if(!f.success)throw new le(l,m,f.error.issues,g);return f.data};return{async snapshot(l){const m=await a().snapshot(e,l);return t?r("output","session.view.snapshot",Bu,m):m},transcript:{async page(l,m){const p=t?r("input","session.view.transcript.page",Pu,l):l,g=await a().transcriptPage(e,p,m);return t?r("output","session.view.transcript.page",Vu,g):g},async catchUp(l,m){const p=t?r("input","session.view.transcript.catchUp",Ou,l):l,g=await a().transcriptCatchUp(e,p,m);return t?r("output","session.view.transcript.catchUp",Hu,g):g},...o?.transcriptEntities===void 0?{}:{async entities(l,m){const p=r("input","session.view.transcript.entities",Ti,{agent_id:l.agentId,kind:l.kind,cursor:l.cursor,limit:l.limit}),g=await a().transcriptEntities(e,{agentId:p.agent_id,kind:p.kind,cursor:p.cursor,limit:p.limit},m);return r("output","session.view.transcript.entities",wi,g)}},...o?.transcriptContent===void 0?{}:{async content(l,m){const p=r("input","session.view.transcript.content",Mu,l),g=await a().transcriptContent(e,p,m);return r("output","session.view.transcript.content",Uu,g)}},...o?.transcriptDetail===void 0?{}:{async detail(l,m){const p=t?r("input","session.view.transcript.detail",Au,l):l,g=await a().transcriptDetail(e,p,m);return t?r("output","session.view.transcript.detail",Wu,g):g}}},subscribe(l,m){const p=t?r("input","session.view.subscribe",xu,l):l;return a().subscribe(e,p,g=>{if(!t){m(g);return}const f=Fu.safeParse(g);if(!f.success){n+=1,m({type:"protocolError",generation:i,recoverable:n===1,detail:"Invalid session view signal; the transcript must be refreshed."});return}i=Math.max(i,f.data.generation),f.data.type==="transcript"&&f.data.event.type==="transcript.reset"&&(n=0),m(f.data)})}}}const He=s().min(1),mo=o=>c({body:o}),ho=c({target:He}),Y=o=>c({target:He,body:o}),go=c({target:He,query:c({agent_id:s().min(1).optional()}).optional()}),mn={read:{method:"GET",suffix:"",input:c({}),output:$t,okCodes:[0]},submit:{method:"POST",suffix:"/prompts",input:mo(Hi),output:Di,okCodes:[0],timeoutMs:0},edit:{method:"POST",suffix:"/messages/{target}:edit",input:Y(Uo),output:Ft,okCodes:[0]},regenerate:{method:"POST",suffix:"/messages/{target}:regenerate",input:Y(Mo),output:Ft,okCodes:[0]},fork:{method:"POST",suffix:":fork",input:mo(Ao),output:$t,okCodes:[0]},abort:{method:"POST",suffix:"/prompts/{target}:abort",input:go,output:xi,okCodes:[0,40903]},abortTurn:{method:"POST",suffix:"/turns/{target}:abort",input:ho,output:Ui,okCodes:[0]},move:{method:"POST",suffix:"/prompts/{target}:move",input:Y(Vi),output:Mi,okCodes:[0]},replace:{method:"POST",suffix:"/prompts/{target}:replace",input:Y(Bi),output:Ai,okCodes:[0]},timing:{method:"POST",suffix:"/prompts/{target}:timing",input:Y(Fi),output:Oi,okCodes:[0]},hold:{method:"POST",suffix:"/prompts/{target}:hold",input:Y($i),output:Pi,okCodes:[0]},steer:{method:"POST",suffix:"/prompts/{target}:steer",input:go,output:Ri,okCodes:[0]},approve:{method:"POST",suffix:"/approvals/{target}",input:Y(Gi),output:Ci,okCodes:[0]},answer:{method:"POST",suffix:"/questions/{target}",input:Y(qi),output:ki,okCodes:[0]},dismiss:{method:"POST",suffix:"/questions/{target}:dismiss",input:ho,output:Ei,okCodes:[0,40909]},cancelTask:{method:"POST",suffix:"/tasks/{target}:cancel",input:c({target:He,query:Li.optional()}),output:$([Ni,ji]),okCodes:[0,40904]}};function vo(o,e){return e===void 0||e==="main"?{target:o}:{target:o,query:{agent_id:e}}}function Ku(o,e,t){const n=(a,r,l,m)=>{const p=l.safeParse(m);if(!p.success)throw new le(a,r,p.error.issues,m);return p.data},i=async(a,r)=>{if(o===void 0)throw new Error("session commands are unavailable on this transport");const l=mn[a],m=`session.commands.${a}`,p=t?n("input",m,l.input,r):r,g=await o.execute(e,a,p);return t?n("output",m,l.output,g):g};return{read:()=>i("read",{}),submit:a=>i("submit",{body:a}),edit:(a,r)=>i("edit",{target:a,body:r}),regenerate:(a,r)=>i("regenerate",{target:a,body:r}),fork:(a={})=>i("fork",{body:a}),abort:(a,r)=>i("abort",vo(a,r)),abortTurn:a=>i("abortTurn",{target:String(a)}),move:(a,r)=>i("move",{target:a,body:r}),replace:(a,r)=>i("replace",{target:a,body:r}),timing:(a,r)=>i("timing",{target:a,body:r}),hold:(a,r)=>i("hold",{target:a,body:r}),steer:(a,r)=>i("steer",vo(a,r)),approve:(a,r)=>i("approve",{target:a,body:r}),answer:(a,r)=>i("answer",{target:a,body:r}),dismiss:a=>i("dismiss",{target:a}),cancelTask:(a,r={})=>i("cancelTask",{target:a,query:r})}}function Qu(o,e){function t(n,i){return o(e,"agentPromptService",i?.waitFor==="terminal"?"submitAndWait":"submit",[n],i===void 0?void 0:{timeoutMs:0,signal:i.signal})}return{media:yu((n,i,a,r)=>o(e,n,i,a,r)),switchModel:n=>o(e,"agentPromptService","switchModel",[n]),getModelSwitch:n=>o(e,"agentPromptService","getModelSwitch",[n]),listModelSwitches:n=>o(e,"agentPromptService","listModelSwitches",[],n),updateModelSwitch:(n,i)=>o(e,"agentPromptService","updateModelSwitch",i===void 0?[n]:[n,i]),cancelModelSwitch:n=>o(e,"agentPromptService","cancelModelSwitch",[n]),recoverModelSwitch:(n,i,a)=>o(e,"agentPromptService","recoverModelSwitch",a===void 0?[n,i]:[n,i,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,i)=>o(e,"agentPermissionModeService",i?.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,i]=await Promise.all([o(e,"agentContextMemoryService","get",[]),o(e,"agentTokenCountingService","statusSize",[])]);return{history:n,tokenCount:i}},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 Yu(o,e={}){const t=e.validate??!0,n=async(l,m,p,g,f)=>{const b=ro[m]?.[p];if(b===void 0)throw new Error(`no contract registered for ${m}.${p}`);if(io(b))throw new Error(`${m}.${p} is a streaming procedure — use callStream instead`);const I=`${m}.${p}`,k=t?co(I,b,g):g,R=await o.call(l,m,p,k,f);return t?uu(I,b,R):R},i=(l,m,p,g)=>{const f=ro[m]?.[p];if(f===void 0)throw new Error(`no contract registered for ${m}.${p}`);if(!io(f))throw new Error(`${m}.${p} is not a streaming procedure — use call instead`);const b=`${m}.${p}`,I=t?co(b,f,g):g,k=o.stream(l,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:pu(b,R,U.value)}},async return(U){return await D.return?.(U),{done:!0,value:void 0}}}}}},a=new Set,r=(l,m)=>{const p=new hu(o,t,l,m);return a.add(p),p};return{rest:o.rest,terminal:yr(o.terminal),global:ku(n,i),events:r({},du),session(l){const m={sessionId:l};return{...Ru(n,l),events:r(m,lu),view:zu(o.sessionView,l,t),commands:Ku(o.sessionCommands,l,t),agent(p){const g={sessionId:l,agentId:p};return{...Qu(n,g),events:r(g,Ia)}}}},close:()=>{for(const l of a)l.close();return a.clear(),o.close()}}}const Ut={kind:"unknown",hasMoreOlder:!0};function Xu(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:Ut,snapshot:gn(t.snapshot)}};if(n==="transcript.ops"){const i=t.ops;return Array.isArray(i)?{...o,event:{...t,ops:i.map(hn)}}:o}return o}function Ju(o){return o===null||typeof o!="object"?o:{...o,coverage:Ut,tool_call_count:void 0}}function Zu(o){if(o===null||typeof o!="object")return o;const e=o.batches;return Array.isArray(e)?{...o,batches:e.map(ep)}:o}function ep(o){if(o===null||typeof o!="object")return o;const e=o.ops;return Array.isArray(e)?{...o,ops:e.map(hn)}:o}function hn(o){if(o===null||typeof o!="object")return o;const e=o;return e.op==="reset"?{...e,coverage:Ut,snapshot:gn(e.snapshot)}:e.op==="tool.count.set"?{...e,count:void 0}:o}function gn(o){return o===null||typeof o!="object"?o:{...o,toolCallCount:void 0,toolCallCountKnown:!1}}class tp{constructor(e){this.host=e}views=new Map;generation=0;get hasDemand(){return this.views.size>0}subscribe(e,t,n){const i=this.host.nextId(),a={id:i,sessionId:e,input:t,handler:n,attachCount:0};this.views.set(i,a);try{n({type:"status",status:"connecting",generation:this.generation}),this.host.connect(),this.host.isOpen()&&this.attach(a)}catch(r){throw this.views.delete(i),r}return{updateSessionCursor:r=>{a.input={...a.input,sessionCursor:r}},setTranscriptGrades:r=>{if(!this.views.has(i))return;const l=a.input.transcriptSince===void 0?void 0:Object.fromEntries(Object.entries(a.input.transcriptSince).filter(([m])=>zt[Kt(r,m)]<=zt[Kt(a.input.transcriptGrades,m)]));a.input={...a.input,transcriptGrades:r,transcriptSince:l},this.host.isOpen()&&this.attach(a)},updateTranscriptCursor:(r,l)=>{a.input={...a.input,transcriptSince:{...a.input.transcriptSince,[r]:l}}},restart:()=>{this.views.has(i)&&this.host.restart()},nudge:()=>{this.views.has(i)&&this.host.nudge()},close:()=>{this.views.delete(i)&&(this.host.isOpen()&&this.host.send({type:"view_detach",id:i}),n({type:"status",status:"closed",generation:this.generation}))}}}opened(){this.generation+=1;for(const e of this.views.values())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,i=n!==null&&typeof n=="object"?n.generation:void 0;if(typeof i=="number"&&i!==this.generation)return!0;const a=xo(n)?n:Xu(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:Do}}),e.attachCount+=1}}const Me=(o,e)=>JSON.stringify([o,e]);class op{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=Me(e,t);let i=this.tracked.get(n);return i===void 0&&(i={sessionId:e,terminalId:t,lastSeq:0},this.tracked.set(n,i)),this.socket.connect(),this.socket.isOpen()?this.attach(i):Promise.reject(new Error("socket is not connected"))};terminalDetach=(e,t)=>{this.tracked.delete(Me(e,t));for(const[n,i]of this.pending)i.sessionId!==e||i.terminalId!==t||(this.pending.delete(n),clearTimeout(i.timer),i.reject(new Error("terminal detached before the attach ack arrived")));this.send("terminal_detach",{session_id:e,terminal_id:t})};terminalInput=(e,t,n)=>{this.send("terminal_input",{session_id:e,terminal_id:t,data:n})};terminalResize=(e,t,n,i)=>{this.send("terminal_resize",{session_id:e,terminal_id:t,cols:n,rows:i})};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,i)=>{const a=setTimeout(()=>{this.pending.delete(t),i(new Error("terminal attach timed out — the server does not answer terminal frames"))},8e3);this.pending.set(t,{...e,resolve:n,reject:i,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(Me(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 l=this.pending.get(e.id??"");if(l===void 0)return!0;if(this.pending.delete(e.id),clearTimeout(l.timer),e.code!==0)return l.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 l.resolve(p),this.emit({kind:"attached",sessionId:l.sessionId,terminalId:l.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,i=t.terminal_id,a=Me(n,i),r=this.tracked.get(a);return r===void 0||(e.type==="terminal_output"&&typeof t.seq=="number"&&Number.isSafeInteger(t.seq)&&t.seq>r.lastSeq?(r.lastSeq=t.seq,this.emit({kind:"output",sessionId:n,terminalId:i,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:i,exitCode:typeof t.payload?.exit_code=="number"?t.payload.exit_code:null}))),!0}}const np=Math.ceil((8<<20)*4/3)+65536,vn={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(vn);const Sn={codes:{DISPATCH_LIMIT_EXCEEDED:"dispatch.limit_exceeded"}};T(Sn);const fn={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(fn);const yn={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(yn);const bn={codes:{TASK_ID_EMPTY:"task.task_id_empty",TASK_LIMIT_EXCEEDED:"task.limit_exceeded"},retryable:["task.limit_exceeded"]};T(bn);const _n={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(_n);const sp="config.invalid",ip="provider.api_error",rp="provider.filtered",ap="provider.rate_limit",cp="provider.auth_error",dp="provider.connection_error",lp="provider.overloaded",up="context.overflow",In={codes:{PROVIDER_API_ERROR:ip,PROVIDER_FILTERED:rp,PROVIDER_RATE_LIMIT:ap,PROVIDER_AUTH_ERROR:cp,PROVIDER_CONNECTION_ERROR:dp,PROVIDER_OVERLOADED:lp,CONTEXT_OVERFLOW:up},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(In);const Tn={codes:{CONFIG_INVALID:sp,CONFIG_PERSIST_BLOCKED:"config.persist_blocked"}};T(Tn);const wn={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(wn);const En={codes:{CAPABILITY_NOT_FOUND:"capability.not_found",CAPABILITY_UNSUPPORTED:"capability.unsupported",CAPABILITY_INSTALL_IN_PROGRESS:"capability.install_in_progress"}};T(En);const kn={codes:{CRON_EXPRESSION_INVALID:"cron.expression_invalid"}};T(kn);const Cn={codes:{DEBUG_SCOPE_NOT_FOUND:"debug.scope_not_found",DEBUG_TOKEN_NOT_FOUND:"debug.token_not_found"}};T(Cn);const Rn={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(Rn);const Pn={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(Pn);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(i=>i.kind==="instance")}o.getInstanceDependencies=t})(J||(J={}));function pp(o,e,t,n="instance"){const i=e;i[J.DI_TARGET]===e?i[J.DI_DEPENDENCIES].push({id:o,index:t,kind:n}):(i[J.DI_DEPENDENCIES]=[{id:o,index:t,kind:n}],i[J.DI_TARGET]=e)}function We(o){const e=J.serviceIds.get(o);if(e)return e;const t=function(i,a,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");pp(t,i,r)};return Object.defineProperty(t,"toString",{value:function(){return o},enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(t,mp,{value:!0,enumerable:!1}),J.serviceIds.set(o,t),t}const mp=Symbol("serviceIdentifier");We("instantiationService");const hp=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}(?::?\d{2})?)$/,So=s().refine(o=>hp.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"}),Wi):new Date(t).toISOString()});c({id:s().min(1),name:s().min(1),media_type:s().min(1),size:u().int().nonnegative(),created_at:So,expires_at:So.optional()});We("fileService");const On={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(On);const An={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(An);const Mn={codes:{COMPACTION_FAILED:"compaction.failed",COMPACTION_UNABLE:"compaction.unable"}};T(Mn);const Un={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(Un);const xn={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(xn);const Dn={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(Dn);const Nn={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(Nn);const jn={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(jn);We("hostProcessService");const ye={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(ye);ye.codes.OS_PROCESS_SPAWN_FAILED,ye.codes.OS_PROCESS_KILL_FAILED,ye.codes.SHELL_GIT_BASH_NOT_FOUND;const Ln={codes:{PLUGIN_NOT_FOUND:"plugin.not_found",PLUGIN_LOAD_FAILED:"plugin.load_failed",PLUGIN_READ_ONLY:"plugin.read_only"}};T(Ln);const qn={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(qn);const Gn={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(Gn);const $n={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($n);const Fn={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(Fn);const Bn={codes:{SESSION_INDEX_BUILDING:"session.index_building"},retryable:["session.index_building"]};T(Bn);const Vn={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(Vn);const Hn={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(Hn);const Wn={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(Wn);const zn={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(zn);We("fileSystemStorageService");const Kn={codes:{TERMINAL_NOT_FOUND:"terminal.not_found"}};T(Kn);const Qn={codes:{TURN_ID_CONFLICT:"usage.turn_id_conflict"}};T(Qn);const Yn={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(Yn);const Xn={codes:{WORKSPACE_NOT_FOUND:"workspace.not_found"}};T(Xn);const Jn={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(Jn);const Zn={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(Zn);({...vn.codes,...Ko.codes,...Sn.codes,...fn.codes,...yn.codes,...bn.codes,..._n.codes,...In.codes,...Tn.codes,...wn.codes,...En.codes,...kn.codes,...Cn.codes,...Pn.codes,...On.codes,...An.codes,...Mn.codes,...Un.codes,...xn.codes,...Dn.codes,...Nn.codes,...Qo.codes,...jn.codes,...ye.codes,...Ln.codes,...qn.codes,...Gn.codes,...$n.codes,...Fn.codes,...Bn.codes,...Vn.codes,...Hn.codes,...zn.codes,...Kn.codes,...Qn.codes,...Yn.codes,...Xn.codes,...Jn.codes,...Zn.codes,...Rn.codes,...Wn.codes});class N extends Error{constructor(e,t,n,i,a,r){super(t),this.code=e,this.details=n,this.reason=i,this.requestId=a,this.data=r,this.name="RPCError"}}const es=Number.POSITIVE_INFINITY;async function gp(o,e=es){if(o.body===null)throw new SyntaxError("Empty response body");const t=o.body.getReader(),n=[];let i=0;try{for(;;){const l=await t.read();if(l.done)break;if(i+=l.value.byteLength,i>e)throw await t.cancel("decoded response budget exceeded"),new N(50001,`Session response exceeded ${e} decoded bytes`);n.push(l.value)}const a=new Uint8Array(i);let r=0;for(const l of n)a.set(l,r),r+=l.byteLength;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}finally{t.releaseLock()}}function fo(o){const e=o.format??Sp(o.filename),t=o.filename??`persona.${e}`,n=new FormData;return n.append("file",new Blob([ts(o.data)],{type:fp(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 vp(o,e,t){const n=e??"application/octet-stream",i=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([ts(o)],{type:n}),`avatar.${i}`),a}function ts(o){return o.slice().buffer}function Sp(o){const e=o?.toLowerCase();if(e?.endsWith(".png"))return"png";if(e?.endsWith(".charx"))return"charx";if(e?.endsWith(".json"))return"json"}function fp(o){return o==="png"?"image/png":o==="charx"?"application/zip":"application/json"}function yp(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,i)=>o.json(e+"/"+t(n)+"/enabled",{method:"PUT",body:{enabled:i}}),retry:n=>o.json(e+"/"+t(n)+"/retry",{method:"POST",body:{}}),summary:(n,i)=>o.json(e+"/"+t(n)+"/call",{...i,method:"POST",body:{operation:"spaceSummary"}}),handshake:()=>o.json(e+"/handshake"),sshPlan:(n,i)=>o.json(e+"/ssh/plan",{...i,method:"POST",body:n}),sshExecute:(n,i,a)=>o.json(e+"/ssh/plans/"+t(n)+"/execute",{...a,method:"POST",body:i}),sshRegister:(n,i)=>o.json(e+"/ssh/register",{...i,method:"POST",body:n}),sshStatus:()=>o.json(e+"/ssh/status")}}function bp(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,i=async(r,l={})=>{const m=new URL(r instanceof Request?r.url:String(r)),p=l.method??(r instanceof Request?r.method:"GET"),g=fr(p,m.pathname);if(g===void 0)throw new N(40301,"Operation is not available to a remote space");const f={};for(const[U,j]of m.searchParams){const Z=f[U];f[U]=Z===void 0?j:Array.isArray(Z)?[...Z,j]:[Z,j]}const b=["media","mediaPreview","file","appearanceAsset","personaAvatar"].includes(g.operation),I=new Headers(l.headers??(r instanceof Request?r.headers:void 0));if(g.operation==="fileUpload")return I.delete("authorization"),o.token!==void 0&&I.set("authorization",`Bearer ${o.token}`),n(t+"/upload",{...l,headers:I,method:"POST",redirect:"error"});const k=typeof l.body=="string"?JSON.parse(l.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:l.signal,redirect:"error",credentials:"same-origin"})},a=new URL(t+"/events");return a.protocol=a.protocol==="https:"?"wss:":"ws:",{fetch:i,eventsUrl:a.toString()}}function _p(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:Qi.parse(t)})),disable:async()=>Ee.parse(await o.json(e,{method:"DELETE"})),issueLink:async()=>Ki.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()=>Je.parse(await o.json(e+"/session",{skipAuth:!0})),exchange:async t=>Je.parse(await o.json(e+"/exchange",{method:"POST",body:zi.parse(t),skipAuth:!0})),logout:async()=>Je.parse(await o.json(e+"/logout",{method:"POST",body:{},skipAuth:!0}))}}function Ip(o){const e="/thread-bridges",t=(n,i)=>e+"/"+n+"/"+encodeURIComponent(i);return{status:n=>o.json(e,n),approve:(n,i)=>o.json(e+"/inbound",{...i,method:"POST",body:n}),registerTarget:(n,i)=>o.json(e+"/targets",{...i,method:"POST",body:n}),provisionLocal:(n,i)=>o.json(e+"/local",{...i,method:"POST",body:n}),install:(n,i)=>o.json(e+"/outbound",{...i,method:"POST",body:n}),setEnabled:(n,i,a,r)=>o.json(t(n,i)+"/enabled",{...r,method:"PUT",body:{enabled:a}}),revoke:(n,i,a)=>o.json(t(n,i)+"/revoke",{...a,method:"POST",body:{}}),receipts:(n,i)=>o.json(e+"/receipts",{...i,query:n}),retry:n=>o.json(e+"/retry",{...n,method:"POST",body:{}})}}function Tp(o){const e="/usage-export",t=(n,i)=>`${e}/destinations/${encodeURIComponent(n)}/${i}`;return{status:async()=>Q.parse(await o.json(e)),saveDraft:async n=>Ze.parse(await o.json(e+"/destinations",{method:"POST",body:er.parse(n)})),beginVibeAuth:async(n,i)=>et.parse(await o.json(t(n,"auth/begin"),{method:"POST",body:Zi.parse(i)})),pollVibeAuth:async n=>et.parse(await o.json(`${e}/auth/${encodeURIComponent(n)}/poll`,{method:"POST",body:{}})),cancelVibeAuth:async n=>et.parse(await o.json(`${e}/auth/${encodeURIComponent(n)}/cancel`,{method:"POST",body:{}})),preview:async n=>Bt.parse(await o.json(t(n,"preview"))),testProtocol:n=>o.json(t(n,"test"),{method:"POST",body:{}}),enable:async(n,i)=>Ze.parse(await o.json(t(n,"enable"),{method:"POST",body:Ji.parse(i)})),disable:async n=>Ze.parse(await o.json(t(n,"disable"),{method:"POST",body:{}})),remove:(n,i)=>o.json(t(n,"remove"),{method:"POST",body:{discard_pending:i}}),syncNow:async n=>Q.parse(await o.json(t(n,"sync"),{method:"POST",body:{}})),backfill:async(n,i)=>Bt.parse(await o.json(t(n,"backfill"),{method:"POST",body:Xi.parse(i)})),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,i)=>Q.parse(await o.json(t(n,"clear-queue"),{method:"POST",body:{acknowledge:i}})),withdraw:async(n,i)=>Q.parse(await o.json(t(n,"withdraw"),{method:"POST",body:{acknowledge:i}})),handoff:async n=>pe.nullable().parse(await o.json(t(n,"handoff"))),planHandoff:async(n,i)=>pe.parse(await o.json(t(n,"handoff/plan"),{method:"POST",body:{cutoff_at:i}})),armHandoff:async(n,i)=>pe.parse(await o.json(t(n,"handoff/arm"),{method:"POST",body:Yi.parse(i)})),refreshHandoff:async n=>pe.nullable().parse(await o.json(t(n,"handoff/refresh"),{method:"POST",body:{}})),rollbackHandoff:async(n,i,a)=>pe.parse(await o.json(t(n,"handoff/rollback"),{method:"POST",body:{cutoff_at:i,acknowledge:a}}))}}function wp(o){return{webAccess:_p(o),connections:yp(o),threadBridges:Ip(o),usageExport:Tp(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:{setupPresets:()=>o.json("/browser/setup"),setupStatus:e=>o.json(`/browser/setup/${encodeURIComponent(e)}`),prepare:(e,t)=>o.json(`/browser/setup/${encodeURIComponent(e)}:prepare`,{method:"POST",body:t}),connectPreset:(e,t={})=>o.json(`/browser/setup/${encodeURIComponent(e)}:connect`,{method:"POST",body:t}),cancelSetup:e=>o.json(`/browser/setup/${encodeURIComponent(e)}:cancel`,{method:"POST",body:{}}),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}}),listAgentTasks:async(e,t={},n={})=>{const i=tr.parse(t);return or.parse(await o.json(`/sessions/${encodeURIComponent(e)}/agent-tasks`,{...n,query:{page_size:i.page_size,page_token:i.page_token}}))},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)=>ae(o,`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(t)}`,{signal:n?.signal,timeoutMs:n?.timeoutMs,headers:re(n)}),mediaPreview:async(e,t,n)=>ae(o,`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(t)}/preview`,{query:{media_type:n?.mediaType},signal:n?.signal,timeoutMs:n?.timeoutMs,headers:re(n)},Qt),downloadMedia:(e,t,n,i)=>o.raw(`/sessions/${encodeURIComponent(e)}/media/${encodeURIComponent(t)}`,{method:"GET",expectBinary:!0,signal:i?.signal,timeoutMs:i?.timeoutMs??0,headers:re(i)},a=>ht(a,n,i?.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")??"",i=/filename\*?=(?:UTF-8'')?"?([^";]+)"?/iu.exec(n);return{blob:await t.blob(),filename:i?.[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:fo(e)}),importCard:e=>o.json("/personas/import",{method:"POST",rawBody:fo(e)}),exportCard:(e,t,n)=>ae(o,`/personas/${encodeURIComponent(e)}/export`,{query:{format:t,includeMemory:n?.includeMemory},signal:n?.signal,timeoutMs:n?.timeoutMs}),getAvatar:(e,t)=>ae(o,`/personas/${encodeURIComponent(e)}/avatar`,{signal:t?.signal,timeoutMs:t?.timeoutMs}),putAvatar:(e,t,n,i)=>o.json(`/personas/${encodeURIComponent(e)}/avatar`,{method:"PUT",rawBody:vp(t,n,i)}),deleteAvatar:e=>o.json(`/personas/${encodeURIComponent(e)}/avatar`,{method:"DELETE"}),avatar:({id:e,name:t,avatarMime:n,avatarShape:i})=>({id:e,name:t,avatarUrl:n===void 0?void 0:`/api/personas/${encodeURIComponent(e)}/avatar`,avatarShape:n===void 0?void 0:i})},skills:{readBuiltinContent:(e,t)=>o.json(`/skills/${encodeURIComponent(e)}:content`,{signal:t?.signal,timeoutMs:t?.timeoutMs}),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,i)=>o.json("/nb-search/credentials/write",{method:"POST",body:{instance_id:e,value:t,expected_version:n,expected_binding:i}})},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:{listCompletions:()=>o.json("/notifications/completions"),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,i)=>o.json(`/executors/${encodeURIComponent(e)}/local-sessions/${encodeURIComponent(t)}/resume`,{...i,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,t)=>o.raw("/fs:content",{method:"GET",query:{path:e},signal:t?.signal,timeoutMs:t?.timeoutMs},n=>n.text()),previewHostFile:(e,t,n)=>o.raw("/fs:content",{method:"GET",query:{path:e},headers:{range:`bytes=0-${t-1}`},signal:n?.signal,timeoutMs:n?.timeoutMs},async i=>({text:await i.text(),truncated:i.status===206&&Number(i.headers.get("content-range")?.split("/")[1])>t})),readHostFileBytes:(e,t)=>ae(o,"/fs:content",{query:{path:e},signal:t?.signal,timeoutMs:t?.timeoutMs,headers:re(t)}),readHostMediaPreview:(e,t)=>ae(o,"/fs:content",{query:{path:e,preview:"media"},signal:t?.signal,timeoutMs:t?.timeoutMs,headers:re(t)},Qt),downloadHostFile:(e,t,n)=>o.raw("/fs:content",{method:"GET",expectBinary:!0,query:{path:e},signal:n?.signal,timeoutMs:n?.timeoutMs??0,headers:re(n)},i=>ht(i,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:{get:(e,t={})=>o.json(`/cron/${encodeURIComponent(e)}`,{query:{session_id:t.session_id}}),create:e=>o.json("/cron",{method:"POST",body:e}),update:(e,t,n={})=>o.json(`/cron/${encodeURIComponent(e)}`,{method:"PATCH",body:t,query:{session_id:n.session_id}}),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 re(o){return{...o?.ifNoneMatch===void 0?{}:{"if-none-match":o.ifNoneMatch},...o?.range===void 0?{}:{range:o.range}}}function os(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 i=o.headers.get("content-range")??void 0,a=i?.match(/\/(\d+)$/u)?.[1]??o.headers.get("content-length"),r=a==null?void 0:Number(a);return{mime:e,name:n,etag:o.headers.get("etag")??void 0,contentRange:i,totalBytes:r!==void 0&&Number.isSafeInteger(r)&&r>=0?r:void 0,notModified:o.status===304}}async function ht(o,e,t,n=1/0){const i=os(o);let a=0;if(t?.throwIfAborted(),o.body===null)return{...i,bytes:a};const r=o.body.getReader(),l=()=>{r.cancel(t?.reason).catch(()=>{})};t?.addEventListener("abort",l,{once:!0});let m=!1;try{for(;;){t?.throwIfAborted();const p=await r.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,{...i,bytes:a})}}return{...i,bytes:a}}finally{t?.removeEventListener("abort",l),m||await r.cancel().catch(()=>{}),r.releaseLock()}}async function ae(o,e,t,n){return o.raw(e,{...t,method:"GET",expectBinary:!0},async i=>{if(n===void 0)return{...os(i),bytes:new Uint8Array(await i.arrayBuffer())};const a=[],r=await ht(i,p=>{a.push(p)},t?.signal,n),l=new Uint8Array(r.bytes);let m=0;for(const p of a)l.set(p,m),m+=p.byteLength;return{...r,bytes:l}})}function ns(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 gt(o){return o.agentId!==void 0?"agent":o.sessionId!==void 0?"session":o.workspaceId!==void 0?"workspace":"core"}function Ep(o,e,t){return{scope:gt(o),service:e,method:t,workspaceId:o.workspaceId,sessionId:o.sessionId,agentId:o.agentId}}function kp(o){return JSON.stringify(o)}function Cp(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 Rp=3e4,Pp=500,Op="kimi-code.bearer.",ss="transport.timeout";class Ap{endpoint;token;fetchImpl;defaultTimeoutMs;readingTimeoutMs;socket;activeCalls=new Set;rest;closed=!1;terminal={listTerminals:async e=>ir.parse(await this.viewRequest(this.terminalPath(e),{})),createTerminal:async(e,t={})=>Vt.parse(await this.viewRequest(this.terminalPath(e),{},{method:"POST",body:sr.parse(t),okCodes:[0]})),getTerminal:async(e,t)=>Vt.parse(await this.viewRequest(this.terminalPath(e,t),{})),closeTerminal:async(e,t)=>nr.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,i)=>this.socket.terminals.terminalResize(e,t,n,i),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,n)=>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},n),transcriptCatchUp:(e,t,n)=>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"},n),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 i=mn[t],a=n,r=i.suffix.replace("{target}",encodeURIComponent(a.target??""));return this.viewRequest(`/api/sessions/${encodeURIComponent(e)}${r}`,{agent_id:a.query?.agent_id},{method:i.method,body:i.method==="GET"?void 0:a.body??{},okCodes:i.okCodes,timeoutMs:"timeoutMs"in i?i.timeoutMs:void 0})}};viewRequest(e,t,n){return this.requestJson(e,{...n,query:t})}async transcriptRequest(e,t,n,i){const a=await this.viewRequest(t,{...n,transcript_coverage_version:Do},{signal:i?.signal,timeoutMs:i?.timeoutMs});return xo(a)?a:e==="page"?Ju(a):Zu(a)}requestJson(e,t={}){const i=/\/klient\/session-view\//.test(e)||/\/transcript(?:\/(?:detail|details|ops))?$/.test(e)?{...t,timeoutMs:t.timeoutMs??this.readingTimeoutMs()}:t;return this.performFetch(e,i,async a=>{if(a.status===404&&t.allowMissingRoute===!0){await a.body?.cancel();return}const r=/\/klient\/session-view\//.test(e)||/\/transcript(?:\/(?:detail|details|ops))?$/.test(e),l=await this.readEnvelope(a,t.signal,r?es:4*1024*1024),m=t.okCodes??[0];if(a.ok===!1||!m.includes(l.code))throw new N(m.includes(l.code)?a.status:l.code,l.msg,l.details,l.reason,l.request_id,l.data);return l.data})}requestRaw(e,t,n){const i=t??{};return this.performFetch(e,i,async a=>{const r=a.headers.get("content-type")??"";if((a.ok||a.status===304&&i.headers?.["if-none-match"]!==void 0)&&!(i.jsonErrorOnSuccess===!0&&r.includes("json")))return n(a);const l=await this.readEnvelope(a,i.signal),m=i.okCodes??[0];throw new N(m.includes(l.code)?a.status:l.code,l.msg,l.details,l.reason,l.request_id,l.data)})}async performFetch(e,t,n){if(this.closed)throw new Error("http closed");const i=t.rawBody??(t.body===void 0?void 0:JSON.stringify(t.body)),a=typeof i=="string"?new TextEncoder().encode(i).byteLength:i instanceof Uint8Array?i.byteLength:void 0;if(a!==void 0&&a>np)throw new N(40001,"request body exceeds the allowed size limit");const r=new AbortController,l={controller:r};this.activeCalls.add(l);const m=t.timeoutMs??this.defaultTimeoutMs;let p=!1;const g=m===0?void 0:setTimeout(()=>{p=!0,r.abort()},m),f=t.signal,b=()=>{r.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 ms of we)U.searchParams.append(x,ms);else we!==void 0&&U.searchParams.set(x,String(we));const j={accept:t.expectBinary===!0?"application/octet-stream":"application/json",...t.headers};this.token!==void 0&&t.skipAuth!==!0&&(j.authorization=`Bearer ${this.token}`),t.body!==void 0&&j["content-type"]===void 0&&(j["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:i,headers:j,signal:r.signal,redirect:"error"})}catch(x){throw p?this.transportTimeoutError(m):this.closed&&r.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&&r.signal.aborted?new Error("http closed",{cause:x}):x instanceof TypeError&&!r.signal.aborted?new N(-1,x.message):x}}finally{g!==void 0&&clearTimeout(g),f?.removeEventListener("abort",b),this.activeCalls.delete(l)}}transportTimeoutError(e){return new N(50001,`call timed out after ${e}ms`,void 0,ss)}async readEnvelope(e,t,n=4*1024*1024){let i;try{i=await gp(e,n)}catch(a){throw xp(a)||t?.aborted===!0||!(a instanceof SyntaxError)?a:new N(e.status,`HTTP ${e.status} — non-JSON response`)}if(i===null||typeof i.code!="number"||typeof i.msg!="string")throw new N(e.status,`HTTP ${e.status} — non-JSON response`);return i}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??Rp,this.readingTimeoutMs=e.readingTimeoutMs??(()=>0),this.socket=new Mp({endpoint:t,eventsUrl:e.eventsUrl,token:e.token,WebSocket:e.WebSocket,onDiagnostic:e.onSocketDiagnostic}),this.rest=wp({json:(i,a)=>this.requestJson(i,a),raw:(i,a,r)=>this.requestRaw(i,a,r)})}call(e,t,n,i,a){return this.requestJson("/api/klient/call",{method:"POST",body:{procedure:Ep(e,t,n),params:ns(i)},timeoutMs:a?.timeoutMs,signal:a?.signal})}stream(e,t,n,i){return this.closed?Dp(new Error("http closed")):this.socket.stream(e,t,n,i)}listen(e,t,n,i,a){if(this.closed)throw new Error("http closed");return this.socket.listen(e,t,n,i,a)}close(){if(this.closed)return Promise.resolve();this.closed=!0;for(const e of this.activeCalls)e.controller.abort();return this.activeCalls.clear(),this.socket.close(),Promise.resolve()}}class Mp{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 op({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 tp({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 i of this.streams.values())i.error(n);this.streams.clear(),this.notifyDisconnect(n),this.sessionViews.connecting(),this.ensureConnected()}nudge(){if(!this.closed){if(this.state==="open"){this.heartbeatMs!==void 0&&Date.now()-this.lastInboundAt>Math.max(45e3,this.heartbeatMs*3)&&this.restart("stale_heartbeat");return}this.ws===void 0&&(this.fatalRetriesLeft=void 0,this.reconnectAttempt=0,this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.state="idle",this.ensureConnected())}}constructor(e){this.wsUrl=e.eventsUrl??Up(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,i,a){this.requireWebSocket();const r=this.nextId(),l={type:"subscribe",id:r,scope:gt(e),workspaceId:e.workspaceId,sessionId:e.sessionId,agentId:e.agentId},m=t.kind==="stream"?{...l,event:t.name}:{...l,service:t.service,event:t.event};return this.listens.set(r,{frame:m,handler:n,onError:i,onReady:a}),this.ensureConnected(),this.state==="open"&&this.send(m),{dispose:()=>{this.listens.delete(r)&&this.state==="open"&&this.send({type:"unsubscribe",id:r})}}}stream(e,t,n,i){return{[Symbol.asyncIterator]:()=>{const a=[],r=[];let l=!1,m;const p={frame:{type:"stream",scope:gt(e),service:t,method:n,arg:ns(i),workspaceId:e.workspaceId,sessionId:e.sessionId,agentId:e.agentId},sent:!1,push(b){if(l)return;const I={done:!1,value:b},k=r.shift();k===void 0?a.push(I):k.resolve(I)},end:()=>{if(l)return;l=!0,m!==void 0&&this.streams.delete(m);const b={done:!0,value:void 0},I=r.shift();I===void 0?a.push(b):I.resolve(b);for(const k of r)k.resolve({done:!0,value:void 0});r.length=0},error:b=>{if(l)return;l=!0,m!==void 0&&this.streams.delete(m);const I=r.shift();I===void 0?a.push(b):I.reject(b);for(const k of r)k.reject(b);r.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):l?Promise.resolve({done:!0,value:void 0}):new Promise((I,k)=>{r.push({resolve:I,reject:k})})},return:()=>{if(!l){if(l=!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 r)b.resolve({done:!0,value:void 0});r.length=0}return Promise.resolve({done:!0,value:void 0})}}}}}close(){if(this.closed)return;this.closed=!0,this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.state="closed",this.ws?.close(1e3,"klient closed"),this.ws=void 0;const e=new Error("http event socket closed");this.notifyDisconnect(e);for(const 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?[`${Op}${this.token}`]:void 0;let n;try{n=new e(this.wsUrl,t)}catch(i){this.notifyDisconnect(i instanceof Error?i:new Error(String(i))),this.scheduleReconnect();return}this.ws=n,this.heartbeatMs=void 0,this.lastInboundAt=0,this.openedAt=0,clearTimeout(this.establishmentTimer),this.establishmentTimer=setTimeout(()=>{this.ws!==n||this.closed||(this.ws=void 0,this.reportClose("establish_timeout"),n.close(4e3,"WebSocket establishment timed out"),this.onClose())},12e3),n.addEventListener("open",()=>{if(!(this.ws!==n||this.closed)){clearTimeout(this.establishmentTimer),this.diagnose({kind:"open",attempt:this.reconnectAttempt}),this.openedAt=Date.now(),this.reconnectAttempt=0,this.state="open";for(const i of this.listens.values())this.send(i.frame);for(const i of this.streams.values())this.sendStream(i);this.sessionViews.opened(),this.terminals.opened()}}),n.addEventListener("message",i=>{this.ws!==n||typeof i.data!="string"||(this.lastInboundAt=Date.now(),this.onFrame(Cp(i.data)))}),n.addEventListener("close",i=>{this.ws===n&&(this.ws=void 0,this.closed||this.reportClose("server",i),[4001,1008].includes(i.code)&&(this.fatalRetriesLeft=0),this.onClose())}),n.addEventListener("error",()=>{})}onFrame(e){if(e===void 0)return;if(e.type==="error"&&e.data?.fatal===!0){this.fatalRetriesLeft??=4;const n=this.ws;this.ws=void 0,this.state="closed",this.reportClose("fatal_frame",{reason:e.msg}),n?.close(4e3,"fatal protocol error"),this.onClose();return}if(e.type!=="error"&&(this.fatalRetriesLeft=void 0),this.sessionViews.receive(e)||this.terminals.receive(e))return;if(e.type==="ping"){const n=e.data;typeof n?.heartbeatMs=="number"&&n.heartbeatMs>0&&(this.heartbeatMs=n.heartbeatMs),this.send({type:"pong",data:{nonce:n?.nonce}});return}const 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?.(yo(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(yo(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(Pp*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(kp(e))}catch{}}nextId(){return this.seq+=1,`${this.idPrefix}_${this.seq}`}}function yo(o){return new N(typeof o.code=="number"?o.code:50001,o.msg??"error",o.details,o.reason)}function Up(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 xp(o){return typeof o=="object"&&o!==null&&"name"in o&&o.name==="AbortError"}function Dp(o){return{[Symbol.asyncIterator](){return{async next(){throw o}}}}}function Np(o){return Yu(new Ap(o),o)}class G 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 K={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},jp={"*":"off",main:"delta"};function lm(o){return o===void 0||o==="main"?jp:{"*":"off",main:"off",[o]:"delta"}}function Lp(o){const e=async i=>{try{return await i()}catch(a){throw a instanceof N?new G({code:a.code,msg:a.message,data:a.data,request_id:a.requestId}):a}},t=i=>o.session(i).commands,n=(i,a)=>e(async()=>{if(!await o.session(i).resume())throw new N(40401,`session ${i} does not exist`);return a()});return{getSession:i=>e(()=>t(i).read()),submitPrompt:(i,a)=>n(i,()=>t(i).submit(a)),editMessage:(i,a,r)=>n(i,()=>t(i).edit(a,Uo.parse(r))),regenerateMessage:(i,a,r)=>n(i,()=>t(i).regenerate(a,Mo.parse(r))),forkSession:(i,a)=>e(()=>t(i).fork(Ao.parse(a))),abortPrompt:(i,a,r)=>e(()=>t(i).abort(a,r)),abortTurn:(i,a)=>e(()=>t(i).abortTurn(a)),movePrompt:(i,a,r)=>e(()=>t(i).move(a,r)),replacePrompt:(i,a,r)=>e(()=>t(i).replace(a,r)),timingPrompt:(i,a,r)=>e(()=>t(i).timing(a,r)),holdPrompt:(i,a,r)=>e(()=>t(i).hold(a,r)),steerPrompt:(i,a,r)=>n(i,()=>t(i).steer(a,r)),resolveApproval:(i,a,r)=>n(i,()=>t(i).approve(a,r)),resolveQuestion:(i,a,r)=>n(i,()=>t(i).answer(a,r)),dismissQuestion:(i,a)=>n(i,()=>t(i).dismiss(a)),cancelTask:(i,a,r)=>n(i,()=>t(i).cancelTask(a,r))}}const P="main",ce={roster:1,live:2,task:3};function vt(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 qp(o,e){if(o.agentId===P||e.agentId===P)return vt(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),i=Number.isFinite(t),a=Number.isFinite(n);return i&&a&&t!==n?n-t:i!==a?i?-1:1:vt(o.agentId,e.agentId)}function xt(){return Object.create(null)}function Gp(){return{roots:Object.freeze([]),byId:Object.freeze(xt())}}function nt(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 $p(o,e){if(o===e)return!0;if(o===void 0||e===void 0||!nt(o.currentTurn,e.currentTurn)||!nt(o.total,e.total))return!1;const t=Object.keys(o.byModel??{}),n=Object.keys(e.byModel??{});return t.length===n.length&&t.every(i=>nt(o.byModel?.[i],e.byModel?.[i]))}function Fp(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.nameSource===e.nameSource&&o.statusSource===e.statusSource&&o.model===e.model&&o.thinkingEffort===e.thinkingEffort&&o.contextTokens===e.contextTokens&&o.maxContextTokens===e.maxContextTokens&&$p(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 um(o,e){if(o===void 0||o===e)return e;const t=xt(),n=new Set,i=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=i(D);(U===void 0||U!==o.byId[D])&&(k=!1)}n.delete(g);const R=I!==void 0&&k&&Fp(I,b)?I:b;return t[g]=R,R};for(const g of e.roots)i(g.agentId);for(const g of Object.keys(e.byId))i(g);const a=e.roots.map(g=>t[g.agentId]),r=Object.keys(o.byId),l=Object.keys(e.byId),m=r.length===l.length&&l.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 pm(o,e,t){const n=new Map;for(const p of Kp(t??[])){const g=as(p),f=Ue(n,g);Bp(f,p)}for(const p of e??[]){if(!oe(p.agentId))continue;const g=Ue(n,p.agentId);Vp(g,p)}for(const p of o){if(!oe(p.subagentId))continue;const g=Ue(n,p.subagentId);Hp(g,p)}if(n.size===0)return Gp();for(const p of n.values())(p.rosterParentAgentId??p.parentAgentId)===P&&!n.has(P)&&Ue(n,P);const i=new Map;for(const p of n.values())i.set(p.agentId,Wp(p,n));zp(i);const a=new Map;for(const p of n.keys())a.set(p,[]);const r=[];for(const[p,g]of i){if(g===void 0){r.push(p);continue}a.get(g).push(p)}const l=(p,g)=>qp(n.get(p),n.get(g));for(const p of a.values())p.sort(l);if(r.sort(l),n.has(P)&&!i.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&&ne(b.status??"completed")})?"running":"completed"}}const m=xt();for(const p of n.values()){const g=i.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:Xp(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:r.map(p=>m[p]),byId:m}}function mm(o,e){const t=o.byId[e];if(t===void 0)return[];const n=[],i=new Set;let a=t;for(;a!==void 0&&!i.has(a.agentId);){i.add(a.agentId),n.push(a);const r=a.parentAgentId;a=r===void 0?void 0:o.byId[r]}return n.reverse()}function hm(o,e){const t=o.byId[e];return t===void 0?[]:t.childIds.flatMap(n=>{const i=o.byId[n];return i===void 0?[]:[i]})}function Ue(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 is(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 Bp(o,e){const t=de(e.status,e.detached===!0),n=E(e.startedAt,e.started_at),i=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:Dt(o,t,ce.task,n,i).accepted)&&(o.model=E(e.model)??o.model,o.thinkingEffort=E(e.thinkingEffort,e.thinking_effort)??o.thinkingEffort,o.startedAt??=n,o.endedAt??=i,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 Vp(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,is(o,e.toolCallCount,e.toolCallCountKnown,e.toolCallCountAuthoritative);const n=L(e.disposedAt);n!==void 0&&(o.disposedAt===void 0||n>o.disposedAt)&&(o.disposedAt=n,rs(o,n,ce.roster));const i=L(e.endedAt??e.startedAt),a=e.refreshing===!0&&e.disposedAt===void 0&&(L(e.refreshingUntil)??0)>Date.now()&&(i===void 0||(o.statusStartedAt===void 0||o.statusStartedAt<=i)&&(o.statusEndedAt===void 0||o.statusEndedAt<=i)),r=de(e.status,e.detached===!0),l=e.statusSource===void 0?ce.roster:4,m=e.statusSource==="metadata"&&r==="unknown",p=L(e.endedAt??e.startedAt),g=p!==void 0&&o.statusStartedAt!==void 0&&p<o.statusStartedAt,f=e.statusSource!==void 0&&!m&&!g&&(r==="idle"||r==="unknown");f&&(o.status=r,o.statusAuthority=l,o.busy=!1);const b=f||(r===void 0?o.status===void 0&&o.disposedAt===void 0:Dt(o,r,l,e.startedAt,e.endedAt).accepted);a&&(o.refreshing=!0,o.refreshingUntil=e.refreshingUntil),b&&(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 rs(o,e,t){o.status===void 0||!ne(o.status)||o.statusStartedAt!==void 0&&o.statusStartedAt>e||(o.status="unknown",o.statusAuthority=t,cs(o),o.busy=!1)}function Hp(o,e){if(o.parentAgentId=o.parentAgentId??B(e.parentAgentId),o.parentToolCallId=E(e.parentToolCallId)??o.parentToolCallId,(e.name!==e.subagentId||o.name===void 0)&&(o.name=E(e.name)??o.name),o.label=E(e.label)??o.label,o.description=E(e.description)??o.description,is(o,e.toolCallCount,e.toolCallCountKnown,e.toolCallCountAuthoritative),o.statusAuthority===4&&(o.status==="unknown"||o.status==="idle")&&ne(de(e.status)??"unknown"))return;const t=L(e.disposedAt);t!==void 0&&(o.disposedAt===void 0||t>o.disposedAt)&&(o.disposedAt=t,rs(o,t,ce.live));const n=de(e.status);(n===void 0?o.status===void 0&&o.disposedAt===void 0:Dt(o,n,ce.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=ne(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 Wp(o,e){const t=o.rosterParentAgentId??o.parentAgentId;if(!(t===void 0||t===o.agentId)&&e.has(t))return t}function zp(o){const e=new Set(o.keys());for(;e.size>0;){const t=e.values().next().value;if(t===void 0)break;const n=[],i=new Map;let a=t;for(;a!==void 0&&e.has(a);){const r=i.get(a);if(r!==void 0){const m=n.slice(r).reduce((p,g)=>vt(g,p)>0?g:p);o.set(m,void 0);break}i.set(a,n.length),n.push(a),a=o.get(a)}for(const r of n)e.delete(r)}}function as(o){return B(o.agentId)}function Kp(o){const e=new Map;for(const t of o){const n=as(t);if(n===void 0)continue;const i=e.get(n);(i===void 0||Qp(t,i))&&e.set(n,t)}return[...e.values()]}function Qp(o,e){const t=L(E(o.startedAt,o.started_at)),n=L(E(e.startedAt,e.started_at)),i=L(E(o.endedAt,o.completed_at)),a=L(E(e.endedAt,e.completed_at)),r=B(o.id),l=B(e.id);if(r!==void 0&&l!==void 0&&r!==l){if(t!==void 0&&a!==void 0&&t>a)return!0;if(n!==void 0&&i!==void 0&&n>i)return!1}if(t!==n)return t===void 0?!1:n===void 0?!0:t>n;const p=de(o.status,o.detached===!0),g=de(e.status,e.detached===!0),f=p===void 0?-1:_e(p),b=g===void 0?-1:_e(g);return f!==b?f>b:i!==a?i===void 0?!1:a===void 0?!0:i>a:r!==l?r===void 0?!1:l===void 0?!0:r>l:bo(o)>bo(e)}function bo(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 L(o){if(o===void 0)return;const e=Date.parse(o);return Number.isFinite(e)?e:void 0}function de(o,e=!1){if(!oe(o))return e?"background":void 0;switch(o){case"unknown":case"idle":case"lost":return o;case"running":case"queued":case"working":case"in_progress":return e?"background":"running";case"suspended":return"suspended";case"completed":return"completed";case"failed":case"timed_out":return"failed";case"cancelled":case"killed":return"cancelled";case"background":return"background";default:return e?"background":void 0}}function _e(o){return o==="unknown"?0:o==="completed"||o==="failed"||o==="cancelled"||o==="lost"?2:1}function _o(o){return o==="suspended"?2:ne(o)?1:0}function Yp(o,e,t){if(_e(e)===2||o.disposedAt===void 0)return!1;const n=L(t);return n===void 0||n<=o.disposedAt}function cs(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 Dt(o,e,t,n,i){const a=o.status===void 0?-1:_e(o.status),r=_e(e),l=L(n),m=L(i);if(Yp(o,e,n))return{accepted:!1,newGeneration:!1};const p=a>0&&r>0,g=L(o.startedAt),b=ne(e)&&l!==void 0&&o.disposedAt!==void 0&&l>o.disposedAt&&(o.statusStartedAt===void 0||o.statusStartedAt<=o.disposedAt)||a<=0&&r===1&&l!==void 0&&g!==void 0&&l>g||p&&l!==void 0&&o.statusEndedAt!==void 0&&l>o.statusEndedAt;if(t<ce.task&&r===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:_o(o.status),D=_o(e),U=r===a&&(r===1?D<R||D===R&&t<o.statusAuthority:t<o.statusAuthority),j=r<a||U;return!b&&j?{accepted:!1,newGeneration:!1}:(b?(cs(o),o.taskId=void 0,o.statusStartedAt=l,o.statusEndedAt=m):r>0&&(o.statusStartedAt??=l,o.statusEndedAt=m??o.statusEndedAt),o.status=e,o.statusAuthority=t,{accepted:!0,newGeneration:b})}function ne(o){return o==="running"||o==="suspended"||o==="background"}function Xp(o,e){return o==="completed"||o==="failed"||o==="cancelled"||o==="lost"||o==="idle"?!1:e??ne(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 Io=200,Jp=5e3,To=1e3,ve=[],St=new Set;let ds=[];function ee(o,e=Date.now()){ve.push({...o,at:e}),ve.length>Io&&ve.splice(0,ve.length-Io),ds=ve.slice();for(const t of St)t()}function Zp(){return ds}function gm(o){return St.add(o),()=>{St.delete(o)}}function em(o){return o.map(e=>{const{at:t,kind:n,...i}=e,a=Object.entries(i).filter(([,r])=>r!==void 0).map(([r,l])=>`${r}=${typeof l=="string"?JSON.stringify(l):String(l)}`);return[new Date(t).toISOString(),n,...a].join(" ")}).join(`
|
|
2
|
+
`)}let xe=0,st=null;function vm(){if(typeof window>"u"||typeof document>"u")return()=>{};if(xe+=1,xe===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})},i=()=>{ee({kind:"online",online:!1})};document.addEventListener("visibilitychange",o),window.addEventListener("focus",e),window.addEventListener("blur",t),window.addEventListener("online",n),window.addEventListener("offline",i);let a=Date.now();const r=window.setInterval(()=>{const m=Date.now(),p=m-a-To;a=m,p>=Jp&&ee({kind:"timer_gap",gapMs:p,visibility:document.visibilityState},m)},To),l=window;l.__kikiConnectionLog=()=>em(Zp()),st=()=>{document.removeEventListener("visibilitychange",o),window.removeEventListener("focus",e),window.removeEventListener("blur",t),window.removeEventListener("online",n),window.removeEventListener("offline",i),window.clearInterval(r),delete l.__kikiConnectionLog}}return()=>{xe-=1,xe===0&&(st?.(),st=null)}}function tm(o){return o instanceof G&&o.code===K.SESSION_INDEX_BUILDING}function om(o){return o.includes("session.not_found")||o.includes(`code ${K.SESSION_NOT_FOUND}`)}function wo(o){if(typeof o!="object"||o===null||Array.isArray(o))return!1;const e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function Se(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 G({code:K.INVALID_RESPONSE,msg:`Invalid config response: ${e} must be a string or string array`,data:o})}function ft(o){if(!wo(o))throw new G({code:K.INVALID_RESPONSE,msg:"Invalid config response: data must be a plain object",data:o});const e=o.tools;if(e!=null&&!wo(e))throw new G({code:K.INVALID_RESPONSE,msg:"Invalid config response: tools must be a plain object",data:e});const t=e??{};return{...o,extra_agent_dirs:Se(o.extra_agent_dirs,"extra_agent_dirs"),skip_builtin_profile_installation:Se(o.skip_builtin_profile_installation,"skip_builtin_profile_installation"),disabled_named_profiles:Se(o.disabled_named_profiles,"disabled_named_profiles"),tools:{...t,enabled:Se(t.enabled,"tools.enabled"),disabled:Se(t.disabled,"tools.disabled")}}}const nm=["user","feedback","project","reference"],sm=40423,im=40944;function rm(o){const e=o.endpoint===""?globalThis.location.origin:o.endpoint;return new ps({baseUrl:e,token:o.token,timeoutMs:o.timeoutMs,onSessionMutation:o.onSessionMutation,transport:bp({...o,endpoint:e})})}class ls extends Error{constructor(){super("External agent messages support text only. Remove attachments and retry."),this.name="ExternalAgentAttachmentUnsupportedError"}}class Nt extends Error{constructor(e){super("Native child prompt result unknown",{cause:e}),this.name="NativeChildPromptSendError"}}class us extends Nt{constructor(e){super(e),this.name="NativeChildPromptConflictError"}}class ps{baseUrl;klient;sessions;token;transport;serverLeaseId;previewBytes=new Map;previewCacheBytes=0;previewFlights=new Map;onSessionMutation;constructor(e){this.onSessionMutation=e.onSessionMutation,this.transport=e.transport,this.baseUrl=e.baseUrl,this.token=e.token!==void 0&&e.token!==""?e.token:void 0,this.klient=Np({endpoint:this.baseUrl,token:this.token,timeoutMs:e.timeoutMs,readingTimeoutMs:()=>this.readingOptions().timeoutMs,onSocketDiagnostic:n=>{ee(n)},...e.transport});const t=Lp(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}readingOptions(){return{timeoutMs:typeof localStorage>"u"?0:rr().readingTimeoutSeconds*1e3}}sessionView(e){const t=this.klient.session(e).view;return{snapshot:n=>this.run(()=>t.snapshot(n)),transcript:t.transcript,subscribe:(n,i)=>t.subscribe(n,i)}}get rest(){const e=this.klient.rest;if(e===void 0)throw new Error("KAP REST domains are unavailable on this transport");return e}async run(e){try{return await(typeof e=="function"?e():e)}catch(t){if(t instanceof N){const n=t.reason===ss;throw new G({code:n?K.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,i,a,r){const l=this.klient.session(e),m=await this.run(()=>l.agents());if(m[t]!==void 0&&(m[t].executor??"native")!=="native"){if(i?.some(f=>f.type!=="text"))throw new ls;return this.run(()=>l.sendUserAgentMessage({targetAgentId:t,content:n,idempotencyKey:a}))}const p=i===void 0?[{type:"text",text:n}]:[...i],g=t!==P&&p.every(f=>f.type==="text");try{await this.submitPrompt(e,{content:p,agent_id:t,after_model_switch:r,prompt_id:g?a:void 0})}catch(f){throw g&&f instanceof G&&f.code===40938?new us(f):t!==P?new Nt(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,n){return this.run(this.klient.session(e).agent(t).listModelSwitches({signal:n}))}updateAgentModelSwitch(e,t,n,i){return this.run(this.klient.session(e).agent(t).updateModelSwitch(n,i))}cancelAgentModelSwitch(e,t,n){return this.run(this.klient.session(e).agent(t).cancelModelSwitch(n))}recoverAgentModelSwitch(e,t,n,i,a){const r=this.klient.session(e).agent(t);return this.run(i==="retry"?r.recoverModelSwitch(n,i,a):r.recoverModelSwitch(n,i))}subscribeAgentModelSwitches(e,t,n){const i=this.klient.session(e).agent(t).events,a=i.on("prompt.model_switch_queued",l=>{n({kind:"queued",entry:l.entry,queueIndex:l.queueIndex})}),r=i.on("prompt.model_switch_status",l=>{n({kind:"status",operationId:l.operationId,receipt:l.receipt})});return{ready:Promise.all([a.ready,r.ready]).then(()=>{}),dispose:()=>{a.dispose(),r.dispose()}}}listTerminals(e){return this.klient.terminal.listTerminals(e)}createTerminal(e,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 ft(await this.run(this.rest.config.get()))}previewModelGenerationMigration(){return this.run(this.rest.config.previewModelGenerationMigration())}applyModelGenerationMigration(e){return this.run(this.rest.config.applyModelGenerationMigration(e))}restoreModelGenerationMigration(e,t){return this.run(this.rest.config.restoreModelGenerationMigration(e,t))}async getNbSearchCapabilities(){return ar.parse(await this.run(this.rest.nbSearch.capabilities()))}async testNbSearch(e){return cr.parse(await this.run(this.rest.nbSearch.test({signal:e})))}async readNbSearchKeyUsage(e,t=!1,n){return dr.parse(await this.run(this.rest.nbSearch.keyUsage(e,t,{signal:n})))}async readNbSearchCredential(e,t=!1){return Wt.parse(await this.run(this.rest.nbSearch.readCredential(e,t)))}async revealSecret(e){return lr.parse(await this.run(this.rest.secrets.reveal(e)))}async writeNbSearchCredential(e,t,n,i){return Wt.parse(await this.run(this.rest.nbSearch.writeCredential(e,t,n,i)))}get requestIdentity(){const e=this.rest.requestIdentity,t=async n=>mr.parse(await this.run(n));return{get:()=>t(e.get()),preview:async n=>ur.parse(await this.run(e.preview(n))),duplicateProfile:(n,i)=>t(e.duplicateProfile(n,i)),updateProfile:(n,i)=>t(e.updateProfile(n,i)),deleteProfile:n=>t(e.deleteProfile(n)),checkTrack:(n,i)=>t(e.checkTrack(n,i)),applyTrack:(n,i)=>t(e.applyTrack(n,i)),trackAction:(n,i)=>t(e.trackAction(n,i)),pinTrack:(n,i)=>t(e.pinTrack(n,i)),setManifestUrl:n=>t(e.setManifestUrl(n))}}get notifications(){const e=this.rest.notifications,t=n=>(...i)=>this.run(()=>n(...i));return{listCompletions:t(e.listCompletions.bind(e)),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}))}listAgentTasks(e,t,n){return this.run(this.rest.sessions.listAgentTasks(e,t,n))}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,t){return this.run(this.rest.filesystem.readHostFile(e,{...this.readingOptions(),...t}))}async readBuiltinSkill(e,t){return(await this.run(this.rest.skills.readBuiltinContent(e,{...this.readingOptions(),...t}))).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,n){return this.run(this.rest.filesystem.previewHostFile(e,t,{...this.readingOptions(),...n}))}cachedPreviewBytes(e,t,n){if(n?.aborted===!0)return Promise.reject(n.reason);let i=this.previewFlights.get(e);if(i===void 0){const r=new AbortController;i={controller:r,users:0,promise:this.readAndCachePreview(e,p=>t(p,r.signal))},this.previewFlights.set(e,i);const l=i,m=()=>{this.previewFlights.get(e)===l&&this.previewFlights.delete(e)};l.promise.then(m,m)}const a=i;return a.users+=1,new Promise((r,l)=>{let m=!1;const p=f=>{m||(m=!0,n?.removeEventListener("abort",g),a.users-=1,a.users===0&&this.previewFlights.get(e)===a&&(this.previewFlights.delete(e),a.controller.abort()),f())},g=()=>{p(()=>{l(n?.reason)})};n?.addEventListener("abort",g,{once:!0}),a.promise.then(f=>{p(()=>{r(f)})},f=>{p(()=>{l(f)})})})}async readAndCachePreview(e,t){const n=this.previewBytes.get(e),i=await this.run(t(n?.etag));if(i.notModified){if(n===void 0)throw new Error("Preview cache is missing a validated response");return n}if(n!==void 0&&(this.previewBytes.delete(e),this.previewCacheBytes-=n.bytes.byteLength),i.etag!==void 0&&i.bytes.byteLength<=32*1024*1024)for(this.previewBytes.set(e,{...i,etag:i.etag}),this.previewCacheBytes+=i.bytes.byteLength;this.previewBytes.size>8||this.previewCacheBytes>32*1024*1024;){const a=this.previewBytes.keys().next().value;this.previewCacheBytes-=this.previewBytes.get(a).bytes.byteLength,this.previewBytes.delete(a)}return i}readHostFileBytes(e,t){return this.run(this.rest.filesystem.readHostFileBytes(e,{...this.readingOptions(),...t}))}readHostMediaPreviewBytes(e,t){return this.cachedPreviewBytes(`host-preview:${e}:${t?.mediaType??""}`,(n,i)=>this.rest.filesystem.readHostMediaPreview(e,{...this.readingOptions(),...t,signal:i,ifNoneMatch:n}),t?.signal)}downloadHostFile(e,t,n){return this.run(this.rest.filesystem.downloadHostFile(e,t,{...this.readingOptions(),...n}))}readSessionMediaBytes(e,t,n){return this.run(this.rest.sessions.media(e,t,{...this.readingOptions(),...n}))}readSessionMediaPreviewBytes(e,t,n){return this.cachedPreviewBytes(`media-preview:${e}:${t}:${n?.mediaType??""}`,(i,a)=>this.rest.sessions.mediaPreview(e,t,{...this.readingOptions(),...n,signal:a,ifNoneMatch:i}),n?.signal)}downloadSessionMedia(e,t,n,i){return this.run(this.rest.sessions.downloadMedia(e,t,n,{...this.readingOptions(),...i}))}downloadTranscriptContent(e,t,n,i,a){const r=gr(t,n);return r===void 0?Promise.reject(new Error("This content has no original-file consumer")):this.downloadSessionMedia(e,r,i,a)}listWorkspaces(){return this.run(this.rest.workspaces.list())}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 i=hr(e.type).defaultContextSize;return n.map(a=>({id:"",remoteId:a,maxContextSize:i,displayName:"",capabilities:[],supportEfforts:[],requestIdentityChoice:"inherit",requestIdentityOverridesJson:"",imageAcceptedTypes:null,imageConvertUnsupported:null}))};try{const n=await this.run(this.rest.providers.probe({type:e.type,base_url:e.baseUrl,api_key:e.apiKey}));if(!n.ok)throw new Error(n.error.message);return t(n.models)}catch(n){if(!(n instanceof G))throw n;return pr(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,n){return this.run(this.klient.global.capabilities.install(e,t,n))}cancelCapability(e){return this.run(this.klient.global.capabilities.cancel(e))}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))}getCronTask(e,t){return this.run(this.rest.cron.get(e,{session_id:t}))}createCronTask(e){return this.run(this.rest.cron.create(e))}updateCronTask(e,t,n){return this.run(this.rest.cron.update(e,t,{session_id:n}))}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={},n){return this.memoryRequest("GET",`/memory/${e.scope}`,{target:e,signal:n,query:t.cursor!==void 0?{cursor:t.cursor}:{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,mode:t.mode,statuses:t.statuses?.join(","),page_size:t.page_size?.toString()}})}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}})}async memoryInbox(e,t={},n){const i=await this.memoryRequest("GET",`/memory/${e.scope}/inbox`,{target:e,signal:n,query:t.cursor!==void 0?{cursor:t.cursor}:{page_size:t.page_size?.toString()}});return Array.isArray(i)?{items:i}:i}undoMemory(e,t){return this.memoryRequest("POST",`/memory/${e.scope}/undo`,{target:e,body:{operation_id:t}})}async memoryRequest(e,t,n={}){const i=this.baseUrl.replace(/\/+$/u,""),a=i===""?new URL(`/api${t}`,globalThis.location?.origin??"http://localhost"):new URL(`${i}/api${t}`),r=n.target?.scope,l={...n.query,workspace_id:r==="workspace"||r==="persona_workspace"?n.target?.workspaceId:void 0,persona_id:r==="persona"||r==="persona_workspace"?n.target?.personaId:void 0};for(const[f,b]of Object.entries(l))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:n.signal===void 0?AbortSignal.timeout(n.timeoutMs??3e4):AbortSignal.any([n.signal,AbortSignal.timeout(n.timeoutMs??3e4)])})}catch(f){throw f instanceof DOMException&&f.name==="TimeoutError"?new G({code:K.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 G({code:K.INVALID_RESPONSE,msg:`HTTP ${p.status} — non-JSON response`,data:null});if(g.code!==0)throw new G({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 ft(await this.run(this.rest.config.patch(e)))}listPersonas(e={}){return this.run(()=>this.rest.personas.list(e))}getPersona(e){return this.run(()=>this.rest.personas.get(e))}putPersona(e){return this.run(()=>this.rest.personas.put(e))}duplicatePersona(e,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:yt(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:yt(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 i=new Uint8Array(await t.arrayBuffer());return this.run(()=>this.rest.personas.putAvatar(e,i,t.type,n))}deletePersonaAvatar(e){return this.run(()=>this.rest.personas.deleteAvatar(e))}}const am=40945,cm=40946;function yt(o){const e=o.name.toLowerCase();return o.type==="image/png"||e.endsWith(".png")?"png":e.endsWith(".charx")?"charx":"json"}const Sm=Object.freeze(Object.defineProperty({__proto__:null,API_CODES:K,ApiError:G,ExternalAgentAttachmentUnsupportedError:ls,KikiClient:ps,MEMORY_NOT_FOUND:sm,MEMORY_REVISION_CONFLICT:im,MEMORY_TYPES:nm,NativeChildPromptConflictError:us,NativeChildPromptSendError:Nt,PERSONA_ALREADY_EXISTS:am,PERSONA_REVISION_CONFLICT:cm,createRemoteSpaceClient:rm,isSessionIndexBuildingError:tm,isSessionNotFoundMessage:om,parseKikiConfigResponse:ft,personaCardFormatOf:yt},Symbol.toStringTag,{value:"Module"}));export{G as A,jp as D,ls as E,zt as G,ps as K,P as M,Nt as N,cm as P,N as R,K as a,pm as b,rm as c,hm as d,gr as e,im as f,Kt as g,mm as h,nm as i,sm as j,om as k,am as l,gm as m,Zp as n,em as o,tm as p,Sm as q,um as s,lm as t,vm as w};
|